Revert of Enable GpuMemoryBuffers video frames on MacOS. (patchset #1 id:1 of https...
[chromium-blink-merge.git] / content / browser / renderer_host / render_process_host_impl.cc
blob100887d3c51b2828ad4ca25f3df9023751c3fd61
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/tracing/tracing_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 std::string UintVectorToString(const std::vector<unsigned>& vector) {
408 std::string str;
409 for (auto it : vector) {
410 if (!str.empty())
411 str += ",";
412 str += base::UintToString(it);
414 return str;
417 } // namespace
419 RendererMainThreadFactoryFunction g_renderer_main_thread_factory = NULL;
421 base::MessageLoop* g_in_process_thread;
423 base::MessageLoop*
424 RenderProcessHostImpl::GetInProcessRendererThreadForTesting() {
425 return g_in_process_thread;
428 // Stores the maximum number of renderer processes the content module can
429 // create.
430 static size_t g_max_renderer_count_override = 0;
432 // static
433 size_t RenderProcessHost::GetMaxRendererProcessCount() {
434 if (g_max_renderer_count_override)
435 return g_max_renderer_count_override;
437 #if defined(OS_ANDROID)
438 // On Android we don't maintain a limit of renderer process hosts - we are
439 // happy with keeping a lot of these, as long as the number of live renderer
440 // processes remains reasonable, and on Android the OS takes care of that.
441 return std::numeric_limits<size_t>::max();
442 #endif
444 // On other platforms, we calculate the maximum number of renderer process
445 // hosts according to the amount of installed memory as reported by the OS.
446 // The calculation assumes that you want the renderers to use half of the
447 // installed RAM and assuming that each WebContents uses ~40MB. If you modify
448 // this assumption, you need to adjust the ThirtyFourTabs test to match the
449 // expected number of processes.
451 // With the given amounts of installed memory below on a 32-bit CPU, the
452 // maximum renderer count will roughly be as follows:
454 // 128 MB -> 3
455 // 512 MB -> 6
456 // 1024 MB -> 12
457 // 4096 MB -> 51
458 // 16384 MB -> 82 (kMaxRendererProcessCount)
460 static size_t max_count = 0;
461 if (!max_count) {
462 const size_t kEstimatedWebContentsMemoryUsage =
463 #if defined(ARCH_CPU_64_BITS)
464 60; // In MB
465 #else
466 40; // In MB
467 #endif
468 max_count = base::SysInfo::AmountOfPhysicalMemoryMB() / 2;
469 max_count /= kEstimatedWebContentsMemoryUsage;
471 const size_t kMinRendererProcessCount = 3;
472 max_count = std::max(max_count, kMinRendererProcessCount);
473 max_count = std::min(max_count, kMaxRendererProcessCount);
475 return max_count;
478 // static
479 bool g_run_renderer_in_process_ = false;
481 // static
482 void RenderProcessHost::SetMaxRendererProcessCount(size_t count) {
483 g_max_renderer_count_override = count;
486 RenderProcessHostImpl::RenderProcessHostImpl(
487 BrowserContext* browser_context,
488 StoragePartitionImpl* storage_partition_impl,
489 bool is_for_guests_only)
490 : fast_shutdown_started_(false),
491 deleting_soon_(false),
492 #ifndef NDEBUG
493 is_self_deleted_(false),
494 #endif
495 pending_views_(0),
496 mojo_application_host_(new MojoApplicationHost),
497 visible_widgets_(0),
498 backgrounded_(true),
499 is_initialized_(false),
500 id_(ChildProcessHostImpl::GenerateChildProcessUniqueId()),
501 browser_context_(browser_context),
502 storage_partition_impl_(storage_partition_impl),
503 sudden_termination_allowed_(true),
504 ignore_input_events_(false),
505 is_for_guests_only_(is_for_guests_only),
506 gpu_observer_registered_(false),
507 delayed_cleanup_needed_(false),
508 within_process_died_observer_(false),
509 power_monitor_broadcaster_(this),
510 worker_ref_count_(0),
511 max_worker_count_(0),
512 permission_service_context_(new PermissionServiceContext(this)),
513 pending_valuebuffer_state_(new gpu::ValueStateMap()),
514 subscribe_uniform_enabled_(false),
515 weak_factory_(this) {
516 widget_helper_ = new RenderWidgetHelper();
518 ChildProcessSecurityPolicyImpl::GetInstance()->Add(GetID());
520 CHECK(!g_exited_main_message_loop);
521 RegisterHost(GetID(), this);
522 g_all_hosts.Get().set_check_on_null_data(true);
523 // Initialize |child_process_activity_time_| to a reasonable value.
524 mark_child_process_activity_time();
526 if (!GetBrowserContext()->IsOffTheRecord() &&
527 !base::CommandLine::ForCurrentProcess()->HasSwitch(
528 switches::kDisableGpuShaderDiskCache)) {
529 BrowserThread::PostTask(BrowserThread::IO, FROM_HERE,
530 base::Bind(&CacheShaderInfo, GetID(),
531 storage_partition_impl_->GetPath()));
533 subscribe_uniform_enabled_ =
534 base::CommandLine::ForCurrentProcess()->HasSwitch(
535 switches::kEnableSubscribeUniformExtension);
537 // Note: When we create the RenderProcessHostImpl, it's technically
538 // backgrounded, because it has no visible listeners. But the process
539 // doesn't actually exist yet, so we'll Background it later, after
540 // creation.
543 // static
544 void RenderProcessHostImpl::ShutDownInProcessRenderer() {
545 DCHECK(g_run_renderer_in_process_);
547 switch (g_all_hosts.Pointer()->size()) {
548 case 0:
549 return;
550 case 1: {
551 RenderProcessHostImpl* host = static_cast<RenderProcessHostImpl*>(
552 AllHostsIterator().GetCurrentValue());
553 FOR_EACH_OBSERVER(RenderProcessHostObserver,
554 host->observers_,
555 RenderProcessHostDestroyed(host));
556 #ifndef NDEBUG
557 host->is_self_deleted_ = true;
558 #endif
559 delete host;
560 return;
562 default:
563 NOTREACHED() << "There should be only one RenderProcessHost when running "
564 << "in-process.";
568 void RenderProcessHostImpl::RegisterRendererMainThreadFactory(
569 RendererMainThreadFactoryFunction create) {
570 g_renderer_main_thread_factory = create;
573 RenderProcessHostImpl::~RenderProcessHostImpl() {
574 #ifndef NDEBUG
575 DCHECK(is_self_deleted_)
576 << "RenderProcessHostImpl is destroyed by something other than itself";
577 #endif
579 // Make sure to clean up the in-process renderer before the channel, otherwise
580 // it may still run and have its IPCs fail, causing asserts.
581 in_process_renderer_.reset();
583 ChildProcessSecurityPolicyImpl::GetInstance()->Remove(GetID());
585 if (gpu_observer_registered_) {
586 ui::GpuSwitchingManager::GetInstance()->RemoveObserver(this);
587 gpu_observer_registered_ = false;
590 // We may have some unsent messages at this point, but that's OK.
591 channel_.reset();
592 while (!queued_messages_.empty()) {
593 delete queued_messages_.front();
594 queued_messages_.pop();
597 UnregisterHost(GetID());
599 if (!base::CommandLine::ForCurrentProcess()->HasSwitch(
600 switches::kDisableGpuShaderDiskCache)) {
601 BrowserThread::PostTask(BrowserThread::IO, FROM_HERE,
602 base::Bind(&RemoveShaderInfo, GetID()));
606 void RenderProcessHostImpl::EnableSendQueue() {
607 is_initialized_ = false;
610 bool RenderProcessHostImpl::Init() {
611 // calling Init() more than once does nothing, this makes it more convenient
612 // for the view host which may not be sure in some cases
613 if (channel_)
614 return true;
616 base::CommandLine::StringType renderer_prefix;
617 // A command prefix is something prepended to the command line of the spawned
618 // process.
619 const base::CommandLine& browser_command_line =
620 *base::CommandLine::ForCurrentProcess();
621 renderer_prefix =
622 browser_command_line.GetSwitchValueNative(switches::kRendererCmdPrefix);
624 #if defined(OS_LINUX)
625 int flags = renderer_prefix.empty() ? ChildProcessHost::CHILD_ALLOW_SELF :
626 ChildProcessHost::CHILD_NORMAL;
627 #else
628 int flags = ChildProcessHost::CHILD_NORMAL;
629 #endif
631 // Find the renderer before creating the channel so if this fails early we
632 // return without creating the channel.
633 base::FilePath renderer_path = ChildProcessHost::GetChildPath(flags);
634 if (renderer_path.empty())
635 return false;
637 // Setup the IPC channel.
638 const std::string channel_id =
639 IPC::Channel::GenerateVerifiedChannelID(std::string());
640 channel_ = CreateChannelProxy(channel_id);
642 // Setup the Mojo channel.
643 mojo_application_host_->Init();
645 // Call the embedder first so that their IPC filters have priority.
646 GetContentClient()->browser()->RenderProcessWillLaunch(this);
648 CreateMessageFilters();
649 RegisterMojoServices();
651 if (run_renderer_in_process()) {
652 DCHECK(g_renderer_main_thread_factory);
653 // Crank up a thread and run the initialization there. With the way that
654 // messages flow between the browser and renderer, this thread is required
655 // to prevent a deadlock in single-process mode. Since the primordial
656 // thread in the renderer process runs the WebKit code and can sometimes
657 // make blocking calls to the UI thread (i.e. this thread), they need to run
658 // on separate threads.
659 in_process_renderer_.reset(
660 g_renderer_main_thread_factory(InProcessChildThreadParams(
661 channel_id, BrowserThread::UnsafeGetMessageLoopForThread(
662 BrowserThread::IO)->task_runner())));
664 base::Thread::Options options;
665 #if defined(OS_WIN) && !defined(OS_MACOSX)
666 // In-process plugins require this to be a UI message loop.
667 options.message_loop_type = base::MessageLoop::TYPE_UI;
668 #else
669 // We can't have multiple UI loops on Linux and Android, so we don't support
670 // in-process plugins.
671 options.message_loop_type = base::MessageLoop::TYPE_DEFAULT;
672 #endif
674 // As for execution sequence, this callback should have no any dependency
675 // on starting in-process-render-thread.
676 // So put it here to trigger ChannelMojo initialization earlier to enable
677 // in-process-render-thread using ChannelMojo there.
678 OnProcessLaunched(); // Fake a callback that the process is ready.
680 in_process_renderer_->StartWithOptions(options);
682 g_in_process_thread = in_process_renderer_->message_loop();
684 } else {
685 // Build command line for renderer. We call AppendRendererCommandLine()
686 // first so the process type argument will appear first.
687 base::CommandLine* cmd_line = new base::CommandLine(renderer_path);
688 if (!renderer_prefix.empty())
689 cmd_line->PrependWrapper(renderer_prefix);
690 AppendRendererCommandLine(cmd_line);
691 cmd_line->AppendSwitchASCII(switches::kProcessChannelID, channel_id);
693 // Spawn the child process asynchronously to avoid blocking the UI thread.
694 // As long as there's no renderer prefix, we can use the zygote process
695 // at this stage.
696 child_process_launcher_.reset(new ChildProcessLauncher(
697 new RendererSandboxedProcessLauncherDelegate(channel_.get()),
698 cmd_line,
699 GetID(),
700 this));
702 fast_shutdown_started_ = false;
705 if (!gpu_observer_registered_) {
706 gpu_observer_registered_ = true;
707 ui::GpuSwitchingManager::GetInstance()->AddObserver(this);
710 power_monitor_broadcaster_.Init();
712 is_initialized_ = true;
713 init_time_ = base::TimeTicks::Now();
714 return true;
717 scoped_ptr<IPC::ChannelProxy> RenderProcessHostImpl::CreateChannelProxy(
718 const std::string& channel_id) {
719 scoped_refptr<base::SingleThreadTaskRunner> runner =
720 BrowserThread::GetMessageLoopProxyForThread(BrowserThread::IO);
721 scoped_refptr<base::SequencedTaskRunner> mojo_task_runner =
722 BrowserThread::UnsafeGetMessageLoopForThread(BrowserThread::IO)
723 ->task_runner();
724 if (ShouldUseMojoChannel()) {
725 VLOG(1) << "Mojo Channel is enabled on host";
727 return IPC::ChannelProxy::Create(
728 IPC::ChannelMojo::CreateServerFactory(
729 mojo_task_runner, channel_id,
730 content::ChildProcessHost::GetAttachmentBroker()),
731 this, runner.get());
734 return IPC::ChannelProxy::Create(
735 channel_id, IPC::Channel::MODE_SERVER, this, runner.get(),
736 content::ChildProcessHost::GetAttachmentBroker());
739 void RenderProcessHostImpl::CreateMessageFilters() {
740 DCHECK_CURRENTLY_ON(BrowserThread::UI);
741 const base::CommandLine& browser_command_line =
742 *base::CommandLine::ForCurrentProcess();
743 AddFilter(new ResourceSchedulerFilter(GetID()));
744 MediaInternals* media_internals = MediaInternals::GetInstance();
745 media::AudioManager* audio_manager =
746 BrowserMainLoop::GetInstance()->audio_manager();
747 // Add BrowserPluginMessageFilter to ensure it gets the first stab at messages
748 // from guests.
749 scoped_refptr<BrowserPluginMessageFilter> bp_message_filter(
750 new BrowserPluginMessageFilter(GetID()));
751 AddFilter(bp_message_filter.get());
753 scoped_refptr<RenderMessageFilter> render_message_filter(
754 new RenderMessageFilter(
755 GetID(),
756 #if defined(ENABLE_PLUGINS)
757 PluginServiceImpl::GetInstance(),
758 #else
759 NULL,
760 #endif
761 GetBrowserContext(),
762 GetBrowserContext()->GetRequestContextForRenderProcess(GetID()),
763 widget_helper_.get(),
764 audio_manager,
765 media_internals,
766 storage_partition_impl_->GetDOMStorageContext()));
767 AddFilter(render_message_filter.get());
768 AddFilter(
769 new RenderFrameMessageFilter(GetID(), widget_helper_.get()));
770 BrowserContext* browser_context = GetBrowserContext();
771 ResourceContext* resource_context = browser_context->GetResourceContext();
773 scoped_refptr<net::URLRequestContextGetter> request_context(
774 browser_context->GetRequestContextForRenderProcess(GetID()));
775 scoped_refptr<net::URLRequestContextGetter> media_request_context(
776 browser_context->GetMediaRequestContextForRenderProcess(GetID()));
778 ResourceMessageFilter::GetContextsCallback get_contexts_callback(
779 base::Bind(&GetContexts, browser_context->GetResourceContext(),
780 request_context, media_request_context));
782 ResourceMessageFilter* resource_message_filter = new ResourceMessageFilter(
783 GetID(), PROCESS_TYPE_RENDERER,
784 storage_partition_impl_->GetAppCacheService(),
785 ChromeBlobStorageContext::GetFor(browser_context),
786 storage_partition_impl_->GetFileSystemContext(),
787 storage_partition_impl_->GetServiceWorkerContext(),
788 storage_partition_impl_->GetHostZoomLevelContext(),
789 get_contexts_callback);
791 AddFilter(resource_message_filter);
792 MediaStreamManager* media_stream_manager =
793 BrowserMainLoop::GetInstance()->media_stream_manager();
794 AddFilter(new AudioInputRendererHost(
795 GetID(),
796 audio_manager,
797 media_stream_manager,
798 AudioMirroringManager::GetInstance(),
799 BrowserMainLoop::GetInstance()->user_input_monitor()));
800 // The AudioRendererHost needs to be available for lookup, so it's
801 // stashed in a member variable.
802 audio_renderer_host_ = new AudioRendererHost(
803 GetID(),
804 audio_manager,
805 AudioMirroringManager::GetInstance(),
806 media_internals,
807 media_stream_manager,
808 browser_context->GetResourceContext()->GetMediaDeviceIDSalt());
809 AddFilter(audio_renderer_host_.get());
810 AddFilter(
811 new MidiHost(GetID(), BrowserMainLoop::GetInstance()->midi_manager()));
812 AddFilter(new VideoCaptureHost(media_stream_manager));
813 AddFilter(new AppCacheDispatcherHost(
814 storage_partition_impl_->GetAppCacheService(),
815 GetID()));
816 AddFilter(new ClipboardMessageFilter);
817 AddFilter(new DOMStorageMessageFilter(
818 storage_partition_impl_->GetDOMStorageContext()));
819 AddFilter(new IndexedDBDispatcherHost(
820 GetID(),
821 storage_partition_impl_->GetURLRequestContext(),
822 storage_partition_impl_->GetIndexedDBContext(),
823 ChromeBlobStorageContext::GetFor(browser_context)));
825 gpu_message_filter_ = new GpuMessageFilter(GetID(), widget_helper_.get());
826 AddFilter(gpu_message_filter_);
827 #if defined(ENABLE_WEBRTC)
828 AddFilter(new WebRTCIdentityServiceHost(
829 GetID(),
830 storage_partition_impl_->GetWebRTCIdentityStore(),
831 resource_context));
832 peer_connection_tracker_host_ = new PeerConnectionTrackerHost(GetID());
833 AddFilter(peer_connection_tracker_host_.get());
834 AddFilter(new MediaStreamDispatcherHost(
835 GetID(),
836 browser_context->GetResourceContext()->GetMediaDeviceIDSalt(),
837 media_stream_manager));
838 AddFilter(new MediaStreamTrackMetricsHost());
839 #endif
840 #if defined(ENABLE_PLUGINS)
841 AddFilter(new PepperRendererConnection(GetID()));
842 #endif
843 AddFilter(new SpeechRecognitionDispatcherHost(
844 GetID(), storage_partition_impl_->GetURLRequestContext()));
845 AddFilter(new FileAPIMessageFilter(
846 GetID(),
847 storage_partition_impl_->GetURLRequestContext(),
848 storage_partition_impl_->GetFileSystemContext(),
849 ChromeBlobStorageContext::GetFor(browser_context),
850 StreamContext::GetFor(browser_context)));
851 AddFilter(new FileUtilitiesMessageFilter(GetID()));
852 AddFilter(new MimeRegistryMessageFilter());
853 AddFilter(new DatabaseMessageFilter(
854 storage_partition_impl_->GetDatabaseTracker()));
855 #if defined(OS_MACOSX)
856 AddFilter(new TextInputClientMessageFilter(GetID()));
857 #elif defined(OS_WIN)
858 // The FontCacheDispatcher is required only when we're using GDI rendering.
859 // TODO(scottmg): pdf/ppapi still require the renderer to be able to precache
860 // GDI fonts (http://crbug.com/383227), even when using DirectWrite. This
861 // should eventually be if (!ShouldUseDirectWrite()) guarded.
862 channel_->AddFilter(new FontCacheDispatcher());
863 #elif defined(OS_ANDROID)
864 browser_demuxer_android_ = new BrowserDemuxerAndroid();
865 AddFilter(browser_demuxer_android_.get());
866 #endif
867 #if defined(ENABLE_BROWSER_CDMS)
868 AddFilter(new BrowserCdmManager(GetID(), NULL));
869 #endif
871 WebSocketDispatcherHost::GetRequestContextCallback
872 websocket_request_context_callback(
873 base::Bind(&GetRequestContext, request_context,
874 media_request_context, RESOURCE_TYPE_SUB_RESOURCE));
876 AddFilter(
877 new WebSocketDispatcherHost(GetID(), websocket_request_context_callback));
879 message_port_message_filter_ = new MessagePortMessageFilter(
880 base::Bind(&RenderWidgetHelper::GetNextRoutingID,
881 base::Unretained(widget_helper_.get())));
882 AddFilter(message_port_message_filter_.get());
884 scoped_refptr<CacheStorageDispatcherHost> cache_storage_filter =
885 new CacheStorageDispatcherHost();
886 cache_storage_filter->Init(storage_partition_impl_->GetCacheStorageContext());
887 AddFilter(cache_storage_filter.get());
889 scoped_refptr<ServiceWorkerDispatcherHost> service_worker_filter =
890 new ServiceWorkerDispatcherHost(
891 GetID(), message_port_message_filter_.get(), resource_context);
892 service_worker_filter->Init(
893 storage_partition_impl_->GetServiceWorkerContext());
894 AddFilter(service_worker_filter.get());
896 AddFilter(new SharedWorkerMessageFilter(
897 GetID(),
898 resource_context,
899 WorkerStoragePartition(
900 storage_partition_impl_->GetURLRequestContext(),
901 storage_partition_impl_->GetMediaURLRequestContext(),
902 storage_partition_impl_->GetAppCacheService(),
903 storage_partition_impl_->GetQuotaManager(),
904 storage_partition_impl_->GetFileSystemContext(),
905 storage_partition_impl_->GetDatabaseTracker(),
906 storage_partition_impl_->GetIndexedDBContext(),
907 storage_partition_impl_->GetServiceWorkerContext()),
908 message_port_message_filter_.get()));
910 #if defined(ENABLE_WEBRTC)
911 p2p_socket_dispatcher_host_ = new P2PSocketDispatcherHost(
912 resource_context,
913 browser_context->GetRequestContextForRenderProcess(GetID()));
914 AddFilter(p2p_socket_dispatcher_host_.get());
915 #endif
917 AddFilter(new TraceMessageFilter(GetID()));
918 AddFilter(new ResolveProxyMsgHelper(
919 browser_context->GetRequestContextForRenderProcess(GetID())));
920 AddFilter(new QuotaDispatcherHost(
921 GetID(),
922 storage_partition_impl_->GetQuotaManager(),
923 GetContentClient()->browser()->CreateQuotaPermissionContext()));
925 notification_message_filter_ = new NotificationMessageFilter(
926 GetID(),
927 storage_partition_impl_->GetPlatformNotificationContext(),
928 resource_context,
929 browser_context);
930 AddFilter(notification_message_filter_.get());
932 AddFilter(new GamepadBrowserMessageFilter());
933 AddFilter(new DeviceLightMessageFilter());
934 AddFilter(new DeviceMotionMessageFilter());
935 AddFilter(new DeviceOrientationMessageFilter());
936 AddFilter(new ProfilerMessageFilter(PROCESS_TYPE_RENDERER));
937 AddFilter(new HistogramMessageFilter());
938 #if defined(USE_TCMALLOC) && (defined(OS_LINUX) || defined(OS_ANDROID))
939 if (browser_command_line.HasSwitch(switches::kEnableMemoryBenchmarking))
940 AddFilter(new MemoryBenchmarkMessageFilter());
941 #endif
942 AddFilter(new PushMessagingMessageFilter(
943 GetID(), storage_partition_impl_->GetServiceWorkerContext()));
944 #if defined(OS_ANDROID)
945 AddFilter(new ScreenOrientationMessageFilterAndroid());
946 #endif
947 AddFilter(new GeofencingDispatcherHost(
948 storage_partition_impl_->GetGeofencingManager()));
949 if (browser_command_line.HasSwitch(switches::kEnableWebBluetooth)) {
950 bluetooth_dispatcher_host_ = new BluetoothDispatcherHost(GetID());
951 AddFilter(bluetooth_dispatcher_host_.get());
955 void RenderProcessHostImpl::RegisterMojoServices() {
956 mojo_application_host_->service_registry()->AddService(
957 base::Bind(&device::BatteryMonitorImpl::Create));
959 #if !defined(OS_ANDROID)
960 mojo_application_host_->service_registry()->AddService(
961 base::Bind(&device::VibrationManagerImpl::Create));
962 #endif
964 mojo_application_host_->service_registry()->AddService(
965 base::Bind(&PermissionServiceContext::CreateService,
966 base::Unretained(permission_service_context_.get())));
968 mojo_application_host_->service_registry()->AddService(base::Bind(
969 &BackgroundSyncContextImpl::CreateService,
970 base::Unretained(storage_partition_impl_->GetBackgroundSyncContext())));
972 mojo_application_host_->service_registry()->AddService(base::Bind(
973 &content::ServicePortServiceImpl::Create,
974 make_scoped_refptr(storage_partition_impl_->GetNavigatorConnectContext()),
975 message_port_message_filter_));
977 #if defined(OS_ANDROID)
978 ServiceRegistrarAndroid::RegisterProcessHostServices(
979 mojo_application_host_->service_registry_android());
980 #endif
982 GetContentClient()->browser()->RegisterRenderProcessMojoServices(
983 mojo_application_host_->service_registry());
986 int RenderProcessHostImpl::GetNextRoutingID() {
987 return widget_helper_->GetNextRoutingID();
990 void RenderProcessHostImpl::ResumeDeferredNavigation(
991 const GlobalRequestID& request_id) {
992 widget_helper_->ResumeDeferredNavigation(request_id);
995 void RenderProcessHostImpl::NotifyTimezoneChange(const std::string& zone_id) {
996 Send(new ViewMsg_TimezoneChange(zone_id));
999 ServiceRegistry* RenderProcessHostImpl::GetServiceRegistry() {
1000 DCHECK(mojo_application_host_);
1001 return mojo_application_host_->service_registry();
1004 const base::TimeTicks& RenderProcessHostImpl::GetInitTimeForNavigationMetrics()
1005 const {
1006 return init_time_;
1009 bool RenderProcessHostImpl::SubscribeUniformEnabled() const {
1010 return subscribe_uniform_enabled_;
1013 void RenderProcessHostImpl::OnAddSubscription(unsigned int target) {
1014 DCHECK(subscribe_uniform_enabled_);
1015 subscription_set_.insert(target);
1016 const gpu::ValueState* state = pending_valuebuffer_state_->GetState(target);
1017 if (state) {
1018 SendUpdateValueState(target, *state);
1022 void RenderProcessHostImpl::OnRemoveSubscription(unsigned int target) {
1023 DCHECK(subscribe_uniform_enabled_);
1024 subscription_set_.erase(target);
1027 void RenderProcessHostImpl::SendUpdateValueState(unsigned int target,
1028 const gpu::ValueState& state) {
1029 DCHECK(subscribe_uniform_enabled_);
1030 if (subscription_set_.find(target) != subscription_set_.end()) {
1031 GpuProcessHost::SendOnIO(
1032 GpuProcessHost::GPU_PROCESS_KIND_SANDBOXED,
1033 CAUSE_FOR_GPU_LAUNCH_NO_LAUNCH,
1034 new GpuMsg_UpdateValueState(id_, target, state));
1035 } else {
1036 // Store the ValueState locally in case a Valuebuffer subscribes to it later
1037 pending_valuebuffer_state_->UpdateState(target, state);
1041 #if defined(ENABLE_BROWSER_CDMS)
1042 media::BrowserCdm* RenderProcessHostImpl::GetBrowserCdm(int render_frame_id,
1043 int cdm_id) const {
1044 DCHECK_CURRENTLY_ON(BrowserThread::UI);
1045 BrowserCdmManager* manager = BrowserCdmManager::FromProcess(GetID());
1046 if (!manager)
1047 return nullptr;
1048 return manager->GetCdm(render_frame_id, cdm_id);
1050 #endif
1052 void RenderProcessHostImpl::AddRoute(
1053 int32 routing_id,
1054 IPC::Listener* listener) {
1055 CHECK(!listeners_.Lookup(routing_id))
1056 << "Found Routing ID Conflict: " << routing_id;
1057 listeners_.AddWithID(listener, routing_id);
1060 void RenderProcessHostImpl::RemoveRoute(int32 routing_id) {
1061 DCHECK(listeners_.Lookup(routing_id) != NULL);
1062 listeners_.Remove(routing_id);
1064 // Keep the one renderer thread around forever in single process mode.
1065 if (!run_renderer_in_process())
1066 Cleanup();
1069 void RenderProcessHostImpl::AddObserver(RenderProcessHostObserver* observer) {
1070 observers_.AddObserver(observer);
1073 void RenderProcessHostImpl::RemoveObserver(
1074 RenderProcessHostObserver* observer) {
1075 observers_.RemoveObserver(observer);
1078 void RenderProcessHostImpl::ShutdownForBadMessage() {
1079 base::CommandLine* command_line = base::CommandLine::ForCurrentProcess();
1080 if (command_line->HasSwitch(switches::kDisableKillAfterBadIPC))
1081 return;
1083 if (run_renderer_in_process()) {
1084 // In single process mode it is better if we don't suicide but just
1085 // crash.
1086 CHECK(false);
1088 // We kill the renderer but don't include a NOTREACHED, because we want the
1089 // browser to try to survive when it gets illegal messages from the renderer.
1090 Shutdown(RESULT_CODE_KILLED_BAD_MESSAGE, false);
1093 void RenderProcessHostImpl::WidgetRestored() {
1094 // Verify we were properly backgrounded.
1095 DCHECK_EQ(backgrounded_, (visible_widgets_ == 0));
1096 visible_widgets_++;
1097 SetBackgrounded(false);
1100 void RenderProcessHostImpl::WidgetHidden() {
1101 // On startup, the browser will call Hide
1102 if (backgrounded_)
1103 return;
1105 DCHECK_EQ(backgrounded_, (visible_widgets_ == 0));
1106 visible_widgets_--;
1107 DCHECK_GE(visible_widgets_, 0);
1108 if (visible_widgets_ == 0) {
1109 DCHECK(!backgrounded_);
1110 SetBackgrounded(true);
1114 int RenderProcessHostImpl::VisibleWidgetCount() const {
1115 return visible_widgets_;
1118 bool RenderProcessHostImpl::IsForGuestsOnly() const {
1119 return is_for_guests_only_;
1122 StoragePartition* RenderProcessHostImpl::GetStoragePartition() const {
1123 return storage_partition_impl_;
1126 static void AppendCompositorCommandLineFlags(base::CommandLine* command_line) {
1127 if (IsPropertyTreeVerificationEnabled())
1128 command_line->AppendSwitch(cc::switches::kEnablePropertyTreeVerification);
1130 if (IsDelegatedRendererEnabled())
1131 command_line->AppendSwitch(switches::kEnableDelegatedRenderer);
1133 command_line->AppendSwitchASCII(
1134 switches::kNumRasterThreads,
1135 base::IntToString(NumberOfRendererRasterThreads()));
1137 if (IsGpuRasterizationEnabled())
1138 command_line->AppendSwitch(switches::kEnableGpuRasterization);
1140 int msaa_sample_count = GpuRasterizationMSAASampleCount();
1141 if (msaa_sample_count >= 0) {
1142 command_line->AppendSwitchASCII(
1143 switches::kGpuRasterizationMSAASampleCount,
1144 base::IntToString(msaa_sample_count));
1147 DCHECK_IMPLIES(IsZeroCopyUploadEnabled(), !IsOneCopyUploadEnabled());
1148 DCHECK_IMPLIES(IsOneCopyUploadEnabled(), !IsZeroCopyUploadEnabled());
1149 if (IsZeroCopyUploadEnabled())
1150 command_line->AppendSwitch(switches::kEnableZeroCopy);
1151 if (!IsOneCopyUploadEnabled())
1152 command_line->AppendSwitch(switches::kDisableOneCopy);
1153 if (IsPersistentGpuMemoryBufferEnabled())
1154 command_line->AppendSwitch(switches::kEnablePersistentGpuMemoryBuffer);
1156 if (IsForceGpuRasterizationEnabled())
1157 command_line->AppendSwitch(switches::kForceGpuRasterization);
1159 gfx::BufferUsage buffer_usage = IsPersistentGpuMemoryBufferEnabled()
1160 ? gfx::BufferUsage::PERSISTENT_MAP
1161 : gfx::BufferUsage::MAP;
1162 std::vector<unsigned> image_targets(
1163 static_cast<size_t>(gfx::BufferFormat::LAST) + 1, GL_TEXTURE_2D);
1164 for (size_t format = 0;
1165 format < static_cast<size_t>(gfx::BufferFormat::LAST) + 1; format++) {
1166 image_targets[format] =
1167 BrowserGpuMemoryBufferManager::GetImageTextureTarget(
1168 static_cast<gfx::BufferFormat>(format), buffer_usage);
1170 command_line->AppendSwitchASCII(switches::kContentImageTextureTarget,
1171 UintVectorToString(image_targets));
1173 command_line->AppendSwitchASCII(
1174 switches::kVideoImageTextureTarget,
1175 base::UintToString(BrowserGpuMemoryBufferManager::GetImageTextureTarget(
1176 gfx::BufferFormat::R_8, gfx::BufferUsage::MAP)));
1178 // Appending disable-gpu-feature switches due to software rendering list.
1179 GpuDataManagerImpl* gpu_data_manager = GpuDataManagerImpl::GetInstance();
1180 DCHECK(gpu_data_manager);
1181 gpu_data_manager->AppendRendererCommandLine(command_line);
1184 void RenderProcessHostImpl::AppendRendererCommandLine(
1185 base::CommandLine* command_line) const {
1186 // Pass the process type first, so it shows first in process listings.
1187 command_line->AppendSwitchASCII(switches::kProcessType,
1188 switches::kRendererProcess);
1190 // Now send any options from our own command line we want to propagate.
1191 const base::CommandLine& browser_command_line =
1192 *base::CommandLine::ForCurrentProcess();
1193 PropagateBrowserCommandLineToRenderer(browser_command_line, command_line);
1195 // Pass on the browser locale.
1196 const std::string locale =
1197 GetContentClient()->browser()->GetApplicationLocale();
1198 command_line->AppendSwitchASCII(switches::kLang, locale);
1200 // If we run base::FieldTrials, we want to pass to their state to the
1201 // renderer so that it can act in accordance with each state, or record
1202 // histograms relating to the base::FieldTrial states.
1203 std::string field_trial_states;
1204 base::FieldTrialList::AllStatesToString(&field_trial_states);
1205 if (!field_trial_states.empty()) {
1206 command_line->AppendSwitchASCII(switches::kForceFieldTrials,
1207 field_trial_states);
1210 GetContentClient()->browser()->AppendExtraCommandLineSwitches(
1211 command_line, GetID());
1213 if (IsPinchToZoomEnabled())
1214 command_line->AppendSwitch(switches::kEnablePinch);
1216 #if defined(OS_WIN)
1217 command_line->AppendSwitchASCII(switches::kDeviceScaleFactor,
1218 base::DoubleToString(gfx::GetDPIScale()));
1219 #endif
1221 AppendCompositorCommandLineFlags(command_line);
1224 void RenderProcessHostImpl::PropagateBrowserCommandLineToRenderer(
1225 const base::CommandLine& browser_cmd,
1226 base::CommandLine* renderer_cmd) const {
1227 // Propagate the following switches to the renderer command line (along
1228 // with any associated values) if present in the browser command line.
1229 static const char* const kSwitchNames[] = {
1230 switches::kAllowLoopbackInPeerConnection,
1231 switches::kAudioBufferSize,
1232 switches::kBlinkPlatformLogChannels,
1233 switches::kBlinkSettings,
1234 switches::kDefaultTileWidth,
1235 switches::kDefaultTileHeight,
1236 switches::kDisable3DAPIs,
1237 switches::kDisableAcceleratedJpegDecoding,
1238 switches::kDisableAcceleratedVideoDecode,
1239 switches::kDisableBlinkFeatures,
1240 switches::kDisableBreakpad,
1241 switches::kDisablePreferCompositingToLCDText,
1242 switches::kDisableDatabases,
1243 switches::kDisableDelayAgnosticAec,
1244 switches::kDisableDirectNPAPIRequests,
1245 switches::kDisableDisplayList2dCanvas,
1246 switches::kDisableDistanceFieldText,
1247 switches::kDisableEncryptedMedia,
1248 switches::kDisableFileSystem,
1249 switches::kDisableGpuCompositing,
1250 switches::kDisableGpuVsync,
1251 switches::kDisableLowResTiling,
1252 switches::kDisableHistogramCustomizer,
1253 switches::kDisableIconNtp,
1254 switches::kDisableLCDText,
1255 switches::kDisableLocalStorage,
1256 switches::kDisableLogging,
1257 switches::kDisableMediaSource,
1258 switches::kDisableMojoChannel,
1259 switches::kDisableNewVideoRenderer,
1260 switches::kDisableNotifications,
1261 switches::kDisableOverlayScrollbar,
1262 switches::kDisablePermissionsAPI,
1263 switches::kDisablePresentationAPI,
1264 switches::kDisablePinch,
1265 switches::kDisablePrefixedEncryptedMedia,
1266 switches::kDisableRGBA4444Textures,
1267 switches::kDisableSeccompFilterSandbox,
1268 switches::kDisableSharedWorkers,
1269 switches::kDisableSlimmingPaint,
1270 switches::kDisableSpeechAPI,
1271 switches::kDisableSVG1DOM,
1272 switches::kDisableThreadedCompositing,
1273 switches::kDisableThreadedScrolling,
1274 switches::kDisableTouchAdjustment,
1275 switches::kDisableTouchDragDrop,
1276 switches::kDisableTouchEditing,
1277 switches::kDisableV8IdleTasks,
1278 switches::kDomAutomationController,
1279 switches::kEnableBleedingEdgeRenderingFastPaths,
1280 switches::kEnableBlinkFeatures,
1281 switches::kEnableBrowserSideNavigation,
1282 switches::kEnableCompositorAnimationTimelines,
1283 switches::kEnableCredentialManagerAPI,
1284 switches::kEnableDelayAgnosticAec,
1285 switches::kEnableDisplayList2dCanvas,
1286 switches::kEnableDistanceFieldText,
1287 switches::kEnableExperimentalCanvasFeatures,
1288 switches::kEnableExperimentalWebPlatformFeatures,
1289 switches::kEnableGPUClientLogging,
1290 switches::kEnableGpuClientTracing,
1291 switches::kEnableGpuMemoryBufferVideoFrames,
1292 switches::kEnableGPUServiceLogging,
1293 switches::kEnableIconNtp,
1294 switches::kEnableLinkDisambiguationPopup,
1295 switches::kEnableLowResTiling,
1296 switches::kEnableInbandTextTracks,
1297 switches::kEnableLCDText,
1298 switches::kEnableLogging,
1299 switches::kEnableMemoryBenchmarking,
1300 switches::kEnableNetworkInformation,
1301 switches::kEnableOverlayFullscreenVideo,
1302 switches::kEnableOverlayScrollbar,
1303 switches::kEnablePinch,
1304 switches::kEnablePluginPlaceholderTesting,
1305 switches::kEnablePreciseMemoryInfo,
1306 switches::kEnablePreferCompositingToLCDText,
1307 switches::kEnablePushMessagePayload,
1308 switches::kEnableRGBA4444Textures,
1309 switches::kEnableRendererMojoChannel,
1310 switches::kEnableRTCSmoothnessAlgorithm,
1311 switches::kEnableSeccompFilterSandbox,
1312 switches::kEnableSkiaBenchmarking,
1313 switches::kEnableSlimmingPaint,
1314 switches::kEnableSlimmingPaintV2,
1315 switches::kEnableSmoothScrolling,
1316 switches::kEnableStaleWhileRevalidate,
1317 switches::kEnableStatsTable,
1318 switches::kEnableThreadedCompositing,
1319 switches::kEnableTouchDragDrop,
1320 switches::kEnableTouchEditing,
1321 switches::kEnableUnsafeES3APIs,
1322 switches::kEnableViewport,
1323 switches::kEnableViewportMeta,
1324 switches::kInvertViewportScrollOrder,
1325 switches::kEnableVtune,
1326 switches::kEnableWebBluetooth,
1327 switches::kEnableWebGLDraftExtensions,
1328 switches::kEnableWebGLImageChromium,
1329 switches::kEnableWebVR,
1330 switches::kExplicitlyAllowedPorts,
1331 switches::kForceDeviceScaleFactor,
1332 switches::kForceDisplayList2dCanvas,
1333 switches::kForceOverlayFullscreenVideo,
1334 switches::kFullMemoryCrashReport,
1335 switches::kIPCConnectionTimeout,
1336 switches::kJavaScriptFlags,
1337 switches::kLoggingLevel,
1338 switches::kMainFrameResizesAreOrientationChanges,
1339 switches::kMaxUntiledLayerWidth,
1340 switches::kMaxUntiledLayerHeight,
1341 switches::kMemoryMetrics,
1342 switches::kNoReferrers,
1343 switches::kNoSandbox,
1344 switches::kOverridePluginPowerSaverForTesting,
1345 switches::kPpapiInProcess,
1346 switches::kProfilerTiming,
1347 switches::kReducedReferrerGranularity,
1348 switches::kReduceSecurityForTesting,
1349 switches::kRegisterPepperPlugins,
1350 switches::kRendererStartupDialog,
1351 switches::kRootLayerScrolls,
1352 switches::kShowPaintRects,
1353 switches::kSitePerProcess,
1354 switches::kStatsCollectionController,
1355 switches::kTestType,
1356 switches::kTouchEvents,
1357 switches::kTouchTextSelectionStrategy,
1358 switches::kTraceToConsole,
1359 // This flag needs to be propagated to the renderer process for
1360 // --in-process-webgl.
1361 switches::kUseGL,
1362 switches::kUseMobileUserAgent,
1363 switches::kUseNormalPriorityForTileTaskWorkerThreads,
1364 switches::kV,
1365 switches::kVideoThreads,
1366 switches::kVideoUnderflowThresholdMs,
1367 switches::kVModule,
1368 // Please keep these in alphabetical order. Compositor switches here should
1369 // also be added to chrome/browser/chromeos/login/chrome_restart_request.cc.
1370 cc::switches::kCompositeToMailbox,
1371 cc::switches::kDisableCompositedAntialiasing,
1372 cc::switches::kDisableMainFrameBeforeActivation,
1373 cc::switches::kDisableThreadedAnimation,
1374 cc::switches::kEnableBeginFrameScheduling,
1375 cc::switches::kEnableGpuBenchmarking,
1376 cc::switches::kEnableMainFrameBeforeActivation,
1377 cc::switches::kShowCompositedLayerBorders,
1378 cc::switches::kShowFPSCounter,
1379 cc::switches::kShowLayerAnimationBounds,
1380 cc::switches::kShowPropertyChangedRects,
1381 cc::switches::kShowReplicaScreenSpaceRects,
1382 cc::switches::kShowScreenSpaceRects,
1383 cc::switches::kShowSurfaceDamageRects,
1384 cc::switches::kSlowDownRasterScaleFactor,
1385 cc::switches::kStrictLayerPropertyChangeChecking,
1386 cc::switches::kTopControlsHideThreshold,
1387 cc::switches::kTopControlsShowThreshold,
1389 #if defined(ENABLE_PLUGINS)
1390 switches::kEnablePepperTesting,
1391 #endif
1392 #if defined(ENABLE_WEBRTC)
1393 switches::kDisableWebRtcHWDecoding,
1394 switches::kDisableWebRtcHWEncoding,
1395 switches::kEnableWebRtcDtls12,
1396 switches::kEnableWebRtcHWH264Encoding,
1397 switches::kEnableWebRtcStunOrigin,
1398 switches::kWebRtcMaxCaptureFramerate,
1399 #endif
1400 switches::kEnableLowEndDeviceMode,
1401 switches::kDisableLowEndDeviceMode,
1402 #if defined(OS_ANDROID)
1403 switches::kDisableGestureRequirementForMediaPlayback,
1404 switches::kDisableWebAudio,
1405 switches::kRendererWaitForJavaDebugger,
1406 #endif
1407 #if defined(OS_MACOSX)
1408 // Allow this to be set when invoking the browser and relayed along.
1409 switches::kEnableSandboxLogging,
1410 #endif
1411 #if defined(OS_WIN)
1412 switches::kDisableDirectWrite,
1413 switches::kDisableWin32kRendererLockDown,
1414 switches::kTraceExportEventsToETW,
1415 #endif
1416 #if defined(USE_OZONE)
1417 switches::kOzonePlatform,
1418 #endif
1419 #if defined(OS_CHROMEOS)
1420 switches::kDisableVaapiAcceleratedVideoEncode,
1421 #endif
1423 renderer_cmd->CopySwitchesFrom(browser_cmd, kSwitchNames,
1424 arraysize(kSwitchNames));
1426 if (browser_cmd.HasSwitch(switches::kTraceStartup) &&
1427 BrowserMainLoop::GetInstance()->is_tracing_startup()) {
1428 // Pass kTraceStartup switch to renderer only if startup tracing has not
1429 // finished.
1430 renderer_cmd->AppendSwitchASCII(
1431 switches::kTraceStartup,
1432 browser_cmd.GetSwitchValueASCII(switches::kTraceStartup));
1435 #if defined(ENABLE_WEBRTC)
1436 // Only run the Stun trials in the first renderer.
1437 if (!has_done_stun_trials &&
1438 browser_cmd.HasSwitch(switches::kWebRtcStunProbeTrialParameter)) {
1439 has_done_stun_trials = true;
1440 renderer_cmd->AppendSwitchASCII(
1441 switches::kWebRtcStunProbeTrialParameter,
1442 browser_cmd.GetSwitchValueASCII(
1443 switches::kWebRtcStunProbeTrialParameter));
1445 #endif
1447 // Disable databases in incognito mode.
1448 if (GetBrowserContext()->IsOffTheRecord() &&
1449 !browser_cmd.HasSwitch(switches::kDisableDatabases)) {
1450 renderer_cmd->AppendSwitch(switches::kDisableDatabases);
1453 // Add kWaitForDebugger to let renderer process wait for a debugger.
1454 if (browser_cmd.HasSwitch(switches::kWaitForDebuggerChildren)) {
1455 // Look to pass-on the kWaitForDebugger flag.
1456 std::string value =
1457 browser_cmd.GetSwitchValueASCII(switches::kWaitForDebuggerChildren);
1458 if (value.empty() || value == switches::kRendererProcess) {
1459 renderer_cmd->AppendSwitch(switches::kWaitForDebugger);
1464 base::ProcessHandle RenderProcessHostImpl::GetHandle() const {
1465 if (run_renderer_in_process())
1466 return base::GetCurrentProcessHandle();
1468 if (!child_process_launcher_.get() || child_process_launcher_->IsStarting())
1469 return base::kNullProcessHandle;
1471 return child_process_launcher_->GetProcess().Handle();
1474 bool RenderProcessHostImpl::Shutdown(int exit_code, bool wait) {
1475 if (run_renderer_in_process())
1476 return false; // Single process mode never shuts down the renderer.
1478 #if defined(OS_ANDROID)
1479 // Android requires a different approach for killing.
1480 StopChildProcess(GetHandle());
1481 return true;
1482 #else
1483 if (!child_process_launcher_.get() || child_process_launcher_->IsStarting())
1484 return false;
1486 return child_process_launcher_->GetProcess().Terminate(exit_code, wait);
1487 #endif
1490 bool RenderProcessHostImpl::FastShutdownIfPossible() {
1491 if (run_renderer_in_process())
1492 return false; // Single process mode never shuts down the renderer.
1494 if (!GetContentClient()->browser()->IsFastShutdownPossible())
1495 return false;
1497 if (!child_process_launcher_.get() ||
1498 child_process_launcher_->IsStarting() ||
1499 !GetHandle())
1500 return false; // Render process hasn't started or is probably crashed.
1502 // Test if there's an unload listener.
1503 // NOTE: It's possible that an onunload listener may be installed
1504 // while we're shutting down, so there's a small race here. Given that
1505 // the window is small, it's unlikely that the web page has much
1506 // state that will be lost by not calling its unload handlers properly.
1507 if (!SuddenTerminationAllowed())
1508 return false;
1510 if (worker_ref_count_ != 0) {
1511 if (survive_for_worker_start_time_.is_null())
1512 survive_for_worker_start_time_ = base::TimeTicks::Now();
1513 return false;
1516 // Set this before ProcessDied() so observers can tell if the render process
1517 // died due to fast shutdown versus another cause.
1518 fast_shutdown_started_ = true;
1520 ProcessDied(false /* already_dead */, nullptr);
1521 return true;
1524 bool RenderProcessHostImpl::Send(IPC::Message* msg) {
1525 TRACE_EVENT0("renderer_host", "RenderProcessHostImpl::Send");
1526 if (!channel_) {
1527 if (!is_initialized_) {
1528 queued_messages_.push(msg);
1529 return true;
1530 } else {
1531 delete msg;
1532 return false;
1536 if (child_process_launcher_.get() && child_process_launcher_->IsStarting()) {
1537 queued_messages_.push(msg);
1538 return true;
1541 return channel_->Send(msg);
1544 bool RenderProcessHostImpl::OnMessageReceived(const IPC::Message& msg) {
1545 // If we're about to be deleted, or have initiated the fast shutdown sequence,
1546 // we ignore incoming messages.
1548 if (deleting_soon_ || fast_shutdown_started_)
1549 return false;
1551 mark_child_process_activity_time();
1552 if (msg.routing_id() == MSG_ROUTING_CONTROL) {
1553 // Dispatch control messages.
1554 IPC_BEGIN_MESSAGE_MAP(RenderProcessHostImpl, msg)
1555 IPC_MESSAGE_HANDLER(ChildProcessHostMsg_ShutdownRequest,
1556 OnShutdownRequest)
1557 IPC_MESSAGE_HANDLER(ViewHostMsg_SuddenTerminationChanged,
1558 SuddenTerminationChanged)
1559 IPC_MESSAGE_HANDLER(ViewHostMsg_UserMetricsRecordAction,
1560 OnUserMetricsRecordAction)
1561 IPC_MESSAGE_HANDLER(ViewHostMsg_SavedPageAsMHTML, OnSavedPageAsMHTML)
1562 IPC_MESSAGE_HANDLER(ViewHostMsg_Close_ACK, OnCloseACK)
1563 #if defined(ENABLE_WEBRTC)
1564 IPC_MESSAGE_HANDLER(AecDumpMsg_RegisterAecDumpConsumer,
1565 OnRegisterAecDumpConsumer)
1566 IPC_MESSAGE_HANDLER(AecDumpMsg_UnregisterAecDumpConsumer,
1567 OnUnregisterAecDumpConsumer)
1568 #endif
1569 // Adding single handlers for your service here is fine, but once your
1570 // service needs more than one handler, please extract them into a new
1571 // message filter and add that filter to CreateMessageFilters().
1572 IPC_END_MESSAGE_MAP()
1574 return true;
1577 // Dispatch incoming messages to the appropriate IPC::Listener.
1578 IPC::Listener* listener = listeners_.Lookup(msg.routing_id());
1579 if (!listener) {
1580 if (msg.is_sync()) {
1581 // The listener has gone away, so we must respond or else the caller will
1582 // hang waiting for a reply.
1583 IPC::Message* reply = IPC::SyncMessage::GenerateReply(&msg);
1584 reply->set_reply_error();
1585 Send(reply);
1587 return true;
1589 return listener->OnMessageReceived(msg);
1592 void RenderProcessHostImpl::OnChannelConnected(int32 peer_pid) {
1593 #if defined(IPC_MESSAGE_LOG_ENABLED)
1594 Send(new ChildProcessMsg_SetIPCLoggingEnabled(
1595 IPC::Logging::GetInstance()->Enabled()));
1596 #endif
1598 tracked_objects::ThreadData::Status status =
1599 tracked_objects::ThreadData::status();
1600 Send(new ChildProcessMsg_SetProfilerStatus(status));
1602 #if defined(OS_MACOSX) && !defined(OS_IOS)
1603 io_surface_manager_token_ =
1604 BrowserIOSurfaceManager::GetInstance()->GenerateChildProcessToken(
1605 GetID());
1606 Send(new ChildProcessMsg_SetIOSurfaceManagerToken(io_surface_manager_token_));
1607 #endif
1610 void RenderProcessHostImpl::OnChannelError() {
1611 ProcessDied(true /* already_dead */, nullptr);
1614 void RenderProcessHostImpl::OnBadMessageReceived(const IPC::Message& message) {
1615 // Message de-serialization failed. We consider this a capital crime. Kill the
1616 // renderer if we have one.
1617 LOG(ERROR) << "bad message " << message.type() << " terminating renderer.";
1618 BrowserChildProcessHostImpl::HistogramBadMessageTerminated(
1619 PROCESS_TYPE_RENDERER);
1621 // Create a memory dump. This will contain enough stack frames to work out
1622 // what the bad message was.
1623 base::debug::DumpWithoutCrashing();
1625 bad_message::ReceivedBadMessage(this,
1626 bad_message::RPH_DESERIALIZATION_FAILED);
1629 BrowserContext* RenderProcessHostImpl::GetBrowserContext() const {
1630 return browser_context_;
1633 bool RenderProcessHostImpl::InSameStoragePartition(
1634 StoragePartition* partition) const {
1635 return storage_partition_impl_ == partition;
1638 int RenderProcessHostImpl::GetID() const {
1639 return id_;
1642 bool RenderProcessHostImpl::HasConnection() const {
1643 return channel_.get() != NULL;
1646 void RenderProcessHostImpl::SetIgnoreInputEvents(bool ignore_input_events) {
1647 ignore_input_events_ = ignore_input_events;
1650 bool RenderProcessHostImpl::IgnoreInputEvents() const {
1651 return ignore_input_events_;
1654 void RenderProcessHostImpl::Cleanup() {
1655 // If within_process_died_observer_ is true, one of our observers performed an
1656 // action that caused us to die (e.g. http://crbug.com/339504). Therefore,
1657 // delay the destruction until all of the observer callbacks have been made,
1658 // and guarantee that the RenderProcessHostDestroyed observer callback is
1659 // always the last callback fired.
1660 if (within_process_died_observer_) {
1661 delayed_cleanup_needed_ = true;
1662 return;
1664 delayed_cleanup_needed_ = false;
1666 // Records the time when the process starts surviving for workers for UMA.
1667 if (listeners_.IsEmpty() && worker_ref_count_ > 0 &&
1668 survive_for_worker_start_time_.is_null()) {
1669 survive_for_worker_start_time_ = base::TimeTicks::Now();
1672 // When there are no other owners of this object, we can delete ourselves.
1673 if (listeners_.IsEmpty() && worker_ref_count_ == 0) {
1674 if (!survive_for_worker_start_time_.is_null()) {
1675 UMA_HISTOGRAM_LONG_TIMES(
1676 "SharedWorker.RendererSurviveForWorkerTime",
1677 base::TimeTicks::Now() - survive_for_worker_start_time_);
1680 if (max_worker_count_ > 0) {
1681 // Record the max number of workers (SharedWorker or ServiceWorker)
1682 // that are simultaneously hosted in this renderer process.
1683 UMA_HISTOGRAM_COUNTS("Render.Workers.MaxWorkerCountInRendererProcess",
1684 max_worker_count_);
1687 // We cannot clean up twice; if this fails, there is an issue with our
1688 // control flow.
1689 DCHECK(!deleting_soon_);
1691 DCHECK_EQ(0, pending_views_);
1692 FOR_EACH_OBSERVER(RenderProcessHostObserver,
1693 observers_,
1694 RenderProcessHostDestroyed(this));
1695 NotificationService::current()->Notify(
1696 NOTIFICATION_RENDERER_PROCESS_TERMINATED,
1697 Source<RenderProcessHost>(this),
1698 NotificationService::NoDetails());
1700 #ifndef NDEBUG
1701 is_self_deleted_ = true;
1702 #endif
1703 base::MessageLoop::current()->DeleteSoon(FROM_HERE, this);
1704 deleting_soon_ = true;
1705 // It's important not to wait for the DeleteTask to delete the channel
1706 // proxy. Kill it off now. That way, in case the profile is going away, the
1707 // rest of the objects attached to this RenderProcessHost start going
1708 // away first, since deleting the channel proxy will post a
1709 // OnChannelClosed() to IPC::ChannelProxy::Context on the IO thread.
1710 channel_.reset();
1712 // The following members should be cleared in ProcessDied() as well!
1713 gpu_message_filter_ = NULL;
1714 message_port_message_filter_ = NULL;
1716 RemoveUserData(kSessionStorageHolderKey);
1718 // Remove ourself from the list of renderer processes so that we can't be
1719 // reused in between now and when the Delete task runs.
1720 UnregisterHost(GetID());
1722 #if defined(OS_MACOSX) && !defined(OS_IOS)
1723 if (!io_surface_manager_token_.IsZero()) {
1724 BrowserIOSurfaceManager::GetInstance()->InvalidateChildProcessToken(
1725 io_surface_manager_token_);
1726 io_surface_manager_token_.SetZero();
1728 #endif
1733 void RenderProcessHostImpl::AddPendingView() {
1734 pending_views_++;
1737 void RenderProcessHostImpl::RemovePendingView() {
1738 DCHECK(pending_views_);
1739 pending_views_--;
1742 void RenderProcessHostImpl::SetSuddenTerminationAllowed(bool enabled) {
1743 sudden_termination_allowed_ = enabled;
1746 bool RenderProcessHostImpl::SuddenTerminationAllowed() const {
1747 return sudden_termination_allowed_;
1750 base::TimeDelta RenderProcessHostImpl::GetChildProcessIdleTime() const {
1751 return base::TimeTicks::Now() - child_process_activity_time_;
1754 void RenderProcessHostImpl::ResumeRequestsForView(int route_id) {
1755 widget_helper_->ResumeRequestsForView(route_id);
1758 void RenderProcessHostImpl::FilterURL(bool empty_allowed, GURL* url) {
1759 FilterURL(this, empty_allowed, url);
1762 #if defined(ENABLE_WEBRTC)
1763 void RenderProcessHostImpl::EnableAecDump(const base::FilePath& file) {
1764 DCHECK_CURRENTLY_ON(BrowserThread::UI);
1765 // Enable AEC dump for each registered consumer.
1766 for (std::vector<int>::iterator it = aec_dump_consumers_.begin();
1767 it != aec_dump_consumers_.end(); ++it) {
1768 EnableAecDumpForId(file, *it);
1772 void RenderProcessHostImpl::DisableAecDump() {
1773 DCHECK_CURRENTLY_ON(BrowserThread::UI);
1774 // Posting on the FILE thread and then replying back on the UI thread is only
1775 // for avoiding races between enable and disable. Nothing is done on the FILE
1776 // thread.
1777 BrowserThread::PostTaskAndReply(
1778 BrowserThread::FILE, FROM_HERE,
1779 base::Bind(&DisableAecDumpOnFileThread),
1780 base::Bind(&RenderProcessHostImpl::SendDisableAecDumpToRenderer,
1781 weak_factory_.GetWeakPtr()));
1784 void RenderProcessHostImpl::SetWebRtcLogMessageCallback(
1785 base::Callback<void(const std::string&)> callback) {
1786 webrtc_log_message_callback_ = callback;
1789 RenderProcessHostImpl::WebRtcStopRtpDumpCallback
1790 RenderProcessHostImpl::StartRtpDump(
1791 bool incoming,
1792 bool outgoing,
1793 const WebRtcRtpPacketCallback& packet_callback) {
1794 if (!p2p_socket_dispatcher_host_.get())
1795 return WebRtcStopRtpDumpCallback();
1797 BrowserThread::PostTask(BrowserThread::IO,
1798 FROM_HERE,
1799 base::Bind(&P2PSocketDispatcherHost::StartRtpDump,
1800 p2p_socket_dispatcher_host_,
1801 incoming,
1802 outgoing,
1803 packet_callback));
1805 if (stop_rtp_dump_callback_.is_null()) {
1806 stop_rtp_dump_callback_ =
1807 base::Bind(&P2PSocketDispatcherHost::StopRtpDumpOnUIThread,
1808 p2p_socket_dispatcher_host_);
1810 return stop_rtp_dump_callback_;
1812 #endif
1814 IPC::ChannelProxy* RenderProcessHostImpl::GetChannel() {
1815 return channel_.get();
1818 void RenderProcessHostImpl::AddFilter(BrowserMessageFilter* filter) {
1819 channel_->AddFilter(filter->GetFilter());
1822 bool RenderProcessHostImpl::FastShutdownForPageCount(size_t count) {
1823 if (static_cast<size_t>(GetActiveViewCount()) == count)
1824 return FastShutdownIfPossible();
1825 return false;
1828 bool RenderProcessHostImpl::FastShutdownStarted() const {
1829 return fast_shutdown_started_;
1832 // static
1833 void RenderProcessHostImpl::RegisterHost(int host_id, RenderProcessHost* host) {
1834 g_all_hosts.Get().AddWithID(host, host_id);
1837 // static
1838 void RenderProcessHostImpl::UnregisterHost(int host_id) {
1839 RenderProcessHost* host = g_all_hosts.Get().Lookup(host_id);
1840 if (!host)
1841 return;
1843 g_all_hosts.Get().Remove(host_id);
1845 // Look up the map of site to process for the given browser_context,
1846 // in case we need to remove this process from it. It will be registered
1847 // under any sites it rendered that use process-per-site mode.
1848 SiteProcessMap* map =
1849 GetSiteProcessMapForBrowserContext(host->GetBrowserContext());
1850 map->RemoveProcess(host);
1853 // static
1854 void RenderProcessHostImpl::FilterURL(RenderProcessHost* rph,
1855 bool empty_allowed,
1856 GURL* url) {
1857 ChildProcessSecurityPolicyImpl* policy =
1858 ChildProcessSecurityPolicyImpl::GetInstance();
1860 if (empty_allowed && url->is_empty())
1861 return;
1863 // The browser process should never hear the swappedout:// URL from any
1864 // of the renderer's messages. Check for this in debug builds, but don't
1865 // let it crash a release browser.
1866 DCHECK(GURL(kSwappedOutURL) != *url);
1868 if (!url->is_valid()) {
1869 // Have to use about:blank for the denied case, instead of an empty GURL.
1870 // This is because the browser treats navigation to an empty GURL as a
1871 // navigation to the home page. This is often a privileged page
1872 // (chrome://newtab/) which is exactly what we don't want.
1873 *url = GURL(url::kAboutBlankURL);
1874 return;
1877 if (url->SchemeIs(url::kAboutScheme)) {
1878 // The renderer treats all URLs in the about: scheme as being about:blank.
1879 // Canonicalize about: URLs to about:blank.
1880 *url = GURL(url::kAboutBlankURL);
1883 // Do not allow browser plugin guests to navigate to non-web URLs, since they
1884 // cannot swap processes or grant bindings.
1885 bool non_web_url_in_guest = rph->IsForGuestsOnly() &&
1886 !(url->is_valid() && policy->IsWebSafeScheme(url->scheme()));
1888 if (non_web_url_in_guest || !policy->CanRequestURL(rph->GetID(), *url)) {
1889 // If this renderer is not permitted to request this URL, we invalidate the
1890 // URL. This prevents us from storing the blocked URL and becoming confused
1891 // later.
1892 VLOG(1) << "Blocked URL " << url->spec();
1893 *url = GURL(url::kAboutBlankURL);
1897 // static
1898 bool RenderProcessHostImpl::IsSuitableHost(
1899 RenderProcessHost* host,
1900 BrowserContext* browser_context,
1901 const GURL& site_url) {
1902 if (run_renderer_in_process())
1903 return true;
1905 if (host->GetBrowserContext() != browser_context)
1906 return false;
1908 // Do not allow sharing of guest hosts. This is to prevent bugs where guest
1909 // and non-guest storage gets mixed. In the future, we might consider enabling
1910 // the sharing of guests, in this case this check should be removed and
1911 // InSameStoragePartition should handle the possible sharing.
1912 if (host->IsForGuestsOnly())
1913 return false;
1915 // Check whether the given host and the intended site_url will be using the
1916 // same StoragePartition, since a RenderProcessHost can only support a single
1917 // StoragePartition. This is relevant for packaged apps.
1918 StoragePartition* dest_partition =
1919 BrowserContext::GetStoragePartitionForSite(browser_context, site_url);
1920 if (!host->InSameStoragePartition(dest_partition))
1921 return false;
1923 // TODO(nick): Consult the SiteIsolationPolicy here. https://crbug.com/513036
1924 if (ChildProcessSecurityPolicyImpl::GetInstance()->HasWebUIBindings(
1925 host->GetID()) !=
1926 WebUIControllerFactoryRegistry::GetInstance()->UseWebUIBindingsForURL(
1927 browser_context, site_url)) {
1928 return false;
1931 return GetContentClient()->browser()->IsSuitableHost(host, site_url);
1934 // static
1935 bool RenderProcessHost::run_renderer_in_process() {
1936 return g_run_renderer_in_process_;
1939 // static
1940 void RenderProcessHost::SetRunRendererInProcess(bool value) {
1941 g_run_renderer_in_process_ = value;
1943 base::CommandLine* command_line = base::CommandLine::ForCurrentProcess();
1944 if (value) {
1945 if (!command_line->HasSwitch(switches::kLang)) {
1946 // Modify the current process' command line to include the browser locale,
1947 // as the renderer expects this flag to be set.
1948 const std::string locale =
1949 GetContentClient()->browser()->GetApplicationLocale();
1950 command_line->AppendSwitchASCII(switches::kLang, locale);
1952 // TODO(piman): we should really send configuration through bools rather
1953 // than by parsing strings, i.e. sending an IPC rather than command line
1954 // args. crbug.com/314909
1955 AppendCompositorCommandLineFlags(command_line);
1959 // static
1960 RenderProcessHost::iterator RenderProcessHost::AllHostsIterator() {
1961 DCHECK_CURRENTLY_ON(BrowserThread::UI);
1962 return iterator(g_all_hosts.Pointer());
1965 // static
1966 RenderProcessHost* RenderProcessHost::FromID(int render_process_id) {
1967 DCHECK_CURRENTLY_ON(BrowserThread::UI);
1968 return g_all_hosts.Get().Lookup(render_process_id);
1971 // static
1972 bool RenderProcessHost::ShouldTryToUseExistingProcessHost(
1973 BrowserContext* browser_context, const GURL& url) {
1974 // If --site-per-process is enabled, do not try to reuse renderer processes
1975 // when over the limit.
1976 // TODO(nick): This is overly conservative and isn't launchable. Move this
1977 // logic into IsSuitableHost, and check |url| against the URL the process is
1978 // dedicated to. This will allow pages from the same site to share, and will
1979 // also allow non-isolated sites to share processes. https://crbug.com/513036
1980 if (SiteIsolationPolicy::AreCrossProcessFramesPossible())
1981 return false;
1983 if (run_renderer_in_process())
1984 return true;
1986 // NOTE: Sometimes it's necessary to create more render processes than
1987 // GetMaxRendererProcessCount(), for instance when we want to create
1988 // a renderer process for a browser context that has no existing
1989 // renderers. This is OK in moderation, since the
1990 // GetMaxRendererProcessCount() is conservative.
1991 if (g_all_hosts.Get().size() >= GetMaxRendererProcessCount())
1992 return true;
1994 return GetContentClient()->browser()->
1995 ShouldTryToUseExistingProcessHost(browser_context, url);
1998 // static
1999 RenderProcessHost* RenderProcessHost::GetExistingProcessHost(
2000 BrowserContext* browser_context,
2001 const GURL& site_url) {
2002 // First figure out which existing renderers we can use.
2003 std::vector<RenderProcessHost*> suitable_renderers;
2004 suitable_renderers.reserve(g_all_hosts.Get().size());
2006 iterator iter(AllHostsIterator());
2007 while (!iter.IsAtEnd()) {
2008 if (GetContentClient()->browser()->MayReuseHost(iter.GetCurrentValue()) &&
2009 RenderProcessHostImpl::IsSuitableHost(
2010 iter.GetCurrentValue(),
2011 browser_context, site_url)) {
2012 suitable_renderers.push_back(iter.GetCurrentValue());
2014 iter.Advance();
2017 // Now pick a random suitable renderer, if we have any.
2018 if (!suitable_renderers.empty()) {
2019 int suitable_count = static_cast<int>(suitable_renderers.size());
2020 int random_index = base::RandInt(0, suitable_count - 1);
2021 return suitable_renderers[random_index];
2024 return NULL;
2027 // static
2028 bool RenderProcessHost::ShouldUseProcessPerSite(
2029 BrowserContext* browser_context,
2030 const GURL& url) {
2031 // Returns true if we should use the process-per-site model. This will be
2032 // the case if the --process-per-site switch is specified, or in
2033 // process-per-site-instance for particular sites (e.g., WebUI).
2034 // Note that --single-process is handled in ShouldTryToUseExistingProcessHost.
2035 const base::CommandLine& command_line =
2036 *base::CommandLine::ForCurrentProcess();
2037 if (command_line.HasSwitch(switches::kProcessPerSite))
2038 return true;
2040 // We want to consolidate particular sites like WebUI even when we are using
2041 // the process-per-tab or process-per-site-instance models.
2042 // Note: DevTools pages have WebUI type but should not reuse the same host.
2043 if (WebUIControllerFactoryRegistry::GetInstance()->UseWebUIForURL(
2044 browser_context, url) &&
2045 !url.SchemeIs(kChromeDevToolsScheme)) {
2046 return true;
2049 // Otherwise let the content client decide, defaulting to false.
2050 return GetContentClient()->browser()->ShouldUseProcessPerSite(browser_context,
2051 url);
2054 // static
2055 RenderProcessHost* RenderProcessHostImpl::GetProcessHostForSite(
2056 BrowserContext* browser_context,
2057 const GURL& url) {
2058 // Look up the map of site to process for the given browser_context.
2059 SiteProcessMap* map =
2060 GetSiteProcessMapForBrowserContext(browser_context);
2062 // See if we have an existing process with appropriate bindings for this site.
2063 // If not, the caller should create a new process and register it.
2064 std::string site = SiteInstance::GetSiteForURL(browser_context, url)
2065 .possibly_invalid_spec();
2066 RenderProcessHost* host = map->FindProcess(site);
2067 if (host && (!GetContentClient()->browser()->MayReuseHost(host) ||
2068 !IsSuitableHost(host, browser_context, url))) {
2069 // The registered process does not have an appropriate set of bindings for
2070 // the url. Remove it from the map so we can register a better one.
2071 RecordAction(
2072 base::UserMetricsAction("BindingsMismatch_GetProcessHostPerSite"));
2073 map->RemoveProcess(host);
2074 host = NULL;
2077 return host;
2080 void RenderProcessHostImpl::RegisterProcessHostForSite(
2081 BrowserContext* browser_context,
2082 RenderProcessHost* process,
2083 const GURL& url) {
2084 // Look up the map of site to process for the given browser_context.
2085 SiteProcessMap* map =
2086 GetSiteProcessMapForBrowserContext(browser_context);
2088 // Only register valid, non-empty sites. Empty or invalid sites will not
2089 // use process-per-site mode. We cannot check whether the process has
2090 // appropriate bindings here, because the bindings have not yet been granted.
2091 std::string site = SiteInstance::GetSiteForURL(browser_context, url)
2092 .possibly_invalid_spec();
2093 if (!site.empty())
2094 map->RegisterProcess(site, process);
2097 void RenderProcessHostImpl::ProcessDied(bool already_dead,
2098 RendererClosedDetails* known_details) {
2099 // Our child process has died. If we didn't expect it, it's a crash.
2100 // In any case, we need to let everyone know it's gone.
2101 // The OnChannelError notification can fire multiple times due to nested sync
2102 // calls to a renderer. If we don't have a valid channel here it means we
2103 // already handled the error.
2105 // It should not be possible for us to be called re-entrantly.
2106 DCHECK(!within_process_died_observer_);
2108 // It should not be possible for a process death notification to come in while
2109 // we are dying.
2110 DCHECK(!deleting_soon_);
2112 // child_process_launcher_ can be NULL in single process mode or if fast
2113 // termination happened.
2114 base::TerminationStatus status = base::TERMINATION_STATUS_NORMAL_TERMINATION;
2115 int exit_code = 0;
2116 if (known_details) {
2117 status = known_details->status;
2118 exit_code = known_details->exit_code;
2119 } else if (child_process_launcher_.get()) {
2120 status = child_process_launcher_->GetChildTerminationStatus(already_dead,
2121 &exit_code);
2122 if (already_dead && status == base::TERMINATION_STATUS_STILL_RUNNING) {
2123 // May be in case of IPC error, if it takes long time for renderer
2124 // to exit. Child process will be killed in any case during
2125 // child_process_launcher_.reset(). Make sure we will not broadcast
2126 // FrameHostMsg_RenderProcessGone with status
2127 // TERMINATION_STATUS_STILL_RUNNING, since this will break WebContentsImpl
2128 // logic.
2129 status = base::TERMINATION_STATUS_PROCESS_CRASHED;
2133 RendererClosedDetails details(status, exit_code);
2134 mojo_application_host_->WillDestroySoon();
2136 child_process_launcher_.reset();
2137 channel_.reset();
2138 while (!queued_messages_.empty()) {
2139 delete queued_messages_.front();
2140 queued_messages_.pop();
2143 within_process_died_observer_ = true;
2144 NotificationService::current()->Notify(
2145 NOTIFICATION_RENDERER_PROCESS_CLOSED,
2146 Source<RenderProcessHost>(this),
2147 Details<RendererClosedDetails>(&details));
2148 FOR_EACH_OBSERVER(RenderProcessHostObserver,
2149 observers_,
2150 RenderProcessExited(this, status, exit_code));
2151 within_process_died_observer_ = false;
2153 gpu_message_filter_ = NULL;
2154 message_port_message_filter_ = NULL;
2155 RemoveUserData(kSessionStorageHolderKey);
2157 IDMap<IPC::Listener>::iterator iter(&listeners_);
2158 while (!iter.IsAtEnd()) {
2159 iter.GetCurrentValue()->OnMessageReceived(
2160 FrameHostMsg_RenderProcessGone(iter.GetCurrentKey(),
2161 static_cast<int>(status),
2162 exit_code));
2163 iter.Advance();
2166 mojo_application_host_.reset(new MojoApplicationHost);
2168 // It's possible that one of the calls out to the observers might have caused
2169 // this object to be no longer needed.
2170 if (delayed_cleanup_needed_)
2171 Cleanup();
2173 // This object is not deleted at this point and might be reused later.
2174 // TODO(darin): clean this up
2177 int RenderProcessHost::GetActiveViewCount() {
2178 int num_active_views = 0;
2179 scoped_ptr<RenderWidgetHostIterator> widgets(
2180 RenderWidgetHost::GetRenderWidgetHosts());
2181 while (RenderWidgetHost* widget = widgets->GetNextHost()) {
2182 // Count only RenderWidgetHosts in this process.
2183 if (widget->GetProcess()->GetID() == GetID())
2184 num_active_views++;
2186 return num_active_views;
2189 // Frame subscription API for this class is for accelerated composited path
2190 // only. These calls are redirected to GpuMessageFilter.
2191 void RenderProcessHostImpl::BeginFrameSubscription(
2192 int route_id,
2193 scoped_ptr<RenderWidgetHostViewFrameSubscriber> subscriber) {
2194 if (!gpu_message_filter_)
2195 return;
2196 BrowserThread::PostTask(BrowserThread::IO, FROM_HERE, base::Bind(
2197 &GpuMessageFilter::BeginFrameSubscription,
2198 gpu_message_filter_,
2199 route_id, base::Passed(&subscriber)));
2202 void RenderProcessHostImpl::EndFrameSubscription(int route_id) {
2203 if (!gpu_message_filter_)
2204 return;
2205 BrowserThread::PostTask(BrowserThread::IO, FROM_HERE, base::Bind(
2206 &GpuMessageFilter::EndFrameSubscription,
2207 gpu_message_filter_,
2208 route_id));
2211 #if defined(ENABLE_WEBRTC)
2212 void RenderProcessHostImpl::WebRtcLogMessage(const std::string& message) {
2213 DCHECK_CURRENTLY_ON(BrowserThread::UI);
2214 if (!webrtc_log_message_callback_.is_null())
2215 webrtc_log_message_callback_.Run(message);
2217 #endif
2219 void RenderProcessHostImpl::ReleaseOnCloseACK(
2220 RenderProcessHost* host,
2221 const SessionStorageNamespaceMap& sessions,
2222 int view_route_id) {
2223 DCHECK(host);
2224 if (sessions.empty())
2225 return;
2226 SessionStorageHolder* holder = static_cast<SessionStorageHolder*>
2227 (host->GetUserData(kSessionStorageHolderKey));
2228 if (!holder) {
2229 holder = new SessionStorageHolder();
2230 host->SetUserData(
2231 kSessionStorageHolderKey,
2232 holder);
2234 holder->Hold(sessions, view_route_id);
2237 void RenderProcessHostImpl::OnShutdownRequest() {
2238 // Don't shut down if there are active RenderViews, or if there are pending
2239 // RenderViews being swapped back in.
2240 // In single process mode, we never shutdown the renderer.
2241 int num_active_views = GetActiveViewCount();
2242 if (pending_views_ || num_active_views > 0 || run_renderer_in_process())
2243 return;
2245 // Notify any contents that might have swapped out renderers from this
2246 // process. They should not attempt to swap them back in.
2247 FOR_EACH_OBSERVER(RenderProcessHostObserver, observers_,
2248 RenderProcessWillExit(this));
2250 mojo_application_host_->WillDestroySoon();
2252 Send(new ChildProcessMsg_Shutdown());
2255 void RenderProcessHostImpl::SuddenTerminationChanged(bool enabled) {
2256 SetSuddenTerminationAllowed(enabled);
2259 void RenderProcessHostImpl::SetBackgrounded(bool backgrounded) {
2260 TRACE_EVENT1("renderer_host", "RenderProcessHostImpl::SetBackgrounded",
2261 "backgrounded", backgrounded);
2262 // Note: we always set the backgrounded_ value. If the process is NULL
2263 // (and hence hasn't been created yet), we will set the process priority
2264 // later when we create the process.
2265 backgrounded_ = backgrounded;
2266 if (!child_process_launcher_.get() || child_process_launcher_->IsStarting())
2267 return;
2269 // Don't background processes which have active audio streams.
2270 if (backgrounded_ && audio_renderer_host_->HasActiveAudio())
2271 return;
2273 const base::CommandLine* command_line =
2274 base::CommandLine::ForCurrentProcess();
2275 if (command_line->HasSwitch(switches::kDisableRendererBackgrounding))
2276 return;
2278 #if defined(OS_WIN)
2279 // The cbstext.dll loads as a global GetMessage hook in the browser process
2280 // and intercepts/unintercepts the kernel32 API SetPriorityClass in a
2281 // background thread. If the UI thread invokes this API just when it is
2282 // intercepted the stack is messed up on return from the interceptor
2283 // which causes random crashes in the browser process. Our hack for now
2284 // is to not invoke the SetPriorityClass API if the dll is loaded.
2285 if (GetModuleHandle(L"cbstext.dll"))
2286 return;
2287 #endif // OS_WIN
2289 #if defined(OS_WIN) || defined(OS_MACOSX)
2290 // Same as below, but bound to an experiment (http://crbug.com/458594 on
2291 // Windows, http://crbug.com/398103 on the Mac). Enabled by default in the
2292 // absence of field trials to get coverage on the perf waterfall.
2293 base::FieldTrial* trial =
2294 base::FieldTrialList::Find("BackgroundRendererProcesses");
2295 if (!trial || !base::StartsWith(trial->group_name(), "Disallow",
2296 base::CompareCase::SENSITIVE)) {
2297 child_process_launcher_->SetProcessBackgrounded(backgrounded);
2299 #else
2300 // Control the background state from the browser process, otherwise the task
2301 // telling the renderer to "unbackground" itself may be preempted by other
2302 // tasks executing at lowered priority ahead of it or simply by not being
2303 // swiftly scheduled by the OS per the low process priority
2304 // (http://crbug.com/398103).
2305 child_process_launcher_->SetProcessBackgrounded(backgrounded);
2306 #endif // OS_WIN
2308 // Notify the child process of background state.
2309 Send(new ChildProcessMsg_SetProcessBackgrounded(backgrounded));
2312 void RenderProcessHostImpl::OnProcessLaunched() {
2313 // TODO(erikchen): Remove ScopedTracker below once http://crbug.com/465841
2314 // is fixed.
2315 tracked_objects::ScopedTracker tracking_profile1(
2316 FROM_HERE_WITH_EXPLICIT_FUNCTION(
2317 "465841 RenderProcessHostImpl::OnProcessLaunched::Start"));
2318 // No point doing anything, since this object will be destructed soon. We
2319 // especially don't want to send the RENDERER_PROCESS_CREATED notification,
2320 // since some clients might expect a RENDERER_PROCESS_TERMINATED afterwards to
2321 // properly cleanup.
2322 if (deleting_soon_)
2323 return;
2325 if (child_process_launcher_) {
2326 // TODO(erikchen): Remove ScopedTracker below once http://crbug.com/465841
2327 // is fixed.
2328 tracked_objects::ScopedTracker tracking_profile2(
2329 FROM_HERE_WITH_EXPLICIT_FUNCTION(
2330 "465841 RenderProcessHostImpl::OnProcessLaunched::Backgrounded"));
2331 DCHECK(child_process_launcher_->GetProcess().IsValid());
2332 SetBackgrounded(backgrounded_);
2335 // TODO(erikchen): Remove ScopedTracker below once http://crbug.com/465841
2336 // is fixed.
2337 tracked_objects::ScopedTracker tracking_profile3(
2338 FROM_HERE_WITH_EXPLICIT_FUNCTION(
2339 "465841 RenderProcessHostImpl::OnProcessLaunched::Notify"));
2340 // NOTE: This needs to be before sending queued messages because
2341 // ExtensionService uses this notification to initialize the renderer process
2342 // with state that must be there before any JavaScript executes.
2344 // The queued messages contain such things as "navigate". If this notification
2345 // was after, we can end up executing JavaScript before the initialization
2346 // happens.
2347 NotificationService::current()->Notify(
2348 NOTIFICATION_RENDERER_PROCESS_CREATED,
2349 Source<RenderProcessHost>(this),
2350 NotificationService::NoDetails());
2352 // TODO(erikchen): Remove ScopedTracker below once http://crbug.com/465841
2353 // is fixed.
2354 tracked_objects::ScopedTracker tracking_profile4(
2355 FROM_HERE_WITH_EXPLICIT_FUNCTION(
2356 "465841 RenderProcessHostImpl::OnProcessLaunched::MojoActivate"));
2357 // Allow Mojo to be setup before the renderer sees any Chrome IPC messages.
2358 // This way, Mojo can be safely used from the renderer in response to any
2359 // Chrome IPC message.
2360 mojo_application_host_->Activate(this, GetHandle());
2362 // TODO(erikchen): Remove ScopedTracker below once http://crbug.com/465841
2363 // is fixed.
2364 tracked_objects::ScopedTracker tracking_profile5(
2365 FROM_HERE_WITH_EXPLICIT_FUNCTION(
2366 "465841 RenderProcessHostImpl::OnProcessLaunched::MojoClientLaunch"));
2368 // TODO(erikchen): Remove ScopedTracker below once http://crbug.com/465841
2369 // is fixed.
2370 tracked_objects::ScopedTracker tracking_profile6(
2371 FROM_HERE_WITH_EXPLICIT_FUNCTION(
2372 "465841 "
2373 "RenderProcessHostImpl::OnProcessLaunched::SendQueuedMessages"));
2374 while (!queued_messages_.empty()) {
2375 Send(queued_messages_.front());
2376 queued_messages_.pop();
2379 #if defined(ENABLE_WEBRTC)
2380 // TODO(erikchen): Remove ScopedTracker below once http://crbug.com/465841
2381 // is fixed.
2382 tracked_objects::ScopedTracker tracking_profile7(
2383 FROM_HERE_WITH_EXPLICIT_FUNCTION(
2384 "465841 RenderProcessHostImpl::OnProcessLaunched::EnableAec"));
2385 if (WebRTCInternals::GetInstance()->aec_dump_enabled())
2386 EnableAecDump(WebRTCInternals::GetInstance()->aec_dump_file_path());
2387 #endif
2390 void RenderProcessHostImpl::OnProcessLaunchFailed() {
2391 // If this object will be destructed soon, then observers have already been
2392 // sent a RenderProcessHostDestroyed notification, and we must observe our
2393 // contract that says that will be the last call.
2394 if (deleting_soon_)
2395 return;
2397 RendererClosedDetails details { base::TERMINATION_STATUS_PROCESS_WAS_KILLED,
2398 -1 };
2399 ProcessDied(true, &details);
2402 scoped_refptr<AudioRendererHost>
2403 RenderProcessHostImpl::audio_renderer_host() const {
2404 return audio_renderer_host_;
2407 void RenderProcessHostImpl::OnUserMetricsRecordAction(
2408 const std::string& action) {
2409 RecordComputedAction(action);
2412 void RenderProcessHostImpl::OnCloseACK(int old_route_id) {
2413 SessionStorageHolder* holder = static_cast<SessionStorageHolder*>
2414 (GetUserData(kSessionStorageHolderKey));
2415 if (!holder)
2416 return;
2417 holder->Release(old_route_id);
2420 void RenderProcessHostImpl::OnSavedPageAsMHTML(int job_id, int64 data_size) {
2421 MHTMLGenerationManager::GetInstance()->MHTMLGenerated(job_id, data_size);
2424 void RenderProcessHostImpl::OnGpuSwitched() {
2425 // We are updating all widgets including swapped out ones.
2426 scoped_ptr<RenderWidgetHostIterator> widgets(
2427 RenderWidgetHostImpl::GetAllRenderWidgetHosts());
2428 while (RenderWidgetHost* widget = widgets->GetNextHost()) {
2429 if (!widget->IsRenderView())
2430 continue;
2432 // Skip widgets in other processes.
2433 if (widget->GetProcess()->GetID() != GetID())
2434 continue;
2436 RenderViewHost* rvh = RenderViewHost::From(widget);
2437 rvh->OnWebkitPreferencesChanged();
2441 #if defined(ENABLE_WEBRTC)
2442 void RenderProcessHostImpl::OnRegisterAecDumpConsumer(int id) {
2443 BrowserThread::PostTask(
2444 BrowserThread::UI,
2445 FROM_HERE,
2446 base::Bind(
2447 &RenderProcessHostImpl::RegisterAecDumpConsumerOnUIThread,
2448 weak_factory_.GetWeakPtr(),
2449 id));
2452 void RenderProcessHostImpl::OnUnregisterAecDumpConsumer(int id) {
2453 BrowserThread::PostTask(
2454 BrowserThread::UI,
2455 FROM_HERE,
2456 base::Bind(
2457 &RenderProcessHostImpl::UnregisterAecDumpConsumerOnUIThread,
2458 weak_factory_.GetWeakPtr(),
2459 id));
2462 void RenderProcessHostImpl::RegisterAecDumpConsumerOnUIThread(int id) {
2463 DCHECK_CURRENTLY_ON(BrowserThread::UI);
2464 aec_dump_consumers_.push_back(id);
2465 if (WebRTCInternals::GetInstance()->aec_dump_enabled()) {
2466 EnableAecDumpForId(WebRTCInternals::GetInstance()->aec_dump_file_path(),
2467 id);
2471 void RenderProcessHostImpl::UnregisterAecDumpConsumerOnUIThread(int id) {
2472 DCHECK_CURRENTLY_ON(BrowserThread::UI);
2473 for (std::vector<int>::iterator it = aec_dump_consumers_.begin();
2474 it != aec_dump_consumers_.end(); ++it) {
2475 if (*it == id) {
2476 aec_dump_consumers_.erase(it);
2477 break;
2482 #if defined(OS_WIN)
2483 #define IntToStringType base::IntToString16
2484 #else
2485 #define IntToStringType base::IntToString
2486 #endif
2488 void RenderProcessHostImpl::EnableAecDumpForId(const base::FilePath& file,
2489 int id) {
2490 DCHECK_CURRENTLY_ON(BrowserThread::UI);
2491 base::FilePath unique_file =
2492 file.AddExtension(IntToStringType(base::GetProcId(GetHandle())))
2493 .AddExtension(IntToStringType(id));
2494 BrowserThread::PostTaskAndReplyWithResult(
2495 BrowserThread::FILE, FROM_HERE,
2496 base::Bind(&CreateAecDumpFileForProcess, unique_file, GetHandle()),
2497 base::Bind(&RenderProcessHostImpl::SendAecDumpFileToRenderer,
2498 weak_factory_.GetWeakPtr(),
2499 id));
2502 #undef IntToStringType
2504 void RenderProcessHostImpl::SendAecDumpFileToRenderer(
2505 int id,
2506 IPC::PlatformFileForTransit file_for_transit) {
2507 if (file_for_transit == IPC::InvalidPlatformFileForTransit())
2508 return;
2509 Send(new AecDumpMsg_EnableAecDump(id, file_for_transit));
2512 void RenderProcessHostImpl::SendDisableAecDumpToRenderer() {
2513 Send(new AecDumpMsg_DisableAecDump());
2515 #endif
2517 void RenderProcessHostImpl::IncrementWorkerRefCount() {
2518 DCHECK_CURRENTLY_ON(BrowserThread::UI);
2519 ++worker_ref_count_;
2520 if (worker_ref_count_ > max_worker_count_)
2521 max_worker_count_ = worker_ref_count_;
2524 void RenderProcessHostImpl::DecrementWorkerRefCount() {
2525 DCHECK_CURRENTLY_ON(BrowserThread::UI);
2526 DCHECK_GT(worker_ref_count_, 0);
2527 --worker_ref_count_;
2528 if (worker_ref_count_ == 0)
2529 Cleanup();
2532 void RenderProcessHostImpl::GetAudioOutputControllers(
2533 const GetAudioOutputControllersCallback& callback) const {
2534 audio_renderer_host()->GetOutputControllers(callback);
2537 BluetoothDispatcherHost* RenderProcessHostImpl::GetBluetoothDispatcherHost() {
2538 return bluetooth_dispatcher_host_.get();
2541 } // namespace content