Add ICU message format support
[chromium-blink-merge.git] / content / browser / renderer_host / render_process_host_impl.cc
blobd290778c2ef396872a90bc8ac67359e78b6a3f7e
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_memory_buffer_manager.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/service_port_service_impl.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_messages.h"
121 #include "content/common/in_process_child_thread_params.h"
122 #include "content/common/mojo/channel_init.h"
123 #include "content/common/mojo/mojo_messages.h"
124 #include "content/common/resource_messages.h"
125 #include "content/common/site_isolation_policy.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/child_process_host.h"
141 #include "content/public/common/content_constants.h"
142 #include "content/public/common/content_switches.h"
143 #include "content/public/common/mojo_channel_switches.h"
144 #include "content/public/common/process_type.h"
145 #include "content/public/common/resource_type.h"
146 #include "content/public/common/result_codes.h"
147 #include "content/public/common/sandboxed_process_launcher_delegate.h"
148 #include "content/public/common/url_constants.h"
149 #include "device/battery/battery_monitor_impl.h"
150 #include "device/vibration/vibration_manager_impl.h"
151 #include "gpu/GLES2/gl2extchromium.h"
152 #include "gpu/command_buffer/client/gpu_switches.h"
153 #include "gpu/command_buffer/common/gles2_cmd_utils.h"
154 #include "gpu/command_buffer/service/gpu_switches.h"
155 #include "ipc/ipc_channel.h"
156 #include "ipc/ipc_logging.h"
157 #include "ipc/ipc_switches.h"
158 #include "ipc/mojo/ipc_channel_mojo.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(USE_OZONE)
194 #include "ui/ozone/public/ozone_switches.h"
195 #endif
197 #if defined(ENABLE_BROWSER_CDMS)
198 #include "content/browser/media/cdm/browser_cdm_manager.h"
199 #endif
201 #if defined(ENABLE_PLUGINS)
202 #include "content/browser/plugin_service_impl.h"
203 #endif
205 #if defined(ENABLE_WEBRTC)
206 #include "content/browser/media/webrtc_internals.h"
207 #include "content/browser/renderer_host/media/media_stream_track_metrics_host.h"
208 #include "content/browser/renderer_host/media/webrtc_identity_service_host.h"
209 #include "content/browser/renderer_host/p2p/socket_dispatcher_host.h"
210 #include "content/common/media/aec_dump_messages.h"
211 #include "content/common/media/media_stream_messages.h"
212 #endif
214 extern bool g_exited_main_message_loop;
216 namespace content {
217 namespace {
219 const char kSiteProcessMapKeyName[] = "content_site_process_map";
221 void CacheShaderInfo(int32 id, base::FilePath path) {
222 ShaderCacheFactory::GetInstance()->SetCacheInfo(id, path);
225 void RemoveShaderInfo(int32 id) {
226 ShaderCacheFactory::GetInstance()->RemoveCacheInfo(id);
229 net::URLRequestContext* GetRequestContext(
230 scoped_refptr<net::URLRequestContextGetter> request_context,
231 scoped_refptr<net::URLRequestContextGetter> media_request_context,
232 ResourceType resource_type) {
233 // If the request has resource type of RESOURCE_TYPE_MEDIA, we use a request
234 // context specific to media for handling it because these resources have
235 // specific needs for caching.
236 if (resource_type == RESOURCE_TYPE_MEDIA)
237 return media_request_context->GetURLRequestContext();
238 return request_context->GetURLRequestContext();
241 void GetContexts(
242 ResourceContext* resource_context,
243 scoped_refptr<net::URLRequestContextGetter> request_context,
244 scoped_refptr<net::URLRequestContextGetter> media_request_context,
245 const ResourceHostMsg_Request& request,
246 ResourceContext** resource_context_out,
247 net::URLRequestContext** request_context_out) {
248 *resource_context_out = resource_context;
249 *request_context_out =
250 GetRequestContext(request_context, media_request_context,
251 request.resource_type);
254 #if defined(ENABLE_WEBRTC)
256 // Allow us to only run the trial in the first renderer.
257 bool has_done_stun_trials = false;
259 // Creates a file used for diagnostic echo canceller recordings for handing
260 // over to the renderer.
261 IPC::PlatformFileForTransit CreateAecDumpFileForProcess(
262 base::FilePath file_path,
263 base::ProcessHandle process) {
264 DCHECK_CURRENTLY_ON(BrowserThread::FILE);
265 base::File dump_file(file_path,
266 base::File::FLAG_OPEN_ALWAYS | base::File::FLAG_APPEND);
267 if (!dump_file.IsValid()) {
268 VLOG(1) << "Could not open AEC dump file, error=" <<
269 dump_file.error_details();
270 return IPC::InvalidPlatformFileForTransit();
272 return IPC::TakeFileHandleForProcess(dump_file.Pass(), process);
275 // Does nothing. Just to avoid races between enable and disable.
276 void DisableAecDumpOnFileThread() {
277 DCHECK_CURRENTLY_ON(BrowserThread::FILE);
279 #endif
281 // the global list of all renderer processes
282 base::LazyInstance<IDMap<RenderProcessHost> >::Leaky
283 g_all_hosts = LAZY_INSTANCE_INITIALIZER;
285 // Map of site to process, to ensure we only have one RenderProcessHost per
286 // site in process-per-site mode. Each map is specific to a BrowserContext.
287 class SiteProcessMap : public base::SupportsUserData::Data {
288 public:
289 typedef base::hash_map<std::string, RenderProcessHost*> SiteToProcessMap;
290 SiteProcessMap() {}
292 void RegisterProcess(const std::string& site, RenderProcessHost* process) {
293 map_[site] = process;
296 RenderProcessHost* FindProcess(const std::string& site) {
297 SiteToProcessMap::iterator i = map_.find(site);
298 if (i != map_.end())
299 return i->second;
300 return NULL;
303 void RemoveProcess(RenderProcessHost* host) {
304 // Find all instances of this process in the map, then separately remove
305 // them.
306 std::set<std::string> sites;
307 for (SiteToProcessMap::const_iterator i = map_.begin();
308 i != map_.end();
309 i++) {
310 if (i->second == host)
311 sites.insert(i->first);
313 for (std::set<std::string>::iterator i = sites.begin();
314 i != sites.end();
315 i++) {
316 SiteToProcessMap::iterator iter = map_.find(*i);
317 if (iter != map_.end()) {
318 DCHECK_EQ(iter->second, host);
319 map_.erase(iter);
324 private:
325 SiteToProcessMap map_;
328 // Find the SiteProcessMap specific to the given context.
329 SiteProcessMap* GetSiteProcessMapForBrowserContext(BrowserContext* context) {
330 DCHECK(context);
331 SiteProcessMap* map = static_cast<SiteProcessMap*>(
332 context->GetUserData(kSiteProcessMapKeyName));
333 if (!map) {
334 map = new SiteProcessMap();
335 context->SetUserData(kSiteProcessMapKeyName, map);
337 return map;
340 // NOTE: changes to this class need to be reviewed by the security team.
341 class RendererSandboxedProcessLauncherDelegate
342 : public SandboxedProcessLauncherDelegate {
343 public:
344 explicit RendererSandboxedProcessLauncherDelegate(IPC::ChannelProxy* channel)
345 #if defined(OS_POSIX)
346 : ipc_fd_(channel->TakeClientFileDescriptor())
347 #endif // OS_POSIX
350 ~RendererSandboxedProcessLauncherDelegate() override {}
352 #if defined(OS_WIN)
353 void PreSpawnTarget(sandbox::TargetPolicy* policy, bool* success) override {
354 AddBaseHandleClosePolicy(policy);
356 const base::string16& sid =
357 GetContentClient()->browser()->GetAppContainerSidForSandboxType(
358 GetSandboxType());
359 if (!sid.empty())
360 AddAppContainerPolicy(policy, sid.c_str());
362 GetContentClient()->browser()->PreSpawnRenderer(policy, success);
365 #elif defined(OS_POSIX)
366 bool ShouldUseZygote() override {
367 const base::CommandLine& browser_command_line =
368 *base::CommandLine::ForCurrentProcess();
369 base::CommandLine::StringType renderer_prefix =
370 browser_command_line.GetSwitchValueNative(switches::kRendererCmdPrefix);
371 return renderer_prefix.empty();
373 base::ScopedFD TakeIpcFd() override { return ipc_fd_.Pass(); }
374 #endif // OS_WIN
376 SandboxType GetSandboxType() override {
377 return SANDBOX_TYPE_RENDERER;
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_for_guests_only)
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_for_guests_only_(is_for_guests_only),
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";
717 return IPC::ChannelProxy::Create(
718 IPC::ChannelMojo::CreateServerFactory(
719 mojo_task_runner, channel_id,
720 content::ChildProcessHost::GetAttachmentBroker()),
721 this, runner.get());
724 return IPC::ChannelProxy::Create(
725 channel_id, IPC::Channel::MODE_SERVER, this, runner.get(),
726 content::ChildProcessHost::GetAttachmentBroker());
729 void RenderProcessHostImpl::CreateMessageFilters() {
730 DCHECK_CURRENTLY_ON(BrowserThread::UI);
731 const base::CommandLine& browser_command_line =
732 *base::CommandLine::ForCurrentProcess();
733 AddFilter(new ResourceSchedulerFilter(GetID()));
734 MediaInternals* media_internals = MediaInternals::GetInstance();
735 media::AudioManager* audio_manager =
736 BrowserMainLoop::GetInstance()->audio_manager();
737 // Add BrowserPluginMessageFilter to ensure it gets the first stab at messages
738 // from guests.
739 scoped_refptr<BrowserPluginMessageFilter> bp_message_filter(
740 new BrowserPluginMessageFilter(GetID()));
741 AddFilter(bp_message_filter.get());
743 scoped_refptr<RenderMessageFilter> render_message_filter(
744 new RenderMessageFilter(
745 GetID(),
746 #if defined(ENABLE_PLUGINS)
747 PluginServiceImpl::GetInstance(),
748 #else
749 NULL,
750 #endif
751 GetBrowserContext(),
752 GetBrowserContext()->GetRequestContextForRenderProcess(GetID()),
753 widget_helper_.get(),
754 audio_manager,
755 media_internals,
756 storage_partition_impl_->GetDOMStorageContext()));
757 AddFilter(render_message_filter.get());
758 AddFilter(
759 new RenderFrameMessageFilter(GetID(), widget_helper_.get()));
760 BrowserContext* browser_context = GetBrowserContext();
761 ResourceContext* resource_context = browser_context->GetResourceContext();
763 scoped_refptr<net::URLRequestContextGetter> request_context(
764 browser_context->GetRequestContextForRenderProcess(GetID()));
765 scoped_refptr<net::URLRequestContextGetter> media_request_context(
766 browser_context->GetMediaRequestContextForRenderProcess(GetID()));
768 ResourceMessageFilter::GetContextsCallback get_contexts_callback(
769 base::Bind(&GetContexts, browser_context->GetResourceContext(),
770 request_context, media_request_context));
772 ResourceMessageFilter* resource_message_filter = new ResourceMessageFilter(
773 GetID(), PROCESS_TYPE_RENDERER,
774 storage_partition_impl_->GetAppCacheService(),
775 ChromeBlobStorageContext::GetFor(browser_context),
776 storage_partition_impl_->GetFileSystemContext(),
777 storage_partition_impl_->GetServiceWorkerContext(),
778 storage_partition_impl_->GetHostZoomLevelContext(),
779 get_contexts_callback);
781 AddFilter(resource_message_filter);
782 MediaStreamManager* media_stream_manager =
783 BrowserMainLoop::GetInstance()->media_stream_manager();
784 AddFilter(new AudioInputRendererHost(
785 GetID(),
786 audio_manager,
787 media_stream_manager,
788 AudioMirroringManager::GetInstance(),
789 BrowserMainLoop::GetInstance()->user_input_monitor()));
790 // The AudioRendererHost needs to be available for lookup, so it's
791 // stashed in a member variable.
792 audio_renderer_host_ = new AudioRendererHost(
793 GetID(),
794 audio_manager,
795 AudioMirroringManager::GetInstance(),
796 media_internals,
797 media_stream_manager,
798 browser_context->GetResourceContext()->GetMediaDeviceIDSalt());
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(),
820 storage_partition_impl_->GetWebRTCIdentityStore(),
821 resource_context));
822 peer_connection_tracker_host_ = new PeerConnectionTrackerHost(GetID());
823 AddFilter(peer_connection_tracker_host_.get());
824 AddFilter(new MediaStreamDispatcherHost(
825 GetID(),
826 browser_context->GetResourceContext()->GetMediaDeviceIDSalt(),
827 media_stream_manager));
828 AddFilter(new MediaStreamTrackMetricsHost());
829 #endif
830 #if defined(ENABLE_PLUGINS)
831 AddFilter(new PepperRendererConnection(GetID()));
832 #endif
833 AddFilter(new SpeechRecognitionDispatcherHost(
834 GetID(), storage_partition_impl_->GetURLRequestContext()));
835 AddFilter(new FileAPIMessageFilter(
836 GetID(),
837 storage_partition_impl_->GetURLRequestContext(),
838 storage_partition_impl_->GetFileSystemContext(),
839 ChromeBlobStorageContext::GetFor(browser_context),
840 StreamContext::GetFor(browser_context)));
841 AddFilter(new FileUtilitiesMessageFilter(GetID()));
842 AddFilter(new MimeRegistryMessageFilter());
843 AddFilter(new DatabaseMessageFilter(
844 storage_partition_impl_->GetDatabaseTracker()));
845 #if defined(OS_MACOSX)
846 AddFilter(new TextInputClientMessageFilter(GetID()));
847 #elif defined(OS_WIN)
848 // The FontCacheDispatcher is required only when we're using GDI rendering.
849 // TODO(scottmg): pdf/ppapi still require the renderer to be able to precache
850 // GDI fonts (http://crbug.com/383227), even when using DirectWrite. This
851 // should eventually be if (!ShouldUseDirectWrite()) guarded.
852 channel_->AddFilter(new FontCacheDispatcher());
853 #elif defined(OS_ANDROID)
854 browser_demuxer_android_ = new BrowserDemuxerAndroid();
855 AddFilter(browser_demuxer_android_.get());
856 #endif
857 #if defined(ENABLE_BROWSER_CDMS)
858 AddFilter(new BrowserCdmManager(GetID(), NULL));
859 #endif
861 WebSocketDispatcherHost::GetRequestContextCallback
862 websocket_request_context_callback(
863 base::Bind(&GetRequestContext, request_context,
864 media_request_context, RESOURCE_TYPE_SUB_RESOURCE));
866 AddFilter(
867 new WebSocketDispatcherHost(GetID(), websocket_request_context_callback));
869 message_port_message_filter_ = new MessagePortMessageFilter(
870 base::Bind(&RenderWidgetHelper::GetNextRoutingID,
871 base::Unretained(widget_helper_.get())));
872 AddFilter(message_port_message_filter_.get());
874 scoped_refptr<CacheStorageDispatcherHost> cache_storage_filter =
875 new CacheStorageDispatcherHost();
876 cache_storage_filter->Init(storage_partition_impl_->GetCacheStorageContext());
877 AddFilter(cache_storage_filter.get());
879 scoped_refptr<ServiceWorkerDispatcherHost> service_worker_filter =
880 new ServiceWorkerDispatcherHost(
881 GetID(), message_port_message_filter_.get(), resource_context);
882 service_worker_filter->Init(
883 storage_partition_impl_->GetServiceWorkerContext());
884 AddFilter(service_worker_filter.get());
886 AddFilter(new SharedWorkerMessageFilter(
887 GetID(),
888 resource_context,
889 WorkerStoragePartition(
890 storage_partition_impl_->GetURLRequestContext(),
891 storage_partition_impl_->GetMediaURLRequestContext(),
892 storage_partition_impl_->GetAppCacheService(),
893 storage_partition_impl_->GetQuotaManager(),
894 storage_partition_impl_->GetFileSystemContext(),
895 storage_partition_impl_->GetDatabaseTracker(),
896 storage_partition_impl_->GetIndexedDBContext(),
897 storage_partition_impl_->GetServiceWorkerContext()),
898 message_port_message_filter_.get()));
900 #if defined(ENABLE_WEBRTC)
901 p2p_socket_dispatcher_host_ = new P2PSocketDispatcherHost(
902 resource_context,
903 browser_context->GetRequestContextForRenderProcess(GetID()));
904 AddFilter(p2p_socket_dispatcher_host_.get());
905 #endif
907 AddFilter(new TraceMessageFilter(GetID()));
908 AddFilter(new ResolveProxyMsgHelper(
909 browser_context->GetRequestContextForRenderProcess(GetID())));
910 AddFilter(new QuotaDispatcherHost(
911 GetID(),
912 storage_partition_impl_->GetQuotaManager(),
913 GetContentClient()->browser()->CreateQuotaPermissionContext()));
915 notification_message_filter_ = new NotificationMessageFilter(
916 GetID(),
917 storage_partition_impl_->GetPlatformNotificationContext(),
918 resource_context,
919 browser_context);
920 AddFilter(notification_message_filter_.get());
922 AddFilter(new GamepadBrowserMessageFilter());
923 AddFilter(new DeviceLightMessageFilter());
924 AddFilter(new DeviceMotionMessageFilter());
925 AddFilter(new DeviceOrientationMessageFilter());
926 AddFilter(new ProfilerMessageFilter(PROCESS_TYPE_RENDERER));
927 AddFilter(new HistogramMessageFilter());
928 #if defined(USE_TCMALLOC) && (defined(OS_LINUX) || defined(OS_ANDROID))
929 if (browser_command_line.HasSwitch(switches::kEnableMemoryBenchmarking))
930 AddFilter(new MemoryBenchmarkMessageFilter());
931 #endif
932 AddFilter(new PushMessagingMessageFilter(
933 GetID(), storage_partition_impl_->GetServiceWorkerContext()));
934 #if defined(OS_ANDROID)
935 AddFilter(new ScreenOrientationMessageFilterAndroid());
936 #endif
937 AddFilter(new GeofencingDispatcherHost(
938 storage_partition_impl_->GetGeofencingManager()));
939 if (browser_command_line.HasSwitch(switches::kEnableWebBluetooth)) {
940 bluetooth_dispatcher_host_ = new BluetoothDispatcherHost(GetID());
941 AddFilter(bluetooth_dispatcher_host_.get());
945 void RenderProcessHostImpl::RegisterMojoServices() {
946 mojo_application_host_->service_registry()->AddService(
947 base::Bind(&device::BatteryMonitorImpl::Create));
949 mojo_application_host_->service_registry()->AddService(
950 base::Bind(&device::VibrationManagerImpl::Create));
952 mojo_application_host_->service_registry()->AddService(
953 base::Bind(&PermissionServiceContext::CreateService,
954 base::Unretained(permission_service_context_.get())));
956 mojo_application_host_->service_registry()->AddService(base::Bind(
957 &content::BackgroundSyncServiceImpl::Create,
958 base::Unretained(storage_partition_impl_->GetBackgroundSyncContext())));
960 mojo_application_host_->service_registry()->AddService(base::Bind(
961 &content::ServicePortServiceImpl::Create,
962 make_scoped_refptr(storage_partition_impl_->GetNavigatorConnectContext()),
963 message_port_message_filter_));
965 #if defined(OS_ANDROID)
966 ServiceRegistrarAndroid::RegisterProcessHostServices(
967 mojo_application_host_->service_registry_android());
968 #endif
970 GetContentClient()->browser()->RegisterRenderProcessMojoServices(
971 mojo_application_host_->service_registry());
974 int RenderProcessHostImpl::GetNextRoutingID() {
975 return widget_helper_->GetNextRoutingID();
978 void RenderProcessHostImpl::ResumeDeferredNavigation(
979 const GlobalRequestID& request_id) {
980 widget_helper_->ResumeDeferredNavigation(request_id);
983 void RenderProcessHostImpl::NotifyTimezoneChange(const std::string& zone_id) {
984 Send(new ViewMsg_TimezoneChange(zone_id));
987 ServiceRegistry* RenderProcessHostImpl::GetServiceRegistry() {
988 DCHECK(mojo_application_host_);
989 return mojo_application_host_->service_registry();
992 const base::TimeTicks& RenderProcessHostImpl::GetInitTimeForNavigationMetrics()
993 const {
994 return init_time_;
997 bool RenderProcessHostImpl::SubscribeUniformEnabled() const {
998 return subscribe_uniform_enabled_;
1001 void RenderProcessHostImpl::OnAddSubscription(unsigned int target) {
1002 DCHECK(subscribe_uniform_enabled_);
1003 subscription_set_.insert(target);
1004 const gpu::ValueState* state = pending_valuebuffer_state_->GetState(target);
1005 if (state) {
1006 SendUpdateValueState(target, *state);
1010 void RenderProcessHostImpl::OnRemoveSubscription(unsigned int target) {
1011 DCHECK(subscribe_uniform_enabled_);
1012 subscription_set_.erase(target);
1015 void RenderProcessHostImpl::SendUpdateValueState(unsigned int target,
1016 const gpu::ValueState& state) {
1017 DCHECK(subscribe_uniform_enabled_);
1018 if (subscription_set_.find(target) != subscription_set_.end()) {
1019 GpuProcessHost::SendOnIO(
1020 GpuProcessHost::GPU_PROCESS_KIND_SANDBOXED,
1021 CAUSE_FOR_GPU_LAUNCH_NO_LAUNCH,
1022 new GpuMsg_UpdateValueState(id_, target, state));
1023 } else {
1024 // Store the ValueState locally in case a Valuebuffer subscribes to it later
1025 pending_valuebuffer_state_->UpdateState(target, state);
1029 #if defined(ENABLE_BROWSER_CDMS)
1030 media::BrowserCdm* RenderProcessHostImpl::GetBrowserCdm(int render_frame_id,
1031 int cdm_id) const {
1032 DCHECK_CURRENTLY_ON(BrowserThread::UI);
1033 BrowserCdmManager* manager = BrowserCdmManager::FromProcess(GetID());
1034 if (!manager)
1035 return nullptr;
1036 return manager->GetCdm(render_frame_id, cdm_id);
1038 #endif
1040 void RenderProcessHostImpl::AddRoute(
1041 int32 routing_id,
1042 IPC::Listener* listener) {
1043 CHECK(!listeners_.Lookup(routing_id))
1044 << "Found Routing ID Conflict: " << routing_id;
1045 listeners_.AddWithID(listener, routing_id);
1048 void RenderProcessHostImpl::RemoveRoute(int32 routing_id) {
1049 DCHECK(listeners_.Lookup(routing_id) != NULL);
1050 listeners_.Remove(routing_id);
1052 // Keep the one renderer thread around forever in single process mode.
1053 if (!run_renderer_in_process())
1054 Cleanup();
1057 void RenderProcessHostImpl::AddObserver(RenderProcessHostObserver* observer) {
1058 observers_.AddObserver(observer);
1061 void RenderProcessHostImpl::RemoveObserver(
1062 RenderProcessHostObserver* observer) {
1063 observers_.RemoveObserver(observer);
1066 void RenderProcessHostImpl::ShutdownForBadMessage() {
1067 base::CommandLine* command_line = base::CommandLine::ForCurrentProcess();
1068 if (command_line->HasSwitch(switches::kDisableKillAfterBadIPC))
1069 return;
1071 if (run_renderer_in_process()) {
1072 // In single process mode it is better if we don't suicide but just
1073 // crash.
1074 CHECK(false);
1076 // We kill the renderer but don't include a NOTREACHED, because we want the
1077 // browser to try to survive when it gets illegal messages from the renderer.
1078 Shutdown(RESULT_CODE_KILLED_BAD_MESSAGE, false);
1081 void RenderProcessHostImpl::WidgetRestored() {
1082 // Verify we were properly backgrounded.
1083 DCHECK_EQ(backgrounded_, (visible_widgets_ == 0));
1084 visible_widgets_++;
1085 SetBackgrounded(false);
1088 void RenderProcessHostImpl::WidgetHidden() {
1089 // On startup, the browser will call Hide
1090 if (backgrounded_)
1091 return;
1093 DCHECK_EQ(backgrounded_, (visible_widgets_ == 0));
1094 visible_widgets_--;
1095 DCHECK_GE(visible_widgets_, 0);
1096 if (visible_widgets_ == 0) {
1097 DCHECK(!backgrounded_);
1098 SetBackgrounded(true);
1102 int RenderProcessHostImpl::VisibleWidgetCount() const {
1103 return visible_widgets_;
1106 bool RenderProcessHostImpl::IsForGuestsOnly() const {
1107 return is_for_guests_only_;
1110 StoragePartition* RenderProcessHostImpl::GetStoragePartition() const {
1111 return storage_partition_impl_;
1114 static void AppendCompositorCommandLineFlags(base::CommandLine* command_line) {
1115 if (IsPropertyTreeVerificationEnabled())
1116 command_line->AppendSwitch(cc::switches::kEnablePropertyTreeVerification);
1118 if (IsDelegatedRendererEnabled())
1119 command_line->AppendSwitch(switches::kEnableDelegatedRenderer);
1121 command_line->AppendSwitchASCII(
1122 switches::kNumRasterThreads,
1123 base::IntToString(NumberOfRendererRasterThreads()));
1125 if (IsGpuRasterizationEnabled())
1126 command_line->AppendSwitch(switches::kEnableGpuRasterization);
1128 int msaa_sample_count = GpuRasterizationMSAASampleCount();
1129 if (msaa_sample_count > 0) {
1130 command_line->AppendSwitchASCII(
1131 switches::kGpuRasterizationMSAASampleCount,
1132 base::IntToString(msaa_sample_count));
1135 DCHECK_IMPLIES(IsZeroCopyUploadEnabled(), !IsOneCopyUploadEnabled());
1136 DCHECK_IMPLIES(IsOneCopyUploadEnabled(), !IsZeroCopyUploadEnabled());
1137 if (IsZeroCopyUploadEnabled())
1138 command_line->AppendSwitch(switches::kEnableZeroCopy);
1139 if (!IsOneCopyUploadEnabled())
1140 command_line->AppendSwitch(switches::kDisableOneCopy);
1142 if (IsForceGpuRasterizationEnabled())
1143 command_line->AppendSwitch(switches::kForceGpuRasterization);
1145 command_line->AppendSwitchASCII(
1146 switches::kContentImageTextureTarget,
1147 base::UintToString(
1148 // TODO(reveman): We currently assume that the compositor will use
1149 // BGRA_8888 if it's able to, and RGBA_8888 otherwise. Since we don't
1150 // know what it will use we hardcode BGRA_8888 here for now. We should
1151 // instead move decisions about GpuMemoryBuffer format to the browser
1152 // embedder so we know it here, and pass that decision to the
1153 // compositor for each usage.
1154 // crbug.com/490362
1155 BrowserGpuMemoryBufferManager::GetImageTextureTarget(
1156 gfx::BufferFormat::BGRA_8888,
1157 // TODO(danakj): When one-copy supports partial update, change
1158 // this usage to PERSISTENT_MAP for one-copy.
1159 gfx::BufferUsage::MAP)));
1161 command_line->AppendSwitchASCII(
1162 switches::kVideoImageTextureTarget,
1163 base::UintToString(BrowserGpuMemoryBufferManager::GetImageTextureTarget(
1164 gfx::BufferFormat::R_8, gfx::BufferUsage::MAP)));
1166 // Appending disable-gpu-feature switches due to software rendering list.
1167 GpuDataManagerImpl* gpu_data_manager = GpuDataManagerImpl::GetInstance();
1168 DCHECK(gpu_data_manager);
1169 gpu_data_manager->AppendRendererCommandLine(command_line);
1172 void RenderProcessHostImpl::AppendRendererCommandLine(
1173 base::CommandLine* command_line) const {
1174 // Pass the process type first, so it shows first in process listings.
1175 command_line->AppendSwitchASCII(switches::kProcessType,
1176 switches::kRendererProcess);
1178 // Now send any options from our own command line we want to propagate.
1179 const base::CommandLine& browser_command_line =
1180 *base::CommandLine::ForCurrentProcess();
1181 PropagateBrowserCommandLineToRenderer(browser_command_line, command_line);
1183 // Pass on the browser locale.
1184 const std::string locale =
1185 GetContentClient()->browser()->GetApplicationLocale();
1186 command_line->AppendSwitchASCII(switches::kLang, locale);
1188 // If we run base::FieldTrials, we want to pass to their state to the
1189 // renderer so that it can act in accordance with each state, or record
1190 // histograms relating to the base::FieldTrial states.
1191 std::string field_trial_states;
1192 base::FieldTrialList::AllStatesToString(&field_trial_states);
1193 if (!field_trial_states.empty()) {
1194 command_line->AppendSwitchASCII(switches::kForceFieldTrials,
1195 field_trial_states);
1198 GetContentClient()->browser()->AppendExtraCommandLineSwitches(
1199 command_line, GetID());
1201 if (IsPinchToZoomEnabled())
1202 command_line->AppendSwitch(switches::kEnablePinch);
1204 #if defined(OS_WIN)
1205 command_line->AppendSwitchASCII(switches::kDeviceScaleFactor,
1206 base::DoubleToString(gfx::GetDPIScale()));
1207 #endif
1209 AppendCompositorCommandLineFlags(command_line);
1212 void RenderProcessHostImpl::PropagateBrowserCommandLineToRenderer(
1213 const base::CommandLine& browser_cmd,
1214 base::CommandLine* renderer_cmd) const {
1215 // Propagate the following switches to the renderer command line (along
1216 // with any associated values) if present in the browser command line.
1217 static const char* const kSwitchNames[] = {
1218 switches::kAllowLoopbackInPeerConnection,
1219 switches::kAudioBufferSize,
1220 switches::kBlinkPlatformLogChannels,
1221 switches::kBlinkSettings,
1222 switches::kDefaultTileWidth,
1223 switches::kDefaultTileHeight,
1224 switches::kDisable3DAPIs,
1225 switches::kDisableAcceleratedJpegDecoding,
1226 switches::kDisableAcceleratedVideoDecode,
1227 switches::kDisableBlinkFeatures,
1228 switches::kDisableBreakpad,
1229 switches::kDisablePreferCompositingToLCDText,
1230 switches::kDisableDatabases,
1231 switches::kDisableDelayAgnosticAec,
1232 switches::kDisableDirectNPAPIRequests,
1233 switches::kDisableDisplayList2dCanvas,
1234 switches::kDisableDistanceFieldText,
1235 switches::kDisableEncryptedMedia,
1236 switches::kDisableFileSystem,
1237 switches::kDisableGpuCompositing,
1238 switches::kDisableGpuVsync,
1239 switches::kDisableLowResTiling,
1240 switches::kDisableHistogramCustomizer,
1241 switches::kDisableIconNtp,
1242 switches::kDisableLCDText,
1243 switches::kDisableLocalStorage,
1244 switches::kDisableLogging,
1245 switches::kDisableMediaSource,
1246 switches::kDisableMojoChannel,
1247 switches::kDisableNewVideoRenderer,
1248 switches::kDisableNotifications,
1249 switches::kDisableOverlayScrollbar,
1250 switches::kDisablePermissionsAPI,
1251 switches::kDisablePinch,
1252 switches::kDisablePrefixedEncryptedMedia,
1253 switches::kDisableSeccompFilterSandbox,
1254 switches::kDisableSharedWorkers,
1255 switches::kDisableSlimmingPaint,
1256 switches::kDisableSpeechAPI,
1257 switches::kDisableSVG1DOM,
1258 switches::kDisableThreadedCompositing,
1259 switches::kDisableThreadedScrolling,
1260 switches::kDisableTouchAdjustment,
1261 switches::kDisableTouchDragDrop,
1262 switches::kDisableTouchEditing,
1263 switches::kDisableV8IdleTasks,
1264 switches::kDomAutomationController,
1265 switches::kEnableBleedingEdgeRenderingFastPaths,
1266 switches::kEnableBlinkFeatures,
1267 switches::kEnableBrowserSideNavigation,
1268 switches::kEnableCompositorAnimationTimelines,
1269 switches::kEnableCredentialManagerAPI,
1270 switches::kEnableDelayAgnosticAec,
1271 switches::kEnableDisplayList2dCanvas,
1272 switches::kEnableDistanceFieldText,
1273 switches::kEnableExperimentalCanvasFeatures,
1274 switches::kEnableExperimentalWebPlatformFeatures,
1275 switches::kEnableGPUClientLogging,
1276 switches::kEnableGpuClientTracing,
1277 switches::kEnableGPUServiceLogging,
1278 switches::kEnableIconNtp,
1279 switches::kEnableLinkDisambiguationPopup,
1280 switches::kEnableLowResTiling,
1281 switches::kEnableInbandTextTracks,
1282 switches::kEnableLCDText,
1283 switches::kEnableLogging,
1284 switches::kEnableMemoryBenchmarking,
1285 switches::kEnableNetworkInformation,
1286 switches::kEnableOverlayFullscreenVideo,
1287 switches::kEnableOverlayScrollbar,
1288 switches::kEnablePinch,
1289 switches::kEnablePluginPlaceholderTesting,
1290 switches::kEnablePreciseMemoryInfo,
1291 switches::kEnablePreferCompositingToLCDText,
1292 switches::kEnablePushMessagePayload,
1293 switches::kEnableRendererMojoChannel,
1294 switches::kEnableRTCSmoothnessAlgorithm,
1295 switches::kEnableSeccompFilterSandbox,
1296 switches::kEnableSkiaBenchmarking,
1297 switches::kEnableSlimmingPaint,
1298 switches::kEnableSmoothScrolling,
1299 switches::kEnableStaleWhileRevalidate,
1300 switches::kEnableStatsTable,
1301 switches::kEnableThreadedCompositing,
1302 switches::kEnableTouchDragDrop,
1303 switches::kEnableTouchEditing,
1304 switches::kEnableUnsafeES3APIs,
1305 switches::kEnableViewport,
1306 switches::kEnableViewportMeta,
1307 switches::kInvertViewportScrollOrder,
1308 switches::kEnableVtune,
1309 switches::kEnableWebBluetooth,
1310 switches::kEnableWebGLDraftExtensions,
1311 switches::kEnableWebGLImageChromium,
1312 switches::kEnableWebVR,
1313 switches::kExplicitlyAllowedPorts,
1314 switches::kForceDeviceScaleFactor,
1315 switches::kForceDisplayList2dCanvas,
1316 switches::kFullMemoryCrashReport,
1317 switches::kIPCConnectionTimeout,
1318 switches::kJavaScriptFlags,
1319 switches::kLoggingLevel,
1320 switches::kMainFrameResizesAreOrientationChanges,
1321 switches::kMaxUntiledLayerWidth,
1322 switches::kMaxUntiledLayerHeight,
1323 switches::kMemoryMetrics,
1324 switches::kNoReferrers,
1325 switches::kNoSandbox,
1326 switches::kOverridePluginPowerSaverForTesting,
1327 switches::kPpapiInProcess,
1328 switches::kProfilerTiming,
1329 switches::kReducedReferrerGranularity,
1330 switches::kReduceSecurityForTesting,
1331 switches::kRegisterPepperPlugins,
1332 switches::kRendererStartupDialog,
1333 switches::kRootLayerScrolls,
1334 switches::kShowPaintRects,
1335 switches::kSitePerProcess,
1336 switches::kStatsCollectionController,
1337 switches::kTestType,
1338 switches::kTouchEvents,
1339 switches::kTouchTextSelectionStrategy,
1340 switches::kTraceToConsole,
1341 // This flag needs to be propagated to the renderer process for
1342 // --in-process-webgl.
1343 switches::kUseGL,
1344 switches::kUseMobileUserAgent,
1345 switches::kUseNormalPriorityForTileTaskWorkerThreads,
1346 switches::kV,
1347 switches::kVideoThreads,
1348 switches::kVideoUnderflowThresholdMs,
1349 switches::kVModule,
1350 // Please keep these in alphabetical order. Compositor switches here should
1351 // also be added to chrome/browser/chromeos/login/chrome_restart_request.cc.
1352 cc::switches::kCompositeToMailbox,
1353 cc::switches::kDisableCompositedAntialiasing,
1354 cc::switches::kDisableMainFrameBeforeActivation,
1355 cc::switches::kDisableThreadedAnimation,
1356 cc::switches::kEnableBeginFrameScheduling,
1357 cc::switches::kEnableGpuBenchmarking,
1358 cc::switches::kEnableMainFrameBeforeActivation,
1359 cc::switches::kMaxUnusedResourceMemoryUsagePercentage,
1360 cc::switches::kShowCompositedLayerBorders,
1361 cc::switches::kShowFPSCounter,
1362 cc::switches::kShowLayerAnimationBounds,
1363 cc::switches::kShowPropertyChangedRects,
1364 cc::switches::kShowReplicaScreenSpaceRects,
1365 cc::switches::kShowScreenSpaceRects,
1366 cc::switches::kShowSurfaceDamageRects,
1367 cc::switches::kSlowDownRasterScaleFactor,
1368 cc::switches::kStrictLayerPropertyChangeChecking,
1369 cc::switches::kTopControlsHideThreshold,
1370 cc::switches::kTopControlsShowThreshold,
1372 scheduler::switches::kDisableBlinkScheduler,
1374 #if defined(ENABLE_PLUGINS)
1375 switches::kEnablePepperTesting,
1376 #endif
1377 #if defined(ENABLE_WEBRTC)
1378 switches::kDisableWebRtcHWDecoding,
1379 switches::kDisableWebRtcHWEncoding,
1380 switches::kEnableWebRtcDtls12,
1381 switches::kEnableWebRtcHWH264Encoding,
1382 switches::kEnableWebRtcStunOrigin,
1383 switches::kWebRtcMaxCaptureFramerate,
1384 #endif
1385 switches::kEnableLowEndDeviceMode,
1386 switches::kDisableLowEndDeviceMode,
1387 #if defined(OS_ANDROID)
1388 switches::kDisableGestureRequirementForMediaPlayback,
1389 switches::kDisableWebRTC,
1390 switches::kDisableWebAudio,
1391 switches::kRendererWaitForJavaDebugger,
1392 #endif
1393 #if defined(OS_MACOSX)
1394 // Allow this to be set when invoking the browser and relayed along.
1395 switches::kEnableSandboxLogging,
1396 #endif
1397 #if defined(OS_WIN)
1398 switches::kDisableDirectWrite,
1399 switches::kDisableWin32kRendererLockDown,
1400 switches::kTraceExportEventsToETW,
1401 #endif
1402 #if defined(USE_OZONE)
1403 switches::kOzonePlatform,
1404 #endif
1405 #if defined(OS_CHROMEOS)
1406 switches::kDisableVaapiAcceleratedVideoEncode,
1407 #endif
1409 renderer_cmd->CopySwitchesFrom(browser_cmd, kSwitchNames,
1410 arraysize(kSwitchNames));
1412 if (browser_cmd.HasSwitch(switches::kTraceStartup) &&
1413 BrowserMainLoop::GetInstance()->is_tracing_startup()) {
1414 // Pass kTraceStartup switch to renderer only if startup tracing has not
1415 // finished.
1416 renderer_cmd->AppendSwitchASCII(
1417 switches::kTraceStartup,
1418 browser_cmd.GetSwitchValueASCII(switches::kTraceStartup));
1421 #if defined(ENABLE_WEBRTC)
1422 // Only run the Stun trials in the first renderer.
1423 if (!has_done_stun_trials &&
1424 browser_cmd.HasSwitch(switches::kWebRtcStunProbeTrialParameter)) {
1425 has_done_stun_trials = true;
1426 renderer_cmd->AppendSwitchASCII(
1427 switches::kWebRtcStunProbeTrialParameter,
1428 browser_cmd.GetSwitchValueASCII(
1429 switches::kWebRtcStunProbeTrialParameter));
1431 #endif
1433 // Disable databases in incognito mode.
1434 if (GetBrowserContext()->IsOffTheRecord() &&
1435 !browser_cmd.HasSwitch(switches::kDisableDatabases)) {
1436 renderer_cmd->AppendSwitch(switches::kDisableDatabases);
1439 // Add kWaitForDebugger to let renderer process wait for a debugger.
1440 if (browser_cmd.HasSwitch(switches::kWaitForDebuggerChildren)) {
1441 // Look to pass-on the kWaitForDebugger flag.
1442 std::string value =
1443 browser_cmd.GetSwitchValueASCII(switches::kWaitForDebuggerChildren);
1444 if (value.empty() || value == switches::kRendererProcess) {
1445 renderer_cmd->AppendSwitch(switches::kWaitForDebugger);
1450 base::ProcessHandle RenderProcessHostImpl::GetHandle() const {
1451 if (run_renderer_in_process())
1452 return base::GetCurrentProcessHandle();
1454 if (!child_process_launcher_.get() || child_process_launcher_->IsStarting())
1455 return base::kNullProcessHandle;
1457 return child_process_launcher_->GetProcess().Handle();
1460 bool RenderProcessHostImpl::Shutdown(int exit_code, bool wait) {
1461 if (run_renderer_in_process())
1462 return false; // Single process mode never shuts down the renderer.
1464 #if defined(OS_ANDROID)
1465 // Android requires a different approach for killing.
1466 StopChildProcess(GetHandle());
1467 return true;
1468 #else
1469 if (!child_process_launcher_.get() || child_process_launcher_->IsStarting())
1470 return false;
1472 return child_process_launcher_->GetProcess().Terminate(exit_code, wait);
1473 #endif
1476 bool RenderProcessHostImpl::FastShutdownIfPossible() {
1477 if (run_renderer_in_process())
1478 return false; // Single process mode never shuts down the renderer.
1480 if (!GetContentClient()->browser()->IsFastShutdownPossible())
1481 return false;
1483 if (!child_process_launcher_.get() ||
1484 child_process_launcher_->IsStarting() ||
1485 !GetHandle())
1486 return false; // Render process hasn't started or is probably crashed.
1488 // Test if there's an unload listener.
1489 // NOTE: It's possible that an onunload listener may be installed
1490 // while we're shutting down, so there's a small race here. Given that
1491 // the window is small, it's unlikely that the web page has much
1492 // state that will be lost by not calling its unload handlers properly.
1493 if (!SuddenTerminationAllowed())
1494 return false;
1496 if (worker_ref_count_ != 0) {
1497 if (survive_for_worker_start_time_.is_null())
1498 survive_for_worker_start_time_ = base::TimeTicks::Now();
1499 return false;
1502 // Set this before ProcessDied() so observers can tell if the render process
1503 // died due to fast shutdown versus another cause.
1504 fast_shutdown_started_ = true;
1506 ProcessDied(false /* already_dead */, nullptr);
1507 return true;
1510 bool RenderProcessHostImpl::Send(IPC::Message* msg) {
1511 TRACE_EVENT0("renderer_host", "RenderProcessHostImpl::Send");
1512 if (!channel_) {
1513 if (!is_initialized_) {
1514 queued_messages_.push(msg);
1515 return true;
1516 } else {
1517 delete msg;
1518 return false;
1522 if (child_process_launcher_.get() && child_process_launcher_->IsStarting()) {
1523 queued_messages_.push(msg);
1524 return true;
1527 return channel_->Send(msg);
1530 bool RenderProcessHostImpl::OnMessageReceived(const IPC::Message& msg) {
1531 // If we're about to be deleted, or have initiated the fast shutdown sequence,
1532 // we ignore incoming messages.
1534 if (deleting_soon_ || fast_shutdown_started_)
1535 return false;
1537 mark_child_process_activity_time();
1538 if (msg.routing_id() == MSG_ROUTING_CONTROL) {
1539 // Dispatch control messages.
1540 IPC_BEGIN_MESSAGE_MAP(RenderProcessHostImpl, msg)
1541 IPC_MESSAGE_HANDLER(ChildProcessHostMsg_ShutdownRequest,
1542 OnShutdownRequest)
1543 IPC_MESSAGE_HANDLER(ViewHostMsg_SuddenTerminationChanged,
1544 SuddenTerminationChanged)
1545 IPC_MESSAGE_HANDLER(ViewHostMsg_UserMetricsRecordAction,
1546 OnUserMetricsRecordAction)
1547 IPC_MESSAGE_HANDLER(ViewHostMsg_SavedPageAsMHTML, OnSavedPageAsMHTML)
1548 IPC_MESSAGE_HANDLER(ViewHostMsg_Close_ACK, OnCloseACK)
1549 #if defined(ENABLE_WEBRTC)
1550 IPC_MESSAGE_HANDLER(AecDumpMsg_RegisterAecDumpConsumer,
1551 OnRegisterAecDumpConsumer)
1552 IPC_MESSAGE_HANDLER(AecDumpMsg_UnregisterAecDumpConsumer,
1553 OnUnregisterAecDumpConsumer)
1554 #endif
1555 // Adding single handlers for your service here is fine, but once your
1556 // service needs more than one handler, please extract them into a new
1557 // message filter and add that filter to CreateMessageFilters().
1558 IPC_END_MESSAGE_MAP()
1560 return true;
1563 // Dispatch incoming messages to the appropriate IPC::Listener.
1564 IPC::Listener* listener = listeners_.Lookup(msg.routing_id());
1565 if (!listener) {
1566 if (msg.is_sync()) {
1567 // The listener has gone away, so we must respond or else the caller will
1568 // hang waiting for a reply.
1569 IPC::Message* reply = IPC::SyncMessage::GenerateReply(&msg);
1570 reply->set_reply_error();
1571 Send(reply);
1573 return true;
1575 return listener->OnMessageReceived(msg);
1578 void RenderProcessHostImpl::OnChannelConnected(int32 peer_pid) {
1579 #if defined(IPC_MESSAGE_LOG_ENABLED)
1580 Send(new ChildProcessMsg_SetIPCLoggingEnabled(
1581 IPC::Logging::GetInstance()->Enabled()));
1582 #endif
1584 tracked_objects::ThreadData::Status status =
1585 tracked_objects::ThreadData::status();
1586 Send(new ChildProcessMsg_SetProfilerStatus(status));
1588 #if defined(OS_MACOSX) && !defined(OS_IOS)
1589 io_surface_manager_token_ =
1590 BrowserIOSurfaceManager::GetInstance()->GenerateChildProcessToken(
1591 GetID());
1592 Send(new ChildProcessMsg_SetIOSurfaceManagerToken(io_surface_manager_token_));
1593 #endif
1596 void RenderProcessHostImpl::OnChannelError() {
1597 ProcessDied(true /* already_dead */, nullptr);
1600 void RenderProcessHostImpl::OnBadMessageReceived(const IPC::Message& message) {
1601 // Message de-serialization failed. We consider this a capital crime. Kill the
1602 // renderer if we have one.
1603 LOG(ERROR) << "bad message " << message.type() << " terminating renderer.";
1604 BrowserChildProcessHostImpl::HistogramBadMessageTerminated(
1605 PROCESS_TYPE_RENDERER);
1607 // Create a memory dump. This will contain enough stack frames to work out
1608 // what the bad message was.
1609 base::debug::DumpWithoutCrashing();
1611 bad_message::ReceivedBadMessage(this,
1612 bad_message::RPH_DESERIALIZATION_FAILED);
1615 BrowserContext* RenderProcessHostImpl::GetBrowserContext() const {
1616 return browser_context_;
1619 bool RenderProcessHostImpl::InSameStoragePartition(
1620 StoragePartition* partition) const {
1621 return storage_partition_impl_ == partition;
1624 int RenderProcessHostImpl::GetID() const {
1625 return id_;
1628 bool RenderProcessHostImpl::HasConnection() const {
1629 return channel_.get() != NULL;
1632 void RenderProcessHostImpl::SetIgnoreInputEvents(bool ignore_input_events) {
1633 ignore_input_events_ = ignore_input_events;
1636 bool RenderProcessHostImpl::IgnoreInputEvents() const {
1637 return ignore_input_events_;
1640 void RenderProcessHostImpl::Cleanup() {
1641 // If within_process_died_observer_ is true, one of our observers performed an
1642 // action that caused us to die (e.g. http://crbug.com/339504). Therefore,
1643 // delay the destruction until all of the observer callbacks have been made,
1644 // and guarantee that the RenderProcessHostDestroyed observer callback is
1645 // always the last callback fired.
1646 if (within_process_died_observer_) {
1647 delayed_cleanup_needed_ = true;
1648 return;
1650 delayed_cleanup_needed_ = false;
1652 // Records the time when the process starts surviving for workers for UMA.
1653 if (listeners_.IsEmpty() && worker_ref_count_ > 0 &&
1654 survive_for_worker_start_time_.is_null()) {
1655 survive_for_worker_start_time_ = base::TimeTicks::Now();
1658 // When there are no other owners of this object, we can delete ourselves.
1659 if (listeners_.IsEmpty() && worker_ref_count_ == 0) {
1660 if (!survive_for_worker_start_time_.is_null()) {
1661 UMA_HISTOGRAM_LONG_TIMES(
1662 "SharedWorker.RendererSurviveForWorkerTime",
1663 base::TimeTicks::Now() - survive_for_worker_start_time_);
1666 if (max_worker_count_ > 0) {
1667 // Record the max number of workers (SharedWorker or ServiceWorker)
1668 // that are simultaneously hosted in this renderer process.
1669 UMA_HISTOGRAM_COUNTS("Render.Workers.MaxWorkerCountInRendererProcess",
1670 max_worker_count_);
1673 // We cannot clean up twice; if this fails, there is an issue with our
1674 // control flow.
1675 DCHECK(!deleting_soon_);
1677 DCHECK_EQ(0, pending_views_);
1678 FOR_EACH_OBSERVER(RenderProcessHostObserver,
1679 observers_,
1680 RenderProcessHostDestroyed(this));
1681 NotificationService::current()->Notify(
1682 NOTIFICATION_RENDERER_PROCESS_TERMINATED,
1683 Source<RenderProcessHost>(this),
1684 NotificationService::NoDetails());
1686 #ifndef NDEBUG
1687 is_self_deleted_ = true;
1688 #endif
1689 base::MessageLoop::current()->DeleteSoon(FROM_HERE, this);
1690 deleting_soon_ = true;
1691 // It's important not to wait for the DeleteTask to delete the channel
1692 // proxy. Kill it off now. That way, in case the profile is going away, the
1693 // rest of the objects attached to this RenderProcessHost start going
1694 // away first, since deleting the channel proxy will post a
1695 // OnChannelClosed() to IPC::ChannelProxy::Context on the IO thread.
1696 channel_.reset();
1698 // The following members should be cleared in ProcessDied() as well!
1699 gpu_message_filter_ = NULL;
1700 message_port_message_filter_ = NULL;
1702 RemoveUserData(kSessionStorageHolderKey);
1704 // Remove ourself from the list of renderer processes so that we can't be
1705 // reused in between now and when the Delete task runs.
1706 UnregisterHost(GetID());
1708 #if defined(OS_MACOSX) && !defined(OS_IOS)
1709 if (!io_surface_manager_token_.IsZero()) {
1710 BrowserIOSurfaceManager::GetInstance()->InvalidateChildProcessToken(
1711 io_surface_manager_token_);
1712 io_surface_manager_token_.SetZero();
1714 #endif
1719 void RenderProcessHostImpl::AddPendingView() {
1720 pending_views_++;
1723 void RenderProcessHostImpl::RemovePendingView() {
1724 DCHECK(pending_views_);
1725 pending_views_--;
1728 void RenderProcessHostImpl::SetSuddenTerminationAllowed(bool enabled) {
1729 sudden_termination_allowed_ = enabled;
1732 bool RenderProcessHostImpl::SuddenTerminationAllowed() const {
1733 return sudden_termination_allowed_;
1736 base::TimeDelta RenderProcessHostImpl::GetChildProcessIdleTime() const {
1737 return base::TimeTicks::Now() - child_process_activity_time_;
1740 void RenderProcessHostImpl::ResumeRequestsForView(int route_id) {
1741 widget_helper_->ResumeRequestsForView(route_id);
1744 void RenderProcessHostImpl::FilterURL(bool empty_allowed, GURL* url) {
1745 FilterURL(this, empty_allowed, url);
1748 #if defined(ENABLE_WEBRTC)
1749 void RenderProcessHostImpl::EnableAecDump(const base::FilePath& file) {
1750 DCHECK_CURRENTLY_ON(BrowserThread::UI);
1751 // Enable AEC dump for each registered consumer.
1752 for (std::vector<int>::iterator it = aec_dump_consumers_.begin();
1753 it != aec_dump_consumers_.end(); ++it) {
1754 EnableAecDumpForId(file, *it);
1758 void RenderProcessHostImpl::DisableAecDump() {
1759 DCHECK_CURRENTLY_ON(BrowserThread::UI);
1760 // Posting on the FILE thread and then replying back on the UI thread is only
1761 // for avoiding races between enable and disable. Nothing is done on the FILE
1762 // thread.
1763 BrowserThread::PostTaskAndReply(
1764 BrowserThread::FILE, FROM_HERE,
1765 base::Bind(&DisableAecDumpOnFileThread),
1766 base::Bind(&RenderProcessHostImpl::SendDisableAecDumpToRenderer,
1767 weak_factory_.GetWeakPtr()));
1770 void RenderProcessHostImpl::SetWebRtcLogMessageCallback(
1771 base::Callback<void(const std::string&)> callback) {
1772 webrtc_log_message_callback_ = callback;
1775 RenderProcessHostImpl::WebRtcStopRtpDumpCallback
1776 RenderProcessHostImpl::StartRtpDump(
1777 bool incoming,
1778 bool outgoing,
1779 const WebRtcRtpPacketCallback& packet_callback) {
1780 if (!p2p_socket_dispatcher_host_.get())
1781 return WebRtcStopRtpDumpCallback();
1783 BrowserThread::PostTask(BrowserThread::IO,
1784 FROM_HERE,
1785 base::Bind(&P2PSocketDispatcherHost::StartRtpDump,
1786 p2p_socket_dispatcher_host_,
1787 incoming,
1788 outgoing,
1789 packet_callback));
1791 if (stop_rtp_dump_callback_.is_null()) {
1792 stop_rtp_dump_callback_ =
1793 base::Bind(&P2PSocketDispatcherHost::StopRtpDumpOnUIThread,
1794 p2p_socket_dispatcher_host_);
1796 return stop_rtp_dump_callback_;
1798 #endif
1800 IPC::ChannelProxy* RenderProcessHostImpl::GetChannel() {
1801 return channel_.get();
1804 void RenderProcessHostImpl::AddFilter(BrowserMessageFilter* filter) {
1805 channel_->AddFilter(filter->GetFilter());
1808 bool RenderProcessHostImpl::FastShutdownForPageCount(size_t count) {
1809 if (static_cast<size_t>(GetActiveViewCount()) == count)
1810 return FastShutdownIfPossible();
1811 return false;
1814 bool RenderProcessHostImpl::FastShutdownStarted() const {
1815 return fast_shutdown_started_;
1818 // static
1819 void RenderProcessHostImpl::RegisterHost(int host_id, RenderProcessHost* host) {
1820 g_all_hosts.Get().AddWithID(host, host_id);
1823 // static
1824 void RenderProcessHostImpl::UnregisterHost(int host_id) {
1825 RenderProcessHost* host = g_all_hosts.Get().Lookup(host_id);
1826 if (!host)
1827 return;
1829 g_all_hosts.Get().Remove(host_id);
1831 // Look up the map of site to process for the given browser_context,
1832 // in case we need to remove this process from it. It will be registered
1833 // under any sites it rendered that use process-per-site mode.
1834 SiteProcessMap* map =
1835 GetSiteProcessMapForBrowserContext(host->GetBrowserContext());
1836 map->RemoveProcess(host);
1839 // static
1840 void RenderProcessHostImpl::FilterURL(RenderProcessHost* rph,
1841 bool empty_allowed,
1842 GURL* url) {
1843 ChildProcessSecurityPolicyImpl* policy =
1844 ChildProcessSecurityPolicyImpl::GetInstance();
1846 if (empty_allowed && url->is_empty())
1847 return;
1849 // The browser process should never hear the swappedout:// URL from any
1850 // of the renderer's messages. Check for this in debug builds, but don't
1851 // let it crash a release browser.
1852 DCHECK(GURL(kSwappedOutURL) != *url);
1854 if (!url->is_valid()) {
1855 // Have to use about:blank for the denied case, instead of an empty GURL.
1856 // This is because the browser treats navigation to an empty GURL as a
1857 // navigation to the home page. This is often a privileged page
1858 // (chrome://newtab/) which is exactly what we don't want.
1859 *url = GURL(url::kAboutBlankURL);
1860 return;
1863 if (url->SchemeIs(url::kAboutScheme)) {
1864 // The renderer treats all URLs in the about: scheme as being about:blank.
1865 // Canonicalize about: URLs to about:blank.
1866 *url = GURL(url::kAboutBlankURL);
1869 // Do not allow browser plugin guests to navigate to non-web URLs, since they
1870 // cannot swap processes or grant bindings.
1871 bool non_web_url_in_guest = rph->IsForGuestsOnly() &&
1872 !(url->is_valid() && policy->IsWebSafeScheme(url->scheme()));
1874 if (non_web_url_in_guest || !policy->CanRequestURL(rph->GetID(), *url)) {
1875 // If this renderer is not permitted to request this URL, we invalidate the
1876 // URL. This prevents us from storing the blocked URL and becoming confused
1877 // later.
1878 VLOG(1) << "Blocked URL " << url->spec();
1879 *url = GURL(url::kAboutBlankURL);
1883 // static
1884 bool RenderProcessHostImpl::IsSuitableHost(
1885 RenderProcessHost* host,
1886 BrowserContext* browser_context,
1887 const GURL& site_url) {
1888 if (run_renderer_in_process())
1889 return true;
1891 if (host->GetBrowserContext() != browser_context)
1892 return false;
1894 // Do not allow sharing of guest hosts. This is to prevent bugs where guest
1895 // and non-guest storage gets mixed. In the future, we might consider enabling
1896 // the sharing of guests, in this case this check should be removed and
1897 // InSameStoragePartition should handle the possible sharing.
1898 if (host->IsForGuestsOnly())
1899 return false;
1901 // Check whether the given host and the intended site_url will be using the
1902 // same StoragePartition, since a RenderProcessHost can only support a single
1903 // StoragePartition. This is relevant for packaged apps.
1904 StoragePartition* dest_partition =
1905 BrowserContext::GetStoragePartitionForSite(browser_context, site_url);
1906 if (!host->InSameStoragePartition(dest_partition))
1907 return false;
1909 // TODO(nick): Consult the SiteIsolationPolicy here. https://crbug.com/513036
1910 if (ChildProcessSecurityPolicyImpl::GetInstance()->HasWebUIBindings(
1911 host->GetID()) !=
1912 WebUIControllerFactoryRegistry::GetInstance()->UseWebUIBindingsForURL(
1913 browser_context, site_url)) {
1914 return false;
1917 return GetContentClient()->browser()->IsSuitableHost(host, site_url);
1920 // static
1921 bool RenderProcessHost::run_renderer_in_process() {
1922 return g_run_renderer_in_process_;
1925 // static
1926 void RenderProcessHost::SetRunRendererInProcess(bool value) {
1927 g_run_renderer_in_process_ = value;
1929 base::CommandLine* command_line = base::CommandLine::ForCurrentProcess();
1930 if (value) {
1931 if (!command_line->HasSwitch(switches::kLang)) {
1932 // Modify the current process' command line to include the browser locale,
1933 // as the renderer expects this flag to be set.
1934 const std::string locale =
1935 GetContentClient()->browser()->GetApplicationLocale();
1936 command_line->AppendSwitchASCII(switches::kLang, locale);
1938 // TODO(piman): we should really send configuration through bools rather
1939 // than by parsing strings, i.e. sending an IPC rather than command line
1940 // args. crbug.com/314909
1941 AppendCompositorCommandLineFlags(command_line);
1945 // static
1946 RenderProcessHost::iterator RenderProcessHost::AllHostsIterator() {
1947 DCHECK_CURRENTLY_ON(BrowserThread::UI);
1948 return iterator(g_all_hosts.Pointer());
1951 // static
1952 RenderProcessHost* RenderProcessHost::FromID(int render_process_id) {
1953 DCHECK_CURRENTLY_ON(BrowserThread::UI);
1954 return g_all_hosts.Get().Lookup(render_process_id);
1957 // static
1958 bool RenderProcessHost::ShouldTryToUseExistingProcessHost(
1959 BrowserContext* browser_context, const GURL& url) {
1960 // If --site-per-process is enabled, do not try to reuse renderer processes
1961 // when over the limit.
1962 // TODO(nick): This is overly conservative and isn't launchable. Move this
1963 // logic into IsSuitableHost, and check |url| against the URL the process is
1964 // dedicated to. This will allow pages from the same site to share, and will
1965 // also allow non-isolated sites to share processes. https://crbug.com/513036
1966 if (SiteIsolationPolicy::AreCrossProcessFramesPossible())
1967 return false;
1969 if (run_renderer_in_process())
1970 return true;
1972 // NOTE: Sometimes it's necessary to create more render processes than
1973 // GetMaxRendererProcessCount(), for instance when we want to create
1974 // a renderer process for a browser context that has no existing
1975 // renderers. This is OK in moderation, since the
1976 // GetMaxRendererProcessCount() is conservative.
1977 if (g_all_hosts.Get().size() >= GetMaxRendererProcessCount())
1978 return true;
1980 return GetContentClient()->browser()->
1981 ShouldTryToUseExistingProcessHost(browser_context, url);
1984 // static
1985 RenderProcessHost* RenderProcessHost::GetExistingProcessHost(
1986 BrowserContext* browser_context,
1987 const GURL& site_url) {
1988 // First figure out which existing renderers we can use.
1989 std::vector<RenderProcessHost*> suitable_renderers;
1990 suitable_renderers.reserve(g_all_hosts.Get().size());
1992 iterator iter(AllHostsIterator());
1993 while (!iter.IsAtEnd()) {
1994 if (GetContentClient()->browser()->MayReuseHost(iter.GetCurrentValue()) &&
1995 RenderProcessHostImpl::IsSuitableHost(
1996 iter.GetCurrentValue(),
1997 browser_context, site_url)) {
1998 suitable_renderers.push_back(iter.GetCurrentValue());
2000 iter.Advance();
2003 // Now pick a random suitable renderer, if we have any.
2004 if (!suitable_renderers.empty()) {
2005 int suitable_count = static_cast<int>(suitable_renderers.size());
2006 int random_index = base::RandInt(0, suitable_count - 1);
2007 return suitable_renderers[random_index];
2010 return NULL;
2013 // static
2014 bool RenderProcessHost::ShouldUseProcessPerSite(
2015 BrowserContext* browser_context,
2016 const GURL& url) {
2017 // Returns true if we should use the process-per-site model. This will be
2018 // the case if the --process-per-site switch is specified, or in
2019 // process-per-site-instance for particular sites (e.g., WebUI).
2020 // Note that --single-process is handled in ShouldTryToUseExistingProcessHost.
2021 const base::CommandLine& command_line =
2022 *base::CommandLine::ForCurrentProcess();
2023 if (command_line.HasSwitch(switches::kProcessPerSite))
2024 return true;
2026 // We want to consolidate particular sites like WebUI even when we are using
2027 // the process-per-tab or process-per-site-instance models.
2028 // Note: DevTools pages have WebUI type but should not reuse the same host.
2029 if (WebUIControllerFactoryRegistry::GetInstance()->UseWebUIForURL(
2030 browser_context, url) &&
2031 !url.SchemeIs(kChromeDevToolsScheme)) {
2032 return true;
2035 // Otherwise let the content client decide, defaulting to false.
2036 return GetContentClient()->browser()->ShouldUseProcessPerSite(browser_context,
2037 url);
2040 // static
2041 RenderProcessHost* RenderProcessHostImpl::GetProcessHostForSite(
2042 BrowserContext* browser_context,
2043 const GURL& url) {
2044 // Look up the map of site to process for the given browser_context.
2045 SiteProcessMap* map =
2046 GetSiteProcessMapForBrowserContext(browser_context);
2048 // See if we have an existing process with appropriate bindings for this site.
2049 // If not, the caller should create a new process and register it.
2050 std::string site = SiteInstance::GetSiteForURL(browser_context, url)
2051 .possibly_invalid_spec();
2052 RenderProcessHost* host = map->FindProcess(site);
2053 if (host && (!GetContentClient()->browser()->MayReuseHost(host) ||
2054 !IsSuitableHost(host, browser_context, url))) {
2055 // The registered process does not have an appropriate set of bindings for
2056 // the url. Remove it from the map so we can register a better one.
2057 RecordAction(
2058 base::UserMetricsAction("BindingsMismatch_GetProcessHostPerSite"));
2059 map->RemoveProcess(host);
2060 host = NULL;
2063 return host;
2066 void RenderProcessHostImpl::RegisterProcessHostForSite(
2067 BrowserContext* browser_context,
2068 RenderProcessHost* process,
2069 const GURL& url) {
2070 // Look up the map of site to process for the given browser_context.
2071 SiteProcessMap* map =
2072 GetSiteProcessMapForBrowserContext(browser_context);
2074 // Only register valid, non-empty sites. Empty or invalid sites will not
2075 // use process-per-site mode. We cannot check whether the process has
2076 // appropriate bindings here, because the bindings have not yet been granted.
2077 std::string site = SiteInstance::GetSiteForURL(browser_context, url)
2078 .possibly_invalid_spec();
2079 if (!site.empty())
2080 map->RegisterProcess(site, process);
2083 void RenderProcessHostImpl::ProcessDied(bool already_dead,
2084 RendererClosedDetails* known_details) {
2085 // Our child process has died. If we didn't expect it, it's a crash.
2086 // In any case, we need to let everyone know it's gone.
2087 // The OnChannelError notification can fire multiple times due to nested sync
2088 // calls to a renderer. If we don't have a valid channel here it means we
2089 // already handled the error.
2091 // It should not be possible for us to be called re-entrantly.
2092 DCHECK(!within_process_died_observer_);
2094 // It should not be possible for a process death notification to come in while
2095 // we are dying.
2096 DCHECK(!deleting_soon_);
2098 // child_process_launcher_ can be NULL in single process mode or if fast
2099 // termination happened.
2100 base::TerminationStatus status = base::TERMINATION_STATUS_NORMAL_TERMINATION;
2101 int exit_code = 0;
2102 if (known_details) {
2103 status = known_details->status;
2104 exit_code = known_details->exit_code;
2105 } else if (child_process_launcher_.get()) {
2106 status = child_process_launcher_->GetChildTerminationStatus(already_dead,
2107 &exit_code);
2108 if (already_dead && status == base::TERMINATION_STATUS_STILL_RUNNING) {
2109 // May be in case of IPC error, if it takes long time for renderer
2110 // to exit. Child process will be killed in any case during
2111 // child_process_launcher_.reset(). Make sure we will not broadcast
2112 // FrameHostMsg_RenderProcessGone with status
2113 // TERMINATION_STATUS_STILL_RUNNING, since this will break WebContentsImpl
2114 // logic.
2115 status = base::TERMINATION_STATUS_PROCESS_CRASHED;
2119 RendererClosedDetails details(status, exit_code);
2120 mojo_application_host_->WillDestroySoon();
2122 child_process_launcher_.reset();
2123 channel_.reset();
2124 while (!queued_messages_.empty()) {
2125 delete queued_messages_.front();
2126 queued_messages_.pop();
2129 within_process_died_observer_ = true;
2130 NotificationService::current()->Notify(
2131 NOTIFICATION_RENDERER_PROCESS_CLOSED,
2132 Source<RenderProcessHost>(this),
2133 Details<RendererClosedDetails>(&details));
2134 FOR_EACH_OBSERVER(RenderProcessHostObserver,
2135 observers_,
2136 RenderProcessExited(this, status, exit_code));
2137 within_process_died_observer_ = false;
2139 gpu_message_filter_ = NULL;
2140 message_port_message_filter_ = NULL;
2141 RemoveUserData(kSessionStorageHolderKey);
2143 IDMap<IPC::Listener>::iterator iter(&listeners_);
2144 while (!iter.IsAtEnd()) {
2145 iter.GetCurrentValue()->OnMessageReceived(
2146 FrameHostMsg_RenderProcessGone(iter.GetCurrentKey(),
2147 static_cast<int>(status),
2148 exit_code));
2149 iter.Advance();
2152 mojo_application_host_.reset(new MojoApplicationHost);
2154 // It's possible that one of the calls out to the observers might have caused
2155 // this object to be no longer needed.
2156 if (delayed_cleanup_needed_)
2157 Cleanup();
2159 // This object is not deleted at this point and might be reused later.
2160 // TODO(darin): clean this up
2163 int RenderProcessHost::GetActiveViewCount() {
2164 int num_active_views = 0;
2165 scoped_ptr<RenderWidgetHostIterator> widgets(
2166 RenderWidgetHost::GetRenderWidgetHosts());
2167 while (RenderWidgetHost* widget = widgets->GetNextHost()) {
2168 // Count only RenderWidgetHosts in this process.
2169 if (widget->GetProcess()->GetID() == GetID())
2170 num_active_views++;
2172 return num_active_views;
2175 // Frame subscription API for this class is for accelerated composited path
2176 // only. These calls are redirected to GpuMessageFilter.
2177 void RenderProcessHostImpl::BeginFrameSubscription(
2178 int route_id,
2179 scoped_ptr<RenderWidgetHostViewFrameSubscriber> subscriber) {
2180 if (!gpu_message_filter_)
2181 return;
2182 BrowserThread::PostTask(BrowserThread::IO, FROM_HERE, base::Bind(
2183 &GpuMessageFilter::BeginFrameSubscription,
2184 gpu_message_filter_,
2185 route_id, base::Passed(&subscriber)));
2188 void RenderProcessHostImpl::EndFrameSubscription(int route_id) {
2189 if (!gpu_message_filter_)
2190 return;
2191 BrowserThread::PostTask(BrowserThread::IO, FROM_HERE, base::Bind(
2192 &GpuMessageFilter::EndFrameSubscription,
2193 gpu_message_filter_,
2194 route_id));
2197 #if defined(ENABLE_WEBRTC)
2198 void RenderProcessHostImpl::WebRtcLogMessage(const std::string& message) {
2199 DCHECK_CURRENTLY_ON(BrowserThread::UI);
2200 if (!webrtc_log_message_callback_.is_null())
2201 webrtc_log_message_callback_.Run(message);
2203 #endif
2205 void RenderProcessHostImpl::ReleaseOnCloseACK(
2206 RenderProcessHost* host,
2207 const SessionStorageNamespaceMap& sessions,
2208 int view_route_id) {
2209 DCHECK(host);
2210 if (sessions.empty())
2211 return;
2212 SessionStorageHolder* holder = static_cast<SessionStorageHolder*>
2213 (host->GetUserData(kSessionStorageHolderKey));
2214 if (!holder) {
2215 holder = new SessionStorageHolder();
2216 host->SetUserData(
2217 kSessionStorageHolderKey,
2218 holder);
2220 holder->Hold(sessions, view_route_id);
2223 void RenderProcessHostImpl::OnShutdownRequest() {
2224 // Don't shut down if there are active RenderViews, or if there are pending
2225 // RenderViews being swapped back in.
2226 // In single process mode, we never shutdown the renderer.
2227 int num_active_views = GetActiveViewCount();
2228 if (pending_views_ || num_active_views > 0 || run_renderer_in_process())
2229 return;
2231 // Notify any contents that might have swapped out renderers from this
2232 // process. They should not attempt to swap them back in.
2233 FOR_EACH_OBSERVER(RenderProcessHostObserver, observers_,
2234 RenderProcessWillExit(this));
2236 mojo_application_host_->WillDestroySoon();
2238 Send(new ChildProcessMsg_Shutdown());
2241 void RenderProcessHostImpl::SuddenTerminationChanged(bool enabled) {
2242 SetSuddenTerminationAllowed(enabled);
2245 void RenderProcessHostImpl::SetBackgrounded(bool backgrounded) {
2246 TRACE_EVENT1("renderer_host", "RenderProcessHostImpl::SetBackgrounded",
2247 "backgrounded", backgrounded);
2248 // Note: we always set the backgrounded_ value. If the process is NULL
2249 // (and hence hasn't been created yet), we will set the process priority
2250 // later when we create the process.
2251 backgrounded_ = backgrounded;
2252 if (!child_process_launcher_.get() || child_process_launcher_->IsStarting())
2253 return;
2255 // Don't background processes which have active audio streams.
2256 if (backgrounded_ && audio_renderer_host_->HasActiveAudio())
2257 return;
2259 const base::CommandLine* command_line =
2260 base::CommandLine::ForCurrentProcess();
2261 if (command_line->HasSwitch(switches::kDisableRendererBackgrounding))
2262 return;
2264 #if defined(OS_WIN)
2265 // The cbstext.dll loads as a global GetMessage hook in the browser process
2266 // and intercepts/unintercepts the kernel32 API SetPriorityClass in a
2267 // background thread. If the UI thread invokes this API just when it is
2268 // intercepted the stack is messed up on return from the interceptor
2269 // which causes random crashes in the browser process. Our hack for now
2270 // is to not invoke the SetPriorityClass API if the dll is loaded.
2271 if (GetModuleHandle(L"cbstext.dll"))
2272 return;
2273 #endif // OS_WIN
2275 #if defined(OS_WIN) || defined(OS_MACOSX)
2276 // Same as below, but bound to an experiment (http://crbug.com/458594 on
2277 // Windows, http://crbug.com/398103 on the Mac). Enabled by default in the
2278 // absence of field trials to get coverage on the perf waterfall.
2279 base::FieldTrial* trial =
2280 base::FieldTrialList::Find("BackgroundRendererProcesses");
2281 if (!trial || !base::StartsWith(trial->group_name(), "Disallow",
2282 base::CompareCase::SENSITIVE)) {
2283 child_process_launcher_->SetProcessBackgrounded(backgrounded);
2285 #else
2286 // Control the background state from the browser process, otherwise the task
2287 // telling the renderer to "unbackground" itself may be preempted by other
2288 // tasks executing at lowered priority ahead of it or simply by not being
2289 // swiftly scheduled by the OS per the low process priority
2290 // (http://crbug.com/398103).
2291 child_process_launcher_->SetProcessBackgrounded(backgrounded);
2292 #endif // OS_WIN
2294 // Notify the child process of background state.
2295 Send(new ChildProcessMsg_SetProcessBackgrounded(backgrounded));
2298 void RenderProcessHostImpl::OnProcessLaunched() {
2299 // TODO(erikchen): Remove ScopedTracker below once http://crbug.com/465841
2300 // is fixed.
2301 tracked_objects::ScopedTracker tracking_profile1(
2302 FROM_HERE_WITH_EXPLICIT_FUNCTION(
2303 "465841 RenderProcessHostImpl::OnProcessLaunched::Start"));
2304 // No point doing anything, since this object will be destructed soon. We
2305 // especially don't want to send the RENDERER_PROCESS_CREATED notification,
2306 // since some clients might expect a RENDERER_PROCESS_TERMINATED afterwards to
2307 // properly cleanup.
2308 if (deleting_soon_)
2309 return;
2311 if (child_process_launcher_) {
2312 // TODO(erikchen): Remove ScopedTracker below once http://crbug.com/465841
2313 // is fixed.
2314 tracked_objects::ScopedTracker tracking_profile2(
2315 FROM_HERE_WITH_EXPLICIT_FUNCTION(
2316 "465841 RenderProcessHostImpl::OnProcessLaunched::Backgrounded"));
2317 DCHECK(child_process_launcher_->GetProcess().IsValid());
2318 SetBackgrounded(backgrounded_);
2321 // TODO(erikchen): Remove ScopedTracker below once http://crbug.com/465841
2322 // is fixed.
2323 tracked_objects::ScopedTracker tracking_profile3(
2324 FROM_HERE_WITH_EXPLICIT_FUNCTION(
2325 "465841 RenderProcessHostImpl::OnProcessLaunched::Notify"));
2326 // NOTE: This needs to be before sending queued messages because
2327 // ExtensionService uses this notification to initialize the renderer process
2328 // with state that must be there before any JavaScript executes.
2330 // The queued messages contain such things as "navigate". If this notification
2331 // was after, we can end up executing JavaScript before the initialization
2332 // happens.
2333 NotificationService::current()->Notify(
2334 NOTIFICATION_RENDERER_PROCESS_CREATED,
2335 Source<RenderProcessHost>(this),
2336 NotificationService::NoDetails());
2338 // TODO(erikchen): Remove ScopedTracker below once http://crbug.com/465841
2339 // is fixed.
2340 tracked_objects::ScopedTracker tracking_profile4(
2341 FROM_HERE_WITH_EXPLICIT_FUNCTION(
2342 "465841 RenderProcessHostImpl::OnProcessLaunched::MojoActivate"));
2343 // Allow Mojo to be setup before the renderer sees any Chrome IPC messages.
2344 // This way, Mojo can be safely used from the renderer in response to any
2345 // Chrome IPC message.
2346 mojo_application_host_->Activate(this, GetHandle());
2348 // TODO(erikchen): Remove ScopedTracker below once http://crbug.com/465841
2349 // is fixed.
2350 tracked_objects::ScopedTracker tracking_profile5(
2351 FROM_HERE_WITH_EXPLICIT_FUNCTION(
2352 "465841 RenderProcessHostImpl::OnProcessLaunched::MojoClientLaunch"));
2354 // TODO(erikchen): Remove ScopedTracker below once http://crbug.com/465841
2355 // is fixed.
2356 tracked_objects::ScopedTracker tracking_profile6(
2357 FROM_HERE_WITH_EXPLICIT_FUNCTION(
2358 "465841 "
2359 "RenderProcessHostImpl::OnProcessLaunched::SendQueuedMessages"));
2360 while (!queued_messages_.empty()) {
2361 Send(queued_messages_.front());
2362 queued_messages_.pop();
2365 #if defined(ENABLE_WEBRTC)
2366 // TODO(erikchen): Remove ScopedTracker below once http://crbug.com/465841
2367 // is fixed.
2368 tracked_objects::ScopedTracker tracking_profile7(
2369 FROM_HERE_WITH_EXPLICIT_FUNCTION(
2370 "465841 RenderProcessHostImpl::OnProcessLaunched::EnableAec"));
2371 if (WebRTCInternals::GetInstance()->aec_dump_enabled())
2372 EnableAecDump(WebRTCInternals::GetInstance()->aec_dump_file_path());
2373 #endif
2376 void RenderProcessHostImpl::OnProcessLaunchFailed() {
2377 // If this object will be destructed soon, then observers have already been
2378 // sent a RenderProcessHostDestroyed notification, and we must observe our
2379 // contract that says that will be the last call.
2380 if (deleting_soon_)
2381 return;
2383 RendererClosedDetails details { base::TERMINATION_STATUS_PROCESS_WAS_KILLED,
2384 -1 };
2385 ProcessDied(true, &details);
2388 scoped_refptr<AudioRendererHost>
2389 RenderProcessHostImpl::audio_renderer_host() const {
2390 return audio_renderer_host_;
2393 void RenderProcessHostImpl::OnUserMetricsRecordAction(
2394 const std::string& action) {
2395 RecordComputedAction(action);
2398 void RenderProcessHostImpl::OnCloseACK(int old_route_id) {
2399 SessionStorageHolder* holder = static_cast<SessionStorageHolder*>
2400 (GetUserData(kSessionStorageHolderKey));
2401 if (!holder)
2402 return;
2403 holder->Release(old_route_id);
2406 void RenderProcessHostImpl::OnSavedPageAsMHTML(int job_id, int64 data_size) {
2407 MHTMLGenerationManager::GetInstance()->MHTMLGenerated(job_id, data_size);
2410 void RenderProcessHostImpl::OnGpuSwitched() {
2411 // We are updating all widgets including swapped out ones.
2412 scoped_ptr<RenderWidgetHostIterator> widgets(
2413 RenderWidgetHostImpl::GetAllRenderWidgetHosts());
2414 while (RenderWidgetHost* widget = widgets->GetNextHost()) {
2415 if (!widget->IsRenderView())
2416 continue;
2418 // Skip widgets in other processes.
2419 if (widget->GetProcess()->GetID() != GetID())
2420 continue;
2422 RenderViewHost* rvh = RenderViewHost::From(widget);
2423 rvh->OnWebkitPreferencesChanged();
2427 #if defined(ENABLE_WEBRTC)
2428 void RenderProcessHostImpl::OnRegisterAecDumpConsumer(int id) {
2429 BrowserThread::PostTask(
2430 BrowserThread::UI,
2431 FROM_HERE,
2432 base::Bind(
2433 &RenderProcessHostImpl::RegisterAecDumpConsumerOnUIThread,
2434 weak_factory_.GetWeakPtr(),
2435 id));
2438 void RenderProcessHostImpl::OnUnregisterAecDumpConsumer(int id) {
2439 BrowserThread::PostTask(
2440 BrowserThread::UI,
2441 FROM_HERE,
2442 base::Bind(
2443 &RenderProcessHostImpl::UnregisterAecDumpConsumerOnUIThread,
2444 weak_factory_.GetWeakPtr(),
2445 id));
2448 void RenderProcessHostImpl::RegisterAecDumpConsumerOnUIThread(int id) {
2449 DCHECK_CURRENTLY_ON(BrowserThread::UI);
2450 aec_dump_consumers_.push_back(id);
2451 if (WebRTCInternals::GetInstance()->aec_dump_enabled()) {
2452 EnableAecDumpForId(WebRTCInternals::GetInstance()->aec_dump_file_path(),
2453 id);
2457 void RenderProcessHostImpl::UnregisterAecDumpConsumerOnUIThread(int id) {
2458 DCHECK_CURRENTLY_ON(BrowserThread::UI);
2459 for (std::vector<int>::iterator it = aec_dump_consumers_.begin();
2460 it != aec_dump_consumers_.end(); ++it) {
2461 if (*it == id) {
2462 aec_dump_consumers_.erase(it);
2463 break;
2468 #if defined(OS_WIN)
2469 #define IntToStringType base::IntToString16
2470 #else
2471 #define IntToStringType base::IntToString
2472 #endif
2474 void RenderProcessHostImpl::EnableAecDumpForId(const base::FilePath& file,
2475 int id) {
2476 DCHECK_CURRENTLY_ON(BrowserThread::UI);
2477 base::FilePath unique_file =
2478 file.AddExtension(IntToStringType(base::GetProcId(GetHandle())))
2479 .AddExtension(IntToStringType(id));
2480 BrowserThread::PostTaskAndReplyWithResult(
2481 BrowserThread::FILE, FROM_HERE,
2482 base::Bind(&CreateAecDumpFileForProcess, unique_file, GetHandle()),
2483 base::Bind(&RenderProcessHostImpl::SendAecDumpFileToRenderer,
2484 weak_factory_.GetWeakPtr(),
2485 id));
2488 #undef IntToStringType
2490 void RenderProcessHostImpl::SendAecDumpFileToRenderer(
2491 int id,
2492 IPC::PlatformFileForTransit file_for_transit) {
2493 if (file_for_transit == IPC::InvalidPlatformFileForTransit())
2494 return;
2495 Send(new AecDumpMsg_EnableAecDump(id, file_for_transit));
2498 void RenderProcessHostImpl::SendDisableAecDumpToRenderer() {
2499 Send(new AecDumpMsg_DisableAecDump());
2501 #endif
2503 void RenderProcessHostImpl::IncrementWorkerRefCount() {
2504 DCHECK_CURRENTLY_ON(BrowserThread::UI);
2505 ++worker_ref_count_;
2506 if (worker_ref_count_ > max_worker_count_)
2507 max_worker_count_ = worker_ref_count_;
2510 void RenderProcessHostImpl::DecrementWorkerRefCount() {
2511 DCHECK_CURRENTLY_ON(BrowserThread::UI);
2512 DCHECK_GT(worker_ref_count_, 0);
2513 --worker_ref_count_;
2514 if (worker_ref_count_ == 0)
2515 Cleanup();
2518 void RenderProcessHostImpl::GetAudioOutputControllers(
2519 const GetAudioOutputControllersCallback& callback) const {
2520 audio_renderer_host()->GetOutputControllers(callback);
2523 BluetoothDispatcherHost* RenderProcessHostImpl::GetBluetoothDispatcherHost() {
2524 return bluetooth_dispatcher_host_.get();
2527 } // namespace content