content: Remove use of MessageLoopProxy and deprecated MessageLoop APIs
[chromium-blink-merge.git] / content / browser / renderer_host / render_process_host_impl.cc
blobd4da1d4bb6376591e332a546da3f5d35088470e9
1 // Copyright 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 // Represents the browser side of the browser <--> renderer communication
6 // channel. There will be one RenderProcessHost per renderer process.
8 #include "content/browser/renderer_host/render_process_host_impl.h"
10 #include <algorithm>
11 #include <limits>
12 #include <vector>
14 #include "base/base_switches.h"
15 #include "base/bind.h"
16 #include "base/bind_helpers.h"
17 #include "base/callback.h"
18 #include "base/command_line.h"
19 #include "base/debug/dump_without_crashing.h"
20 #include "base/files/file.h"
21 #include "base/lazy_instance.h"
22 #include "base/location.h"
23 #include "base/logging.h"
24 #include "base/metrics/field_trial.h"
25 #include "base/metrics/histogram.h"
26 #include "base/process/process_handle.h"
27 #include "base/profiler/scoped_tracker.h"
28 #include "base/rand_util.h"
29 #include "base/single_thread_task_runner.h"
30 #include "base/stl_util.h"
31 #include "base/strings/string_number_conversions.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/trace_event/trace_event.h"
38 #include "base/tracked_objects.h"
39 #include "cc/base/switches.h"
40 #include "components/scheduler/common/scheduler_switches.h"
41 #include "content/browser/appcache/appcache_dispatcher_host.h"
42 #include "content/browser/appcache/chrome_appcache_service.h"
43 #include "content/browser/background_sync/background_sync_service_impl.h"
44 #include "content/browser/bad_message.h"
45 #include "content/browser/bluetooth/bluetooth_dispatcher_host.h"
46 #include "content/browser/browser_child_process_host_impl.h"
47 #include "content/browser/browser_main.h"
48 #include "content/browser/browser_main_loop.h"
49 #include "content/browser/browser_plugin/browser_plugin_message_filter.h"
50 #include "content/browser/cache_storage/cache_storage_context_impl.h"
51 #include "content/browser/cache_storage/cache_storage_dispatcher_host.h"
52 #include "content/browser/child_process_security_policy_impl.h"
53 #include "content/browser/device_sensors/device_light_message_filter.h"
54 #include "content/browser/device_sensors/device_motion_message_filter.h"
55 #include "content/browser/device_sensors/device_orientation_message_filter.h"
56 #include "content/browser/dom_storage/dom_storage_context_wrapper.h"
57 #include "content/browser/dom_storage/dom_storage_message_filter.h"
58 #include "content/browser/download/mhtml_generation_manager.h"
59 #include "content/browser/fileapi/chrome_blob_storage_context.h"
60 #include "content/browser/fileapi/fileapi_message_filter.h"
61 #include "content/browser/frame_host/render_frame_message_filter.h"
62 #include "content/browser/geofencing/geofencing_dispatcher_host.h"
63 #include "content/browser/gpu/browser_gpu_channel_host_factory.h"
64 #include "content/browser/gpu/compositor_util.h"
65 #include "content/browser/gpu/gpu_data_manager_impl.h"
66 #include "content/browser/gpu/gpu_process_host.h"
67 #include "content/browser/gpu/shader_disk_cache.h"
68 #include "content/browser/histogram_message_filter.h"
69 #include "content/browser/indexed_db/indexed_db_context_impl.h"
70 #include "content/browser/indexed_db/indexed_db_dispatcher_host.h"
71 #include "content/browser/loader/resource_message_filter.h"
72 #include "content/browser/loader/resource_scheduler_filter.h"
73 #include "content/browser/media/capture/audio_mirroring_manager.h"
74 #include "content/browser/media/media_internals.h"
75 #include "content/browser/media/midi_host.h"
76 #include "content/browser/message_port_message_filter.h"
77 #include "content/browser/mime_registry_message_filter.h"
78 #include "content/browser/mojo/mojo_application_host.h"
79 #include "content/browser/navigator_connect/navigator_connect_dispatcher_host.h"
80 #include "content/browser/notifications/notification_message_filter.h"
81 #include "content/browser/permissions/permission_service_context.h"
82 #include "content/browser/permissions/permission_service_impl.h"
83 #include "content/browser/profiler_message_filter.h"
84 #include "content/browser/push_messaging/push_messaging_message_filter.h"
85 #include "content/browser/quota_dispatcher_host.h"
86 #include "content/browser/renderer_host/clipboard_message_filter.h"
87 #include "content/browser/renderer_host/database_message_filter.h"
88 #include "content/browser/renderer_host/file_utilities_message_filter.h"
89 #include "content/browser/renderer_host/gamepad_browser_message_filter.h"
90 #include "content/browser/renderer_host/gpu_message_filter.h"
91 #include "content/browser/renderer_host/media/audio_input_renderer_host.h"
92 #include "content/browser/renderer_host/media/audio_renderer_host.h"
93 #include "content/browser/renderer_host/media/media_stream_dispatcher_host.h"
94 #include "content/browser/renderer_host/media/peer_connection_tracker_host.h"
95 #include "content/browser/renderer_host/media/video_capture_host.h"
96 #include "content/browser/renderer_host/memory_benchmark_message_filter.h"
97 #include "content/browser/renderer_host/pepper/pepper_message_filter.h"
98 #include "content/browser/renderer_host/pepper/pepper_renderer_connection.h"
99 #include "content/browser/renderer_host/render_message_filter.h"
100 #include "content/browser/renderer_host/render_view_host_delegate.h"
101 #include "content/browser/renderer_host/render_view_host_impl.h"
102 #include "content/browser/renderer_host/render_widget_helper.h"
103 #include "content/browser/renderer_host/render_widget_host_impl.h"
104 #include "content/browser/renderer_host/text_input_client_message_filter.h"
105 #include "content/browser/renderer_host/websocket_dispatcher_host.h"
106 #include "content/browser/resolve_proxy_msg_helper.h"
107 #include "content/browser/service_worker/service_worker_context_wrapper.h"
108 #include "content/browser/service_worker/service_worker_dispatcher_host.h"
109 #include "content/browser/shared_worker/shared_worker_message_filter.h"
110 #include "content/browser/shared_worker/worker_storage_partition.h"
111 #include "content/browser/speech/speech_recognition_dispatcher_host.h"
112 #include "content/browser/storage_partition_impl.h"
113 #include "content/browser/streams/stream_context.h"
114 #include "content/browser/tracing/trace_message_filter.h"
115 #include "content/browser/webui/web_ui_controller_factory_registry.h"
116 #include "content/common/child_process_host_impl.h"
117 #include "content/common/child_process_messages.h"
118 #include "content/common/content_switches_internal.h"
119 #include "content/common/frame_messages.h"
120 #include "content/common/gpu/gpu_memory_buffer_factory.h"
121 #include "content/common/gpu/gpu_messages.h"
122 #include "content/common/in_process_child_thread_params.h"
123 #include "content/common/mojo/channel_init.h"
124 #include "content/common/mojo/mojo_messages.h"
125 #include "content/common/resource_messages.h"
126 #include "content/common/view_messages.h"
127 #include "content/public/browser/browser_context.h"
128 #include "content/public/browser/content_browser_client.h"
129 #include "content/public/browser/navigator_connect_context.h"
130 #include "content/public/browser/notification_service.h"
131 #include "content/public/browser/notification_types.h"
132 #include "content/public/browser/render_process_host_factory.h"
133 #include "content/public/browser/render_process_host_observer.h"
134 #include "content/public/browser/render_widget_host.h"
135 #include "content/public/browser/render_widget_host_iterator.h"
136 #include "content/public/browser/render_widget_host_view_frame_subscriber.h"
137 #include "content/public/browser/resource_context.h"
138 #include "content/public/browser/user_metrics.h"
139 #include "content/public/browser/worker_service.h"
140 #include "content/public/common/content_constants.h"
141 #include "content/public/common/content_switches.h"
142 #include "content/public/common/mojo_channel_switches.h"
143 #include "content/public/common/process_type.h"
144 #include "content/public/common/resource_type.h"
145 #include "content/public/common/result_codes.h"
146 #include "content/public/common/sandboxed_process_launcher_delegate.h"
147 #include "content/public/common/url_constants.h"
148 #include "device/battery/battery_monitor_impl.h"
149 #include "device/vibration/vibration_manager_impl.h"
150 #include "gpu/GLES2/gl2extchromium.h"
151 #include "gpu/command_buffer/client/gpu_switches.h"
152 #include "gpu/command_buffer/common/gles2_cmd_utils.h"
153 #include "gpu/command_buffer/service/gpu_switches.h"
154 #include "ipc/ipc_channel.h"
155 #include "ipc/ipc_logging.h"
156 #include "ipc/ipc_switches.h"
157 #include "ipc/mojo/ipc_channel_mojo.h"
158 #include "ipc/mojo/ipc_channel_mojo_host.h"
159 #include "media/base/media_switches.h"
160 #include "net/url_request/url_request_context_getter.h"
161 #include "ppapi/shared_impl/ppapi_switches.h"
162 #include "storage/browser/fileapi/sandbox_file_system_backend.h"
163 #include "third_party/icu/source/common/unicode/unistr.h"
164 #include "third_party/icu/source/i18n/unicode/timezone.h"
165 #include "third_party/skia/include/core/SkBitmap.h"
166 #include "ui/base/ui_base_switches.h"
167 #include "ui/events/event_switches.h"
168 #include "ui/gfx/switches.h"
169 #include "ui/gl/gl_switches.h"
170 #include "ui/gl/gpu_switching_manager.h"
171 #include "ui/native_theme/native_theme_switches.h"
173 #if defined(OS_ANDROID)
174 #include "content/browser/android/child_process_launcher_android.h"
175 #include "content/browser/media/android/browser_demuxer_android.h"
176 #include "content/browser/mojo/service_registrar_android.h"
177 #include "content/browser/screen_orientation/screen_orientation_message_filter_android.h"
178 #endif
180 #if defined(OS_WIN)
181 #include "base/win/scoped_com_initializer.h"
182 #include "base/win/windows_version.h"
183 #include "content/common/font_cache_dispatcher_win.h"
184 #include "content/common/sandbox_win.h"
185 #include "sandbox/win/src/sandbox_policy.h"
186 #include "ui/gfx/win/dpi.h"
187 #endif
189 #if defined(OS_MACOSX) && !defined(OS_IOS)
190 #include "content/browser/browser_io_surface_manager_mac.h"
191 #endif
193 #if defined(ENABLE_BROWSER_CDMS)
194 #include "content/browser/media/cdm/browser_cdm_manager.h"
195 #endif
197 #if defined(ENABLE_PLUGINS)
198 #include "content/browser/plugin_service_impl.h"
199 #endif
201 #if defined(ENABLE_WEBRTC)
202 #include "content/browser/media/webrtc_internals.h"
203 #include "content/browser/renderer_host/media/media_stream_track_metrics_host.h"
204 #include "content/browser/renderer_host/media/webrtc_identity_service_host.h"
205 #include "content/browser/renderer_host/p2p/socket_dispatcher_host.h"
206 #include "content/common/media/aec_dump_messages.h"
207 #include "content/common/media/media_stream_messages.h"
208 #endif
210 extern bool g_exited_main_message_loop;
212 namespace content {
213 namespace {
215 const char kSiteProcessMapKeyName[] = "content_site_process_map";
217 void CacheShaderInfo(int32 id, base::FilePath path) {
218 ShaderCacheFactory::GetInstance()->SetCacheInfo(id, path);
221 void RemoveShaderInfo(int32 id) {
222 ShaderCacheFactory::GetInstance()->RemoveCacheInfo(id);
225 net::URLRequestContext* GetRequestContext(
226 scoped_refptr<net::URLRequestContextGetter> request_context,
227 scoped_refptr<net::URLRequestContextGetter> media_request_context,
228 ResourceType resource_type) {
229 // If the request has resource type of RESOURCE_TYPE_MEDIA, we use a request
230 // context specific to media for handling it because these resources have
231 // specific needs for caching.
232 if (resource_type == RESOURCE_TYPE_MEDIA)
233 return media_request_context->GetURLRequestContext();
234 return request_context->GetURLRequestContext();
237 void GetContexts(
238 ResourceContext* resource_context,
239 scoped_refptr<net::URLRequestContextGetter> request_context,
240 scoped_refptr<net::URLRequestContextGetter> media_request_context,
241 const ResourceHostMsg_Request& request,
242 ResourceContext** resource_context_out,
243 net::URLRequestContext** request_context_out) {
244 *resource_context_out = resource_context;
245 *request_context_out =
246 GetRequestContext(request_context, media_request_context,
247 request.resource_type);
250 #if defined(ENABLE_WEBRTC)
251 // Creates a file used for diagnostic echo canceller recordings for handing
252 // over to the renderer.
253 IPC::PlatformFileForTransit CreateAecDumpFileForProcess(
254 base::FilePath file_path,
255 base::ProcessHandle process) {
256 DCHECK_CURRENTLY_ON(BrowserThread::FILE);
257 base::File dump_file(file_path,
258 base::File::FLAG_OPEN_ALWAYS | base::File::FLAG_APPEND);
259 if (!dump_file.IsValid()) {
260 VLOG(1) << "Could not open AEC dump file, error=" <<
261 dump_file.error_details();
262 return IPC::InvalidPlatformFileForTransit();
264 return IPC::TakeFileHandleForProcess(dump_file.Pass(), process);
267 // Does nothing. Just to avoid races between enable and disable.
268 void DisableAecDumpOnFileThread() {
269 DCHECK_CURRENTLY_ON(BrowserThread::FILE);
271 #endif
273 // the global list of all renderer processes
274 base::LazyInstance<IDMap<RenderProcessHost> >::Leaky
275 g_all_hosts = LAZY_INSTANCE_INITIALIZER;
277 // Map of site to process, to ensure we only have one RenderProcessHost per
278 // site in process-per-site mode. Each map is specific to a BrowserContext.
279 class SiteProcessMap : public base::SupportsUserData::Data {
280 public:
281 typedef base::hash_map<std::string, RenderProcessHost*> SiteToProcessMap;
282 SiteProcessMap() {}
284 void RegisterProcess(const std::string& site, RenderProcessHost* process) {
285 map_[site] = process;
288 RenderProcessHost* FindProcess(const std::string& site) {
289 SiteToProcessMap::iterator i = map_.find(site);
290 if (i != map_.end())
291 return i->second;
292 return NULL;
295 void RemoveProcess(RenderProcessHost* host) {
296 // Find all instances of this process in the map, then separately remove
297 // them.
298 std::set<std::string> sites;
299 for (SiteToProcessMap::const_iterator i = map_.begin();
300 i != map_.end();
301 i++) {
302 if (i->second == host)
303 sites.insert(i->first);
305 for (std::set<std::string>::iterator i = sites.begin();
306 i != sites.end();
307 i++) {
308 SiteToProcessMap::iterator iter = map_.find(*i);
309 if (iter != map_.end()) {
310 DCHECK_EQ(iter->second, host);
311 map_.erase(iter);
316 private:
317 SiteToProcessMap map_;
320 // Find the SiteProcessMap specific to the given context.
321 SiteProcessMap* GetSiteProcessMapForBrowserContext(BrowserContext* context) {
322 DCHECK(context);
323 SiteProcessMap* map = static_cast<SiteProcessMap*>(
324 context->GetUserData(kSiteProcessMapKeyName));
325 if (!map) {
326 map = new SiteProcessMap();
327 context->SetUserData(kSiteProcessMapKeyName, map);
329 return map;
332 // NOTE: changes to this class need to be reviewed by the security team.
333 class RendererSandboxedProcessLauncherDelegate
334 : public SandboxedProcessLauncherDelegate {
335 public:
336 explicit RendererSandboxedProcessLauncherDelegate(IPC::ChannelProxy* channel)
337 #if defined(OS_POSIX)
338 : ipc_fd_(channel->TakeClientFileDescriptor())
339 #endif // OS_POSIX
342 ~RendererSandboxedProcessLauncherDelegate() override {}
344 #if defined(OS_WIN)
345 void PreSpawnTarget(sandbox::TargetPolicy* policy, bool* success) override {
346 AddBaseHandleClosePolicy(policy);
348 if (base::win::GetVersion() == base::win::VERSION_WIN8 ||
349 base::win::GetVersion() == base::win::VERSION_WIN8_1) {
350 const base::CommandLine& command_line =
351 *base::CommandLine::ForCurrentProcess();
352 if (!command_line.HasSwitch(switches::kDisableAppContainer)) {
353 // TODO(shrikant): Check if these constants should be different across
354 // various versions of Chromium code base or could be same.
355 // If there should be different SID per channel then move this code
356 // in chrome rather than content and assign SID based on
357 // VersionInfo::GetChannel().
358 const wchar_t kAppContainerSid[] =
359 L"S-1-15-2-3251537155-1984446955-2931258699-841473695-1938553385-"
360 L"924012148-129201922";
362 policy->SetLowBox(kAppContainerSid);
366 GetContentClient()->browser()->PreSpawnRenderer(policy, success);
369 #elif defined(OS_POSIX)
370 bool ShouldUseZygote() override {
371 const base::CommandLine& browser_command_line =
372 *base::CommandLine::ForCurrentProcess();
373 base::CommandLine::StringType renderer_prefix =
374 browser_command_line.GetSwitchValueNative(switches::kRendererCmdPrefix);
375 return renderer_prefix.empty();
377 base::ScopedFD TakeIpcFd() override { return ipc_fd_.Pass(); }
378 #endif // OS_WIN
380 private:
381 #if defined(OS_POSIX)
382 base::ScopedFD ipc_fd_;
383 #endif // OS_POSIX
386 const char kSessionStorageHolderKey[] = "kSessionStorageHolderKey";
388 class SessionStorageHolder : public base::SupportsUserData::Data {
389 public:
390 SessionStorageHolder() {}
391 ~SessionStorageHolder() override {}
393 void Hold(const SessionStorageNamespaceMap& sessions, int view_route_id) {
394 session_storage_namespaces_awaiting_close_[view_route_id] = sessions;
397 void Release(int old_route_id) {
398 session_storage_namespaces_awaiting_close_.erase(old_route_id);
401 private:
402 std::map<int, SessionStorageNamespaceMap >
403 session_storage_namespaces_awaiting_close_;
404 DISALLOW_COPY_AND_ASSIGN(SessionStorageHolder);
407 } // namespace
409 RendererMainThreadFactoryFunction g_renderer_main_thread_factory = NULL;
411 base::MessageLoop* g_in_process_thread;
413 base::MessageLoop*
414 RenderProcessHostImpl::GetInProcessRendererThreadForTesting() {
415 return g_in_process_thread;
418 // Stores the maximum number of renderer processes the content module can
419 // create.
420 static size_t g_max_renderer_count_override = 0;
422 // static
423 size_t RenderProcessHost::GetMaxRendererProcessCount() {
424 if (g_max_renderer_count_override)
425 return g_max_renderer_count_override;
427 #if defined(OS_ANDROID)
428 // On Android we don't maintain a limit of renderer process hosts - we are
429 // happy with keeping a lot of these, as long as the number of live renderer
430 // processes remains reasonable, and on Android the OS takes care of that.
431 return std::numeric_limits<size_t>::max();
432 #endif
434 // On other platforms, we calculate the maximum number of renderer process
435 // hosts according to the amount of installed memory as reported by the OS.
436 // The calculation assumes that you want the renderers to use half of the
437 // installed RAM and assuming that each WebContents uses ~40MB. If you modify
438 // this assumption, you need to adjust the ThirtyFourTabs test to match the
439 // expected number of processes.
441 // With the given amounts of installed memory below on a 32-bit CPU, the
442 // maximum renderer count will roughly be as follows:
444 // 128 MB -> 3
445 // 512 MB -> 6
446 // 1024 MB -> 12
447 // 4096 MB -> 51
448 // 16384 MB -> 82 (kMaxRendererProcessCount)
450 static size_t max_count = 0;
451 if (!max_count) {
452 const size_t kEstimatedWebContentsMemoryUsage =
453 #if defined(ARCH_CPU_64_BITS)
454 60; // In MB
455 #else
456 40; // In MB
457 #endif
458 max_count = base::SysInfo::AmountOfPhysicalMemoryMB() / 2;
459 max_count /= kEstimatedWebContentsMemoryUsage;
461 const size_t kMinRendererProcessCount = 3;
462 max_count = std::max(max_count, kMinRendererProcessCount);
463 max_count = std::min(max_count, kMaxRendererProcessCount);
465 return max_count;
468 // static
469 bool g_run_renderer_in_process_ = false;
471 // static
472 void RenderProcessHost::SetMaxRendererProcessCount(size_t count) {
473 g_max_renderer_count_override = count;
476 RenderProcessHostImpl::RenderProcessHostImpl(
477 BrowserContext* browser_context,
478 StoragePartitionImpl* storage_partition_impl,
479 bool is_isolated_guest)
480 : fast_shutdown_started_(false),
481 deleting_soon_(false),
482 #ifndef NDEBUG
483 is_self_deleted_(false),
484 #endif
485 pending_views_(0),
486 mojo_application_host_(new MojoApplicationHost),
487 visible_widgets_(0),
488 backgrounded_(true),
489 is_initialized_(false),
490 id_(ChildProcessHostImpl::GenerateChildProcessUniqueId()),
491 browser_context_(browser_context),
492 storage_partition_impl_(storage_partition_impl),
493 sudden_termination_allowed_(true),
494 ignore_input_events_(false),
495 is_isolated_guest_(is_isolated_guest),
496 gpu_observer_registered_(false),
497 delayed_cleanup_needed_(false),
498 within_process_died_observer_(false),
499 power_monitor_broadcaster_(this),
500 worker_ref_count_(0),
501 max_worker_count_(0),
502 permission_service_context_(new PermissionServiceContext(this)),
503 pending_valuebuffer_state_(new gpu::ValueStateMap()),
504 subscribe_uniform_enabled_(false),
505 weak_factory_(this) {
506 widget_helper_ = new RenderWidgetHelper();
508 ChildProcessSecurityPolicyImpl::GetInstance()->Add(GetID());
510 CHECK(!g_exited_main_message_loop);
511 RegisterHost(GetID(), this);
512 g_all_hosts.Get().set_check_on_null_data(true);
513 // Initialize |child_process_activity_time_| to a reasonable value.
514 mark_child_process_activity_time();
516 if (!GetBrowserContext()->IsOffTheRecord() &&
517 !base::CommandLine::ForCurrentProcess()->HasSwitch(
518 switches::kDisableGpuShaderDiskCache)) {
519 BrowserThread::PostTask(BrowserThread::IO, FROM_HERE,
520 base::Bind(&CacheShaderInfo, GetID(),
521 storage_partition_impl_->GetPath()));
523 subscribe_uniform_enabled_ =
524 base::CommandLine::ForCurrentProcess()->HasSwitch(
525 switches::kEnableSubscribeUniformExtension);
527 // Note: When we create the RenderProcessHostImpl, it's technically
528 // backgrounded, because it has no visible listeners. But the process
529 // doesn't actually exist yet, so we'll Background it later, after
530 // creation.
533 // static
534 void RenderProcessHostImpl::ShutDownInProcessRenderer() {
535 DCHECK(g_run_renderer_in_process_);
537 switch (g_all_hosts.Pointer()->size()) {
538 case 0:
539 return;
540 case 1: {
541 RenderProcessHostImpl* host = static_cast<RenderProcessHostImpl*>(
542 AllHostsIterator().GetCurrentValue());
543 FOR_EACH_OBSERVER(RenderProcessHostObserver,
544 host->observers_,
545 RenderProcessHostDestroyed(host));
546 #ifndef NDEBUG
547 host->is_self_deleted_ = true;
548 #endif
549 delete host;
550 return;
552 default:
553 NOTREACHED() << "There should be only one RenderProcessHost when running "
554 << "in-process.";
558 void RenderProcessHostImpl::RegisterRendererMainThreadFactory(
559 RendererMainThreadFactoryFunction create) {
560 g_renderer_main_thread_factory = create;
563 RenderProcessHostImpl::~RenderProcessHostImpl() {
564 #ifndef NDEBUG
565 DCHECK(is_self_deleted_)
566 << "RenderProcessHostImpl is destroyed by something other than itself";
567 #endif
569 // Make sure to clean up the in-process renderer before the channel, otherwise
570 // it may still run and have its IPCs fail, causing asserts.
571 in_process_renderer_.reset();
573 ChildProcessSecurityPolicyImpl::GetInstance()->Remove(GetID());
575 if (gpu_observer_registered_) {
576 ui::GpuSwitchingManager::GetInstance()->RemoveObserver(this);
577 gpu_observer_registered_ = false;
580 // We may have some unsent messages at this point, but that's OK.
581 channel_.reset();
582 while (!queued_messages_.empty()) {
583 delete queued_messages_.front();
584 queued_messages_.pop();
587 UnregisterHost(GetID());
589 if (!base::CommandLine::ForCurrentProcess()->HasSwitch(
590 switches::kDisableGpuShaderDiskCache)) {
591 BrowserThread::PostTask(BrowserThread::IO, FROM_HERE,
592 base::Bind(&RemoveShaderInfo, GetID()));
596 void RenderProcessHostImpl::EnableSendQueue() {
597 is_initialized_ = false;
600 bool RenderProcessHostImpl::Init() {
601 // calling Init() more than once does nothing, this makes it more convenient
602 // for the view host which may not be sure in some cases
603 if (channel_)
604 return true;
606 base::CommandLine::StringType renderer_prefix;
607 // A command prefix is something prepended to the command line of the spawned
608 // process.
609 const base::CommandLine& browser_command_line =
610 *base::CommandLine::ForCurrentProcess();
611 renderer_prefix =
612 browser_command_line.GetSwitchValueNative(switches::kRendererCmdPrefix);
614 #if defined(OS_LINUX)
615 int flags = renderer_prefix.empty() ? ChildProcessHost::CHILD_ALLOW_SELF :
616 ChildProcessHost::CHILD_NORMAL;
617 #else
618 int flags = ChildProcessHost::CHILD_NORMAL;
619 #endif
621 // Find the renderer before creating the channel so if this fails early we
622 // return without creating the channel.
623 base::FilePath renderer_path = ChildProcessHost::GetChildPath(flags);
624 if (renderer_path.empty())
625 return false;
627 // Setup the IPC channel.
628 const std::string channel_id =
629 IPC::Channel::GenerateVerifiedChannelID(std::string());
630 channel_ = CreateChannelProxy(channel_id);
632 // Setup the Mojo channel.
633 mojo_application_host_->Init();
635 // Call the embedder first so that their IPC filters have priority.
636 GetContentClient()->browser()->RenderProcessWillLaunch(this);
638 CreateMessageFilters();
639 RegisterMojoServices();
641 if (run_renderer_in_process()) {
642 DCHECK(g_renderer_main_thread_factory);
643 // Crank up a thread and run the initialization there. With the way that
644 // messages flow between the browser and renderer, this thread is required
645 // to prevent a deadlock in single-process mode. Since the primordial
646 // thread in the renderer process runs the WebKit code and can sometimes
647 // make blocking calls to the UI thread (i.e. this thread), they need to run
648 // on separate threads.
649 in_process_renderer_.reset(
650 g_renderer_main_thread_factory(InProcessChildThreadParams(
651 channel_id, BrowserThread::UnsafeGetMessageLoopForThread(
652 BrowserThread::IO)->task_runner())));
654 base::Thread::Options options;
655 #if defined(OS_WIN) && !defined(OS_MACOSX)
656 // In-process plugins require this to be a UI message loop.
657 options.message_loop_type = base::MessageLoop::TYPE_UI;
658 #else
659 // We can't have multiple UI loops on Linux and Android, so we don't support
660 // in-process plugins.
661 options.message_loop_type = base::MessageLoop::TYPE_DEFAULT;
662 #endif
664 // As for execution sequence, this callback should have no any dependency
665 // on starting in-process-render-thread.
666 // So put it here to trigger ChannelMojo initialization earlier to enable
667 // in-process-render-thread using ChannelMojo there.
668 OnProcessLaunched(); // Fake a callback that the process is ready.
670 in_process_renderer_->StartWithOptions(options);
672 g_in_process_thread = in_process_renderer_->message_loop();
674 } else {
675 // Build command line for renderer. We call AppendRendererCommandLine()
676 // first so the process type argument will appear first.
677 base::CommandLine* cmd_line = new base::CommandLine(renderer_path);
678 if (!renderer_prefix.empty())
679 cmd_line->PrependWrapper(renderer_prefix);
680 AppendRendererCommandLine(cmd_line);
681 cmd_line->AppendSwitchASCII(switches::kProcessChannelID, channel_id);
683 // Spawn the child process asynchronously to avoid blocking the UI thread.
684 // As long as there's no renderer prefix, we can use the zygote process
685 // at this stage.
686 child_process_launcher_.reset(new ChildProcessLauncher(
687 new RendererSandboxedProcessLauncherDelegate(channel_.get()),
688 cmd_line,
689 GetID(),
690 this));
692 fast_shutdown_started_ = false;
695 if (!gpu_observer_registered_) {
696 gpu_observer_registered_ = true;
697 ui::GpuSwitchingManager::GetInstance()->AddObserver(this);
700 power_monitor_broadcaster_.Init();
702 is_initialized_ = true;
703 init_time_ = base::TimeTicks::Now();
704 return true;
707 scoped_ptr<IPC::ChannelProxy> RenderProcessHostImpl::CreateChannelProxy(
708 const std::string& channel_id) {
709 scoped_refptr<base::SingleThreadTaskRunner> runner =
710 BrowserThread::GetMessageLoopProxyForThread(BrowserThread::IO);
711 scoped_refptr<base::SequencedTaskRunner> mojo_task_runner =
712 BrowserThread::UnsafeGetMessageLoopForThread(BrowserThread::IO)
713 ->task_runner();
714 if (ShouldUseMojoChannel()) {
715 VLOG(1) << "Mojo Channel is enabled on host";
716 if (!channel_mojo_host_) {
717 channel_mojo_host_.reset(new IPC::ChannelMojoHost(mojo_task_runner));
720 return IPC::ChannelProxy::Create(IPC::ChannelMojo::CreateServerFactory(
721 channel_mojo_host_->channel_delegate(),
722 mojo_task_runner, channel_id),
723 this, runner.get());
726 return IPC::ChannelProxy::Create(
727 channel_id, IPC::Channel::MODE_SERVER, this, runner.get());
730 void RenderProcessHostImpl::CreateMessageFilters() {
731 DCHECK_CURRENTLY_ON(BrowserThread::UI);
732 const base::CommandLine& browser_command_line =
733 *base::CommandLine::ForCurrentProcess();
734 AddFilter(new ResourceSchedulerFilter(GetID()));
735 MediaInternals* media_internals = MediaInternals::GetInstance();
736 media::AudioManager* audio_manager =
737 BrowserMainLoop::GetInstance()->audio_manager();
738 // Add BrowserPluginMessageFilter to ensure it gets the first stab at messages
739 // from guests.
740 scoped_refptr<BrowserPluginMessageFilter> bp_message_filter(
741 new BrowserPluginMessageFilter(GetID()));
742 AddFilter(bp_message_filter.get());
744 scoped_refptr<RenderMessageFilter> render_message_filter(
745 new RenderMessageFilter(
746 GetID(),
747 #if defined(ENABLE_PLUGINS)
748 PluginServiceImpl::GetInstance(),
749 #else
750 NULL,
751 #endif
752 GetBrowserContext(),
753 GetBrowserContext()->GetRequestContextForRenderProcess(GetID()),
754 widget_helper_.get(),
755 audio_manager,
756 media_internals,
757 storage_partition_impl_->GetDOMStorageContext()));
758 AddFilter(render_message_filter.get());
759 AddFilter(
760 new RenderFrameMessageFilter(GetID(), widget_helper_.get()));
761 BrowserContext* browser_context = GetBrowserContext();
762 ResourceContext* resource_context = browser_context->GetResourceContext();
764 scoped_refptr<net::URLRequestContextGetter> request_context(
765 browser_context->GetRequestContextForRenderProcess(GetID()));
766 scoped_refptr<net::URLRequestContextGetter> media_request_context(
767 browser_context->GetMediaRequestContextForRenderProcess(GetID()));
769 ResourceMessageFilter::GetContextsCallback get_contexts_callback(
770 base::Bind(&GetContexts, browser_context->GetResourceContext(),
771 request_context, media_request_context));
773 ResourceMessageFilter* resource_message_filter = new ResourceMessageFilter(
774 GetID(), PROCESS_TYPE_RENDERER,
775 storage_partition_impl_->GetAppCacheService(),
776 ChromeBlobStorageContext::GetFor(browser_context),
777 storage_partition_impl_->GetFileSystemContext(),
778 storage_partition_impl_->GetServiceWorkerContext(),
779 storage_partition_impl_->GetHostZoomLevelContext(),
780 get_contexts_callback);
782 AddFilter(resource_message_filter);
783 MediaStreamManager* media_stream_manager =
784 BrowserMainLoop::GetInstance()->media_stream_manager();
785 AddFilter(new AudioInputRendererHost(
786 GetID(),
787 audio_manager,
788 media_stream_manager,
789 AudioMirroringManager::GetInstance(),
790 BrowserMainLoop::GetInstance()->user_input_monitor()));
791 // The AudioRendererHost needs to be available for lookup, so it's
792 // stashed in a member variable.
793 audio_renderer_host_ = new AudioRendererHost(
794 GetID(),
795 audio_manager,
796 AudioMirroringManager::GetInstance(),
797 media_internals,
798 media_stream_manager);
799 AddFilter(audio_renderer_host_.get());
800 AddFilter(
801 new MidiHost(GetID(), BrowserMainLoop::GetInstance()->midi_manager()));
802 AddFilter(new VideoCaptureHost(media_stream_manager));
803 AddFilter(new AppCacheDispatcherHost(
804 storage_partition_impl_->GetAppCacheService(),
805 GetID()));
806 AddFilter(new ClipboardMessageFilter);
807 AddFilter(new DOMStorageMessageFilter(
808 storage_partition_impl_->GetDOMStorageContext()));
809 AddFilter(new IndexedDBDispatcherHost(
810 GetID(),
811 storage_partition_impl_->GetURLRequestContext(),
812 storage_partition_impl_->GetIndexedDBContext(),
813 ChromeBlobStorageContext::GetFor(browser_context)));
815 gpu_message_filter_ = new GpuMessageFilter(GetID(), widget_helper_.get());
816 AddFilter(gpu_message_filter_);
817 #if defined(ENABLE_WEBRTC)
818 AddFilter(new WebRTCIdentityServiceHost(
819 GetID(), storage_partition_impl_->GetWebRTCIdentityStore()));
820 peer_connection_tracker_host_ = new PeerConnectionTrackerHost(GetID());
821 AddFilter(peer_connection_tracker_host_.get());
822 AddFilter(new MediaStreamDispatcherHost(
823 GetID(),
824 browser_context->GetResourceContext()->GetMediaDeviceIDSalt(),
825 media_stream_manager));
826 AddFilter(new MediaStreamTrackMetricsHost());
827 #endif
828 #if defined(ENABLE_PLUGINS)
829 AddFilter(new PepperRendererConnection(GetID()));
830 #endif
831 AddFilter(new SpeechRecognitionDispatcherHost(
832 GetID(), storage_partition_impl_->GetURLRequestContext()));
833 AddFilter(new FileAPIMessageFilter(
834 GetID(),
835 storage_partition_impl_->GetURLRequestContext(),
836 storage_partition_impl_->GetFileSystemContext(),
837 ChromeBlobStorageContext::GetFor(browser_context),
838 StreamContext::GetFor(browser_context)));
839 AddFilter(new FileUtilitiesMessageFilter(GetID()));
840 AddFilter(new MimeRegistryMessageFilter());
841 AddFilter(new DatabaseMessageFilter(
842 storage_partition_impl_->GetDatabaseTracker()));
843 #if defined(OS_MACOSX)
844 AddFilter(new TextInputClientMessageFilter(GetID()));
845 #elif defined(OS_WIN)
846 // The FontCacheDispatcher is required only when we're using GDI rendering.
847 // TODO(scottmg): pdf/ppapi still require the renderer to be able to precache
848 // GDI fonts (http://crbug.com/383227), even when using DirectWrite. This
849 // should eventually be if (!ShouldUseDirectWrite()) guarded.
850 channel_->AddFilter(new FontCacheDispatcher());
851 #elif defined(OS_ANDROID)
852 browser_demuxer_android_ = new BrowserDemuxerAndroid();
853 AddFilter(browser_demuxer_android_.get());
854 #endif
855 #if defined(ENABLE_BROWSER_CDMS)
856 browser_cdm_manager_ = new BrowserCdmManager(GetID(), NULL);
857 AddFilter(browser_cdm_manager_.get());
858 #endif
860 WebSocketDispatcherHost::GetRequestContextCallback
861 websocket_request_context_callback(
862 base::Bind(&GetRequestContext, request_context,
863 media_request_context, RESOURCE_TYPE_SUB_RESOURCE));
865 AddFilter(
866 new WebSocketDispatcherHost(GetID(), websocket_request_context_callback));
868 message_port_message_filter_ = new MessagePortMessageFilter(
869 base::Bind(&RenderWidgetHelper::GetNextRoutingID,
870 base::Unretained(widget_helper_.get())));
871 AddFilter(message_port_message_filter_.get());
873 scoped_refptr<CacheStorageDispatcherHost> cache_storage_filter =
874 new CacheStorageDispatcherHost();
875 cache_storage_filter->Init(storage_partition_impl_->GetCacheStorageContext());
876 AddFilter(cache_storage_filter.get());
878 scoped_refptr<ServiceWorkerDispatcherHost> service_worker_filter =
879 new ServiceWorkerDispatcherHost(
880 GetID(), message_port_message_filter_.get(), resource_context);
881 service_worker_filter->Init(
882 storage_partition_impl_->GetServiceWorkerContext());
883 AddFilter(service_worker_filter.get());
885 AddFilter(new SharedWorkerMessageFilter(
886 GetID(),
887 resource_context,
888 WorkerStoragePartition(
889 storage_partition_impl_->GetURLRequestContext(),
890 storage_partition_impl_->GetMediaURLRequestContext(),
891 storage_partition_impl_->GetAppCacheService(),
892 storage_partition_impl_->GetQuotaManager(),
893 storage_partition_impl_->GetFileSystemContext(),
894 storage_partition_impl_->GetDatabaseTracker(),
895 storage_partition_impl_->GetIndexedDBContext(),
896 storage_partition_impl_->GetServiceWorkerContext()),
897 message_port_message_filter_.get()));
899 #if defined(ENABLE_WEBRTC)
900 p2p_socket_dispatcher_host_ = new P2PSocketDispatcherHost(
901 resource_context,
902 browser_context->GetRequestContextForRenderProcess(GetID()));
903 AddFilter(p2p_socket_dispatcher_host_.get());
904 #endif
906 AddFilter(new TraceMessageFilter());
907 AddFilter(new ResolveProxyMsgHelper(
908 browser_context->GetRequestContextForRenderProcess(GetID())));
909 AddFilter(new QuotaDispatcherHost(
910 GetID(),
911 storage_partition_impl_->GetQuotaManager(),
912 GetContentClient()->browser()->CreateQuotaPermissionContext()));
914 notification_message_filter_ = new NotificationMessageFilter(
915 GetID(),
916 storage_partition_impl_->GetPlatformNotificationContext(),
917 resource_context,
918 browser_context);
919 AddFilter(notification_message_filter_.get());
921 AddFilter(new GamepadBrowserMessageFilter());
922 AddFilter(new DeviceLightMessageFilter());
923 AddFilter(new DeviceMotionMessageFilter());
924 AddFilter(new DeviceOrientationMessageFilter());
925 AddFilter(new ProfilerMessageFilter(PROCESS_TYPE_RENDERER));
926 AddFilter(new HistogramMessageFilter());
927 #if defined(USE_TCMALLOC) && (defined(OS_LINUX) || defined(OS_ANDROID))
928 if (browser_command_line.HasSwitch(switches::kEnableMemoryBenchmarking))
929 AddFilter(new MemoryBenchmarkMessageFilter());
930 #endif
931 AddFilter(new PushMessagingMessageFilter(
932 GetID(), storage_partition_impl_->GetServiceWorkerContext()));
933 #if defined(OS_ANDROID)
934 AddFilter(new ScreenOrientationMessageFilterAndroid());
935 #endif
936 AddFilter(new GeofencingDispatcherHost(
937 storage_partition_impl_->GetGeofencingManager()));
938 AddFilter(new NavigatorConnectDispatcherHost(
939 storage_partition_impl_->GetNavigatorConnectContext(),
940 message_port_message_filter_.get()));
941 if (browser_command_line.HasSwitch(switches::kEnableWebBluetooth)) {
942 bluetooth_dispatcher_host_ = new BluetoothDispatcherHost();
943 AddFilter(bluetooth_dispatcher_host_.get());
947 void RenderProcessHostImpl::RegisterMojoServices() {
948 mojo_application_host_->service_registry()->AddService(
949 base::Bind(&device::BatteryMonitorImpl::Create));
951 mojo_application_host_->service_registry()->AddService(
952 base::Bind(&device::VibrationManagerImpl::Create));
954 mojo_application_host_->service_registry()->AddService(
955 base::Bind(&PermissionServiceContext::CreateService,
956 base::Unretained(permission_service_context_.get())));
958 mojo_application_host_->service_registry()->AddService(base::Bind(
959 &content::BackgroundSyncServiceImpl::Create,
960 base::Unretained(storage_partition_impl_->GetBackgroundSyncContext())));
962 #if defined(OS_ANDROID)
963 ServiceRegistrarAndroid::RegisterProcessHostServices(
964 mojo_application_host_->service_registry_android());
965 #endif
967 GetContentClient()->browser()->OverrideRenderProcessMojoServices(
968 mojo_application_host_->service_registry());
971 int RenderProcessHostImpl::GetNextRoutingID() {
972 return widget_helper_->GetNextRoutingID();
975 void RenderProcessHostImpl::ResumeDeferredNavigation(
976 const GlobalRequestID& request_id) {
977 widget_helper_->ResumeDeferredNavigation(request_id);
980 void RenderProcessHostImpl::NotifyTimezoneChange(const std::string& zone_id) {
981 Send(new ViewMsg_TimezoneChange(zone_id));
984 ServiceRegistry* RenderProcessHostImpl::GetServiceRegistry() {
985 DCHECK(mojo_application_host_);
986 return mojo_application_host_->service_registry();
989 const base::TimeTicks& RenderProcessHostImpl::GetInitTimeForNavigationMetrics()
990 const {
991 return init_time_;
994 bool RenderProcessHostImpl::SubscribeUniformEnabled() const {
995 return subscribe_uniform_enabled_;
998 void RenderProcessHostImpl::OnAddSubscription(unsigned int target) {
999 DCHECK(subscribe_uniform_enabled_);
1000 subscription_set_.insert(target);
1001 const gpu::ValueState* state = pending_valuebuffer_state_->GetState(target);
1002 if (state) {
1003 SendUpdateValueState(target, *state);
1007 void RenderProcessHostImpl::OnRemoveSubscription(unsigned int target) {
1008 DCHECK(subscribe_uniform_enabled_);
1009 subscription_set_.erase(target);
1012 void RenderProcessHostImpl::SendUpdateValueState(unsigned int target,
1013 const gpu::ValueState& state) {
1014 DCHECK(subscribe_uniform_enabled_);
1015 if (subscription_set_.find(target) != subscription_set_.end()) {
1016 GpuProcessHost::SendOnIO(
1017 GpuProcessHost::GPU_PROCESS_KIND_SANDBOXED,
1018 CAUSE_FOR_GPU_LAUNCH_NO_LAUNCH,
1019 new GpuMsg_UpdateValueState(id_, target, state));
1020 } else {
1021 // Store the ValueState locally in case a Valuebuffer subscribes to it later
1022 pending_valuebuffer_state_->UpdateState(target, state);
1026 #if defined(ENABLE_BROWSER_CDMS)
1027 media::BrowserCdm* RenderProcessHostImpl::GetBrowserCdm(int render_frame_id,
1028 int cdm_id) const {
1029 DCHECK_CURRENTLY_ON(BrowserThread::UI);
1030 return browser_cdm_manager_->GetCdm(render_frame_id, cdm_id);
1032 #endif
1034 void RenderProcessHostImpl::AddRoute(
1035 int32 routing_id,
1036 IPC::Listener* listener) {
1037 CHECK(!listeners_.Lookup(routing_id))
1038 << "Found Routing ID Conflict: " << routing_id;
1039 listeners_.AddWithID(listener, routing_id);
1042 void RenderProcessHostImpl::RemoveRoute(int32 routing_id) {
1043 DCHECK(listeners_.Lookup(routing_id) != NULL);
1044 listeners_.Remove(routing_id);
1046 // Keep the one renderer thread around forever in single process mode.
1047 if (!run_renderer_in_process())
1048 Cleanup();
1051 void RenderProcessHostImpl::AddObserver(RenderProcessHostObserver* observer) {
1052 observers_.AddObserver(observer);
1055 void RenderProcessHostImpl::RemoveObserver(
1056 RenderProcessHostObserver* observer) {
1057 observers_.RemoveObserver(observer);
1060 void RenderProcessHostImpl::ShutdownForBadMessage() {
1061 base::CommandLine* command_line = base::CommandLine::ForCurrentProcess();
1062 if (command_line->HasSwitch(switches::kDisableKillAfterBadIPC))
1063 return;
1065 if (run_renderer_in_process()) {
1066 // In single process mode it is better if we don't suicide but just
1067 // crash.
1068 CHECK(false);
1070 // We kill the renderer but don't include a NOTREACHED, because we want the
1071 // browser to try to survive when it gets illegal messages from the renderer.
1072 Shutdown(RESULT_CODE_KILLED_BAD_MESSAGE, false);
1075 void RenderProcessHostImpl::WidgetRestored() {
1076 // Verify we were properly backgrounded.
1077 DCHECK_EQ(backgrounded_, (visible_widgets_ == 0));
1078 visible_widgets_++;
1079 SetBackgrounded(false);
1082 void RenderProcessHostImpl::WidgetHidden() {
1083 // On startup, the browser will call Hide
1084 if (backgrounded_)
1085 return;
1087 DCHECK_EQ(backgrounded_, (visible_widgets_ == 0));
1088 visible_widgets_--;
1089 DCHECK_GE(visible_widgets_, 0);
1090 if (visible_widgets_ == 0) {
1091 DCHECK(!backgrounded_);
1092 SetBackgrounded(true);
1096 int RenderProcessHostImpl::VisibleWidgetCount() const {
1097 return visible_widgets_;
1100 bool RenderProcessHostImpl::IsIsolatedGuest() const {
1101 return is_isolated_guest_;
1104 StoragePartition* RenderProcessHostImpl::GetStoragePartition() const {
1105 return storage_partition_impl_;
1108 static void AppendCompositorCommandLineFlags(base::CommandLine* command_line) {
1109 if (IsPropertyTreeVerificationEnabled())
1110 command_line->AppendSwitch(cc::switches::kEnablePropertyTreeVerification);
1112 if (IsDelegatedRendererEnabled())
1113 command_line->AppendSwitch(switches::kEnableDelegatedRenderer);
1115 if (IsImplSidePaintingEnabled()) {
1116 command_line->AppendSwitchASCII(
1117 switches::kNumRasterThreads,
1118 base::IntToString(NumberOfRendererRasterThreads()));
1119 } else {
1120 command_line->AppendSwitch(switches::kDisableImplSidePainting);
1123 if (IsGpuRasterizationEnabled())
1124 command_line->AppendSwitch(switches::kEnableGpuRasterization);
1126 int msaa_sample_count = GpuRasterizationMSAASampleCount();
1127 if (msaa_sample_count > 0) {
1128 command_line->AppendSwitchASCII(
1129 switches::kGpuRasterizationMSAASampleCount,
1130 base::IntToString(msaa_sample_count));
1133 DCHECK_IMPLIES(IsZeroCopyUploadEnabled(), !IsOneCopyUploadEnabled());
1134 DCHECK_IMPLIES(IsOneCopyUploadEnabled(), !IsZeroCopyUploadEnabled());
1135 if (IsZeroCopyUploadEnabled())
1136 command_line->AppendSwitch(switches::kEnableZeroCopy);
1137 if (!IsOneCopyUploadEnabled())
1138 command_line->AppendSwitch(switches::kDisableOneCopy);
1140 if (IsForceGpuRasterizationEnabled())
1141 command_line->AppendSwitch(switches::kForceGpuRasterization);
1143 // TODO(reveman): We currently assume that the compositor will use BGRA_8888
1144 // if it's able to, and RGBA_8888 otherwise. Since we don't know what it will
1145 // use we hardcode BGRA_8888 here for now. We should instead
1146 // move decisions about GpuMemoryBuffer format to the browser embedder so we
1147 // know it here, and pass that decision to the compositor for each usage.
1148 // crbug.com/490362
1149 gfx::GpuMemoryBuffer::Format format = gfx::GpuMemoryBuffer::BGRA_8888;
1151 // TODO(danakj): When one-copy uploads support partial update, change this
1152 // usage to PERSISTENT_MAP for one-copy.
1153 gfx::GpuMemoryBuffer::Usage usage = gfx::GpuMemoryBuffer::MAP;
1155 command_line->AppendSwitchASCII(
1156 switches::kUseImageTextureTarget,
1157 base::UintToString(
1158 BrowserGpuChannelHostFactory::GetImageTextureTarget(format, usage)));
1160 // Appending disable-gpu-feature switches due to software rendering list.
1161 GpuDataManagerImpl* gpu_data_manager = GpuDataManagerImpl::GetInstance();
1162 DCHECK(gpu_data_manager);
1163 gpu_data_manager->AppendRendererCommandLine(command_line);
1166 void RenderProcessHostImpl::AppendRendererCommandLine(
1167 base::CommandLine* command_line) const {
1168 // Pass the process type first, so it shows first in process listings.
1169 command_line->AppendSwitchASCII(switches::kProcessType,
1170 switches::kRendererProcess);
1172 // Now send any options from our own command line we want to propagate.
1173 const base::CommandLine& browser_command_line =
1174 *base::CommandLine::ForCurrentProcess();
1175 PropagateBrowserCommandLineToRenderer(browser_command_line, command_line);
1177 // Pass on the browser locale.
1178 const std::string locale =
1179 GetContentClient()->browser()->GetApplicationLocale();
1180 command_line->AppendSwitchASCII(switches::kLang, locale);
1182 // If we run base::FieldTrials, we want to pass to their state to the
1183 // renderer so that it can act in accordance with each state, or record
1184 // histograms relating to the base::FieldTrial states.
1185 std::string field_trial_states;
1186 base::FieldTrialList::AllStatesToString(&field_trial_states);
1187 if (!field_trial_states.empty()) {
1188 command_line->AppendSwitchASCII(switches::kForceFieldTrials,
1189 field_trial_states);
1192 GetContentClient()->browser()->AppendExtraCommandLineSwitches(
1193 command_line, GetID());
1195 if (IsPinchToZoomEnabled())
1196 command_line->AppendSwitch(switches::kEnablePinch);
1198 #if defined(OS_WIN)
1199 command_line->AppendSwitchASCII(switches::kDeviceScaleFactor,
1200 base::DoubleToString(gfx::GetDPIScale()));
1201 #endif
1203 AppendCompositorCommandLineFlags(command_line);
1206 void RenderProcessHostImpl::PropagateBrowserCommandLineToRenderer(
1207 const base::CommandLine& browser_cmd,
1208 base::CommandLine* renderer_cmd) const {
1209 // Propagate the following switches to the renderer command line (along
1210 // with any associated values) if present in the browser command line.
1211 static const char* const kSwitchNames[] = {
1212 switches::kAllowLoopbackInPeerConnection,
1213 switches::kAudioBufferSize,
1214 switches::kBlinkPlatformLogChannels,
1215 switches::kBlinkSettings,
1216 switches::kBlockCrossSiteDocuments,
1217 switches::kDefaultTileWidth,
1218 switches::kDefaultTileHeight,
1219 switches::kDisable3DAPIs,
1220 switches::kDisableAcceleratedJpegDecoding,
1221 switches::kDisableAcceleratedVideoDecode,
1222 switches::kDisableBlinkFeatures,
1223 switches::kDisableBreakpad,
1224 switches::kDisablePreferCompositingToLCDText,
1225 switches::kDisableDatabases,
1226 switches::kDisableDelayAgnosticAec,
1227 switches::kDisableDirectNPAPIRequests,
1228 switches::kDisableDisplayList2dCanvas,
1229 switches::kDisableDistanceFieldText,
1230 switches::kDisableEncryptedMedia,
1231 switches::kDisableFileSystem,
1232 switches::kDisableGpuCompositing,
1233 switches::kDisableGpuVsync,
1234 switches::kDisableLowResTiling,
1235 switches::kDisableHistogramCustomizer,
1236 switches::kDisableIconNtp,
1237 switches::kDisableLCDText,
1238 switches::kDisableLocalStorage,
1239 switches::kDisableLogging,
1240 switches::kDisableMediaSource,
1241 switches::kDisableMojoChannel,
1242 switches::kDisableNewVideoRenderer,
1243 switches::kDisableNotifications,
1244 switches::kDisableOverlayScrollbar,
1245 switches::kDisablePermissionsAPI,
1246 switches::kDisablePinch,
1247 switches::kDisablePrefixedEncryptedMedia,
1248 switches::kDisableSeccompFilterSandbox,
1249 switches::kDisableSharedWorkers,
1250 switches::kDisableSpeechAPI,
1251 switches::kDisableSVG1DOM,
1252 switches::kDisableThreadedCompositing,
1253 switches::kDisableThreadedScrolling,
1254 switches::kDisableTouchAdjustment,
1255 switches::kDisableTouchDragDrop,
1256 switches::kDisableTouchEditing,
1257 switches::kDisableV8IdleTasks,
1258 switches::kDomAutomationController,
1259 switches::kEnableBleedingEdgeRenderingFastPaths,
1260 switches::kEnableBlinkFeatures,
1261 switches::kEnableBrowserSideNavigation,
1262 switches::kEnableCompositorAnimationTimelines,
1263 switches::kEnableCredentialManagerAPI,
1264 switches::kEnableDeferredImageDecoding,
1265 switches::kEnableDelayAgnosticAec,
1266 switches::kEnableDisplayList2dCanvas,
1267 switches::kEnableDistanceFieldText,
1268 switches::kEnableExperimentalCanvasFeatures,
1269 switches::kEnableExperimentalWebPlatformFeatures,
1270 switches::kEnableGPUClientLogging,
1271 switches::kEnableGpuClientTracing,
1272 switches::kEnableGPUServiceLogging,
1273 switches::kEnableIconNtp,
1274 switches::kEnableLinkDisambiguationPopup,
1275 switches::kEnableLowResTiling,
1276 switches::kEnableInbandTextTracks,
1277 switches::kEnableLCDText,
1278 switches::kEnableLogging,
1279 switches::kEnableMemoryBenchmarking,
1280 switches::kEnableNetworkInformation,
1281 switches::kEnableOverlayFullscreenVideo,
1282 switches::kEnableOverlayScrollbar,
1283 switches::kEnablePinch,
1284 switches::kEnablePluginPlaceholderTesting,
1285 switches::kEnablePreciseMemoryInfo,
1286 switches::kEnablePreferCompositingToLCDText,
1287 switches::kEnablePushMessagePayload,
1288 switches::kEnableRendererMojoChannel,
1289 switches::kEnableSeccompFilterSandbox,
1290 switches::kEnableSkiaBenchmarking,
1291 switches::kEnableSlimmingPaint,
1292 switches::kEnableSmoothScrolling,
1293 switches::kEnableStaleWhileRevalidate,
1294 switches::kEnableStatsTable,
1295 switches::kEnableStrictSiteIsolation,
1296 switches::kEnableThreadedCompositing,
1297 switches::kEnableTouchDragDrop,
1298 switches::kEnableTouchEditing,
1299 switches::kEnableUnsafeES3APIs,
1300 switches::kEnableViewport,
1301 switches::kEnableViewportMeta,
1302 switches::kEnableVtune,
1303 switches::kEnableWebBluetooth,
1304 switches::kEnableWebGLDraftExtensions,
1305 switches::kEnableWebGLImageChromium,
1306 switches::kExplicitlyAllowedPorts,
1307 switches::kForceDeviceScaleFactor,
1308 switches::kForceDisplayList2dCanvas,
1309 switches::kFullMemoryCrashReport,
1310 switches::kIPCConnectionTimeout,
1311 switches::kJavaScriptFlags,
1312 switches::kLoggingLevel,
1313 switches::kMainFrameResizesAreOrientationChanges,
1314 switches::kMaxUntiledLayerWidth,
1315 switches::kMaxUntiledLayerHeight,
1316 switches::kMemoryMetrics,
1317 switches::kNoReferrers,
1318 switches::kNoSandbox,
1319 switches::kOverridePluginPowerSaverForTesting,
1320 switches::kPpapiInProcess,
1321 switches::kProfilerTiming,
1322 switches::kReducedReferrerGranularity,
1323 switches::kReduceSecurityForTesting,
1324 switches::kRegisterPepperPlugins,
1325 switches::kRendererStartupDialog,
1326 switches::kRootLayerScrolls,
1327 switches::kShowPaintRects,
1328 switches::kSitePerProcess,
1329 switches::kStatsCollectionController,
1330 switches::kTestType,
1331 switches::kTouchEvents,
1332 switches::kTouchTextSelectionStrategy,
1333 switches::kTraceToConsole,
1334 // This flag needs to be propagated to the renderer process for
1335 // --in-process-webgl.
1336 switches::kUseGL,
1337 switches::kUseMobileUserAgent,
1338 switches::kUseNormalPriorityForTileTaskWorkerThreads,
1339 switches::kV,
1340 switches::kVideoThreads,
1341 switches::kVideoUnderflowThresholdMs,
1342 switches::kVModule,
1343 // Please keep these in alphabetical order. Compositor switches here should
1344 // also be added to chrome/browser/chromeos/login/chrome_restart_request.cc.
1345 cc::switches::kCompositeToMailbox,
1346 cc::switches::kDisableCompositedAntialiasing,
1347 cc::switches::kDisableMainFrameBeforeActivation,
1348 cc::switches::kDisableThreadedAnimation,
1349 cc::switches::kEnableBeginFrameScheduling,
1350 cc::switches::kEnableGpuBenchmarking,
1351 cc::switches::kEnableMainFrameBeforeActivation,
1352 cc::switches::kMaxUnusedResourceMemoryUsagePercentage,
1353 cc::switches::kShowCompositedLayerBorders,
1354 cc::switches::kShowFPSCounter,
1355 cc::switches::kShowLayerAnimationBounds,
1356 cc::switches::kShowPropertyChangedRects,
1357 cc::switches::kShowReplicaScreenSpaceRects,
1358 cc::switches::kShowScreenSpaceRects,
1359 cc::switches::kShowSurfaceDamageRects,
1360 cc::switches::kSlowDownRasterScaleFactor,
1361 cc::switches::kStrictLayerPropertyChangeChecking,
1362 cc::switches::kTopControlsHideThreshold,
1363 cc::switches::kTopControlsShowThreshold,
1365 scheduler::switches::kDisableBlinkScheduler,
1367 #if defined(ENABLE_PLUGINS)
1368 switches::kEnablePepperTesting,
1369 #endif
1370 #if defined(ENABLE_WEBRTC)
1371 switches::kDisableWebRtcHWDecoding,
1372 switches::kDisableWebRtcHWEncoding,
1373 switches::kEnableWebRtcDtls12,
1374 switches::kEnableWebRtcHWH264Encoding,
1375 switches::kEnableWebRtcStunOrigin,
1376 switches::kWebRtcMaxCaptureFramerate,
1377 #endif
1378 switches::kEnableLowEndDeviceMode,
1379 switches::kDisableLowEndDeviceMode,
1380 #if defined(OS_ANDROID)
1381 switches::kDisableGestureRequirementForMediaPlayback,
1382 switches::kDisableWebRTC,
1383 switches::kDisableWebAudio,
1384 switches::kRendererWaitForJavaDebugger,
1385 #endif
1386 #if defined(OS_MACOSX)
1387 // Allow this to be set when invoking the browser and relayed along.
1388 switches::kEnableSandboxLogging,
1389 #endif
1390 #if defined(OS_WIN)
1391 switches::kDisableDirectWrite,
1392 switches::kDisableWin32kRendererLockDown,
1393 switches::kTraceExportEventsToETW,
1394 #endif
1395 #if defined(OS_CHROMEOS)
1396 switches::kDisableVaapiAcceleratedVideoEncode,
1397 #endif
1399 renderer_cmd->CopySwitchesFrom(browser_cmd, kSwitchNames,
1400 arraysize(kSwitchNames));
1402 if (browser_cmd.HasSwitch(switches::kTraceStartup) &&
1403 BrowserMainLoop::GetInstance()->is_tracing_startup()) {
1404 // Pass kTraceStartup switch to renderer only if startup tracing has not
1405 // finished.
1406 renderer_cmd->AppendSwitchASCII(
1407 switches::kTraceStartup,
1408 browser_cmd.GetSwitchValueASCII(switches::kTraceStartup));
1411 // Disable databases in incognito mode.
1412 if (GetBrowserContext()->IsOffTheRecord() &&
1413 !browser_cmd.HasSwitch(switches::kDisableDatabases)) {
1414 renderer_cmd->AppendSwitch(switches::kDisableDatabases);
1417 // Enforce the extra command line flags for impl-side painting.
1418 if (IsImplSidePaintingEnabled() &&
1419 !browser_cmd.HasSwitch(switches::kEnableDeferredImageDecoding))
1420 renderer_cmd->AppendSwitch(switches::kEnableDeferredImageDecoding);
1422 // Add kWaitForDebugger to let renderer process wait for a debugger.
1423 if (browser_cmd.HasSwitch(switches::kWaitForDebuggerChildren)) {
1424 // Look to pass-on the kWaitForDebugger flag.
1425 std::string value =
1426 browser_cmd.GetSwitchValueASCII(switches::kWaitForDebuggerChildren);
1427 if (value.empty() || value == switches::kRendererProcess) {
1428 renderer_cmd->AppendSwitch(switches::kWaitForDebugger);
1433 base::ProcessHandle RenderProcessHostImpl::GetHandle() const {
1434 if (run_renderer_in_process())
1435 return base::GetCurrentProcessHandle();
1437 if (!child_process_launcher_.get() || child_process_launcher_->IsStarting())
1438 return base::kNullProcessHandle;
1440 return child_process_launcher_->GetProcess().Handle();
1443 bool RenderProcessHostImpl::Shutdown(int exit_code, bool wait) {
1444 if (run_renderer_in_process())
1445 return false; // Single process mode never shuts down the renderer.
1447 #if defined(OS_ANDROID)
1448 // Android requires a different approach for killing.
1449 StopChildProcess(GetHandle());
1450 return true;
1451 #else
1452 if (!child_process_launcher_.get() || child_process_launcher_->IsStarting())
1453 return false;
1455 return child_process_launcher_->GetProcess().Terminate(exit_code, wait);
1456 #endif
1459 bool RenderProcessHostImpl::FastShutdownIfPossible() {
1460 if (run_renderer_in_process())
1461 return false; // Single process mode never shuts down the renderer.
1463 if (!GetContentClient()->browser()->IsFastShutdownPossible())
1464 return false;
1466 if (!child_process_launcher_.get() ||
1467 child_process_launcher_->IsStarting() ||
1468 !GetHandle())
1469 return false; // Render process hasn't started or is probably crashed.
1471 // Test if there's an unload listener.
1472 // NOTE: It's possible that an onunload listener may be installed
1473 // while we're shutting down, so there's a small race here. Given that
1474 // the window is small, it's unlikely that the web page has much
1475 // state that will be lost by not calling its unload handlers properly.
1476 if (!SuddenTerminationAllowed())
1477 return false;
1479 if (worker_ref_count_ != 0) {
1480 if (survive_for_worker_start_time_.is_null())
1481 survive_for_worker_start_time_ = base::TimeTicks::Now();
1482 return false;
1485 // Set this before ProcessDied() so observers can tell if the render process
1486 // died due to fast shutdown versus another cause.
1487 fast_shutdown_started_ = true;
1489 ProcessDied(false /* already_dead */, nullptr);
1490 return true;
1493 bool RenderProcessHostImpl::Send(IPC::Message* msg) {
1494 TRACE_EVENT0("renderer_host", "RenderProcessHostImpl::Send");
1495 if (!channel_) {
1496 if (!is_initialized_) {
1497 queued_messages_.push(msg);
1498 return true;
1499 } else {
1500 delete msg;
1501 return false;
1505 if (child_process_launcher_.get() && child_process_launcher_->IsStarting()) {
1506 queued_messages_.push(msg);
1507 return true;
1510 return channel_->Send(msg);
1513 bool RenderProcessHostImpl::OnMessageReceived(const IPC::Message& msg) {
1514 // If we're about to be deleted, or have initiated the fast shutdown sequence,
1515 // we ignore incoming messages.
1517 if (deleting_soon_ || fast_shutdown_started_)
1518 return false;
1520 mark_child_process_activity_time();
1521 if (msg.routing_id() == MSG_ROUTING_CONTROL) {
1522 // Dispatch control messages.
1523 IPC_BEGIN_MESSAGE_MAP(RenderProcessHostImpl, msg)
1524 IPC_MESSAGE_HANDLER(ChildProcessHostMsg_ShutdownRequest,
1525 OnShutdownRequest)
1526 IPC_MESSAGE_HANDLER(ViewHostMsg_SuddenTerminationChanged,
1527 SuddenTerminationChanged)
1528 IPC_MESSAGE_HANDLER(ViewHostMsg_UserMetricsRecordAction,
1529 OnUserMetricsRecordAction)
1530 IPC_MESSAGE_HANDLER(ViewHostMsg_SavedPageAsMHTML, OnSavedPageAsMHTML)
1531 IPC_MESSAGE_HANDLER(ViewHostMsg_Close_ACK, OnCloseACK)
1532 #if defined(ENABLE_WEBRTC)
1533 IPC_MESSAGE_HANDLER(AecDumpMsg_RegisterAecDumpConsumer,
1534 OnRegisterAecDumpConsumer)
1535 IPC_MESSAGE_HANDLER(AecDumpMsg_UnregisterAecDumpConsumer,
1536 OnUnregisterAecDumpConsumer)
1537 #endif
1538 // Adding single handlers for your service here is fine, but once your
1539 // service needs more than one handler, please extract them into a new
1540 // message filter and add that filter to CreateMessageFilters().
1541 IPC_END_MESSAGE_MAP()
1543 return true;
1546 // Dispatch incoming messages to the appropriate IPC::Listener.
1547 IPC::Listener* listener = listeners_.Lookup(msg.routing_id());
1548 if (!listener) {
1549 if (msg.is_sync()) {
1550 // The listener has gone away, so we must respond or else the caller will
1551 // hang waiting for a reply.
1552 IPC::Message* reply = IPC::SyncMessage::GenerateReply(&msg);
1553 reply->set_reply_error();
1554 Send(reply);
1556 return true;
1558 return listener->OnMessageReceived(msg);
1561 void RenderProcessHostImpl::OnChannelConnected(int32 peer_pid) {
1562 #if defined(IPC_MESSAGE_LOG_ENABLED)
1563 Send(new ChildProcessMsg_SetIPCLoggingEnabled(
1564 IPC::Logging::GetInstance()->Enabled()));
1565 #endif
1567 tracked_objects::ThreadData::Status status =
1568 tracked_objects::ThreadData::status();
1569 Send(new ChildProcessMsg_SetProfilerStatus(status));
1571 #if defined(OS_MACOSX) && !defined(OS_IOS)
1572 io_surface_manager_token_ =
1573 BrowserIOSurfaceManager::GetInstance()->GenerateChildProcessToken(
1574 GetID());
1575 Send(new ChildProcessMsg_SetIOSurfaceManagerToken(io_surface_manager_token_));
1576 #endif
1579 void RenderProcessHostImpl::OnChannelError() {
1580 ProcessDied(true /* already_dead */, nullptr);
1583 void RenderProcessHostImpl::OnBadMessageReceived(const IPC::Message& message) {
1584 // Message de-serialization failed. We consider this a capital crime. Kill the
1585 // renderer if we have one.
1586 LOG(ERROR) << "bad message " << message.type() << " terminating renderer.";
1587 BrowserChildProcessHostImpl::HistogramBadMessageTerminated(
1588 PROCESS_TYPE_RENDERER);
1590 // Create a memory dump. This will contain enough stack frames to work out
1591 // what the bad message was.
1592 base::debug::DumpWithoutCrashing();
1594 bad_message::ReceivedBadMessage(this,
1595 bad_message::RPH_DESERIALIZATION_FAILED);
1598 BrowserContext* RenderProcessHostImpl::GetBrowserContext() const {
1599 return browser_context_;
1602 bool RenderProcessHostImpl::InSameStoragePartition(
1603 StoragePartition* partition) const {
1604 return storage_partition_impl_ == partition;
1607 int RenderProcessHostImpl::GetID() const {
1608 return id_;
1611 bool RenderProcessHostImpl::HasConnection() const {
1612 return channel_.get() != NULL;
1615 void RenderProcessHostImpl::SetIgnoreInputEvents(bool ignore_input_events) {
1616 ignore_input_events_ = ignore_input_events;
1619 bool RenderProcessHostImpl::IgnoreInputEvents() const {
1620 return ignore_input_events_;
1623 void RenderProcessHostImpl::Cleanup() {
1624 // If within_process_died_observer_ is true, one of our observers performed an
1625 // action that caused us to die (e.g. http://crbug.com/339504). Therefore,
1626 // delay the destruction until all of the observer callbacks have been made,
1627 // and guarantee that the RenderProcessHostDestroyed observer callback is
1628 // always the last callback fired.
1629 if (within_process_died_observer_) {
1630 delayed_cleanup_needed_ = true;
1631 return;
1633 delayed_cleanup_needed_ = false;
1635 // Records the time when the process starts surviving for workers for UMA.
1636 if (listeners_.IsEmpty() && worker_ref_count_ > 0 &&
1637 survive_for_worker_start_time_.is_null()) {
1638 survive_for_worker_start_time_ = base::TimeTicks::Now();
1641 // When there are no other owners of this object, we can delete ourselves.
1642 if (listeners_.IsEmpty() && worker_ref_count_ == 0) {
1643 if (!survive_for_worker_start_time_.is_null()) {
1644 UMA_HISTOGRAM_LONG_TIMES(
1645 "SharedWorker.RendererSurviveForWorkerTime",
1646 base::TimeTicks::Now() - survive_for_worker_start_time_);
1649 if (max_worker_count_ > 0) {
1650 // Record the max number of workers (SharedWorker or ServiceWorker)
1651 // that are simultaneously hosted in this renderer process.
1652 UMA_HISTOGRAM_COUNTS("Render.Workers.MaxWorkerCountInRendererProcess",
1653 max_worker_count_);
1656 // We cannot clean up twice; if this fails, there is an issue with our
1657 // control flow.
1658 DCHECK(!deleting_soon_);
1660 DCHECK_EQ(0, pending_views_);
1661 FOR_EACH_OBSERVER(RenderProcessHostObserver,
1662 observers_,
1663 RenderProcessHostDestroyed(this));
1664 NotificationService::current()->Notify(
1665 NOTIFICATION_RENDERER_PROCESS_TERMINATED,
1666 Source<RenderProcessHost>(this),
1667 NotificationService::NoDetails());
1669 #ifndef NDEBUG
1670 is_self_deleted_ = true;
1671 #endif
1672 base::MessageLoop::current()->DeleteSoon(FROM_HERE, this);
1673 deleting_soon_ = true;
1674 // It's important not to wait for the DeleteTask to delete the channel
1675 // proxy. Kill it off now. That way, in case the profile is going away, the
1676 // rest of the objects attached to this RenderProcessHost start going
1677 // away first, since deleting the channel proxy will post a
1678 // OnChannelClosed() to IPC::ChannelProxy::Context on the IO thread.
1679 channel_.reset();
1681 // The following members should be cleared in ProcessDied() as well!
1682 gpu_message_filter_ = NULL;
1683 message_port_message_filter_ = NULL;
1684 #if defined(ENABLE_BROWSER_CDMS)
1685 browser_cdm_manager_ = NULL;
1686 #endif
1688 RemoveUserData(kSessionStorageHolderKey);
1690 // Remove ourself from the list of renderer processes so that we can't be
1691 // reused in between now and when the Delete task runs.
1692 UnregisterHost(GetID());
1694 #if defined(OS_MACOSX) && !defined(OS_IOS)
1695 if (!io_surface_manager_token_.IsZero()) {
1696 BrowserIOSurfaceManager::GetInstance()->InvalidateChildProcessToken(
1697 io_surface_manager_token_);
1698 io_surface_manager_token_.SetZero();
1700 #endif
1705 void RenderProcessHostImpl::AddPendingView() {
1706 pending_views_++;
1709 void RenderProcessHostImpl::RemovePendingView() {
1710 DCHECK(pending_views_);
1711 pending_views_--;
1714 void RenderProcessHostImpl::SetSuddenTerminationAllowed(bool enabled) {
1715 sudden_termination_allowed_ = enabled;
1718 bool RenderProcessHostImpl::SuddenTerminationAllowed() const {
1719 return sudden_termination_allowed_;
1722 base::TimeDelta RenderProcessHostImpl::GetChildProcessIdleTime() const {
1723 return base::TimeTicks::Now() - child_process_activity_time_;
1726 void RenderProcessHostImpl::ResumeRequestsForView(int route_id) {
1727 widget_helper_->ResumeRequestsForView(route_id);
1730 void RenderProcessHostImpl::FilterURL(bool empty_allowed, GURL* url) {
1731 FilterURL(this, empty_allowed, url);
1734 #if defined(ENABLE_WEBRTC)
1735 void RenderProcessHostImpl::EnableAecDump(const base::FilePath& file) {
1736 DCHECK_CURRENTLY_ON(BrowserThread::UI);
1737 // Enable AEC dump for each registered consumer.
1738 for (std::vector<int>::iterator it = aec_dump_consumers_.begin();
1739 it != aec_dump_consumers_.end(); ++it) {
1740 EnableAecDumpForId(file, *it);
1744 void RenderProcessHostImpl::DisableAecDump() {
1745 DCHECK_CURRENTLY_ON(BrowserThread::UI);
1746 // Posting on the FILE thread and then replying back on the UI thread is only
1747 // for avoiding races between enable and disable. Nothing is done on the FILE
1748 // thread.
1749 BrowserThread::PostTaskAndReply(
1750 BrowserThread::FILE, FROM_HERE,
1751 base::Bind(&DisableAecDumpOnFileThread),
1752 base::Bind(&RenderProcessHostImpl::SendDisableAecDumpToRenderer,
1753 weak_factory_.GetWeakPtr()));
1756 void RenderProcessHostImpl::SetWebRtcLogMessageCallback(
1757 base::Callback<void(const std::string&)> callback) {
1758 webrtc_log_message_callback_ = callback;
1761 RenderProcessHostImpl::WebRtcStopRtpDumpCallback
1762 RenderProcessHostImpl::StartRtpDump(
1763 bool incoming,
1764 bool outgoing,
1765 const WebRtcRtpPacketCallback& packet_callback) {
1766 if (!p2p_socket_dispatcher_host_.get())
1767 return WebRtcStopRtpDumpCallback();
1769 BrowserThread::PostTask(BrowserThread::IO,
1770 FROM_HERE,
1771 base::Bind(&P2PSocketDispatcherHost::StartRtpDump,
1772 p2p_socket_dispatcher_host_,
1773 incoming,
1774 outgoing,
1775 packet_callback));
1777 if (stop_rtp_dump_callback_.is_null()) {
1778 stop_rtp_dump_callback_ =
1779 base::Bind(&P2PSocketDispatcherHost::StopRtpDumpOnUIThread,
1780 p2p_socket_dispatcher_host_);
1782 return stop_rtp_dump_callback_;
1784 #endif
1786 IPC::ChannelProxy* RenderProcessHostImpl::GetChannel() {
1787 return channel_.get();
1790 void RenderProcessHostImpl::AddFilter(BrowserMessageFilter* filter) {
1791 channel_->AddFilter(filter->GetFilter());
1794 bool RenderProcessHostImpl::FastShutdownForPageCount(size_t count) {
1795 if (static_cast<size_t>(GetActiveViewCount()) == count)
1796 return FastShutdownIfPossible();
1797 return false;
1800 bool RenderProcessHostImpl::FastShutdownStarted() const {
1801 return fast_shutdown_started_;
1804 // static
1805 void RenderProcessHostImpl::RegisterHost(int host_id, RenderProcessHost* host) {
1806 g_all_hosts.Get().AddWithID(host, host_id);
1809 // static
1810 void RenderProcessHostImpl::UnregisterHost(int host_id) {
1811 RenderProcessHost* host = g_all_hosts.Get().Lookup(host_id);
1812 if (!host)
1813 return;
1815 g_all_hosts.Get().Remove(host_id);
1817 // Look up the map of site to process for the given browser_context,
1818 // in case we need to remove this process from it. It will be registered
1819 // under any sites it rendered that use process-per-site mode.
1820 SiteProcessMap* map =
1821 GetSiteProcessMapForBrowserContext(host->GetBrowserContext());
1822 map->RemoveProcess(host);
1825 // static
1826 void RenderProcessHostImpl::FilterURL(RenderProcessHost* rph,
1827 bool empty_allowed,
1828 GURL* url) {
1829 ChildProcessSecurityPolicyImpl* policy =
1830 ChildProcessSecurityPolicyImpl::GetInstance();
1832 if (empty_allowed && url->is_empty())
1833 return;
1835 // The browser process should never hear the swappedout:// URL from any
1836 // of the renderer's messages. Check for this in debug builds, but don't
1837 // let it crash a release browser.
1838 DCHECK(GURL(kSwappedOutURL) != *url);
1840 if (!url->is_valid()) {
1841 // Have to use about:blank for the denied case, instead of an empty GURL.
1842 // This is because the browser treats navigation to an empty GURL as a
1843 // navigation to the home page. This is often a privileged page
1844 // (chrome://newtab/) which is exactly what we don't want.
1845 *url = GURL(url::kAboutBlankURL);
1846 return;
1849 if (url->SchemeIs(url::kAboutScheme)) {
1850 // The renderer treats all URLs in the about: scheme as being about:blank.
1851 // Canonicalize about: URLs to about:blank.
1852 *url = GURL(url::kAboutBlankURL);
1855 // Do not allow browser plugin guests to navigate to non-web URLs, since they
1856 // cannot swap processes or grant bindings.
1857 bool non_web_url_in_guest = rph->IsIsolatedGuest() &&
1858 !(url->is_valid() && policy->IsWebSafeScheme(url->scheme()));
1860 if (non_web_url_in_guest || !policy->CanRequestURL(rph->GetID(), *url)) {
1861 // If this renderer is not permitted to request this URL, we invalidate the
1862 // URL. This prevents us from storing the blocked URL and becoming confused
1863 // later.
1864 VLOG(1) << "Blocked URL " << url->spec();
1865 *url = GURL(url::kAboutBlankURL);
1869 // static
1870 bool RenderProcessHostImpl::IsSuitableHost(
1871 RenderProcessHost* host,
1872 BrowserContext* browser_context,
1873 const GURL& site_url) {
1874 if (run_renderer_in_process())
1875 return true;
1877 if (host->GetBrowserContext() != browser_context)
1878 return false;
1880 // Do not allow sharing of guest hosts. This is to prevent bugs where guest
1881 // and non-guest storage gets mixed. In the future, we might consider enabling
1882 // the sharing of guests, in this case this check should be removed and
1883 // InSameStoragePartition should handle the possible sharing.
1884 if (host->IsIsolatedGuest())
1885 return false;
1887 // Check whether the given host and the intended site_url will be using the
1888 // same StoragePartition, since a RenderProcessHost can only support a single
1889 // StoragePartition. This is relevant for packaged apps and isolated sites.
1890 StoragePartition* dest_partition =
1891 BrowserContext::GetStoragePartitionForSite(browser_context, site_url);
1892 if (!host->InSameStoragePartition(dest_partition))
1893 return false;
1895 if (ChildProcessSecurityPolicyImpl::GetInstance()->HasWebUIBindings(
1896 host->GetID()) !=
1897 WebUIControllerFactoryRegistry::GetInstance()->UseWebUIBindingsForURL(
1898 browser_context, site_url)) {
1899 return false;
1902 return GetContentClient()->browser()->IsSuitableHost(host, site_url);
1905 // static
1906 bool RenderProcessHost::run_renderer_in_process() {
1907 return g_run_renderer_in_process_;
1910 // static
1911 void RenderProcessHost::SetRunRendererInProcess(bool value) {
1912 g_run_renderer_in_process_ = value;
1914 base::CommandLine* command_line = base::CommandLine::ForCurrentProcess();
1915 if (value) {
1916 if (!command_line->HasSwitch(switches::kLang)) {
1917 // Modify the current process' command line to include the browser locale,
1918 // as the renderer expects this flag to be set.
1919 const std::string locale =
1920 GetContentClient()->browser()->GetApplicationLocale();
1921 command_line->AppendSwitchASCII(switches::kLang, locale);
1923 // TODO(piman): we should really send configuration through bools rather
1924 // than by parsing strings, i.e. sending an IPC rather than command line
1925 // args. crbug.com/314909
1926 AppendCompositorCommandLineFlags(command_line);
1930 // static
1931 RenderProcessHost::iterator RenderProcessHost::AllHostsIterator() {
1932 DCHECK_CURRENTLY_ON(BrowserThread::UI);
1933 return iterator(g_all_hosts.Pointer());
1936 // static
1937 RenderProcessHost* RenderProcessHost::FromID(int render_process_id) {
1938 DCHECK_CURRENTLY_ON(BrowserThread::UI);
1939 return g_all_hosts.Get().Lookup(render_process_id);
1942 // static
1943 bool RenderProcessHost::ShouldTryToUseExistingProcessHost(
1944 BrowserContext* browser_context, const GURL& url) {
1945 // Experimental:
1946 // If --enable-strict-site-isolation or --site-per-process is enabled, do not
1947 // try to reuse renderer processes when over the limit. (We could allow pages
1948 // from the same site to share, if we knew what the given process was
1949 // dedicated to. Allowing no sharing is simpler for now.) This may cause
1950 // resource exhaustion issues if too many sites are open at once.
1951 const base::CommandLine& command_line =
1952 *base::CommandLine::ForCurrentProcess();
1953 if (command_line.HasSwitch(switches::kEnableStrictSiteIsolation) ||
1954 command_line.HasSwitch(switches::kSitePerProcess))
1955 return false;
1957 if (run_renderer_in_process())
1958 return true;
1960 // NOTE: Sometimes it's necessary to create more render processes than
1961 // GetMaxRendererProcessCount(), for instance when we want to create
1962 // a renderer process for a browser context that has no existing
1963 // renderers. This is OK in moderation, since the
1964 // GetMaxRendererProcessCount() is conservative.
1965 if (g_all_hosts.Get().size() >= GetMaxRendererProcessCount())
1966 return true;
1968 return GetContentClient()->browser()->
1969 ShouldTryToUseExistingProcessHost(browser_context, url);
1972 // static
1973 RenderProcessHost* RenderProcessHost::GetExistingProcessHost(
1974 BrowserContext* browser_context,
1975 const GURL& site_url) {
1976 // First figure out which existing renderers we can use.
1977 std::vector<RenderProcessHost*> suitable_renderers;
1978 suitable_renderers.reserve(g_all_hosts.Get().size());
1980 iterator iter(AllHostsIterator());
1981 while (!iter.IsAtEnd()) {
1982 if (GetContentClient()->browser()->MayReuseHost(iter.GetCurrentValue()) &&
1983 RenderProcessHostImpl::IsSuitableHost(
1984 iter.GetCurrentValue(),
1985 browser_context, site_url)) {
1986 suitable_renderers.push_back(iter.GetCurrentValue());
1988 iter.Advance();
1991 // Now pick a random suitable renderer, if we have any.
1992 if (!suitable_renderers.empty()) {
1993 int suitable_count = static_cast<int>(suitable_renderers.size());
1994 int random_index = base::RandInt(0, suitable_count - 1);
1995 return suitable_renderers[random_index];
1998 return NULL;
2001 // static
2002 bool RenderProcessHost::ShouldUseProcessPerSite(
2003 BrowserContext* browser_context,
2004 const GURL& url) {
2005 // Returns true if we should use the process-per-site model. This will be
2006 // the case if the --process-per-site switch is specified, or in
2007 // process-per-site-instance for particular sites (e.g., WebUI).
2008 // Note that --single-process is handled in ShouldTryToUseExistingProcessHost.
2009 const base::CommandLine& command_line =
2010 *base::CommandLine::ForCurrentProcess();
2011 if (command_line.HasSwitch(switches::kProcessPerSite))
2012 return true;
2014 // We want to consolidate particular sites like WebUI even when we are using
2015 // the process-per-tab or process-per-site-instance models.
2016 // Note: DevTools pages have WebUI type but should not reuse the same host.
2017 if (WebUIControllerFactoryRegistry::GetInstance()->UseWebUIForURL(
2018 browser_context, url) &&
2019 !url.SchemeIs(kChromeDevToolsScheme)) {
2020 return true;
2023 // Otherwise let the content client decide, defaulting to false.
2024 return GetContentClient()->browser()->ShouldUseProcessPerSite(browser_context,
2025 url);
2028 // static
2029 RenderProcessHost* RenderProcessHostImpl::GetProcessHostForSite(
2030 BrowserContext* browser_context,
2031 const GURL& url) {
2032 // Look up the map of site to process for the given browser_context.
2033 SiteProcessMap* map =
2034 GetSiteProcessMapForBrowserContext(browser_context);
2036 // See if we have an existing process with appropriate bindings for this site.
2037 // If not, the caller should create a new process and register it.
2038 std::string site = SiteInstance::GetSiteForURL(browser_context, url)
2039 .possibly_invalid_spec();
2040 RenderProcessHost* host = map->FindProcess(site);
2041 if (host && (!GetContentClient()->browser()->MayReuseHost(host) ||
2042 !IsSuitableHost(host, browser_context, url))) {
2043 // The registered process does not have an appropriate set of bindings for
2044 // the url. Remove it from the map so we can register a better one.
2045 RecordAction(
2046 base::UserMetricsAction("BindingsMismatch_GetProcessHostPerSite"));
2047 map->RemoveProcess(host);
2048 host = NULL;
2051 return host;
2054 void RenderProcessHostImpl::RegisterProcessHostForSite(
2055 BrowserContext* browser_context,
2056 RenderProcessHost* process,
2057 const GURL& url) {
2058 // Look up the map of site to process for the given browser_context.
2059 SiteProcessMap* map =
2060 GetSiteProcessMapForBrowserContext(browser_context);
2062 // Only register valid, non-empty sites. Empty or invalid sites will not
2063 // use process-per-site mode. We cannot check whether the process has
2064 // appropriate bindings here, because the bindings have not yet been granted.
2065 std::string site = SiteInstance::GetSiteForURL(browser_context, url)
2066 .possibly_invalid_spec();
2067 if (!site.empty())
2068 map->RegisterProcess(site, process);
2071 void RenderProcessHostImpl::ProcessDied(bool already_dead,
2072 RendererClosedDetails* known_details) {
2073 // Our child process has died. If we didn't expect it, it's a crash.
2074 // In any case, we need to let everyone know it's gone.
2075 // The OnChannelError notification can fire multiple times due to nested sync
2076 // calls to a renderer. If we don't have a valid channel here it means we
2077 // already handled the error.
2079 // It should not be possible for us to be called re-entrantly.
2080 DCHECK(!within_process_died_observer_);
2082 // It should not be possible for a process death notification to come in while
2083 // we are dying.
2084 DCHECK(!deleting_soon_);
2086 // child_process_launcher_ can be NULL in single process mode or if fast
2087 // termination happened.
2088 base::TerminationStatus status = base::TERMINATION_STATUS_NORMAL_TERMINATION;
2089 int exit_code = 0;
2090 if (known_details) {
2091 status = known_details->status;
2092 exit_code = known_details->exit_code;
2093 } else if (child_process_launcher_.get()) {
2094 status = child_process_launcher_->GetChildTerminationStatus(already_dead,
2095 &exit_code);
2098 RendererClosedDetails details(status, exit_code);
2099 mojo_application_host_->WillDestroySoon();
2101 child_process_launcher_.reset();
2102 channel_.reset();
2103 while (!queued_messages_.empty()) {
2104 delete queued_messages_.front();
2105 queued_messages_.pop();
2108 within_process_died_observer_ = true;
2109 NotificationService::current()->Notify(
2110 NOTIFICATION_RENDERER_PROCESS_CLOSED,
2111 Source<RenderProcessHost>(this),
2112 Details<RendererClosedDetails>(&details));
2113 FOR_EACH_OBSERVER(RenderProcessHostObserver,
2114 observers_,
2115 RenderProcessExited(this, status, exit_code));
2116 within_process_died_observer_ = false;
2118 gpu_message_filter_ = NULL;
2119 message_port_message_filter_ = NULL;
2120 #if defined(ENABLE_BROWSER_CDMS)
2121 browser_cdm_manager_ = NULL;
2122 #endif
2123 RemoveUserData(kSessionStorageHolderKey);
2125 IDMap<IPC::Listener>::iterator iter(&listeners_);
2126 while (!iter.IsAtEnd()) {
2127 iter.GetCurrentValue()->OnMessageReceived(
2128 FrameHostMsg_RenderProcessGone(iter.GetCurrentKey(),
2129 static_cast<int>(status),
2130 exit_code));
2131 iter.Advance();
2134 mojo_application_host_.reset(new MojoApplicationHost);
2136 // It's possible that one of the calls out to the observers might have caused
2137 // this object to be no longer needed.
2138 if (delayed_cleanup_needed_)
2139 Cleanup();
2141 // This object is not deleted at this point and might be reused later.
2142 // TODO(darin): clean this up
2145 int RenderProcessHost::GetActiveViewCount() {
2146 int num_active_views = 0;
2147 scoped_ptr<RenderWidgetHostIterator> widgets(
2148 RenderWidgetHost::GetRenderWidgetHosts());
2149 while (RenderWidgetHost* widget = widgets->GetNextHost()) {
2150 // Count only RenderWidgetHosts in this process.
2151 if (widget->GetProcess()->GetID() == GetID())
2152 num_active_views++;
2154 return num_active_views;
2157 // Frame subscription API for this class is for accelerated composited path
2158 // only. These calls are redirected to GpuMessageFilter.
2159 void RenderProcessHostImpl::BeginFrameSubscription(
2160 int route_id,
2161 scoped_ptr<RenderWidgetHostViewFrameSubscriber> subscriber) {
2162 if (!gpu_message_filter_)
2163 return;
2164 BrowserThread::PostTask(BrowserThread::IO, FROM_HERE, base::Bind(
2165 &GpuMessageFilter::BeginFrameSubscription,
2166 gpu_message_filter_,
2167 route_id, base::Passed(&subscriber)));
2170 void RenderProcessHostImpl::EndFrameSubscription(int route_id) {
2171 if (!gpu_message_filter_)
2172 return;
2173 BrowserThread::PostTask(BrowserThread::IO, FROM_HERE, base::Bind(
2174 &GpuMessageFilter::EndFrameSubscription,
2175 gpu_message_filter_,
2176 route_id));
2179 #if defined(ENABLE_WEBRTC)
2180 void RenderProcessHostImpl::WebRtcLogMessage(const std::string& message) {
2181 DCHECK_CURRENTLY_ON(BrowserThread::UI);
2182 if (!webrtc_log_message_callback_.is_null())
2183 webrtc_log_message_callback_.Run(message);
2185 #endif
2187 void RenderProcessHostImpl::ReleaseOnCloseACK(
2188 RenderProcessHost* host,
2189 const SessionStorageNamespaceMap& sessions,
2190 int view_route_id) {
2191 DCHECK(host);
2192 if (sessions.empty())
2193 return;
2194 SessionStorageHolder* holder = static_cast<SessionStorageHolder*>
2195 (host->GetUserData(kSessionStorageHolderKey));
2196 if (!holder) {
2197 holder = new SessionStorageHolder();
2198 host->SetUserData(
2199 kSessionStorageHolderKey,
2200 holder);
2202 holder->Hold(sessions, view_route_id);
2205 void RenderProcessHostImpl::OnShutdownRequest() {
2206 // Don't shut down if there are active RenderViews, or if there are pending
2207 // RenderViews being swapped back in.
2208 // In single process mode, we never shutdown the renderer.
2209 int num_active_views = GetActiveViewCount();
2210 if (pending_views_ || num_active_views > 0 || run_renderer_in_process())
2211 return;
2213 // Notify any contents that might have swapped out renderers from this
2214 // process. They should not attempt to swap them back in.
2215 NotificationService::current()->Notify(
2216 NOTIFICATION_RENDERER_PROCESS_CLOSING,
2217 Source<RenderProcessHost>(this),
2218 NotificationService::NoDetails());
2220 mojo_application_host_->WillDestroySoon();
2222 Send(new ChildProcessMsg_Shutdown());
2225 void RenderProcessHostImpl::SuddenTerminationChanged(bool enabled) {
2226 SetSuddenTerminationAllowed(enabled);
2229 void RenderProcessHostImpl::SetBackgrounded(bool backgrounded) {
2230 TRACE_EVENT1("renderer_host", "RenderProcessHostImpl::SetBackgrounded",
2231 "backgrounded", backgrounded);
2232 // Note: we always set the backgrounded_ value. If the process is NULL
2233 // (and hence hasn't been created yet), we will set the process priority
2234 // later when we create the process.
2235 backgrounded_ = backgrounded;
2236 if (!child_process_launcher_.get() || child_process_launcher_->IsStarting())
2237 return;
2239 // Don't background processes which have active audio streams.
2240 if (backgrounded_ && audio_renderer_host_->HasActiveAudio())
2241 return;
2243 const base::CommandLine* command_line =
2244 base::CommandLine::ForCurrentProcess();
2245 if (command_line->HasSwitch(switches::kDisableRendererBackgrounding))
2246 return;
2248 #if defined(OS_WIN)
2249 // The cbstext.dll loads as a global GetMessage hook in the browser process
2250 // and intercepts/unintercepts the kernel32 API SetPriorityClass in a
2251 // background thread. If the UI thread invokes this API just when it is
2252 // intercepted the stack is messed up on return from the interceptor
2253 // which causes random crashes in the browser process. Our hack for now
2254 // is to not invoke the SetPriorityClass API if the dll is loaded.
2255 if (GetModuleHandle(L"cbstext.dll"))
2256 return;
2257 #endif // OS_WIN
2259 #if defined(OS_WIN) || defined(OS_MACOSX)
2260 // Same as below, but bound to an experiment (http://crbug.com/458594 on
2261 // Windows, http://crbug.com/398103 on the Mac). Enabled by default in the
2262 // absence of field trials to get coverage on the perf waterfall.
2263 base::FieldTrial* trial =
2264 base::FieldTrialList::Find("BackgroundRendererProcesses");
2265 if (!trial || !StartsWithASCII(trial->group_name(), "Disallow", true)) {
2266 child_process_launcher_->SetProcessBackgrounded(backgrounded);
2268 #else
2269 // Control the background state from the browser process, otherwise the task
2270 // telling the renderer to "unbackground" itself may be preempted by other
2271 // tasks executing at lowered priority ahead of it or simply by not being
2272 // swiftly scheduled by the OS per the low process priority
2273 // (http://crbug.com/398103).
2274 child_process_launcher_->SetProcessBackgrounded(backgrounded);
2275 #endif // OS_WIN
2277 // Notify the child process of background state.
2278 Send(new ChildProcessMsg_SetProcessBackgrounded(backgrounded));
2281 void RenderProcessHostImpl::OnProcessLaunched() {
2282 // TODO(erikchen): Remove ScopedTracker below once http://crbug.com/465841
2283 // is fixed.
2284 tracked_objects::ScopedTracker tracking_profile1(
2285 FROM_HERE_WITH_EXPLICIT_FUNCTION(
2286 "465841 RenderProcessHostImpl::OnProcessLaunched::Start"));
2287 // No point doing anything, since this object will be destructed soon. We
2288 // especially don't want to send the RENDERER_PROCESS_CREATED notification,
2289 // since some clients might expect a RENDERER_PROCESS_TERMINATED afterwards to
2290 // properly cleanup.
2291 if (deleting_soon_)
2292 return;
2294 if (child_process_launcher_) {
2295 // TODO(erikchen): Remove ScopedTracker below once http://crbug.com/465841
2296 // is fixed.
2297 tracked_objects::ScopedTracker tracking_profile2(
2298 FROM_HERE_WITH_EXPLICIT_FUNCTION(
2299 "465841 RenderProcessHostImpl::OnProcessLaunched::Backgrounded"));
2300 DCHECK(child_process_launcher_->GetProcess().IsValid());
2301 SetBackgrounded(backgrounded_);
2304 // TODO(erikchen): Remove ScopedTracker below once http://crbug.com/465841
2305 // is fixed.
2306 tracked_objects::ScopedTracker tracking_profile3(
2307 FROM_HERE_WITH_EXPLICIT_FUNCTION(
2308 "465841 RenderProcessHostImpl::OnProcessLaunched::Notify"));
2309 // NOTE: This needs to be before sending queued messages because
2310 // ExtensionService uses this notification to initialize the renderer process
2311 // with state that must be there before any JavaScript executes.
2313 // The queued messages contain such things as "navigate". If this notification
2314 // was after, we can end up executing JavaScript before the initialization
2315 // happens.
2316 NotificationService::current()->Notify(
2317 NOTIFICATION_RENDERER_PROCESS_CREATED,
2318 Source<RenderProcessHost>(this),
2319 NotificationService::NoDetails());
2321 // TODO(erikchen): Remove ScopedTracker below once http://crbug.com/465841
2322 // is fixed.
2323 tracked_objects::ScopedTracker tracking_profile4(
2324 FROM_HERE_WITH_EXPLICIT_FUNCTION(
2325 "465841 RenderProcessHostImpl::OnProcessLaunched::MojoActivate"));
2326 // Allow Mojo to be setup before the renderer sees any Chrome IPC messages.
2327 // This way, Mojo can be safely used from the renderer in response to any
2328 // Chrome IPC message.
2329 mojo_application_host_->Activate(this, GetHandle());
2331 // TODO(erikchen): Remove ScopedTracker below once http://crbug.com/465841
2332 // is fixed.
2333 tracked_objects::ScopedTracker tracking_profile5(
2334 FROM_HERE_WITH_EXPLICIT_FUNCTION(
2335 "465841 RenderProcessHostImpl::OnProcessLaunched::MojoClientLaunch"));
2336 if (channel_mojo_host_)
2337 channel_mojo_host_->OnClientLaunched(GetHandle());
2339 // TODO(erikchen): Remove ScopedTracker below once http://crbug.com/465841
2340 // is fixed.
2341 tracked_objects::ScopedTracker tracking_profile6(
2342 FROM_HERE_WITH_EXPLICIT_FUNCTION(
2343 "465841 "
2344 "RenderProcessHostImpl::OnProcessLaunched::SendQueuedMessages"));
2345 while (!queued_messages_.empty()) {
2346 Send(queued_messages_.front());
2347 queued_messages_.pop();
2350 #if defined(ENABLE_WEBRTC)
2351 // TODO(erikchen): Remove ScopedTracker below once http://crbug.com/465841
2352 // is fixed.
2353 tracked_objects::ScopedTracker tracking_profile7(
2354 FROM_HERE_WITH_EXPLICIT_FUNCTION(
2355 "465841 RenderProcessHostImpl::OnProcessLaunched::EnableAec"));
2356 if (WebRTCInternals::GetInstance()->aec_dump_enabled())
2357 EnableAecDump(WebRTCInternals::GetInstance()->aec_dump_file_path());
2358 #endif
2361 void RenderProcessHostImpl::OnProcessLaunchFailed() {
2362 // If this object will be destructed soon, then observers have already been
2363 // sent a RenderProcessHostDestroyed notification, and we must observe our
2364 // contract that says that will be the last call.
2365 if (deleting_soon_)
2366 return;
2368 RendererClosedDetails details { base::TERMINATION_STATUS_PROCESS_WAS_KILLED,
2369 -1 };
2370 ProcessDied(true, &details);
2373 scoped_refptr<AudioRendererHost>
2374 RenderProcessHostImpl::audio_renderer_host() const {
2375 return audio_renderer_host_;
2378 void RenderProcessHostImpl::OnUserMetricsRecordAction(
2379 const std::string& action) {
2380 RecordComputedAction(action);
2383 void RenderProcessHostImpl::OnCloseACK(int old_route_id) {
2384 SessionStorageHolder* holder = static_cast<SessionStorageHolder*>
2385 (GetUserData(kSessionStorageHolderKey));
2386 if (!holder)
2387 return;
2388 holder->Release(old_route_id);
2391 void RenderProcessHostImpl::OnSavedPageAsMHTML(int job_id, int64 data_size) {
2392 MHTMLGenerationManager::GetInstance()->MHTMLGenerated(job_id, data_size);
2395 void RenderProcessHostImpl::OnGpuSwitched() {
2396 // We are updating all widgets including swapped out ones.
2397 scoped_ptr<RenderWidgetHostIterator> widgets(
2398 RenderWidgetHostImpl::GetAllRenderWidgetHosts());
2399 while (RenderWidgetHost* widget = widgets->GetNextHost()) {
2400 if (!widget->IsRenderView())
2401 continue;
2403 // Skip widgets in other processes.
2404 if (widget->GetProcess()->GetID() != GetID())
2405 continue;
2407 RenderViewHost* rvh = RenderViewHost::From(widget);
2408 rvh->OnWebkitPreferencesChanged();
2412 #if defined(ENABLE_WEBRTC)
2413 void RenderProcessHostImpl::OnRegisterAecDumpConsumer(int id) {
2414 BrowserThread::PostTask(
2415 BrowserThread::UI,
2416 FROM_HERE,
2417 base::Bind(
2418 &RenderProcessHostImpl::RegisterAecDumpConsumerOnUIThread,
2419 weak_factory_.GetWeakPtr(),
2420 id));
2423 void RenderProcessHostImpl::OnUnregisterAecDumpConsumer(int id) {
2424 BrowserThread::PostTask(
2425 BrowserThread::UI,
2426 FROM_HERE,
2427 base::Bind(
2428 &RenderProcessHostImpl::UnregisterAecDumpConsumerOnUIThread,
2429 weak_factory_.GetWeakPtr(),
2430 id));
2433 void RenderProcessHostImpl::RegisterAecDumpConsumerOnUIThread(int id) {
2434 DCHECK_CURRENTLY_ON(BrowserThread::UI);
2435 aec_dump_consumers_.push_back(id);
2436 if (WebRTCInternals::GetInstance()->aec_dump_enabled()) {
2437 EnableAecDumpForId(WebRTCInternals::GetInstance()->aec_dump_file_path(),
2438 id);
2442 void RenderProcessHostImpl::UnregisterAecDumpConsumerOnUIThread(int id) {
2443 DCHECK_CURRENTLY_ON(BrowserThread::UI);
2444 for (std::vector<int>::iterator it = aec_dump_consumers_.begin();
2445 it != aec_dump_consumers_.end(); ++it) {
2446 if (*it == id) {
2447 aec_dump_consumers_.erase(it);
2448 break;
2453 #if defined(OS_WIN)
2454 #define IntToStringType base::IntToString16
2455 #else
2456 #define IntToStringType base::IntToString
2457 #endif
2459 void RenderProcessHostImpl::EnableAecDumpForId(const base::FilePath& file,
2460 int id) {
2461 DCHECK_CURRENTLY_ON(BrowserThread::UI);
2462 base::FilePath unique_file =
2463 file.AddExtension(IntToStringType(base::GetProcId(GetHandle())))
2464 .AddExtension(IntToStringType(id));
2465 BrowserThread::PostTaskAndReplyWithResult(
2466 BrowserThread::FILE, FROM_HERE,
2467 base::Bind(&CreateAecDumpFileForProcess, unique_file, GetHandle()),
2468 base::Bind(&RenderProcessHostImpl::SendAecDumpFileToRenderer,
2469 weak_factory_.GetWeakPtr(),
2470 id));
2473 #undef IntToStringType
2475 void RenderProcessHostImpl::SendAecDumpFileToRenderer(
2476 int id,
2477 IPC::PlatformFileForTransit file_for_transit) {
2478 if (file_for_transit == IPC::InvalidPlatformFileForTransit())
2479 return;
2480 Send(new AecDumpMsg_EnableAecDump(id, file_for_transit));
2483 void RenderProcessHostImpl::SendDisableAecDumpToRenderer() {
2484 Send(new AecDumpMsg_DisableAecDump());
2486 #endif
2488 void RenderProcessHostImpl::IncrementWorkerRefCount() {
2489 DCHECK_CURRENTLY_ON(BrowserThread::UI);
2490 ++worker_ref_count_;
2491 if (worker_ref_count_ > max_worker_count_)
2492 max_worker_count_ = worker_ref_count_;
2495 void RenderProcessHostImpl::DecrementWorkerRefCount() {
2496 DCHECK_CURRENTLY_ON(BrowserThread::UI);
2497 DCHECK_GT(worker_ref_count_, 0);
2498 --worker_ref_count_;
2499 if (worker_ref_count_ == 0)
2500 Cleanup();
2503 void RenderProcessHostImpl::GetAudioOutputControllers(
2504 const GetAudioOutputControllersCallback& callback) const {
2505 audio_renderer_host()->GetOutputControllers(callback);
2508 BluetoothDispatcherHost* RenderProcessHostImpl::GetBluetoothDispatcherHost() {
2509 return bluetooth_dispatcher_host_.get();
2512 } // namespace content