cygprofile: increase timeouts to allow showing web contents
[chromium-blink-merge.git] / content / browser / renderer_host / render_process_host_impl.cc
blobdd36d5dca8f349b1458e18e11850c127fa47ecb3
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/client_native_pixmap_factory.h"
195 #include "ui/ozone/public/ozone_platform.h"
196 #include "ui/ozone/public/ozone_switches.h"
197 #endif
199 #if defined(ENABLE_BROWSER_CDMS)
200 #include "content/browser/media/cdm/browser_cdm_manager.h"
201 #endif
203 #if defined(ENABLE_PLUGINS)
204 #include "content/browser/plugin_service_impl.h"
205 #endif
207 #if defined(ENABLE_WEBRTC)
208 #include "content/browser/media/webrtc_internals.h"
209 #include "content/browser/renderer_host/media/media_stream_track_metrics_host.h"
210 #include "content/browser/renderer_host/media/webrtc_identity_service_host.h"
211 #include "content/browser/renderer_host/p2p/socket_dispatcher_host.h"
212 #include "content/common/media/aec_dump_messages.h"
213 #include "content/common/media/media_stream_messages.h"
214 #endif
216 #if defined(OS_WIN)
217 #define IntToStringType base::IntToString16
218 #else
219 #define IntToStringType base::IntToString
220 #endif
222 namespace content {
223 namespace {
225 const char kSiteProcessMapKeyName[] = "content_site_process_map";
227 #ifdef ENABLE_WEBRTC
228 const base::FilePath::CharType kAecDumpFileNameAddition[] =
229 FILE_PATH_LITERAL("aec_dump");
230 #endif
232 void CacheShaderInfo(int32 id, base::FilePath path) {
233 ShaderCacheFactory::GetInstance()->SetCacheInfo(id, path);
236 void RemoveShaderInfo(int32 id) {
237 ShaderCacheFactory::GetInstance()->RemoveCacheInfo(id);
240 net::URLRequestContext* GetRequestContext(
241 scoped_refptr<net::URLRequestContextGetter> request_context,
242 scoped_refptr<net::URLRequestContextGetter> media_request_context,
243 ResourceType resource_type) {
244 // If the request has resource type of RESOURCE_TYPE_MEDIA, we use a request
245 // context specific to media for handling it because these resources have
246 // specific needs for caching.
247 if (resource_type == RESOURCE_TYPE_MEDIA)
248 return media_request_context->GetURLRequestContext();
249 return request_context->GetURLRequestContext();
252 void GetContexts(
253 ResourceContext* resource_context,
254 scoped_refptr<net::URLRequestContextGetter> request_context,
255 scoped_refptr<net::URLRequestContextGetter> media_request_context,
256 const ResourceHostMsg_Request& request,
257 ResourceContext** resource_context_out,
258 net::URLRequestContext** request_context_out) {
259 *resource_context_out = resource_context;
260 *request_context_out =
261 GetRequestContext(request_context, media_request_context,
262 request.resource_type);
265 #if defined(ENABLE_WEBRTC)
267 // Allow us to only run the trial in the first renderer.
268 bool has_done_stun_trials = false;
270 // Creates a file used for diagnostic echo canceller recordings for handing
271 // over to the renderer.
272 IPC::PlatformFileForTransit CreateAecDumpFileForProcess(
273 base::FilePath file_path,
274 base::ProcessHandle process) {
275 DCHECK_CURRENTLY_ON(BrowserThread::FILE);
276 base::File dump_file(file_path,
277 base::File::FLAG_OPEN_ALWAYS | base::File::FLAG_APPEND);
278 if (!dump_file.IsValid()) {
279 VLOG(1) << "Could not open AEC dump file, error=" <<
280 dump_file.error_details();
281 return IPC::InvalidPlatformFileForTransit();
283 return IPC::TakeFileHandleForProcess(dump_file.Pass(), process);
286 // Does nothing. Just to avoid races between enable and disable.
287 void DisableAecDumpOnFileThread() {
288 DCHECK_CURRENTLY_ON(BrowserThread::FILE);
290 #endif
292 // the global list of all renderer processes
293 base::LazyInstance<IDMap<RenderProcessHost> >::Leaky
294 g_all_hosts = LAZY_INSTANCE_INITIALIZER;
296 // Map of site to process, to ensure we only have one RenderProcessHost per
297 // site in process-per-site mode. Each map is specific to a BrowserContext.
298 class SiteProcessMap : public base::SupportsUserData::Data {
299 public:
300 typedef base::hash_map<std::string, RenderProcessHost*> SiteToProcessMap;
301 SiteProcessMap() {}
303 void RegisterProcess(const std::string& site, RenderProcessHost* process) {
304 map_[site] = process;
307 RenderProcessHost* FindProcess(const std::string& site) {
308 SiteToProcessMap::iterator i = map_.find(site);
309 if (i != map_.end())
310 return i->second;
311 return NULL;
314 void RemoveProcess(RenderProcessHost* host) {
315 // Find all instances of this process in the map, then separately remove
316 // them.
317 std::set<std::string> sites;
318 for (SiteToProcessMap::const_iterator i = map_.begin();
319 i != map_.end();
320 i++) {
321 if (i->second == host)
322 sites.insert(i->first);
324 for (std::set<std::string>::iterator i = sites.begin();
325 i != sites.end();
326 i++) {
327 SiteToProcessMap::iterator iter = map_.find(*i);
328 if (iter != map_.end()) {
329 DCHECK_EQ(iter->second, host);
330 map_.erase(iter);
335 private:
336 SiteToProcessMap map_;
339 // Find the SiteProcessMap specific to the given context.
340 SiteProcessMap* GetSiteProcessMapForBrowserContext(BrowserContext* context) {
341 DCHECK(context);
342 SiteProcessMap* map = static_cast<SiteProcessMap*>(
343 context->GetUserData(kSiteProcessMapKeyName));
344 if (!map) {
345 map = new SiteProcessMap();
346 context->SetUserData(kSiteProcessMapKeyName, map);
348 return map;
351 // NOTE: changes to this class need to be reviewed by the security team.
352 class RendererSandboxedProcessLauncherDelegate
353 : public SandboxedProcessLauncherDelegate {
354 public:
355 explicit RendererSandboxedProcessLauncherDelegate(IPC::ChannelProxy* channel)
356 #if defined(OS_POSIX)
357 : ipc_fd_(channel->TakeClientFileDescriptor())
358 #endif // OS_POSIX
361 ~RendererSandboxedProcessLauncherDelegate() override {}
363 #if defined(OS_WIN)
364 void PreSpawnTarget(sandbox::TargetPolicy* policy, bool* success) override {
365 AddBaseHandleClosePolicy(policy);
367 const base::string16& sid =
368 GetContentClient()->browser()->GetAppContainerSidForSandboxType(
369 GetSandboxType());
370 if (!sid.empty())
371 AddAppContainerPolicy(policy, sid.c_str());
373 GetContentClient()->browser()->PreSpawnRenderer(policy, success);
376 #elif defined(OS_POSIX)
377 bool ShouldUseZygote() override {
378 const base::CommandLine& browser_command_line =
379 *base::CommandLine::ForCurrentProcess();
380 base::CommandLine::StringType renderer_prefix =
381 browser_command_line.GetSwitchValueNative(switches::kRendererCmdPrefix);
382 return renderer_prefix.empty();
384 base::ScopedFD TakeIpcFd() override { return ipc_fd_.Pass(); }
385 #endif // OS_WIN
387 SandboxType GetSandboxType() override {
388 return SANDBOX_TYPE_RENDERER;
391 private:
392 #if defined(OS_POSIX)
393 base::ScopedFD ipc_fd_;
394 #endif // OS_POSIX
397 const char kSessionStorageHolderKey[] = "kSessionStorageHolderKey";
399 class SessionStorageHolder : public base::SupportsUserData::Data {
400 public:
401 SessionStorageHolder() {}
402 ~SessionStorageHolder() override {}
404 void Hold(const SessionStorageNamespaceMap& sessions, int view_route_id) {
405 session_storage_namespaces_awaiting_close_[view_route_id] = sessions;
408 void Release(int old_route_id) {
409 session_storage_namespaces_awaiting_close_.erase(old_route_id);
412 private:
413 std::map<int, SessionStorageNamespaceMap >
414 session_storage_namespaces_awaiting_close_;
415 DISALLOW_COPY_AND_ASSIGN(SessionStorageHolder);
418 std::string UintVectorToString(const std::vector<unsigned>& vector) {
419 std::string str;
420 for (auto it : vector) {
421 if (!str.empty())
422 str += ",";
423 str += base::UintToString(it);
425 return str;
428 } // namespace
430 RendererMainThreadFactoryFunction g_renderer_main_thread_factory = NULL;
432 base::MessageLoop* g_in_process_thread;
434 base::MessageLoop*
435 RenderProcessHostImpl::GetInProcessRendererThreadForTesting() {
436 return g_in_process_thread;
439 // Stores the maximum number of renderer processes the content module can
440 // create.
441 static size_t g_max_renderer_count_override = 0;
443 // static
444 size_t RenderProcessHost::GetMaxRendererProcessCount() {
445 if (g_max_renderer_count_override)
446 return g_max_renderer_count_override;
448 #if defined(OS_ANDROID)
449 // On Android we don't maintain a limit of renderer process hosts - we are
450 // happy with keeping a lot of these, as long as the number of live renderer
451 // processes remains reasonable, and on Android the OS takes care of that.
452 return std::numeric_limits<size_t>::max();
453 #endif
455 // On other platforms, we calculate the maximum number of renderer process
456 // hosts according to the amount of installed memory as reported by the OS.
457 // The calculation assumes that you want the renderers to use half of the
458 // installed RAM and assuming that each WebContents uses ~40MB. If you modify
459 // this assumption, you need to adjust the ThirtyFourTabs test to match the
460 // expected number of processes.
462 // With the given amounts of installed memory below on a 32-bit CPU, the
463 // maximum renderer count will roughly be as follows:
465 // 128 MB -> 3
466 // 512 MB -> 6
467 // 1024 MB -> 12
468 // 4096 MB -> 51
469 // 16384 MB -> 82 (kMaxRendererProcessCount)
471 static size_t max_count = 0;
472 if (!max_count) {
473 const size_t kEstimatedWebContentsMemoryUsage =
474 #if defined(ARCH_CPU_64_BITS)
475 60; // In MB
476 #else
477 40; // In MB
478 #endif
479 max_count = base::SysInfo::AmountOfPhysicalMemoryMB() / 2;
480 max_count /= kEstimatedWebContentsMemoryUsage;
482 const size_t kMinRendererProcessCount = 3;
483 max_count = std::max(max_count, kMinRendererProcessCount);
484 max_count = std::min(max_count, kMaxRendererProcessCount);
486 return max_count;
489 // static
490 bool g_run_renderer_in_process_ = false;
492 // static
493 void RenderProcessHost::SetMaxRendererProcessCount(size_t count) {
494 g_max_renderer_count_override = count;
497 RenderProcessHostImpl::RenderProcessHostImpl(
498 BrowserContext* browser_context,
499 StoragePartitionImpl* storage_partition_impl,
500 bool is_for_guests_only)
501 : fast_shutdown_started_(false),
502 deleting_soon_(false),
503 #ifndef NDEBUG
504 is_self_deleted_(false),
505 #endif
506 pending_views_(0),
507 mojo_application_host_(new MojoApplicationHost),
508 visible_widgets_(0),
509 backgrounded_(true),
510 is_initialized_(false),
511 id_(ChildProcessHostImpl::GenerateChildProcessUniqueId()),
512 browser_context_(browser_context),
513 storage_partition_impl_(storage_partition_impl),
514 sudden_termination_allowed_(true),
515 ignore_input_events_(false),
516 is_for_guests_only_(is_for_guests_only),
517 gpu_observer_registered_(false),
518 delayed_cleanup_needed_(false),
519 within_process_died_observer_(false),
520 power_monitor_broadcaster_(this),
521 worker_ref_count_(0),
522 max_worker_count_(0),
523 permission_service_context_(new PermissionServiceContext(this)),
524 pending_valuebuffer_state_(new gpu::ValueStateMap()),
525 subscribe_uniform_enabled_(false),
526 weak_factory_(this) {
527 widget_helper_ = new RenderWidgetHelper();
529 ChildProcessSecurityPolicyImpl::GetInstance()->Add(GetID());
531 CHECK(!BrowserMainRunner::ExitedMainMessageLoop());
532 RegisterHost(GetID(), this);
533 g_all_hosts.Get().set_check_on_null_data(true);
534 // Initialize |child_process_activity_time_| to a reasonable value.
535 mark_child_process_activity_time();
537 if (!GetBrowserContext()->IsOffTheRecord() &&
538 !base::CommandLine::ForCurrentProcess()->HasSwitch(
539 switches::kDisableGpuShaderDiskCache)) {
540 BrowserThread::PostTask(BrowserThread::IO, FROM_HERE,
541 base::Bind(&CacheShaderInfo, GetID(),
542 storage_partition_impl_->GetPath()));
544 subscribe_uniform_enabled_ =
545 base::CommandLine::ForCurrentProcess()->HasSwitch(
546 switches::kEnableSubscribeUniformExtension);
548 // Note: When we create the RenderProcessHostImpl, it's technically
549 // backgrounded, because it has no visible listeners. But the process
550 // doesn't actually exist yet, so we'll Background it later, after
551 // creation.
554 // static
555 void RenderProcessHostImpl::ShutDownInProcessRenderer() {
556 DCHECK(g_run_renderer_in_process_);
558 switch (g_all_hosts.Pointer()->size()) {
559 case 0:
560 return;
561 case 1: {
562 RenderProcessHostImpl* host = static_cast<RenderProcessHostImpl*>(
563 AllHostsIterator().GetCurrentValue());
564 FOR_EACH_OBSERVER(RenderProcessHostObserver,
565 host->observers_,
566 RenderProcessHostDestroyed(host));
567 #ifndef NDEBUG
568 host->is_self_deleted_ = true;
569 #endif
570 delete host;
571 return;
573 default:
574 NOTREACHED() << "There should be only one RenderProcessHost when running "
575 << "in-process.";
579 void RenderProcessHostImpl::RegisterRendererMainThreadFactory(
580 RendererMainThreadFactoryFunction create) {
581 g_renderer_main_thread_factory = create;
584 RenderProcessHostImpl::~RenderProcessHostImpl() {
585 #ifndef NDEBUG
586 DCHECK(is_self_deleted_)
587 << "RenderProcessHostImpl is destroyed by something other than itself";
588 #endif
590 // Make sure to clean up the in-process renderer before the channel, otherwise
591 // it may still run and have its IPCs fail, causing asserts.
592 in_process_renderer_.reset();
594 ChildProcessSecurityPolicyImpl::GetInstance()->Remove(GetID());
596 if (gpu_observer_registered_) {
597 ui::GpuSwitchingManager::GetInstance()->RemoveObserver(this);
598 gpu_observer_registered_ = false;
601 // We may have some unsent messages at this point, but that's OK.
602 channel_.reset();
603 while (!queued_messages_.empty()) {
604 delete queued_messages_.front();
605 queued_messages_.pop();
608 UnregisterHost(GetID());
610 if (!base::CommandLine::ForCurrentProcess()->HasSwitch(
611 switches::kDisableGpuShaderDiskCache)) {
612 BrowserThread::PostTask(BrowserThread::IO, FROM_HERE,
613 base::Bind(&RemoveShaderInfo, GetID()));
617 void RenderProcessHostImpl::EnableSendQueue() {
618 is_initialized_ = false;
621 bool RenderProcessHostImpl::Init() {
622 // calling Init() more than once does nothing, this makes it more convenient
623 // for the view host which may not be sure in some cases
624 if (channel_)
625 return true;
627 base::CommandLine::StringType renderer_prefix;
628 // A command prefix is something prepended to the command line of the spawned
629 // process.
630 const base::CommandLine& browser_command_line =
631 *base::CommandLine::ForCurrentProcess();
632 renderer_prefix =
633 browser_command_line.GetSwitchValueNative(switches::kRendererCmdPrefix);
635 #if defined(OS_LINUX)
636 int flags = renderer_prefix.empty() ? ChildProcessHost::CHILD_ALLOW_SELF :
637 ChildProcessHost::CHILD_NORMAL;
638 #else
639 int flags = ChildProcessHost::CHILD_NORMAL;
640 #endif
642 // Find the renderer before creating the channel so if this fails early we
643 // return without creating the channel.
644 base::FilePath renderer_path = ChildProcessHost::GetChildPath(flags);
645 if (renderer_path.empty())
646 return false;
648 // Setup the IPC channel.
649 const std::string channel_id =
650 IPC::Channel::GenerateVerifiedChannelID(std::string());
651 channel_ = CreateChannelProxy(channel_id);
653 // Setup the Mojo channel.
654 mojo_application_host_->Init();
656 // Call the embedder first so that their IPC filters have priority.
657 GetContentClient()->browser()->RenderProcessWillLaunch(this);
659 CreateMessageFilters();
660 RegisterMojoServices();
662 if (run_renderer_in_process()) {
663 DCHECK(g_renderer_main_thread_factory);
664 // Crank up a thread and run the initialization there. With the way that
665 // messages flow between the browser and renderer, this thread is required
666 // to prevent a deadlock in single-process mode. Since the primordial
667 // thread in the renderer process runs the WebKit code and can sometimes
668 // make blocking calls to the UI thread (i.e. this thread), they need to run
669 // on separate threads.
670 in_process_renderer_.reset(
671 g_renderer_main_thread_factory(InProcessChildThreadParams(
672 channel_id, BrowserThread::UnsafeGetMessageLoopForThread(
673 BrowserThread::IO)->task_runner())));
675 base::Thread::Options options;
676 #if defined(OS_WIN) && !defined(OS_MACOSX)
677 // In-process plugins require this to be a UI message loop.
678 options.message_loop_type = base::MessageLoop::TYPE_UI;
679 #else
680 // We can't have multiple UI loops on Linux and Android, so we don't support
681 // in-process plugins.
682 options.message_loop_type = base::MessageLoop::TYPE_DEFAULT;
683 #endif
685 // As for execution sequence, this callback should have no any dependency
686 // on starting in-process-render-thread.
687 // So put it here to trigger ChannelMojo initialization earlier to enable
688 // in-process-render-thread using ChannelMojo there.
689 OnProcessLaunched(); // Fake a callback that the process is ready.
691 in_process_renderer_->StartWithOptions(options);
693 g_in_process_thread = in_process_renderer_->message_loop();
695 } else {
696 // Build command line for renderer. We call AppendRendererCommandLine()
697 // first so the process type argument will appear first.
698 base::CommandLine* cmd_line = new base::CommandLine(renderer_path);
699 if (!renderer_prefix.empty())
700 cmd_line->PrependWrapper(renderer_prefix);
701 AppendRendererCommandLine(cmd_line);
702 cmd_line->AppendSwitchASCII(switches::kProcessChannelID, channel_id);
704 // Spawn the child process asynchronously to avoid blocking the UI thread.
705 // As long as there's no renderer prefix, we can use the zygote process
706 // at this stage.
707 child_process_launcher_.reset(new ChildProcessLauncher(
708 new RendererSandboxedProcessLauncherDelegate(channel_.get()),
709 cmd_line,
710 GetID(),
711 this));
713 fast_shutdown_started_ = false;
716 if (!gpu_observer_registered_) {
717 gpu_observer_registered_ = true;
718 ui::GpuSwitchingManager::GetInstance()->AddObserver(this);
721 power_monitor_broadcaster_.Init();
723 is_initialized_ = true;
724 init_time_ = base::TimeTicks::Now();
725 return true;
728 scoped_ptr<IPC::ChannelProxy> RenderProcessHostImpl::CreateChannelProxy(
729 const std::string& channel_id) {
730 scoped_refptr<base::SingleThreadTaskRunner> runner =
731 BrowserThread::GetMessageLoopProxyForThread(BrowserThread::IO);
732 scoped_refptr<base::SequencedTaskRunner> mojo_task_runner =
733 BrowserThread::UnsafeGetMessageLoopForThread(BrowserThread::IO)
734 ->task_runner();
735 if (ShouldUseMojoChannel()) {
736 VLOG(1) << "Mojo Channel is enabled on host";
738 return IPC::ChannelProxy::Create(
739 IPC::ChannelMojo::CreateServerFactory(
740 mojo_task_runner, channel_id,
741 content::ChildProcessHost::GetAttachmentBroker()),
742 this, runner.get());
745 return IPC::ChannelProxy::Create(
746 channel_id, IPC::Channel::MODE_SERVER, this, runner.get(),
747 content::ChildProcessHost::GetAttachmentBroker());
750 void RenderProcessHostImpl::CreateMessageFilters() {
751 DCHECK_CURRENTLY_ON(BrowserThread::UI);
752 const base::CommandLine& browser_command_line =
753 *base::CommandLine::ForCurrentProcess();
754 AddFilter(new ResourceSchedulerFilter(GetID()));
755 MediaInternals* media_internals = MediaInternals::GetInstance();
756 media::AudioManager* audio_manager =
757 BrowserMainLoop::GetInstance()->audio_manager();
758 // Add BrowserPluginMessageFilter to ensure it gets the first stab at messages
759 // from guests.
760 scoped_refptr<BrowserPluginMessageFilter> bp_message_filter(
761 new BrowserPluginMessageFilter(GetID()));
762 AddFilter(bp_message_filter.get());
764 scoped_refptr<RenderMessageFilter> render_message_filter(
765 new RenderMessageFilter(
766 GetID(),
767 GetBrowserContext(),
768 GetBrowserContext()->GetRequestContextForRenderProcess(GetID()),
769 widget_helper_.get(),
770 audio_manager,
771 media_internals,
772 storage_partition_impl_->GetDOMStorageContext()));
773 AddFilter(render_message_filter.get());
774 AddFilter(new RenderFrameMessageFilter(
775 GetID(),
776 #if defined(ENABLE_PLUGINS)
777 PluginServiceImpl::GetInstance(),
778 #else
779 nullptr,
780 #endif
781 GetBrowserContext(),
782 GetBrowserContext()->GetRequestContextForRenderProcess(GetID()),
783 widget_helper_.get()));
784 BrowserContext* browser_context = GetBrowserContext();
785 ResourceContext* resource_context = browser_context->GetResourceContext();
787 scoped_refptr<net::URLRequestContextGetter> request_context(
788 browser_context->GetRequestContextForRenderProcess(GetID()));
789 scoped_refptr<net::URLRequestContextGetter> media_request_context(
790 browser_context->GetMediaRequestContextForRenderProcess(GetID()));
792 ResourceMessageFilter::GetContextsCallback get_contexts_callback(
793 base::Bind(&GetContexts, browser_context->GetResourceContext(),
794 request_context, media_request_context));
796 ResourceMessageFilter* resource_message_filter = new ResourceMessageFilter(
797 GetID(), PROCESS_TYPE_RENDERER,
798 storage_partition_impl_->GetAppCacheService(),
799 ChromeBlobStorageContext::GetFor(browser_context),
800 storage_partition_impl_->GetFileSystemContext(),
801 storage_partition_impl_->GetServiceWorkerContext(),
802 storage_partition_impl_->GetHostZoomLevelContext(),
803 get_contexts_callback);
805 AddFilter(resource_message_filter);
806 MediaStreamManager* media_stream_manager =
807 BrowserMainLoop::GetInstance()->media_stream_manager();
808 // The AudioInputRendererHost and AudioRendererHost needs to be available for
809 // lookup, so it's stashed in a member variable.
810 audio_input_renderer_host_ = new AudioInputRendererHost(
811 GetID(),
812 base::GetProcId(GetHandle()),
813 audio_manager,
814 media_stream_manager,
815 AudioMirroringManager::GetInstance(),
816 BrowserMainLoop::GetInstance()->user_input_monitor());
817 AddFilter(audio_input_renderer_host_.get());
818 audio_renderer_host_ = new AudioRendererHost(
819 GetID(),
820 audio_manager,
821 AudioMirroringManager::GetInstance(),
822 media_internals,
823 media_stream_manager,
824 browser_context->GetResourceContext()->GetMediaDeviceIDSalt());
825 AddFilter(audio_renderer_host_.get());
826 AddFilter(
827 new MidiHost(GetID(), BrowserMainLoop::GetInstance()->midi_manager()));
828 AddFilter(new VideoCaptureHost(media_stream_manager));
829 AddFilter(new AppCacheDispatcherHost(
830 storage_partition_impl_->GetAppCacheService(),
831 GetID()));
832 AddFilter(new ClipboardMessageFilter);
833 AddFilter(new DOMStorageMessageFilter(
834 storage_partition_impl_->GetDOMStorageContext()));
835 AddFilter(new IndexedDBDispatcherHost(
836 GetID(),
837 storage_partition_impl_->GetURLRequestContext(),
838 storage_partition_impl_->GetIndexedDBContext(),
839 ChromeBlobStorageContext::GetFor(browser_context)));
841 gpu_message_filter_ = new GpuMessageFilter(GetID(), widget_helper_.get());
842 AddFilter(gpu_message_filter_);
843 #if defined(ENABLE_WEBRTC)
844 AddFilter(new WebRTCIdentityServiceHost(
845 GetID(),
846 storage_partition_impl_->GetWebRTCIdentityStore(),
847 resource_context));
848 peer_connection_tracker_host_ = new PeerConnectionTrackerHost(GetID());
849 AddFilter(peer_connection_tracker_host_.get());
850 AddFilter(new MediaStreamDispatcherHost(
851 GetID(),
852 browser_context->GetResourceContext()->GetMediaDeviceIDSalt(),
853 media_stream_manager));
854 AddFilter(new MediaStreamTrackMetricsHost());
855 #endif
856 #if defined(ENABLE_PLUGINS)
857 AddFilter(new PepperRendererConnection(GetID()));
858 #endif
859 AddFilter(new SpeechRecognitionDispatcherHost(
860 GetID(), storage_partition_impl_->GetURLRequestContext()));
861 AddFilter(new FileAPIMessageFilter(
862 GetID(),
863 storage_partition_impl_->GetURLRequestContext(),
864 storage_partition_impl_->GetFileSystemContext(),
865 ChromeBlobStorageContext::GetFor(browser_context),
866 StreamContext::GetFor(browser_context)));
867 AddFilter(new FileUtilitiesMessageFilter(GetID()));
868 AddFilter(new MimeRegistryMessageFilter());
869 AddFilter(new DatabaseMessageFilter(
870 storage_partition_impl_->GetDatabaseTracker()));
871 #if defined(OS_MACOSX)
872 AddFilter(new TextInputClientMessageFilter(GetID()));
873 #elif defined(OS_WIN)
874 // The FontCacheDispatcher is required only when we're using GDI rendering.
875 // TODO(scottmg): pdf/ppapi still require the renderer to be able to precache
876 // GDI fonts (http://crbug.com/383227), even when using DirectWrite. This
877 // should eventually be if (!ShouldUseDirectWrite()) guarded.
878 channel_->AddFilter(new FontCacheDispatcher());
879 #elif defined(OS_ANDROID)
880 browser_demuxer_android_ = new BrowserDemuxerAndroid();
881 AddFilter(browser_demuxer_android_.get());
882 #endif
883 #if defined(ENABLE_BROWSER_CDMS)
884 AddFilter(new BrowserCdmManager(GetID(), NULL));
885 #endif
887 WebSocketDispatcherHost::GetRequestContextCallback
888 websocket_request_context_callback(
889 base::Bind(&GetRequestContext, request_context,
890 media_request_context, RESOURCE_TYPE_SUB_RESOURCE));
892 AddFilter(
893 new WebSocketDispatcherHost(GetID(), websocket_request_context_callback));
895 message_port_message_filter_ = new MessagePortMessageFilter(
896 base::Bind(&RenderWidgetHelper::GetNextRoutingID,
897 base::Unretained(widget_helper_.get())));
898 AddFilter(message_port_message_filter_.get());
900 scoped_refptr<CacheStorageDispatcherHost> cache_storage_filter =
901 new CacheStorageDispatcherHost();
902 cache_storage_filter->Init(storage_partition_impl_->GetCacheStorageContext());
903 AddFilter(cache_storage_filter.get());
905 scoped_refptr<ServiceWorkerDispatcherHost> service_worker_filter =
906 new ServiceWorkerDispatcherHost(
907 GetID(), message_port_message_filter_.get(), resource_context);
908 service_worker_filter->Init(
909 storage_partition_impl_->GetServiceWorkerContext());
910 AddFilter(service_worker_filter.get());
912 AddFilter(new SharedWorkerMessageFilter(
913 GetID(),
914 resource_context,
915 WorkerStoragePartition(
916 storage_partition_impl_->GetURLRequestContext(),
917 storage_partition_impl_->GetMediaURLRequestContext(),
918 storage_partition_impl_->GetAppCacheService(),
919 storage_partition_impl_->GetQuotaManager(),
920 storage_partition_impl_->GetFileSystemContext(),
921 storage_partition_impl_->GetDatabaseTracker(),
922 storage_partition_impl_->GetIndexedDBContext(),
923 storage_partition_impl_->GetServiceWorkerContext()),
924 message_port_message_filter_.get()));
926 #if defined(ENABLE_WEBRTC)
927 p2p_socket_dispatcher_host_ = new P2PSocketDispatcherHost(
928 resource_context,
929 browser_context->GetRequestContextForRenderProcess(GetID()));
930 AddFilter(p2p_socket_dispatcher_host_.get());
931 #endif
933 AddFilter(new TraceMessageFilter(GetID()));
934 AddFilter(new ResolveProxyMsgHelper(
935 browser_context->GetRequestContextForRenderProcess(GetID())));
936 AddFilter(new QuotaDispatcherHost(
937 GetID(),
938 storage_partition_impl_->GetQuotaManager(),
939 GetContentClient()->browser()->CreateQuotaPermissionContext()));
941 notification_message_filter_ = new NotificationMessageFilter(
942 GetID(),
943 storage_partition_impl_->GetPlatformNotificationContext(),
944 resource_context,
945 browser_context);
946 AddFilter(notification_message_filter_.get());
948 AddFilter(new GamepadBrowserMessageFilter());
949 AddFilter(new DeviceLightMessageFilter());
950 AddFilter(new DeviceMotionMessageFilter());
951 AddFilter(new DeviceOrientationMessageFilter());
952 AddFilter(new ProfilerMessageFilter(PROCESS_TYPE_RENDERER));
953 AddFilter(new HistogramMessageFilter());
954 #if defined(USE_TCMALLOC) && (defined(OS_LINUX) || defined(OS_ANDROID))
955 if (browser_command_line.HasSwitch(switches::kEnableMemoryBenchmarking))
956 AddFilter(new MemoryBenchmarkMessageFilter());
957 #endif
958 AddFilter(new PushMessagingMessageFilter(
959 GetID(), storage_partition_impl_->GetServiceWorkerContext()));
960 #if defined(OS_ANDROID)
961 AddFilter(new ScreenOrientationMessageFilterAndroid());
962 #endif
963 AddFilter(new GeofencingDispatcherHost(
964 storage_partition_impl_->GetGeofencingManager()));
965 if (browser_command_line.HasSwitch(switches::kEnableWebBluetooth)) {
966 bluetooth_dispatcher_host_ = new BluetoothDispatcherHost(GetID());
967 AddFilter(bluetooth_dispatcher_host_.get());
971 void RenderProcessHostImpl::RegisterMojoServices() {
972 #if !defined(OS_ANDROID)
973 mojo_application_host_->service_registry()->AddService(
974 base::Bind(&device::BatteryMonitorImpl::Create));
976 mojo_application_host_->service_registry()->AddService(
977 base::Bind(&device::VibrationManagerImpl::Create));
978 #endif
980 mojo_application_host_->service_registry()->AddService(
981 base::Bind(&PermissionServiceContext::CreateService,
982 base::Unretained(permission_service_context_.get())));
984 mojo_application_host_->service_registry()->AddService(base::Bind(
985 &BackgroundSyncContextImpl::CreateService,
986 base::Unretained(storage_partition_impl_->GetBackgroundSyncContext())));
988 mojo_application_host_->service_registry()->AddService(base::Bind(
989 &content::ServicePortServiceImpl::Create,
990 make_scoped_refptr(storage_partition_impl_->GetNavigatorConnectContext()),
991 message_port_message_filter_));
993 #if defined(OS_ANDROID)
994 ServiceRegistrarAndroid::RegisterProcessHostServices(
995 mojo_application_host_->service_registry_android());
996 #endif
998 GetContentClient()->browser()->RegisterRenderProcessMojoServices(
999 mojo_application_host_->service_registry());
1002 int RenderProcessHostImpl::GetNextRoutingID() {
1003 return widget_helper_->GetNextRoutingID();
1006 void RenderProcessHostImpl::ResumeDeferredNavigation(
1007 const GlobalRequestID& request_id) {
1008 widget_helper_->ResumeDeferredNavigation(request_id);
1011 void RenderProcessHostImpl::NotifyTimezoneChange(const std::string& zone_id) {
1012 Send(new ViewMsg_TimezoneChange(zone_id));
1015 ServiceRegistry* RenderProcessHostImpl::GetServiceRegistry() {
1016 DCHECK(mojo_application_host_);
1017 return mojo_application_host_->service_registry();
1020 const base::TimeTicks& RenderProcessHostImpl::GetInitTimeForNavigationMetrics()
1021 const {
1022 return init_time_;
1025 bool RenderProcessHostImpl::SubscribeUniformEnabled() const {
1026 return subscribe_uniform_enabled_;
1029 void RenderProcessHostImpl::OnAddSubscription(unsigned int target) {
1030 DCHECK(subscribe_uniform_enabled_);
1031 subscription_set_.insert(target);
1032 const gpu::ValueState* state = pending_valuebuffer_state_->GetState(target);
1033 if (state) {
1034 SendUpdateValueState(target, *state);
1038 void RenderProcessHostImpl::OnRemoveSubscription(unsigned int target) {
1039 DCHECK(subscribe_uniform_enabled_);
1040 subscription_set_.erase(target);
1043 void RenderProcessHostImpl::SendUpdateValueState(unsigned int target,
1044 const gpu::ValueState& state) {
1045 DCHECK(subscribe_uniform_enabled_);
1046 if (subscription_set_.find(target) != subscription_set_.end()) {
1047 GpuProcessHost::SendOnIO(
1048 GpuProcessHost::GPU_PROCESS_KIND_SANDBOXED,
1049 CAUSE_FOR_GPU_LAUNCH_NO_LAUNCH,
1050 new GpuMsg_UpdateValueState(id_, target, state));
1051 } else {
1052 // Store the ValueState locally in case a Valuebuffer subscribes to it later
1053 pending_valuebuffer_state_->UpdateState(target, state);
1057 #if defined(ENABLE_BROWSER_CDMS)
1058 media::BrowserCdm* RenderProcessHostImpl::GetBrowserCdm(int render_frame_id,
1059 int cdm_id) const {
1060 DCHECK_CURRENTLY_ON(BrowserThread::UI);
1061 BrowserCdmManager* manager = BrowserCdmManager::FromProcess(GetID());
1062 if (!manager)
1063 return nullptr;
1064 return manager->GetCdm(render_frame_id, cdm_id);
1066 #endif
1068 void RenderProcessHostImpl::AddRoute(
1069 int32 routing_id,
1070 IPC::Listener* listener) {
1071 CHECK(!listeners_.Lookup(routing_id))
1072 << "Found Routing ID Conflict: " << routing_id;
1073 listeners_.AddWithID(listener, routing_id);
1076 void RenderProcessHostImpl::RemoveRoute(int32 routing_id) {
1077 DCHECK(listeners_.Lookup(routing_id) != NULL);
1078 listeners_.Remove(routing_id);
1080 // Keep the one renderer thread around forever in single process mode.
1081 if (!run_renderer_in_process())
1082 Cleanup();
1085 void RenderProcessHostImpl::AddObserver(RenderProcessHostObserver* observer) {
1086 observers_.AddObserver(observer);
1089 void RenderProcessHostImpl::RemoveObserver(
1090 RenderProcessHostObserver* observer) {
1091 observers_.RemoveObserver(observer);
1094 void RenderProcessHostImpl::ShutdownForBadMessage() {
1095 base::CommandLine* command_line = base::CommandLine::ForCurrentProcess();
1096 if (command_line->HasSwitch(switches::kDisableKillAfterBadIPC))
1097 return;
1099 if (run_renderer_in_process()) {
1100 // In single process mode it is better if we don't suicide but just
1101 // crash.
1102 CHECK(false);
1104 // We kill the renderer but don't include a NOTREACHED, because we want the
1105 // browser to try to survive when it gets illegal messages from the renderer.
1106 Shutdown(RESULT_CODE_KILLED_BAD_MESSAGE, false);
1109 void RenderProcessHostImpl::WidgetRestored() {
1110 // Verify we were properly backgrounded.
1111 DCHECK_EQ(backgrounded_, (visible_widgets_ == 0));
1112 visible_widgets_++;
1113 SetBackgrounded(false);
1116 void RenderProcessHostImpl::WidgetHidden() {
1117 // On startup, the browser will call Hide
1118 if (backgrounded_)
1119 return;
1121 DCHECK_EQ(backgrounded_, (visible_widgets_ == 0));
1122 visible_widgets_--;
1123 DCHECK_GE(visible_widgets_, 0);
1124 if (visible_widgets_ == 0) {
1125 DCHECK(!backgrounded_);
1126 SetBackgrounded(true);
1130 int RenderProcessHostImpl::VisibleWidgetCount() const {
1131 return visible_widgets_;
1134 bool RenderProcessHostImpl::IsForGuestsOnly() const {
1135 return is_for_guests_only_;
1138 StoragePartition* RenderProcessHostImpl::GetStoragePartition() const {
1139 return storage_partition_impl_;
1142 static void AppendCompositorCommandLineFlags(base::CommandLine* command_line) {
1143 if (IsPropertyTreeVerificationEnabled())
1144 command_line->AppendSwitch(cc::switches::kEnablePropertyTreeVerification);
1146 if (IsDelegatedRendererEnabled())
1147 command_line->AppendSwitch(switches::kEnableDelegatedRenderer);
1149 command_line->AppendSwitchASCII(
1150 switches::kNumRasterThreads,
1151 base::IntToString(NumberOfRendererRasterThreads()));
1153 if (IsGpuRasterizationEnabled())
1154 command_line->AppendSwitch(switches::kEnableGpuRasterization);
1156 int msaa_sample_count = GpuRasterizationMSAASampleCount();
1157 if (msaa_sample_count >= 0) {
1158 command_line->AppendSwitchASCII(
1159 switches::kGpuRasterizationMSAASampleCount,
1160 base::IntToString(msaa_sample_count));
1163 if (IsZeroCopyUploadEnabled())
1164 command_line->AppendSwitch(switches::kEnableZeroCopy);
1165 if (IsPersistentGpuMemoryBufferEnabled())
1166 command_line->AppendSwitch(switches::kEnablePersistentGpuMemoryBuffer);
1168 if (IsForceGpuRasterizationEnabled())
1169 command_line->AppendSwitch(switches::kForceGpuRasterization);
1171 gfx::BufferUsage buffer_usage = IsPersistentGpuMemoryBufferEnabled()
1172 ? gfx::BufferUsage::PERSISTENT_MAP
1173 : gfx::BufferUsage::MAP;
1174 std::vector<unsigned> image_targets(
1175 static_cast<size_t>(gfx::BufferFormat::LAST) + 1, GL_TEXTURE_2D);
1176 for (size_t format = 0;
1177 format < static_cast<size_t>(gfx::BufferFormat::LAST) + 1; format++) {
1178 image_targets[format] =
1179 BrowserGpuMemoryBufferManager::GetImageTextureTarget(
1180 static_cast<gfx::BufferFormat>(format), buffer_usage);
1182 command_line->AppendSwitchASCII(switches::kContentImageTextureTarget,
1183 UintVectorToString(image_targets));
1185 command_line->AppendSwitchASCII(
1186 switches::kVideoImageTextureTarget,
1187 base::UintToString(BrowserGpuMemoryBufferManager::GetImageTextureTarget(
1188 gfx::BufferFormat::R_8, gfx::BufferUsage::MAP)));
1190 // Appending disable-gpu-feature switches due to software rendering list.
1191 GpuDataManagerImpl* gpu_data_manager = GpuDataManagerImpl::GetInstance();
1192 DCHECK(gpu_data_manager);
1193 gpu_data_manager->AppendRendererCommandLine(command_line);
1196 void RenderProcessHostImpl::AppendRendererCommandLine(
1197 base::CommandLine* command_line) const {
1198 // Pass the process type first, so it shows first in process listings.
1199 command_line->AppendSwitchASCII(switches::kProcessType,
1200 switches::kRendererProcess);
1202 // Now send any options from our own command line we want to propagate.
1203 const base::CommandLine& browser_command_line =
1204 *base::CommandLine::ForCurrentProcess();
1205 PropagateBrowserCommandLineToRenderer(browser_command_line, command_line);
1207 // Pass on the browser locale.
1208 const std::string locale =
1209 GetContentClient()->browser()->GetApplicationLocale();
1210 command_line->AppendSwitchASCII(switches::kLang, locale);
1212 // If we run base::FieldTrials, we want to pass to their state to the
1213 // renderer so that it can act in accordance with each state, or record
1214 // histograms relating to the base::FieldTrial states.
1215 std::string field_trial_states;
1216 base::FieldTrialList::AllStatesToString(&field_trial_states);
1217 if (!field_trial_states.empty()) {
1218 command_line->AppendSwitchASCII(switches::kForceFieldTrials,
1219 field_trial_states);
1222 GetContentClient()->browser()->AppendExtraCommandLineSwitches(
1223 command_line, GetID());
1225 if (IsPinchToZoomEnabled())
1226 command_line->AppendSwitch(switches::kEnablePinch);
1228 #if defined(OS_WIN)
1229 command_line->AppendSwitchASCII(switches::kDeviceScaleFactor,
1230 base::DoubleToString(gfx::GetDPIScale()));
1231 #endif
1233 AppendCompositorCommandLineFlags(command_line);
1236 void RenderProcessHostImpl::PropagateBrowserCommandLineToRenderer(
1237 const base::CommandLine& browser_cmd,
1238 base::CommandLine* renderer_cmd) const {
1239 // Propagate the following switches to the renderer command line (along
1240 // with any associated values) if present in the browser command line.
1241 static const char* const kSwitchNames[] = {
1242 switches::kAllowLoopbackInPeerConnection,
1243 switches::kAudioBufferSize,
1244 switches::kBlinkPlatformLogChannels,
1245 switches::kBlinkSettings,
1246 switches::kDefaultTileWidth,
1247 switches::kDefaultTileHeight,
1248 switches::kDisable3DAPIs,
1249 switches::kDisableAcceleratedJpegDecoding,
1250 switches::kDisableAcceleratedVideoDecode,
1251 switches::kDisableBlinkFeatures,
1252 switches::kDisableBreakpad,
1253 switches::kDisablePreferCompositingToLCDText,
1254 switches::kDisableDatabases,
1255 switches::kDisableDelayAgnosticAec,
1256 switches::kDisableDirectNPAPIRequests,
1257 switches::kDisableDisplayList2dCanvas,
1258 switches::kDisableDistanceFieldText,
1259 switches::kDisableEncryptedMedia,
1260 switches::kDisableFileSystem,
1261 switches::kDisableGpuCompositing,
1262 switches::kDisableGpuMemoryBufferVideoFrames,
1263 switches::kDisableGpuVsync,
1264 switches::kDisableLowResTiling,
1265 switches::kDisableHistogramCustomizer,
1266 switches::kDisableIconNtp,
1267 switches::kDisableLCDText,
1268 switches::kDisableLocalStorage,
1269 switches::kDisableLogging,
1270 switches::kDisableMediaSource,
1271 switches::kDisableMojoChannel,
1272 switches::kDisableNewVideoRenderer,
1273 switches::kDisableNotifications,
1274 switches::kDisableOverlayScrollbar,
1275 switches::kDisablePermissionsAPI,
1276 switches::kDisablePresentationAPI,
1277 switches::kDisablePinch,
1278 switches::kDisablePrefixedEncryptedMedia,
1279 switches::kDisableRGBA4444Textures,
1280 switches::kDisableSeccompFilterSandbox,
1281 switches::kDisableSharedWorkers,
1282 switches::kDisableSlimmingPaint,
1283 switches::kDisableSpeechAPI,
1284 switches::kDisableSVG1DOM,
1285 switches::kDisableThreadedCompositing,
1286 switches::kDisableThreadedScrolling,
1287 switches::kDisableTouchAdjustment,
1288 switches::kDisableTouchDragDrop,
1289 switches::kDisableTouchEditing,
1290 switches::kDisableV8IdleTasks,
1291 switches::kDomAutomationController,
1292 switches::kEnableBleedingEdgeRenderingFastPaths,
1293 switches::kEnableBlinkFeatures,
1294 switches::kEnableBrowserSideNavigation,
1295 switches::kEnableCompositorAnimationTimelines,
1296 switches::kEnableCredentialManagerAPI,
1297 switches::kEnableDelayAgnosticAec,
1298 switches::kEnableDisplayList2dCanvas,
1299 switches::kEnableDistanceFieldText,
1300 switches::kEnableExperimentalCanvasFeatures,
1301 switches::kEnableExperimentalWebPlatformFeatures,
1302 switches::kEnableGPUClientLogging,
1303 switches::kEnableGpuClientTracing,
1304 switches::kEnableGpuMemoryBufferVideoFrames,
1305 switches::kEnableGPUServiceLogging,
1306 switches::kEnableIconNtp,
1307 switches::kEnableLinkDisambiguationPopup,
1308 switches::kEnableLowResTiling,
1309 switches::kEnableInbandTextTracks,
1310 switches::kEnableLCDText,
1311 switches::kEnableLogging,
1312 switches::kEnableMemoryBenchmarking,
1313 switches::kEnableNetworkInformation,
1314 switches::kEnableOverlayScrollbar,
1315 switches::kEnablePinch,
1316 switches::kEnablePluginPlaceholderTesting,
1317 switches::kEnablePreciseMemoryInfo,
1318 switches::kEnablePreferCompositingToLCDText,
1319 switches::kEnablePushMessagePayload,
1320 switches::kEnableRGBA4444Textures,
1321 switches::kEnableRendererMojoChannel,
1322 switches::kEnableRTCSmoothnessAlgorithm,
1323 switches::kEnableSeccompFilterSandbox,
1324 switches::kEnableSkiaBenchmarking,
1325 switches::kEnableSlimmingPaint,
1326 switches::kEnableSlimmingPaintV2,
1327 switches::kEnableSmoothScrolling,
1328 switches::kEnableStatsTable,
1329 switches::kEnableThreadedCompositing,
1330 switches::kEnableTouchDragDrop,
1331 switches::kEnableTouchEditing,
1332 switches::kEnableUnsafeES3APIs,
1333 switches::kEnableViewport,
1334 switches::kInvertViewportScrollOrder,
1335 switches::kEnableVtune,
1336 switches::kEnableWebBluetooth,
1337 switches::kEnableWebGLDraftExtensions,
1338 switches::kEnableWebGLImageChromium,
1339 switches::kEnableWebVR,
1340 switches::kExplicitlyAllowedPorts,
1341 switches::kForceDeviceScaleFactor,
1342 switches::kForceDisplayList2dCanvas,
1343 switches::kForceOverlayFullscreenVideo,
1344 switches::kFullMemoryCrashReport,
1345 switches::kIPCConnectionTimeout,
1346 switches::kJavaScriptFlags,
1347 switches::kLoggingLevel,
1348 switches::kMainFrameResizesAreOrientationChanges,
1349 switches::kMaxUntiledLayerWidth,
1350 switches::kMaxUntiledLayerHeight,
1351 switches::kMemoryMetrics,
1352 switches::kNoReferrers,
1353 switches::kNoSandbox,
1354 switches::kOverridePluginPowerSaverForTesting,
1355 switches::kPpapiInProcess,
1356 switches::kProfilerTiming,
1357 switches::kReducedReferrerGranularity,
1358 switches::kReduceSecurityForTesting,
1359 switches::kRegisterPepperPlugins,
1360 switches::kRendererStartupDialog,
1361 switches::kRootLayerScrolls,
1362 switches::kShowPaintRects,
1363 switches::kSitePerProcess,
1364 switches::kStatsCollectionController,
1365 switches::kTestType,
1366 switches::kTouchEvents,
1367 switches::kTouchTextSelectionStrategy,
1368 switches::kTraceConfigFile,
1369 switches::kTraceToConsole,
1370 // This flag needs to be propagated to the renderer process for
1371 // --in-process-webgl.
1372 switches::kUseGL,
1373 switches::kUseMobileUserAgent,
1374 switches::kUseNormalPriorityForTileTaskWorkerThreads,
1375 switches::kV,
1376 switches::kVideoThreads,
1377 switches::kVideoUnderflowThresholdMs,
1378 switches::kVModule,
1379 // Please keep these in alphabetical order. Compositor switches here should
1380 // also be added to chrome/browser/chromeos/login/chrome_restart_request.cc.
1381 cc::switches::kCompositeToMailbox,
1382 cc::switches::kDisableCompositedAntialiasing,
1383 cc::switches::kDisableMainFrameBeforeActivation,
1384 cc::switches::kDisableThreadedAnimation,
1385 cc::switches::kEnableBeginFrameScheduling,
1386 cc::switches::kEnableGpuBenchmarking,
1387 cc::switches::kEnableMainFrameBeforeActivation,
1388 cc::switches::kShowCompositedLayerBorders,
1389 cc::switches::kShowFPSCounter,
1390 cc::switches::kShowLayerAnimationBounds,
1391 cc::switches::kShowPropertyChangedRects,
1392 cc::switches::kShowReplicaScreenSpaceRects,
1393 cc::switches::kShowScreenSpaceRects,
1394 cc::switches::kShowSurfaceDamageRects,
1395 cc::switches::kSlowDownRasterScaleFactor,
1396 cc::switches::kStrictLayerPropertyChangeChecking,
1397 cc::switches::kTopControlsHideThreshold,
1398 cc::switches::kTopControlsShowThreshold,
1400 #if defined(ENABLE_PLUGINS)
1401 switches::kEnablePepperTesting,
1402 #endif
1403 #if defined(ENABLE_WEBRTC)
1404 switches::kDisableWebRtcHWDecoding,
1405 switches::kDisableWebRtcHWEncoding,
1406 switches::kEnableWebRtcDtls12,
1407 switches::kEnableWebRtcHWH264Encoding,
1408 switches::kEnableWebRtcStunOrigin,
1409 switches::kWebRtcMaxCaptureFramerate,
1410 #endif
1411 switches::kEnableLowEndDeviceMode,
1412 switches::kDisableLowEndDeviceMode,
1413 #if defined(OS_ANDROID)
1414 switches::kDisableGestureRequirementForMediaPlayback,
1415 switches::kDisableWebAudio,
1416 switches::kRendererWaitForJavaDebugger,
1417 #endif
1418 #if defined(OS_MACOSX)
1419 // Allow this to be set when invoking the browser and relayed along.
1420 switches::kEnableSandboxLogging,
1421 #endif
1422 #if defined(OS_WIN)
1423 switches::kDisableDirectWrite,
1424 switches::kDisableWin32kRendererLockDown,
1425 switches::kTraceExportEventsToETW,
1426 #endif
1427 #if defined(USE_OZONE)
1428 switches::kOzonePlatform,
1429 #endif
1430 #if defined(OS_CHROMEOS)
1431 switches::kDisableVaapiAcceleratedVideoEncode,
1432 #endif
1434 renderer_cmd->CopySwitchesFrom(browser_cmd, kSwitchNames,
1435 arraysize(kSwitchNames));
1437 if (browser_cmd.HasSwitch(switches::kTraceStartup) &&
1438 BrowserMainLoop::GetInstance()->is_tracing_startup_for_duration()) {
1439 // Pass kTraceStartup switch to renderer only if startup tracing has not
1440 // finished.
1441 renderer_cmd->AppendSwitchASCII(
1442 switches::kTraceStartup,
1443 browser_cmd.GetSwitchValueASCII(switches::kTraceStartup));
1446 #if defined(ENABLE_WEBRTC)
1447 // Only run the Stun trials in the first renderer.
1448 if (!has_done_stun_trials &&
1449 browser_cmd.HasSwitch(switches::kWebRtcStunProbeTrialParameter)) {
1450 has_done_stun_trials = true;
1451 renderer_cmd->AppendSwitchASCII(
1452 switches::kWebRtcStunProbeTrialParameter,
1453 browser_cmd.GetSwitchValueASCII(
1454 switches::kWebRtcStunProbeTrialParameter));
1456 #endif
1458 // Disable databases in incognito mode.
1459 if (GetBrowserContext()->IsOffTheRecord() &&
1460 !browser_cmd.HasSwitch(switches::kDisableDatabases)) {
1461 renderer_cmd->AppendSwitch(switches::kDisableDatabases);
1464 // Add kWaitForDebugger to let renderer process wait for a debugger.
1465 if (browser_cmd.HasSwitch(switches::kWaitForDebuggerChildren)) {
1466 // Look to pass-on the kWaitForDebugger flag.
1467 std::string value =
1468 browser_cmd.GetSwitchValueASCII(switches::kWaitForDebuggerChildren);
1469 if (value.empty() || value == switches::kRendererProcess) {
1470 renderer_cmd->AppendSwitch(switches::kWaitForDebugger);
1475 base::ProcessHandle RenderProcessHostImpl::GetHandle() const {
1476 if (run_renderer_in_process())
1477 return base::GetCurrentProcessHandle();
1479 if (!child_process_launcher_.get() || child_process_launcher_->IsStarting())
1480 return base::kNullProcessHandle;
1482 return child_process_launcher_->GetProcess().Handle();
1485 bool RenderProcessHostImpl::Shutdown(int exit_code, bool wait) {
1486 if (run_renderer_in_process())
1487 return false; // Single process mode never shuts down the renderer.
1489 #if defined(OS_ANDROID)
1490 // Android requires a different approach for killing.
1491 StopChildProcess(GetHandle());
1492 return true;
1493 #else
1494 if (!child_process_launcher_.get() || child_process_launcher_->IsStarting())
1495 return false;
1497 return child_process_launcher_->GetProcess().Terminate(exit_code, wait);
1498 #endif
1501 bool RenderProcessHostImpl::FastShutdownIfPossible() {
1502 if (run_renderer_in_process())
1503 return false; // Single process mode never shuts down the renderer.
1505 if (!GetContentClient()->browser()->IsFastShutdownPossible())
1506 return false;
1508 if (!child_process_launcher_.get() ||
1509 child_process_launcher_->IsStarting() ||
1510 !GetHandle())
1511 return false; // Render process hasn't started or is probably crashed.
1513 // Test if there's an unload listener.
1514 // NOTE: It's possible that an onunload listener may be installed
1515 // while we're shutting down, so there's a small race here. Given that
1516 // the window is small, it's unlikely that the web page has much
1517 // state that will be lost by not calling its unload handlers properly.
1518 if (!SuddenTerminationAllowed())
1519 return false;
1521 if (worker_ref_count_ != 0) {
1522 if (survive_for_worker_start_time_.is_null())
1523 survive_for_worker_start_time_ = base::TimeTicks::Now();
1524 return false;
1527 // Set this before ProcessDied() so observers can tell if the render process
1528 // died due to fast shutdown versus another cause.
1529 fast_shutdown_started_ = true;
1531 ProcessDied(false /* already_dead */, nullptr);
1532 return true;
1535 bool RenderProcessHostImpl::Send(IPC::Message* msg) {
1536 TRACE_EVENT0("renderer_host", "RenderProcessHostImpl::Send");
1537 if (!channel_) {
1538 if (!is_initialized_) {
1539 queued_messages_.push(msg);
1540 return true;
1541 } else {
1542 delete msg;
1543 return false;
1547 if (child_process_launcher_.get() && child_process_launcher_->IsStarting()) {
1548 queued_messages_.push(msg);
1549 return true;
1552 return channel_->Send(msg);
1555 bool RenderProcessHostImpl::OnMessageReceived(const IPC::Message& msg) {
1556 // If we're about to be deleted, or have initiated the fast shutdown sequence,
1557 // we ignore incoming messages.
1559 if (deleting_soon_ || fast_shutdown_started_)
1560 return false;
1562 mark_child_process_activity_time();
1563 if (msg.routing_id() == MSG_ROUTING_CONTROL) {
1564 // Dispatch control messages.
1565 IPC_BEGIN_MESSAGE_MAP(RenderProcessHostImpl, msg)
1566 IPC_MESSAGE_HANDLER(ChildProcessHostMsg_ShutdownRequest,
1567 OnShutdownRequest)
1568 IPC_MESSAGE_HANDLER(ViewHostMsg_SuddenTerminationChanged,
1569 SuddenTerminationChanged)
1570 IPC_MESSAGE_HANDLER(ViewHostMsg_UserMetricsRecordAction,
1571 OnUserMetricsRecordAction)
1572 IPC_MESSAGE_HANDLER(ViewHostMsg_SavedPageAsMHTML, OnSavedPageAsMHTML)
1573 IPC_MESSAGE_HANDLER(ViewHostMsg_Close_ACK, OnCloseACK)
1574 #if defined(ENABLE_WEBRTC)
1575 IPC_MESSAGE_HANDLER(AecDumpMsg_RegisterAecDumpConsumer,
1576 OnRegisterAecDumpConsumer)
1577 IPC_MESSAGE_HANDLER(AecDumpMsg_UnregisterAecDumpConsumer,
1578 OnUnregisterAecDumpConsumer)
1579 #endif
1580 // Adding single handlers for your service here is fine, but once your
1581 // service needs more than one handler, please extract them into a new
1582 // message filter and add that filter to CreateMessageFilters().
1583 IPC_END_MESSAGE_MAP()
1585 return true;
1588 // Dispatch incoming messages to the appropriate IPC::Listener.
1589 IPC::Listener* listener = listeners_.Lookup(msg.routing_id());
1590 if (!listener) {
1591 if (msg.is_sync()) {
1592 // The listener has gone away, so we must respond or else the caller will
1593 // hang waiting for a reply.
1594 IPC::Message* reply = IPC::SyncMessage::GenerateReply(&msg);
1595 reply->set_reply_error();
1596 Send(reply);
1598 return true;
1600 return listener->OnMessageReceived(msg);
1603 void RenderProcessHostImpl::OnChannelConnected(int32 peer_pid) {
1604 #if defined(IPC_MESSAGE_LOG_ENABLED)
1605 Send(new ChildProcessMsg_SetIPCLoggingEnabled(
1606 IPC::Logging::GetInstance()->Enabled()));
1607 #endif
1609 tracked_objects::ThreadData::Status status =
1610 tracked_objects::ThreadData::status();
1611 Send(new ChildProcessMsg_SetProfilerStatus(status));
1613 #if defined(OS_MACOSX) && !defined(OS_IOS)
1614 io_surface_manager_token_ =
1615 BrowserIOSurfaceManager::GetInstance()->GenerateChildProcessToken(
1616 GetID());
1617 Send(new ChildProcessMsg_SetIOSurfaceManagerToken(io_surface_manager_token_));
1618 #endif
1620 #if defined(USE_OZONE)
1621 Send(new ChildProcessMsg_InitializeClientNativePixmapFactory(
1622 base::FileDescriptor(
1623 ui::OzonePlatform::GetInstance()->OpenClientNativePixmapDevice())));
1624 #endif
1626 // Inform AudioInputRendererHost about the new render process PID.
1627 // AudioInputRendererHost is reference counted, so it's lifetime is
1628 // guarantueed during the lifetime of the closure.
1629 BrowserThread::PostTask(
1630 BrowserThread::IO, FROM_HERE,
1631 base::Bind(&AudioInputRendererHost::set_renderer_pid,
1632 audio_input_renderer_host_,
1633 peer_pid));
1636 void RenderProcessHostImpl::OnChannelError() {
1637 ProcessDied(true /* already_dead */, nullptr);
1640 void RenderProcessHostImpl::OnBadMessageReceived(const IPC::Message& message) {
1641 // Message de-serialization failed. We consider this a capital crime. Kill the
1642 // renderer if we have one.
1643 LOG(ERROR) << "bad message " << message.type() << " terminating renderer.";
1644 BrowserChildProcessHostImpl::HistogramBadMessageTerminated(
1645 PROCESS_TYPE_RENDERER);
1647 // Create a memory dump. This will contain enough stack frames to work out
1648 // what the bad message was.
1649 base::debug::DumpWithoutCrashing();
1651 bad_message::ReceivedBadMessage(this,
1652 bad_message::RPH_DESERIALIZATION_FAILED);
1655 BrowserContext* RenderProcessHostImpl::GetBrowserContext() const {
1656 return browser_context_;
1659 bool RenderProcessHostImpl::InSameStoragePartition(
1660 StoragePartition* partition) const {
1661 return storage_partition_impl_ == partition;
1664 int RenderProcessHostImpl::GetID() const {
1665 return id_;
1668 bool RenderProcessHostImpl::HasConnection() const {
1669 return channel_.get() != NULL;
1672 void RenderProcessHostImpl::SetIgnoreInputEvents(bool ignore_input_events) {
1673 ignore_input_events_ = ignore_input_events;
1676 bool RenderProcessHostImpl::IgnoreInputEvents() const {
1677 return ignore_input_events_;
1680 void RenderProcessHostImpl::Cleanup() {
1681 // If within_process_died_observer_ is true, one of our observers performed an
1682 // action that caused us to die (e.g. http://crbug.com/339504). Therefore,
1683 // delay the destruction until all of the observer callbacks have been made,
1684 // and guarantee that the RenderProcessHostDestroyed observer callback is
1685 // always the last callback fired.
1686 if (within_process_died_observer_) {
1687 delayed_cleanup_needed_ = true;
1688 return;
1690 delayed_cleanup_needed_ = false;
1692 // Records the time when the process starts surviving for workers for UMA.
1693 if (listeners_.IsEmpty() && worker_ref_count_ > 0 &&
1694 survive_for_worker_start_time_.is_null()) {
1695 survive_for_worker_start_time_ = base::TimeTicks::Now();
1698 // When there are no other owners of this object, we can delete ourselves.
1699 if (listeners_.IsEmpty() && worker_ref_count_ == 0) {
1700 if (!survive_for_worker_start_time_.is_null()) {
1701 UMA_HISTOGRAM_LONG_TIMES(
1702 "SharedWorker.RendererSurviveForWorkerTime",
1703 base::TimeTicks::Now() - survive_for_worker_start_time_);
1706 if (max_worker_count_ > 0) {
1707 // Record the max number of workers (SharedWorker or ServiceWorker)
1708 // that are simultaneously hosted in this renderer process.
1709 UMA_HISTOGRAM_COUNTS("Render.Workers.MaxWorkerCountInRendererProcess",
1710 max_worker_count_);
1713 // We cannot clean up twice; if this fails, there is an issue with our
1714 // control flow.
1715 DCHECK(!deleting_soon_);
1717 DCHECK_EQ(0, pending_views_);
1718 FOR_EACH_OBSERVER(RenderProcessHostObserver,
1719 observers_,
1720 RenderProcessHostDestroyed(this));
1721 NotificationService::current()->Notify(
1722 NOTIFICATION_RENDERER_PROCESS_TERMINATED,
1723 Source<RenderProcessHost>(this),
1724 NotificationService::NoDetails());
1726 #ifndef NDEBUG
1727 is_self_deleted_ = true;
1728 #endif
1729 base::MessageLoop::current()->DeleteSoon(FROM_HERE, this);
1730 deleting_soon_ = true;
1731 // It's important not to wait for the DeleteTask to delete the channel
1732 // proxy. Kill it off now. That way, in case the profile is going away, the
1733 // rest of the objects attached to this RenderProcessHost start going
1734 // away first, since deleting the channel proxy will post a
1735 // OnChannelClosed() to IPC::ChannelProxy::Context on the IO thread.
1736 channel_.reset();
1738 // The following members should be cleared in ProcessDied() as well!
1739 gpu_message_filter_ = NULL;
1740 message_port_message_filter_ = NULL;
1742 RemoveUserData(kSessionStorageHolderKey);
1744 // Remove ourself from the list of renderer processes so that we can't be
1745 // reused in between now and when the Delete task runs.
1746 UnregisterHost(GetID());
1748 #if defined(OS_MACOSX) && !defined(OS_IOS)
1749 if (!io_surface_manager_token_.IsZero()) {
1750 BrowserIOSurfaceManager::GetInstance()->InvalidateChildProcessToken(
1751 io_surface_manager_token_);
1752 io_surface_manager_token_.SetZero();
1754 #endif
1758 void RenderProcessHostImpl::AddPendingView() {
1759 pending_views_++;
1762 void RenderProcessHostImpl::RemovePendingView() {
1763 DCHECK(pending_views_);
1764 pending_views_--;
1767 void RenderProcessHostImpl::SetSuddenTerminationAllowed(bool enabled) {
1768 sudden_termination_allowed_ = enabled;
1771 bool RenderProcessHostImpl::SuddenTerminationAllowed() const {
1772 return sudden_termination_allowed_;
1775 base::TimeDelta RenderProcessHostImpl::GetChildProcessIdleTime() const {
1776 return base::TimeTicks::Now() - child_process_activity_time_;
1779 void RenderProcessHostImpl::ResumeRequestsForView(int route_id) {
1780 widget_helper_->ResumeRequestsForView(route_id);
1783 void RenderProcessHostImpl::FilterURL(bool empty_allowed, GURL* url) {
1784 FilterURL(this, empty_allowed, url);
1787 #if defined(ENABLE_WEBRTC)
1788 void RenderProcessHostImpl::EnableAudioDebugRecordings(
1789 const base::FilePath& file) {
1790 DCHECK_CURRENTLY_ON(BrowserThread::UI);
1792 // Enable AEC dump for each registered consumer.
1793 base::FilePath file_with_extensions =
1794 GetAecDumpFilePathWithExtensions(file);
1795 for (std::vector<int>::iterator it = aec_dump_consumers_.begin();
1796 it != aec_dump_consumers_.end(); ++it) {
1797 EnableAecDumpForId(file_with_extensions, *it);
1800 // Enable mic input recording. AudioInputRendererHost is reference counted, so
1801 // it's lifetime is guarantueed during the lifetime of the closure.
1802 BrowserThread::PostTask(
1803 BrowserThread::IO, FROM_HERE,
1804 base::Bind(&AudioInputRendererHost::EnableDebugRecording,
1805 audio_input_renderer_host_,
1806 file));
1809 void RenderProcessHostImpl::DisableAudioDebugRecordings() {
1810 DCHECK_CURRENTLY_ON(BrowserThread::UI);
1812 // Posting on the FILE thread and then replying back on the UI thread is only
1813 // for avoiding races between enable and disable. Nothing is done on the FILE
1814 // thread.
1815 BrowserThread::PostTaskAndReply(
1816 BrowserThread::FILE, FROM_HERE,
1817 base::Bind(&DisableAecDumpOnFileThread),
1818 base::Bind(&RenderProcessHostImpl::SendDisableAecDumpToRenderer,
1819 weak_factory_.GetWeakPtr()));
1821 // AudioInputRendererHost is reference counted, so it's lifetime is
1822 // guaranteed during the lifetime of the closure.
1823 BrowserThread::PostTask(
1824 BrowserThread::IO, FROM_HERE,
1825 base::Bind(
1826 &AudioInputRendererHost::DisableDebugRecording,
1827 audio_input_renderer_host_));
1830 void RenderProcessHostImpl::SetWebRtcLogMessageCallback(
1831 base::Callback<void(const std::string&)> callback) {
1832 webrtc_log_message_callback_ = callback;
1835 RenderProcessHostImpl::WebRtcStopRtpDumpCallback
1836 RenderProcessHostImpl::StartRtpDump(
1837 bool incoming,
1838 bool outgoing,
1839 const WebRtcRtpPacketCallback& packet_callback) {
1840 if (!p2p_socket_dispatcher_host_.get())
1841 return WebRtcStopRtpDumpCallback();
1843 BrowserThread::PostTask(BrowserThread::IO,
1844 FROM_HERE,
1845 base::Bind(&P2PSocketDispatcherHost::StartRtpDump,
1846 p2p_socket_dispatcher_host_,
1847 incoming,
1848 outgoing,
1849 packet_callback));
1851 if (stop_rtp_dump_callback_.is_null()) {
1852 stop_rtp_dump_callback_ =
1853 base::Bind(&P2PSocketDispatcherHost::StopRtpDumpOnUIThread,
1854 p2p_socket_dispatcher_host_);
1856 return stop_rtp_dump_callback_;
1858 #endif
1860 IPC::ChannelProxy* RenderProcessHostImpl::GetChannel() {
1861 return channel_.get();
1864 void RenderProcessHostImpl::AddFilter(BrowserMessageFilter* filter) {
1865 channel_->AddFilter(filter->GetFilter());
1868 bool RenderProcessHostImpl::FastShutdownForPageCount(size_t count) {
1869 if (GetActiveViewCount() == count)
1870 return FastShutdownIfPossible();
1871 return false;
1874 bool RenderProcessHostImpl::FastShutdownStarted() const {
1875 return fast_shutdown_started_;
1878 // static
1879 void RenderProcessHostImpl::RegisterHost(int host_id, RenderProcessHost* host) {
1880 g_all_hosts.Get().AddWithID(host, host_id);
1883 // static
1884 void RenderProcessHostImpl::UnregisterHost(int host_id) {
1885 RenderProcessHost* host = g_all_hosts.Get().Lookup(host_id);
1886 if (!host)
1887 return;
1889 g_all_hosts.Get().Remove(host_id);
1891 // Look up the map of site to process for the given browser_context,
1892 // in case we need to remove this process from it. It will be registered
1893 // under any sites it rendered that use process-per-site mode.
1894 SiteProcessMap* map =
1895 GetSiteProcessMapForBrowserContext(host->GetBrowserContext());
1896 map->RemoveProcess(host);
1899 // static
1900 void RenderProcessHostImpl::FilterURL(RenderProcessHost* rph,
1901 bool empty_allowed,
1902 GURL* url) {
1903 ChildProcessSecurityPolicyImpl* policy =
1904 ChildProcessSecurityPolicyImpl::GetInstance();
1906 if (empty_allowed && url->is_empty())
1907 return;
1909 // The browser process should never hear the swappedout:// URL from any
1910 // of the renderer's messages. Check for this in debug builds, but don't
1911 // let it crash a release browser.
1912 DCHECK(GURL(kSwappedOutURL) != *url);
1914 if (!url->is_valid()) {
1915 // Have to use about:blank for the denied case, instead of an empty GURL.
1916 // This is because the browser treats navigation to an empty GURL as a
1917 // navigation to the home page. This is often a privileged page
1918 // (chrome://newtab/) which is exactly what we don't want.
1919 *url = GURL(url::kAboutBlankURL);
1920 return;
1923 if (url->SchemeIs(url::kAboutScheme)) {
1924 // The renderer treats all URLs in the about: scheme as being about:blank.
1925 // Canonicalize about: URLs to about:blank.
1926 *url = GURL(url::kAboutBlankURL);
1929 // Do not allow browser plugin guests to navigate to non-web URLs, since they
1930 // cannot swap processes or grant bindings.
1931 bool non_web_url_in_guest = rph->IsForGuestsOnly() &&
1932 !(url->is_valid() && policy->IsWebSafeScheme(url->scheme()));
1934 if (non_web_url_in_guest || !policy->CanRequestURL(rph->GetID(), *url)) {
1935 // If this renderer is not permitted to request this URL, we invalidate the
1936 // URL. This prevents us from storing the blocked URL and becoming confused
1937 // later.
1938 VLOG(1) << "Blocked URL " << url->spec();
1939 *url = GURL(url::kAboutBlankURL);
1943 // static
1944 bool RenderProcessHostImpl::IsSuitableHost(
1945 RenderProcessHost* host,
1946 BrowserContext* browser_context,
1947 const GURL& site_url) {
1948 if (run_renderer_in_process())
1949 return true;
1951 if (host->GetBrowserContext() != browser_context)
1952 return false;
1954 // Do not allow sharing of guest hosts. This is to prevent bugs where guest
1955 // and non-guest storage gets mixed. In the future, we might consider enabling
1956 // the sharing of guests, in this case this check should be removed and
1957 // InSameStoragePartition should handle the possible sharing.
1958 if (host->IsForGuestsOnly())
1959 return false;
1961 // Check whether the given host and the intended site_url will be using the
1962 // same StoragePartition, since a RenderProcessHost can only support a single
1963 // StoragePartition. This is relevant for packaged apps.
1964 StoragePartition* dest_partition =
1965 BrowserContext::GetStoragePartitionForSite(browser_context, site_url);
1966 if (!host->InSameStoragePartition(dest_partition))
1967 return false;
1969 // TODO(nick): Consult the SiteIsolationPolicy here. https://crbug.com/513036
1970 if (ChildProcessSecurityPolicyImpl::GetInstance()->HasWebUIBindings(
1971 host->GetID()) !=
1972 WebUIControllerFactoryRegistry::GetInstance()->UseWebUIBindingsForURL(
1973 browser_context, site_url)) {
1974 return false;
1977 return GetContentClient()->browser()->IsSuitableHost(host, site_url);
1980 // static
1981 bool RenderProcessHost::run_renderer_in_process() {
1982 return g_run_renderer_in_process_;
1985 // static
1986 void RenderProcessHost::SetRunRendererInProcess(bool value) {
1987 g_run_renderer_in_process_ = value;
1989 base::CommandLine* command_line = base::CommandLine::ForCurrentProcess();
1990 if (value) {
1991 if (!command_line->HasSwitch(switches::kLang)) {
1992 // Modify the current process' command line to include the browser locale,
1993 // as the renderer expects this flag to be set.
1994 const std::string locale =
1995 GetContentClient()->browser()->GetApplicationLocale();
1996 command_line->AppendSwitchASCII(switches::kLang, locale);
1998 // TODO(piman): we should really send configuration through bools rather
1999 // than by parsing strings, i.e. sending an IPC rather than command line
2000 // args. crbug.com/314909
2001 AppendCompositorCommandLineFlags(command_line);
2005 // static
2006 RenderProcessHost::iterator RenderProcessHost::AllHostsIterator() {
2007 DCHECK_CURRENTLY_ON(BrowserThread::UI);
2008 return iterator(g_all_hosts.Pointer());
2011 // static
2012 RenderProcessHost* RenderProcessHost::FromID(int render_process_id) {
2013 DCHECK_CURRENTLY_ON(BrowserThread::UI);
2014 return g_all_hosts.Get().Lookup(render_process_id);
2017 // static
2018 bool RenderProcessHost::ShouldTryToUseExistingProcessHost(
2019 BrowserContext* browser_context, const GURL& url) {
2020 // If --site-per-process is enabled, do not try to reuse renderer processes
2021 // when over the limit.
2022 // TODO(nick): This is overly conservative and isn't launchable. Move this
2023 // logic into IsSuitableHost, and check |url| against the URL the process is
2024 // dedicated to. This will allow pages from the same site to share, and will
2025 // also allow non-isolated sites to share processes. https://crbug.com/513036
2026 if (SiteIsolationPolicy::AreCrossProcessFramesPossible())
2027 return false;
2029 if (run_renderer_in_process())
2030 return true;
2032 // NOTE: Sometimes it's necessary to create more render processes than
2033 // GetMaxRendererProcessCount(), for instance when we want to create
2034 // a renderer process for a browser context that has no existing
2035 // renderers. This is OK in moderation, since the
2036 // GetMaxRendererProcessCount() is conservative.
2037 if (g_all_hosts.Get().size() >= GetMaxRendererProcessCount())
2038 return true;
2040 return GetContentClient()->browser()->
2041 ShouldTryToUseExistingProcessHost(browser_context, url);
2044 // static
2045 RenderProcessHost* RenderProcessHost::GetExistingProcessHost(
2046 BrowserContext* browser_context,
2047 const GURL& site_url) {
2048 // First figure out which existing renderers we can use.
2049 std::vector<RenderProcessHost*> suitable_renderers;
2050 suitable_renderers.reserve(g_all_hosts.Get().size());
2052 iterator iter(AllHostsIterator());
2053 while (!iter.IsAtEnd()) {
2054 if (GetContentClient()->browser()->MayReuseHost(iter.GetCurrentValue()) &&
2055 RenderProcessHostImpl::IsSuitableHost(
2056 iter.GetCurrentValue(),
2057 browser_context, site_url)) {
2058 suitable_renderers.push_back(iter.GetCurrentValue());
2060 iter.Advance();
2063 // Now pick a random suitable renderer, if we have any.
2064 if (!suitable_renderers.empty()) {
2065 int suitable_count = static_cast<int>(suitable_renderers.size());
2066 int random_index = base::RandInt(0, suitable_count - 1);
2067 return suitable_renderers[random_index];
2070 return NULL;
2073 // static
2074 bool RenderProcessHost::ShouldUseProcessPerSite(
2075 BrowserContext* browser_context,
2076 const GURL& url) {
2077 // Returns true if we should use the process-per-site model. This will be
2078 // the case if the --process-per-site switch is specified, or in
2079 // process-per-site-instance for particular sites (e.g., WebUI).
2080 // Note that --single-process is handled in ShouldTryToUseExistingProcessHost.
2081 const base::CommandLine& command_line =
2082 *base::CommandLine::ForCurrentProcess();
2083 if (command_line.HasSwitch(switches::kProcessPerSite))
2084 return true;
2086 // We want to consolidate particular sites like WebUI even when we are using
2087 // the process-per-tab or process-per-site-instance models.
2088 // Note: DevTools pages have WebUI type but should not reuse the same host.
2089 if (WebUIControllerFactoryRegistry::GetInstance()->UseWebUIForURL(
2090 browser_context, url) &&
2091 !url.SchemeIs(kChromeDevToolsScheme)) {
2092 return true;
2095 // Otherwise let the content client decide, defaulting to false.
2096 return GetContentClient()->browser()->ShouldUseProcessPerSite(browser_context,
2097 url);
2100 // static
2101 RenderProcessHost* RenderProcessHostImpl::GetProcessHostForSite(
2102 BrowserContext* browser_context,
2103 const GURL& url) {
2104 // Look up the map of site to process for the given browser_context.
2105 SiteProcessMap* map =
2106 GetSiteProcessMapForBrowserContext(browser_context);
2108 // See if we have an existing process with appropriate bindings for this site.
2109 // If not, the caller should create a new process and register it.
2110 std::string site = SiteInstance::GetSiteForURL(browser_context, url)
2111 .possibly_invalid_spec();
2112 RenderProcessHost* host = map->FindProcess(site);
2113 if (host && (!GetContentClient()->browser()->MayReuseHost(host) ||
2114 !IsSuitableHost(host, browser_context, url))) {
2115 // The registered process does not have an appropriate set of bindings for
2116 // the url. Remove it from the map so we can register a better one.
2117 RecordAction(
2118 base::UserMetricsAction("BindingsMismatch_GetProcessHostPerSite"));
2119 map->RemoveProcess(host);
2120 host = NULL;
2123 return host;
2126 void RenderProcessHostImpl::RegisterProcessHostForSite(
2127 BrowserContext* browser_context,
2128 RenderProcessHost* process,
2129 const GURL& url) {
2130 // Look up the map of site to process for the given browser_context.
2131 SiteProcessMap* map =
2132 GetSiteProcessMapForBrowserContext(browser_context);
2134 // Only register valid, non-empty sites. Empty or invalid sites will not
2135 // use process-per-site mode. We cannot check whether the process has
2136 // appropriate bindings here, because the bindings have not yet been granted.
2137 std::string site = SiteInstance::GetSiteForURL(browser_context, url)
2138 .possibly_invalid_spec();
2139 if (!site.empty())
2140 map->RegisterProcess(site, process);
2143 void RenderProcessHostImpl::ProcessDied(bool already_dead,
2144 RendererClosedDetails* known_details) {
2145 // Our child process has died. If we didn't expect it, it's a crash.
2146 // In any case, we need to let everyone know it's gone.
2147 // The OnChannelError notification can fire multiple times due to nested sync
2148 // calls to a renderer. If we don't have a valid channel here it means we
2149 // already handled the error.
2151 // It should not be possible for us to be called re-entrantly.
2152 DCHECK(!within_process_died_observer_);
2154 // It should not be possible for a process death notification to come in while
2155 // we are dying.
2156 DCHECK(!deleting_soon_);
2158 // child_process_launcher_ can be NULL in single process mode or if fast
2159 // termination happened.
2160 base::TerminationStatus status = base::TERMINATION_STATUS_NORMAL_TERMINATION;
2161 int exit_code = 0;
2162 if (known_details) {
2163 status = known_details->status;
2164 exit_code = known_details->exit_code;
2165 } else if (child_process_launcher_.get()) {
2166 status = child_process_launcher_->GetChildTerminationStatus(already_dead,
2167 &exit_code);
2168 if (already_dead && status == base::TERMINATION_STATUS_STILL_RUNNING) {
2169 // May be in case of IPC error, if it takes long time for renderer
2170 // to exit. Child process will be killed in any case during
2171 // child_process_launcher_.reset(). Make sure we will not broadcast
2172 // FrameHostMsg_RenderProcessGone with status
2173 // TERMINATION_STATUS_STILL_RUNNING, since this will break WebContentsImpl
2174 // logic.
2175 status = base::TERMINATION_STATUS_PROCESS_CRASHED;
2179 RendererClosedDetails details(status, exit_code);
2180 mojo_application_host_->WillDestroySoon();
2182 child_process_launcher_.reset();
2183 channel_.reset();
2184 while (!queued_messages_.empty()) {
2185 delete queued_messages_.front();
2186 queued_messages_.pop();
2189 within_process_died_observer_ = true;
2190 NotificationService::current()->Notify(
2191 NOTIFICATION_RENDERER_PROCESS_CLOSED,
2192 Source<RenderProcessHost>(this),
2193 Details<RendererClosedDetails>(&details));
2194 FOR_EACH_OBSERVER(RenderProcessHostObserver,
2195 observers_,
2196 RenderProcessExited(this, status, exit_code));
2197 within_process_died_observer_ = false;
2199 gpu_message_filter_ = NULL;
2200 message_port_message_filter_ = NULL;
2201 RemoveUserData(kSessionStorageHolderKey);
2203 IDMap<IPC::Listener>::iterator iter(&listeners_);
2204 while (!iter.IsAtEnd()) {
2205 iter.GetCurrentValue()->OnMessageReceived(
2206 FrameHostMsg_RenderProcessGone(iter.GetCurrentKey(),
2207 static_cast<int>(status),
2208 exit_code));
2209 iter.Advance();
2212 mojo_application_host_.reset(new MojoApplicationHost);
2214 // It's possible that one of the calls out to the observers might have caused
2215 // this object to be no longer needed.
2216 if (delayed_cleanup_needed_)
2217 Cleanup();
2219 // This object is not deleted at this point and might be reused later.
2220 // TODO(darin): clean this up
2223 size_t RenderProcessHost::GetActiveViewCount() {
2224 size_t num_active_views = 0;
2225 scoped_ptr<RenderWidgetHostIterator> widgets(
2226 RenderWidgetHost::GetRenderWidgetHosts());
2227 while (RenderWidgetHost* widget = widgets->GetNextHost()) {
2228 // Count only RenderWidgetHosts in this process.
2229 if (widget->GetProcess()->GetID() == GetID())
2230 num_active_views++;
2232 return num_active_views;
2235 // Frame subscription API for this class is for accelerated composited path
2236 // only. These calls are redirected to GpuMessageFilter.
2237 void RenderProcessHostImpl::BeginFrameSubscription(
2238 int route_id,
2239 scoped_ptr<RenderWidgetHostViewFrameSubscriber> subscriber) {
2240 if (!gpu_message_filter_)
2241 return;
2242 BrowserThread::PostTask(BrowserThread::IO, FROM_HERE, base::Bind(
2243 &GpuMessageFilter::BeginFrameSubscription,
2244 gpu_message_filter_,
2245 route_id, base::Passed(&subscriber)));
2248 void RenderProcessHostImpl::EndFrameSubscription(int route_id) {
2249 if (!gpu_message_filter_)
2250 return;
2251 BrowserThread::PostTask(BrowserThread::IO, FROM_HERE, base::Bind(
2252 &GpuMessageFilter::EndFrameSubscription,
2253 gpu_message_filter_,
2254 route_id));
2257 #if defined(ENABLE_WEBRTC)
2258 void RenderProcessHostImpl::WebRtcLogMessage(const std::string& message) {
2259 DCHECK_CURRENTLY_ON(BrowserThread::UI);
2260 if (!webrtc_log_message_callback_.is_null())
2261 webrtc_log_message_callback_.Run(message);
2263 #endif
2265 void RenderProcessHostImpl::ReleaseOnCloseACK(
2266 RenderProcessHost* host,
2267 const SessionStorageNamespaceMap& sessions,
2268 int view_route_id) {
2269 DCHECK(host);
2270 if (sessions.empty())
2271 return;
2272 SessionStorageHolder* holder = static_cast<SessionStorageHolder*>
2273 (host->GetUserData(kSessionStorageHolderKey));
2274 if (!holder) {
2275 holder = new SessionStorageHolder();
2276 host->SetUserData(
2277 kSessionStorageHolderKey,
2278 holder);
2280 holder->Hold(sessions, view_route_id);
2283 void RenderProcessHostImpl::OnShutdownRequest() {
2284 // Don't shut down if there are active RenderViews, or if there are pending
2285 // RenderViews being swapped back in.
2286 // In single process mode, we never shutdown the renderer.
2287 if (pending_views_ || run_renderer_in_process() || GetActiveViewCount() > 0)
2288 return;
2290 // Notify any contents that might have swapped out renderers from this
2291 // process. They should not attempt to swap them back in.
2292 FOR_EACH_OBSERVER(RenderProcessHostObserver, observers_,
2293 RenderProcessWillExit(this));
2295 mojo_application_host_->WillDestroySoon();
2297 Send(new ChildProcessMsg_Shutdown());
2300 void RenderProcessHostImpl::SuddenTerminationChanged(bool enabled) {
2301 SetSuddenTerminationAllowed(enabled);
2304 void RenderProcessHostImpl::SetBackgrounded(bool backgrounded) {
2305 TRACE_EVENT1("renderer_host", "RenderProcessHostImpl::SetBackgrounded",
2306 "backgrounded", backgrounded);
2307 // Note: we always set the backgrounded_ value. If the process is NULL
2308 // (and hence hasn't been created yet), we will set the process priority
2309 // later when we create the process.
2310 backgrounded_ = backgrounded;
2311 if (!child_process_launcher_.get() || child_process_launcher_->IsStarting())
2312 return;
2314 // Don't background processes which have active audio streams.
2315 if (backgrounded_ && audio_renderer_host_->HasActiveAudio())
2316 return;
2318 const base::CommandLine* command_line =
2319 base::CommandLine::ForCurrentProcess();
2320 if (command_line->HasSwitch(switches::kDisableRendererBackgrounding))
2321 return;
2323 #if defined(OS_WIN)
2324 // The cbstext.dll loads as a global GetMessage hook in the browser process
2325 // and intercepts/unintercepts the kernel32 API SetPriorityClass in a
2326 // background thread. If the UI thread invokes this API just when it is
2327 // intercepted the stack is messed up on return from the interceptor
2328 // which causes random crashes in the browser process. Our hack for now
2329 // is to not invoke the SetPriorityClass API if the dll is loaded.
2330 if (GetModuleHandle(L"cbstext.dll"))
2331 return;
2332 #endif // OS_WIN
2334 #if defined(OS_WIN) || defined(OS_MACOSX)
2335 // Same as below, but bound to an experiment (http://crbug.com/458594 on
2336 // Windows, http://crbug.com/398103 on the Mac). Enabled by default in the
2337 // absence of field trials to get coverage on the perf waterfall.
2338 base::FieldTrial* trial =
2339 base::FieldTrialList::Find("BackgroundRendererProcesses");
2340 if (!trial || !base::StartsWith(trial->group_name(), "Disallow",
2341 base::CompareCase::SENSITIVE)) {
2342 child_process_launcher_->SetProcessBackgrounded(backgrounded);
2344 #else
2345 // Control the background state from the browser process, otherwise the task
2346 // telling the renderer to "unbackground" itself may be preempted by other
2347 // tasks executing at lowered priority ahead of it or simply by not being
2348 // swiftly scheduled by the OS per the low process priority
2349 // (http://crbug.com/398103).
2350 child_process_launcher_->SetProcessBackgrounded(backgrounded);
2351 #endif // OS_WIN
2353 // Notify the child process of background state.
2354 Send(new ChildProcessMsg_SetProcessBackgrounded(backgrounded));
2357 void RenderProcessHostImpl::OnProcessLaunched() {
2358 // TODO(erikchen): Remove ScopedTracker below once http://crbug.com/465841
2359 // is fixed.
2360 tracked_objects::ScopedTracker tracking_profile1(
2361 FROM_HERE_WITH_EXPLICIT_FUNCTION(
2362 "465841 RenderProcessHostImpl::OnProcessLaunched::Start"));
2363 // No point doing anything, since this object will be destructed soon. We
2364 // especially don't want to send the RENDERER_PROCESS_CREATED notification,
2365 // since some clients might expect a RENDERER_PROCESS_TERMINATED afterwards to
2366 // properly cleanup.
2367 if (deleting_soon_)
2368 return;
2370 if (child_process_launcher_) {
2371 // TODO(erikchen): Remove ScopedTracker below once http://crbug.com/465841
2372 // is fixed.
2373 tracked_objects::ScopedTracker tracking_profile2(
2374 FROM_HERE_WITH_EXPLICIT_FUNCTION(
2375 "465841 RenderProcessHostImpl::OnProcessLaunched::Backgrounded"));
2376 DCHECK(child_process_launcher_->GetProcess().IsValid());
2377 SetBackgrounded(backgrounded_);
2380 // TODO(erikchen): Remove ScopedTracker below once http://crbug.com/465841
2381 // is fixed.
2382 tracked_objects::ScopedTracker tracking_profile3(
2383 FROM_HERE_WITH_EXPLICIT_FUNCTION(
2384 "465841 RenderProcessHostImpl::OnProcessLaunched::Notify"));
2385 // NOTE: This needs to be before sending queued messages because
2386 // ExtensionService uses this notification to initialize the renderer process
2387 // with state that must be there before any JavaScript executes.
2389 // The queued messages contain such things as "navigate". If this notification
2390 // was after, we can end up executing JavaScript before the initialization
2391 // happens.
2392 NotificationService::current()->Notify(
2393 NOTIFICATION_RENDERER_PROCESS_CREATED,
2394 Source<RenderProcessHost>(this),
2395 NotificationService::NoDetails());
2397 // TODO(erikchen): Remove ScopedTracker below once http://crbug.com/465841
2398 // is fixed.
2399 tracked_objects::ScopedTracker tracking_profile4(
2400 FROM_HERE_WITH_EXPLICIT_FUNCTION(
2401 "465841 RenderProcessHostImpl::OnProcessLaunched::MojoActivate"));
2402 // Allow Mojo to be setup before the renderer sees any Chrome IPC messages.
2403 // This way, Mojo can be safely used from the renderer in response to any
2404 // Chrome IPC message.
2405 mojo_application_host_->Activate(this, GetHandle());
2407 // TODO(erikchen): Remove ScopedTracker below once http://crbug.com/465841
2408 // is fixed.
2409 tracked_objects::ScopedTracker tracking_profile5(
2410 FROM_HERE_WITH_EXPLICIT_FUNCTION(
2411 "465841 RenderProcessHostImpl::OnProcessLaunched::MojoClientLaunch"));
2413 // TODO(erikchen): Remove ScopedTracker below once http://crbug.com/465841
2414 // is fixed.
2415 tracked_objects::ScopedTracker tracking_profile6(
2416 FROM_HERE_WITH_EXPLICIT_FUNCTION(
2417 "465841 "
2418 "RenderProcessHostImpl::OnProcessLaunched::SendQueuedMessages"));
2419 while (!queued_messages_.empty()) {
2420 Send(queued_messages_.front());
2421 queued_messages_.pop();
2424 #if defined(ENABLE_WEBRTC)
2425 // TODO(erikchen): Remove ScopedTracker below once http://crbug.com/465841
2426 // is fixed.
2427 tracked_objects::ScopedTracker tracking_profile7(
2428 FROM_HERE_WITH_EXPLICIT_FUNCTION(
2429 "465841 RenderProcessHostImpl::OnProcessLaunched::EnableAec"));
2430 if (WebRTCInternals::GetInstance()->IsAudioDebugRecordingsEnabled()) {
2431 EnableAudioDebugRecordings(
2432 WebRTCInternals::GetInstance()->GetAudioDebugRecordingsFilePath());
2434 #endif
2437 void RenderProcessHostImpl::OnProcessLaunchFailed() {
2438 // If this object will be destructed soon, then observers have already been
2439 // sent a RenderProcessHostDestroyed notification, and we must observe our
2440 // contract that says that will be the last call.
2441 if (deleting_soon_)
2442 return;
2444 // TODO(wfh): Fill in the real error code here see crbug.com/526198.
2445 RendererClosedDetails details { base::TERMINATION_STATUS_LAUNCH_FAILED,
2446 -1 };
2447 ProcessDied(true, &details);
2450 scoped_refptr<AudioRendererHost>
2451 RenderProcessHostImpl::audio_renderer_host() const {
2452 return audio_renderer_host_;
2455 void RenderProcessHostImpl::OnUserMetricsRecordAction(
2456 const std::string& action) {
2457 RecordComputedAction(action);
2460 void RenderProcessHostImpl::OnCloseACK(int old_route_id) {
2461 SessionStorageHolder* holder = static_cast<SessionStorageHolder*>
2462 (GetUserData(kSessionStorageHolderKey));
2463 if (!holder)
2464 return;
2465 holder->Release(old_route_id);
2468 void RenderProcessHostImpl::OnSavedPageAsMHTML(int job_id, int64 data_size) {
2469 MHTMLGenerationManager::GetInstance()->MHTMLGenerated(job_id, data_size);
2472 void RenderProcessHostImpl::OnGpuSwitched() {
2473 // We are updating all widgets including swapped out ones.
2474 scoped_ptr<RenderWidgetHostIterator> widgets(
2475 RenderWidgetHostImpl::GetAllRenderWidgetHosts());
2476 while (RenderWidgetHost* widget = widgets->GetNextHost()) {
2477 if (!widget->IsRenderView())
2478 continue;
2480 // Skip widgets in other processes.
2481 if (widget->GetProcess()->GetID() != GetID())
2482 continue;
2484 RenderViewHost* rvh = RenderViewHost::From(widget);
2485 rvh->OnWebkitPreferencesChanged();
2489 #if defined(ENABLE_WEBRTC)
2490 void RenderProcessHostImpl::OnRegisterAecDumpConsumer(int id) {
2491 BrowserThread::PostTask(
2492 BrowserThread::UI,
2493 FROM_HERE,
2494 base::Bind(
2495 &RenderProcessHostImpl::RegisterAecDumpConsumerOnUIThread,
2496 weak_factory_.GetWeakPtr(),
2497 id));
2500 void RenderProcessHostImpl::OnUnregisterAecDumpConsumer(int id) {
2501 BrowserThread::PostTask(
2502 BrowserThread::UI,
2503 FROM_HERE,
2504 base::Bind(
2505 &RenderProcessHostImpl::UnregisterAecDumpConsumerOnUIThread,
2506 weak_factory_.GetWeakPtr(),
2507 id));
2510 void RenderProcessHostImpl::RegisterAecDumpConsumerOnUIThread(int id) {
2511 DCHECK_CURRENTLY_ON(BrowserThread::UI);
2512 aec_dump_consumers_.push_back(id);
2514 if (WebRTCInternals::GetInstance()->IsAudioDebugRecordingsEnabled()) {
2515 base::FilePath file_with_extensions = GetAecDumpFilePathWithExtensions(
2516 WebRTCInternals::GetInstance()->GetAudioDebugRecordingsFilePath());
2517 EnableAecDumpForId(file_with_extensions, id);
2521 void RenderProcessHostImpl::UnregisterAecDumpConsumerOnUIThread(int id) {
2522 DCHECK_CURRENTLY_ON(BrowserThread::UI);
2523 for (std::vector<int>::iterator it = aec_dump_consumers_.begin();
2524 it != aec_dump_consumers_.end(); ++it) {
2525 if (*it == id) {
2526 aec_dump_consumers_.erase(it);
2527 break;
2532 void RenderProcessHostImpl::EnableAecDumpForId(const base::FilePath& file,
2533 int id) {
2534 DCHECK_CURRENTLY_ON(BrowserThread::UI);
2535 BrowserThread::PostTaskAndReplyWithResult(
2536 BrowserThread::FILE, FROM_HERE,
2537 base::Bind(&CreateAecDumpFileForProcess,
2538 file.AddExtension(IntToStringType(id)),
2539 GetHandle()),
2540 base::Bind(&RenderProcessHostImpl::SendAecDumpFileToRenderer,
2541 weak_factory_.GetWeakPtr(),
2542 id));
2545 void RenderProcessHostImpl::SendAecDumpFileToRenderer(
2546 int id,
2547 IPC::PlatformFileForTransit file_for_transit) {
2548 if (file_for_transit == IPC::InvalidPlatformFileForTransit())
2549 return;
2550 Send(new AecDumpMsg_EnableAecDump(id, file_for_transit));
2553 void RenderProcessHostImpl::SendDisableAecDumpToRenderer() {
2554 Send(new AecDumpMsg_DisableAecDump());
2557 base::FilePath RenderProcessHostImpl::GetAecDumpFilePathWithExtensions(
2558 const base::FilePath& file) {
2559 return file.AddExtension(IntToStringType(base::GetProcId(GetHandle())))
2560 .AddExtension(kAecDumpFileNameAddition);
2562 #endif // defined(ENABLE_WEBRTC)
2564 void RenderProcessHostImpl::IncrementWorkerRefCount() {
2565 DCHECK_CURRENTLY_ON(BrowserThread::UI);
2566 ++worker_ref_count_;
2567 if (worker_ref_count_ > max_worker_count_)
2568 max_worker_count_ = worker_ref_count_;
2571 void RenderProcessHostImpl::DecrementWorkerRefCount() {
2572 DCHECK_CURRENTLY_ON(BrowserThread::UI);
2573 DCHECK_GT(worker_ref_count_, 0);
2574 --worker_ref_count_;
2575 if (worker_ref_count_ == 0)
2576 Cleanup();
2579 void RenderProcessHostImpl::GetAudioOutputControllers(
2580 const GetAudioOutputControllersCallback& callback) const {
2581 audio_renderer_host()->GetOutputControllers(callback);
2584 BluetoothDispatcherHost* RenderProcessHostImpl::GetBluetoothDispatcherHost() {
2585 return bluetooth_dispatcher_host_.get();
2588 } // namespace content