Roll src/third_party/WebKit c63b89c:29324ab (svn 202546:202547)
[chromium-blink-merge.git] / content / browser / renderer_host / render_process_host_impl.cc
blobee9de26787e4175e33e379bd452f1c9807f0d3dc
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/render_process_messages.h"
125 #include "content/common/resource_messages.h"
126 #include "content/common/site_isolation_policy.h"
127 #include "content/common/view_messages.h"
128 #include "content/public/browser/browser_context.h"
129 #include "content/public/browser/content_browser_client.h"
130 #include "content/public/browser/navigator_connect_context.h"
131 #include "content/public/browser/notification_service.h"
132 #include "content/public/browser/notification_types.h"
133 #include "content/public/browser/render_process_host_factory.h"
134 #include "content/public/browser/render_process_host_observer.h"
135 #include "content/public/browser/render_widget_host.h"
136 #include "content/public/browser/render_widget_host_iterator.h"
137 #include "content/public/browser/render_widget_host_view_frame_subscriber.h"
138 #include "content/public/browser/resource_context.h"
139 #include "content/public/browser/user_metrics.h"
140 #include "content/public/browser/worker_service.h"
141 #include "content/public/common/child_process_host.h"
142 #include "content/public/common/content_constants.h"
143 #include "content/public/common/content_switches.h"
144 #include "content/public/common/mojo_channel_switches.h"
145 #include "content/public/common/process_type.h"
146 #include "content/public/common/resource_type.h"
147 #include "content/public/common/result_codes.h"
148 #include "content/public/common/sandboxed_process_launcher_delegate.h"
149 #include "content/public/common/url_constants.h"
150 #include "device/battery/battery_monitor_impl.h"
151 #include "device/vibration/vibration_manager_impl.h"
152 #include "gpu/GLES2/gl2extchromium.h"
153 #include "gpu/command_buffer/client/gpu_switches.h"
154 #include "gpu/command_buffer/common/gles2_cmd_utils.h"
155 #include "gpu/command_buffer/service/gpu_switches.h"
156 #include "ipc/ipc_channel.h"
157 #include "ipc/ipc_logging.h"
158 #include "ipc/ipc_switches.h"
159 #include "ipc/mojo/ipc_channel_mojo.h"
160 #include "media/base/media_switches.h"
161 #include "net/url_request/url_request_context_getter.h"
162 #include "ppapi/shared_impl/ppapi_switches.h"
163 #include "storage/browser/fileapi/sandbox_file_system_backend.h"
164 #include "third_party/icu/source/common/unicode/unistr.h"
165 #include "third_party/icu/source/i18n/unicode/timezone.h"
166 #include "third_party/skia/include/core/SkBitmap.h"
167 #include "ui/base/ui_base_switches.h"
168 #include "ui/events/event_switches.h"
169 #include "ui/gfx/switches.h"
170 #include "ui/gl/gl_switches.h"
171 #include "ui/gl/gpu_switching_manager.h"
172 #include "ui/native_theme/native_theme_switches.h"
174 #if defined(OS_ANDROID)
175 #include "content/browser/android/child_process_launcher_android.h"
176 #include "content/browser/media/android/browser_demuxer_android.h"
177 #include "content/browser/mojo/service_registrar_android.h"
178 #include "content/browser/screen_orientation/screen_orientation_message_filter_android.h"
179 #endif
181 #if defined(OS_WIN)
182 #include "base/win/scoped_com_initializer.h"
183 #include "base/win/windows_version.h"
184 #include "content/common/font_cache_dispatcher_win.h"
185 #include "content/common/sandbox_win.h"
186 #include "sandbox/win/src/sandbox_policy.h"
187 #include "ui/gfx/win/dpi.h"
188 #endif
190 #if defined(OS_MACOSX) && !defined(OS_IOS)
191 #include "content/browser/bootstrap_sandbox_manager_mac.h"
192 #include "content/browser/browser_io_surface_manager_mac.h"
193 #endif
195 #if defined(USE_OZONE)
196 #include "ui/ozone/public/client_native_pixmap_factory.h"
197 #include "ui/ozone/public/ozone_platform.h"
198 #include "ui/ozone/public/ozone_switches.h"
199 #endif
201 #if defined(ENABLE_BROWSER_CDMS)
202 #include "content/browser/media/cdm/browser_cdm_manager.h"
203 #endif
205 #if defined(ENABLE_PLUGINS)
206 #include "content/browser/plugin_service_impl.h"
207 #endif
209 #if defined(ENABLE_WEBRTC)
210 #include "content/browser/media/webrtc_internals.h"
211 #include "content/browser/renderer_host/media/media_stream_track_metrics_host.h"
212 #include "content/browser/renderer_host/media/webrtc_identity_service_host.h"
213 #include "content/browser/renderer_host/p2p/socket_dispatcher_host.h"
214 #include "content/common/media/aec_dump_messages.h"
215 #include "content/common/media/media_stream_messages.h"
216 #endif
218 #if defined(OS_WIN)
219 #define IntToStringType base::IntToString16
220 #else
221 #define IntToStringType base::IntToString
222 #endif
224 namespace content {
225 namespace {
227 const char kSiteProcessMapKeyName[] = "content_site_process_map";
229 #ifdef ENABLE_WEBRTC
230 const base::FilePath::CharType kAecDumpFileNameAddition[] =
231 FILE_PATH_LITERAL("aec_dump");
232 #endif
234 void CacheShaderInfo(int32 id, base::FilePath path) {
235 ShaderCacheFactory::GetInstance()->SetCacheInfo(id, path);
238 void RemoveShaderInfo(int32 id) {
239 ShaderCacheFactory::GetInstance()->RemoveCacheInfo(id);
242 net::URLRequestContext* GetRequestContext(
243 scoped_refptr<net::URLRequestContextGetter> request_context,
244 scoped_refptr<net::URLRequestContextGetter> media_request_context,
245 ResourceType resource_type) {
246 // If the request has resource type of RESOURCE_TYPE_MEDIA, we use a request
247 // context specific to media for handling it because these resources have
248 // specific needs for caching.
249 if (resource_type == RESOURCE_TYPE_MEDIA)
250 return media_request_context->GetURLRequestContext();
251 return request_context->GetURLRequestContext();
254 void GetContexts(
255 ResourceContext* resource_context,
256 scoped_refptr<net::URLRequestContextGetter> request_context,
257 scoped_refptr<net::URLRequestContextGetter> media_request_context,
258 const ResourceHostMsg_Request& request,
259 ResourceContext** resource_context_out,
260 net::URLRequestContext** request_context_out) {
261 *resource_context_out = resource_context;
262 *request_context_out =
263 GetRequestContext(request_context, media_request_context,
264 request.resource_type);
267 #if defined(ENABLE_WEBRTC)
269 // Allow us to only run the trial in the first renderer.
270 bool has_done_stun_trials = false;
272 // Creates a file used for diagnostic echo canceller recordings for handing
273 // over to the renderer.
274 IPC::PlatformFileForTransit CreateAecDumpFileForProcess(
275 base::FilePath file_path,
276 base::ProcessHandle process) {
277 DCHECK_CURRENTLY_ON(BrowserThread::FILE);
278 base::File dump_file(file_path,
279 base::File::FLAG_OPEN_ALWAYS | base::File::FLAG_APPEND);
280 if (!dump_file.IsValid()) {
281 VLOG(1) << "Could not open AEC dump file, error=" <<
282 dump_file.error_details();
283 return IPC::InvalidPlatformFileForTransit();
285 return IPC::TakeFileHandleForProcess(dump_file.Pass(), process);
288 // Does nothing. Just to avoid races between enable and disable.
289 void DisableAecDumpOnFileThread() {
290 DCHECK_CURRENTLY_ON(BrowserThread::FILE);
292 #endif
294 // the global list of all renderer processes
295 base::LazyInstance<IDMap<RenderProcessHost> >::Leaky
296 g_all_hosts = LAZY_INSTANCE_INITIALIZER;
298 // Map of site to process, to ensure we only have one RenderProcessHost per
299 // site in process-per-site mode. Each map is specific to a BrowserContext.
300 class SiteProcessMap : public base::SupportsUserData::Data {
301 public:
302 typedef base::hash_map<std::string, RenderProcessHost*> SiteToProcessMap;
303 SiteProcessMap() {}
305 void RegisterProcess(const std::string& site, RenderProcessHost* process) {
306 map_[site] = process;
309 RenderProcessHost* FindProcess(const std::string& site) {
310 SiteToProcessMap::iterator i = map_.find(site);
311 if (i != map_.end())
312 return i->second;
313 return NULL;
316 void RemoveProcess(RenderProcessHost* host) {
317 // Find all instances of this process in the map, then separately remove
318 // them.
319 std::set<std::string> sites;
320 for (SiteToProcessMap::const_iterator i = map_.begin();
321 i != map_.end();
322 i++) {
323 if (i->second == host)
324 sites.insert(i->first);
326 for (std::set<std::string>::iterator i = sites.begin();
327 i != sites.end();
328 i++) {
329 SiteToProcessMap::iterator iter = map_.find(*i);
330 if (iter != map_.end()) {
331 DCHECK_EQ(iter->second, host);
332 map_.erase(iter);
337 private:
338 SiteToProcessMap map_;
341 // Find the SiteProcessMap specific to the given context.
342 SiteProcessMap* GetSiteProcessMapForBrowserContext(BrowserContext* context) {
343 DCHECK(context);
344 SiteProcessMap* map = static_cast<SiteProcessMap*>(
345 context->GetUserData(kSiteProcessMapKeyName));
346 if (!map) {
347 map = new SiteProcessMap();
348 context->SetUserData(kSiteProcessMapKeyName, map);
350 return map;
353 // NOTE: changes to this class need to be reviewed by the security team.
354 class RendererSandboxedProcessLauncherDelegate
355 : public SandboxedProcessLauncherDelegate {
356 public:
357 explicit RendererSandboxedProcessLauncherDelegate(IPC::ChannelProxy* channel)
358 #if defined(OS_POSIX)
359 : ipc_fd_(channel->TakeClientFileDescriptor())
360 #endif // OS_POSIX
363 ~RendererSandboxedProcessLauncherDelegate() override {}
365 #if defined(OS_WIN)
366 void PreSpawnTarget(sandbox::TargetPolicy* policy, bool* success) override {
367 AddBaseHandleClosePolicy(policy);
369 const base::string16& sid =
370 GetContentClient()->browser()->GetAppContainerSidForSandboxType(
371 GetSandboxType());
372 if (!sid.empty())
373 AddAppContainerPolicy(policy, sid.c_str());
375 GetContentClient()->browser()->PreSpawnRenderer(policy, success);
378 #elif defined(OS_POSIX)
379 bool ShouldUseZygote() override {
380 const base::CommandLine& browser_command_line =
381 *base::CommandLine::ForCurrentProcess();
382 base::CommandLine::StringType renderer_prefix =
383 browser_command_line.GetSwitchValueNative(switches::kRendererCmdPrefix);
384 return renderer_prefix.empty();
386 base::ScopedFD TakeIpcFd() override { return ipc_fd_.Pass(); }
387 #endif // OS_WIN
389 SandboxType GetSandboxType() override {
390 return SANDBOX_TYPE_RENDERER;
393 private:
394 #if defined(OS_POSIX)
395 base::ScopedFD ipc_fd_;
396 #endif // OS_POSIX
399 const char kSessionStorageHolderKey[] = "kSessionStorageHolderKey";
401 class SessionStorageHolder : public base::SupportsUserData::Data {
402 public:
403 SessionStorageHolder() {}
404 ~SessionStorageHolder() override {}
406 void Hold(const SessionStorageNamespaceMap& sessions, int view_route_id) {
407 session_storage_namespaces_awaiting_close_[view_route_id] = sessions;
410 void Release(int old_route_id) {
411 session_storage_namespaces_awaiting_close_.erase(old_route_id);
414 private:
415 std::map<int, SessionStorageNamespaceMap >
416 session_storage_namespaces_awaiting_close_;
417 DISALLOW_COPY_AND_ASSIGN(SessionStorageHolder);
420 std::string UintVectorToString(const std::vector<unsigned>& vector) {
421 std::string str;
422 for (auto it : vector) {
423 if (!str.empty())
424 str += ",";
425 str += base::UintToString(it);
427 return str;
430 } // namespace
432 RendererMainThreadFactoryFunction g_renderer_main_thread_factory = NULL;
434 base::MessageLoop* g_in_process_thread;
436 base::MessageLoop*
437 RenderProcessHostImpl::GetInProcessRendererThreadForTesting() {
438 return g_in_process_thread;
441 // Stores the maximum number of renderer processes the content module can
442 // create.
443 static size_t g_max_renderer_count_override = 0;
445 // static
446 size_t RenderProcessHost::GetMaxRendererProcessCount() {
447 if (g_max_renderer_count_override)
448 return g_max_renderer_count_override;
450 #if defined(OS_ANDROID)
451 // On Android we don't maintain a limit of renderer process hosts - we are
452 // happy with keeping a lot of these, as long as the number of live renderer
453 // processes remains reasonable, and on Android the OS takes care of that.
454 return std::numeric_limits<size_t>::max();
455 #endif
457 // On other platforms, we calculate the maximum number of renderer process
458 // hosts according to the amount of installed memory as reported by the OS.
459 // The calculation assumes that you want the renderers to use half of the
460 // installed RAM and assuming that each WebContents uses ~40MB. If you modify
461 // this assumption, you need to adjust the ThirtyFourTabs test to match the
462 // expected number of processes.
464 // With the given amounts of installed memory below on a 32-bit CPU, the
465 // maximum renderer count will roughly be as follows:
467 // 128 MB -> 3
468 // 512 MB -> 6
469 // 1024 MB -> 12
470 // 4096 MB -> 51
471 // 16384 MB -> 82 (kMaxRendererProcessCount)
473 static size_t max_count = 0;
474 if (!max_count) {
475 const size_t kEstimatedWebContentsMemoryUsage =
476 #if defined(ARCH_CPU_64_BITS)
477 60; // In MB
478 #else
479 40; // In MB
480 #endif
481 max_count = base::SysInfo::AmountOfPhysicalMemoryMB() / 2;
482 max_count /= kEstimatedWebContentsMemoryUsage;
484 const size_t kMinRendererProcessCount = 3;
485 max_count = std::max(max_count, kMinRendererProcessCount);
486 max_count = std::min(max_count, kMaxRendererProcessCount);
488 return max_count;
491 // static
492 bool g_run_renderer_in_process_ = false;
494 // static
495 void RenderProcessHost::SetMaxRendererProcessCount(size_t count) {
496 g_max_renderer_count_override = count;
499 RenderProcessHostImpl::RenderProcessHostImpl(
500 BrowserContext* browser_context,
501 StoragePartitionImpl* storage_partition_impl,
502 bool is_for_guests_only)
503 : fast_shutdown_started_(false),
504 deleting_soon_(false),
505 #ifndef NDEBUG
506 is_self_deleted_(false),
507 #endif
508 pending_views_(0),
509 mojo_application_host_(new MojoApplicationHost),
510 visible_widgets_(0),
511 backgrounded_(true),
512 is_initialized_(false),
513 id_(ChildProcessHostImpl::GenerateChildProcessUniqueId()),
514 browser_context_(browser_context),
515 storage_partition_impl_(storage_partition_impl),
516 sudden_termination_allowed_(true),
517 ignore_input_events_(false),
518 is_for_guests_only_(is_for_guests_only),
519 gpu_observer_registered_(false),
520 delayed_cleanup_needed_(false),
521 within_process_died_observer_(false),
522 power_monitor_broadcaster_(this),
523 worker_ref_count_(0),
524 max_worker_count_(0),
525 permission_service_context_(new PermissionServiceContext(this)),
526 pending_valuebuffer_state_(new gpu::ValueStateMap()),
527 subscribe_uniform_enabled_(false),
528 weak_factory_(this) {
529 widget_helper_ = new RenderWidgetHelper();
531 ChildProcessSecurityPolicyImpl::GetInstance()->Add(GetID());
533 CHECK(!BrowserMainRunner::ExitedMainMessageLoop());
534 RegisterHost(GetID(), this);
535 g_all_hosts.Get().set_check_on_null_data(true);
536 // Initialize |child_process_activity_time_| to a reasonable value.
537 mark_child_process_activity_time();
539 if (!GetBrowserContext()->IsOffTheRecord() &&
540 !base::CommandLine::ForCurrentProcess()->HasSwitch(
541 switches::kDisableGpuShaderDiskCache)) {
542 BrowserThread::PostTask(BrowserThread::IO, FROM_HERE,
543 base::Bind(&CacheShaderInfo, GetID(),
544 storage_partition_impl_->GetPath()));
546 subscribe_uniform_enabled_ =
547 base::CommandLine::ForCurrentProcess()->HasSwitch(
548 switches::kEnableSubscribeUniformExtension);
550 #if defined(OS_MACOSX)
551 if (BootstrapSandboxManager::ShouldEnable())
552 AddObserver(BootstrapSandboxManager::GetInstance());
553 #endif
555 // Note: When we create the RenderProcessHostImpl, it's technically
556 // backgrounded, because it has no visible listeners. But the process
557 // doesn't actually exist yet, so we'll Background it later, after
558 // creation.
561 // static
562 void RenderProcessHostImpl::ShutDownInProcessRenderer() {
563 DCHECK(g_run_renderer_in_process_);
565 switch (g_all_hosts.Pointer()->size()) {
566 case 0:
567 return;
568 case 1: {
569 RenderProcessHostImpl* host = static_cast<RenderProcessHostImpl*>(
570 AllHostsIterator().GetCurrentValue());
571 FOR_EACH_OBSERVER(RenderProcessHostObserver,
572 host->observers_,
573 RenderProcessHostDestroyed(host));
574 #ifndef NDEBUG
575 host->is_self_deleted_ = true;
576 #endif
577 delete host;
578 return;
580 default:
581 NOTREACHED() << "There should be only one RenderProcessHost when running "
582 << "in-process.";
586 void RenderProcessHostImpl::RegisterRendererMainThreadFactory(
587 RendererMainThreadFactoryFunction create) {
588 g_renderer_main_thread_factory = create;
591 RenderProcessHostImpl::~RenderProcessHostImpl() {
592 #ifndef NDEBUG
593 DCHECK(is_self_deleted_)
594 << "RenderProcessHostImpl is destroyed by something other than itself";
595 #endif
597 // Make sure to clean up the in-process renderer before the channel, otherwise
598 // it may still run and have its IPCs fail, causing asserts.
599 in_process_renderer_.reset();
601 ChildProcessSecurityPolicyImpl::GetInstance()->Remove(GetID());
603 if (gpu_observer_registered_) {
604 ui::GpuSwitchingManager::GetInstance()->RemoveObserver(this);
605 gpu_observer_registered_ = false;
608 // We may have some unsent messages at this point, but that's OK.
609 channel_.reset();
610 while (!queued_messages_.empty()) {
611 delete queued_messages_.front();
612 queued_messages_.pop();
615 UnregisterHost(GetID());
617 if (!base::CommandLine::ForCurrentProcess()->HasSwitch(
618 switches::kDisableGpuShaderDiskCache)) {
619 BrowserThread::PostTask(BrowserThread::IO, FROM_HERE,
620 base::Bind(&RemoveShaderInfo, GetID()));
624 void RenderProcessHostImpl::EnableSendQueue() {
625 is_initialized_ = false;
628 bool RenderProcessHostImpl::Init() {
629 // calling Init() more than once does nothing, this makes it more convenient
630 // for the view host which may not be sure in some cases
631 if (channel_)
632 return true;
634 base::CommandLine::StringType renderer_prefix;
635 // A command prefix is something prepended to the command line of the spawned
636 // process.
637 const base::CommandLine& browser_command_line =
638 *base::CommandLine::ForCurrentProcess();
639 renderer_prefix =
640 browser_command_line.GetSwitchValueNative(switches::kRendererCmdPrefix);
642 #if defined(OS_LINUX)
643 int flags = renderer_prefix.empty() ? ChildProcessHost::CHILD_ALLOW_SELF :
644 ChildProcessHost::CHILD_NORMAL;
645 #else
646 int flags = ChildProcessHost::CHILD_NORMAL;
647 #endif
649 // Find the renderer before creating the channel so if this fails early we
650 // return without creating the channel.
651 base::FilePath renderer_path = ChildProcessHost::GetChildPath(flags);
652 if (renderer_path.empty())
653 return false;
655 // Setup the IPC channel.
656 const std::string channel_id =
657 IPC::Channel::GenerateVerifiedChannelID(std::string());
658 channel_ = CreateChannelProxy(channel_id);
660 // Setup the Mojo channel.
661 mojo_application_host_->Init();
663 // Call the embedder first so that their IPC filters have priority.
664 GetContentClient()->browser()->RenderProcessWillLaunch(this);
666 CreateMessageFilters();
667 RegisterMojoServices();
669 if (run_renderer_in_process()) {
670 DCHECK(g_renderer_main_thread_factory);
671 // Crank up a thread and run the initialization there. With the way that
672 // messages flow between the browser and renderer, this thread is required
673 // to prevent a deadlock in single-process mode. Since the primordial
674 // thread in the renderer process runs the WebKit code and can sometimes
675 // make blocking calls to the UI thread (i.e. this thread), they need to run
676 // on separate threads.
677 in_process_renderer_.reset(
678 g_renderer_main_thread_factory(InProcessChildThreadParams(
679 channel_id, BrowserThread::UnsafeGetMessageLoopForThread(
680 BrowserThread::IO)->task_runner())));
682 base::Thread::Options options;
683 #if defined(OS_WIN) && !defined(OS_MACOSX)
684 // In-process plugins require this to be a UI message loop.
685 options.message_loop_type = base::MessageLoop::TYPE_UI;
686 #else
687 // We can't have multiple UI loops on Linux and Android, so we don't support
688 // in-process plugins.
689 options.message_loop_type = base::MessageLoop::TYPE_DEFAULT;
690 #endif
692 // As for execution sequence, this callback should have no any dependency
693 // on starting in-process-render-thread.
694 // So put it here to trigger ChannelMojo initialization earlier to enable
695 // in-process-render-thread using ChannelMojo there.
696 OnProcessLaunched(); // Fake a callback that the process is ready.
698 in_process_renderer_->StartWithOptions(options);
700 g_in_process_thread = in_process_renderer_->message_loop();
702 } else {
703 // Build command line for renderer. We call AppendRendererCommandLine()
704 // first so the process type argument will appear first.
705 base::CommandLine* cmd_line = new base::CommandLine(renderer_path);
706 if (!renderer_prefix.empty())
707 cmd_line->PrependWrapper(renderer_prefix);
708 AppendRendererCommandLine(cmd_line);
709 cmd_line->AppendSwitchASCII(switches::kProcessChannelID, channel_id);
711 // Spawn the child process asynchronously to avoid blocking the UI thread.
712 // As long as there's no renderer prefix, we can use the zygote process
713 // at this stage.
714 child_process_launcher_.reset(new ChildProcessLauncher(
715 new RendererSandboxedProcessLauncherDelegate(channel_.get()),
716 cmd_line,
717 GetID(),
718 this));
720 fast_shutdown_started_ = false;
723 if (!gpu_observer_registered_) {
724 gpu_observer_registered_ = true;
725 ui::GpuSwitchingManager::GetInstance()->AddObserver(this);
728 power_monitor_broadcaster_.Init();
730 is_initialized_ = true;
731 init_time_ = base::TimeTicks::Now();
732 return true;
735 scoped_ptr<IPC::ChannelProxy> RenderProcessHostImpl::CreateChannelProxy(
736 const std::string& channel_id) {
737 scoped_refptr<base::SingleThreadTaskRunner> runner =
738 BrowserThread::GetMessageLoopProxyForThread(BrowserThread::IO);
739 scoped_refptr<base::SequencedTaskRunner> mojo_task_runner =
740 BrowserThread::UnsafeGetMessageLoopForThread(BrowserThread::IO)
741 ->task_runner();
742 if (ShouldUseMojoChannel()) {
743 VLOG(1) << "Mojo Channel is enabled on host";
745 return IPC::ChannelProxy::Create(
746 IPC::ChannelMojo::CreateServerFactory(
747 mojo_task_runner, channel_id),
748 this, runner.get());
751 return IPC::ChannelProxy::Create(
752 channel_id, IPC::Channel::MODE_SERVER, this, runner.get());
755 void RenderProcessHostImpl::CreateMessageFilters() {
756 DCHECK_CURRENTLY_ON(BrowserThread::UI);
757 const base::CommandLine& browser_command_line =
758 *base::CommandLine::ForCurrentProcess();
759 AddFilter(new ResourceSchedulerFilter(GetID()));
760 MediaInternals* media_internals = MediaInternals::GetInstance();
761 media::AudioManager* audio_manager =
762 BrowserMainLoop::GetInstance()->audio_manager();
763 // Add BrowserPluginMessageFilter to ensure it gets the first stab at messages
764 // from guests.
765 scoped_refptr<BrowserPluginMessageFilter> bp_message_filter(
766 new BrowserPluginMessageFilter(GetID()));
767 AddFilter(bp_message_filter.get());
769 scoped_refptr<RenderMessageFilter> render_message_filter(
770 new RenderMessageFilter(
771 GetID(),
772 GetBrowserContext(),
773 GetBrowserContext()->GetRequestContextForRenderProcess(GetID()),
774 widget_helper_.get(),
775 audio_manager,
776 media_internals,
777 storage_partition_impl_->GetDOMStorageContext()));
778 AddFilter(render_message_filter.get());
779 AddFilter(new RenderFrameMessageFilter(
780 GetID(),
781 #if defined(ENABLE_PLUGINS)
782 PluginServiceImpl::GetInstance(),
783 #else
784 nullptr,
785 #endif
786 GetBrowserContext(),
787 GetBrowserContext()->GetRequestContextForRenderProcess(GetID()),
788 widget_helper_.get()));
789 BrowserContext* browser_context = GetBrowserContext();
790 ResourceContext* resource_context = browser_context->GetResourceContext();
792 scoped_refptr<net::URLRequestContextGetter> request_context(
793 browser_context->GetRequestContextForRenderProcess(GetID()));
794 scoped_refptr<net::URLRequestContextGetter> media_request_context(
795 browser_context->GetMediaRequestContextForRenderProcess(GetID()));
797 ResourceMessageFilter::GetContextsCallback get_contexts_callback(
798 base::Bind(&GetContexts, browser_context->GetResourceContext(),
799 request_context, media_request_context));
801 ResourceMessageFilter* resource_message_filter = new ResourceMessageFilter(
802 GetID(), PROCESS_TYPE_RENDERER,
803 storage_partition_impl_->GetAppCacheService(),
804 ChromeBlobStorageContext::GetFor(browser_context),
805 storage_partition_impl_->GetFileSystemContext(),
806 storage_partition_impl_->GetServiceWorkerContext(),
807 storage_partition_impl_->GetHostZoomLevelContext(),
808 get_contexts_callback);
810 AddFilter(resource_message_filter);
811 MediaStreamManager* media_stream_manager =
812 BrowserMainLoop::GetInstance()->media_stream_manager();
813 // The AudioInputRendererHost and AudioRendererHost needs to be available for
814 // lookup, so it's stashed in a member variable.
815 audio_input_renderer_host_ = new AudioInputRendererHost(
816 GetID(),
817 base::GetProcId(GetHandle()),
818 audio_manager,
819 media_stream_manager,
820 AudioMirroringManager::GetInstance(),
821 BrowserMainLoop::GetInstance()->user_input_monitor());
822 AddFilter(audio_input_renderer_host_.get());
823 audio_renderer_host_ = new AudioRendererHost(
824 GetID(),
825 audio_manager,
826 AudioMirroringManager::GetInstance(),
827 media_internals,
828 media_stream_manager,
829 browser_context->GetResourceContext()->GetMediaDeviceIDSalt());
830 AddFilter(audio_renderer_host_.get());
831 AddFilter(
832 new MidiHost(GetID(), BrowserMainLoop::GetInstance()->midi_manager()));
833 AddFilter(new VideoCaptureHost(media_stream_manager));
834 AddFilter(new AppCacheDispatcherHost(
835 storage_partition_impl_->GetAppCacheService(),
836 GetID()));
837 AddFilter(new ClipboardMessageFilter);
838 AddFilter(new DOMStorageMessageFilter(
839 storage_partition_impl_->GetDOMStorageContext()));
840 AddFilter(new IndexedDBDispatcherHost(
841 GetID(),
842 storage_partition_impl_->GetURLRequestContext(),
843 storage_partition_impl_->GetIndexedDBContext(),
844 ChromeBlobStorageContext::GetFor(browser_context)));
846 gpu_message_filter_ = new GpuMessageFilter(GetID(), widget_helper_.get());
847 AddFilter(gpu_message_filter_);
848 #if defined(ENABLE_WEBRTC)
849 AddFilter(new WebRTCIdentityServiceHost(
850 GetID(),
851 storage_partition_impl_->GetWebRTCIdentityStore(),
852 resource_context));
853 peer_connection_tracker_host_ = new PeerConnectionTrackerHost(GetID());
854 AddFilter(peer_connection_tracker_host_.get());
855 AddFilter(new MediaStreamDispatcherHost(
856 GetID(),
857 browser_context->GetResourceContext()->GetMediaDeviceIDSalt(),
858 media_stream_manager));
859 AddFilter(new MediaStreamTrackMetricsHost());
860 #endif
861 #if defined(ENABLE_PLUGINS)
862 AddFilter(new PepperRendererConnection(GetID()));
863 #endif
864 AddFilter(new SpeechRecognitionDispatcherHost(
865 GetID(), storage_partition_impl_->GetURLRequestContext()));
866 AddFilter(new FileAPIMessageFilter(
867 GetID(),
868 storage_partition_impl_->GetURLRequestContext(),
869 storage_partition_impl_->GetFileSystemContext(),
870 ChromeBlobStorageContext::GetFor(browser_context),
871 StreamContext::GetFor(browser_context)));
872 AddFilter(new FileUtilitiesMessageFilter(GetID()));
873 AddFilter(new MimeRegistryMessageFilter());
874 AddFilter(new DatabaseMessageFilter(
875 storage_partition_impl_->GetDatabaseTracker()));
876 #if defined(OS_MACOSX)
877 AddFilter(new TextInputClientMessageFilter(GetID()));
878 #elif defined(OS_WIN)
879 // The FontCacheDispatcher is required only when we're using GDI rendering.
880 // TODO(scottmg): pdf/ppapi still require the renderer to be able to precache
881 // GDI fonts (http://crbug.com/383227), even when using DirectWrite. This
882 // should eventually be if (!ShouldUseDirectWrite()) guarded.
883 channel_->AddFilter(new FontCacheDispatcher());
884 #elif defined(OS_ANDROID)
885 browser_demuxer_android_ = new BrowserDemuxerAndroid();
886 AddFilter(browser_demuxer_android_.get());
887 #endif
888 #if defined(ENABLE_BROWSER_CDMS)
889 AddFilter(new BrowserCdmManager(GetID(), NULL));
890 #endif
892 WebSocketDispatcherHost::GetRequestContextCallback
893 websocket_request_context_callback(
894 base::Bind(&GetRequestContext, request_context,
895 media_request_context, RESOURCE_TYPE_SUB_RESOURCE));
897 AddFilter(
898 new WebSocketDispatcherHost(GetID(), websocket_request_context_callback));
900 message_port_message_filter_ = new MessagePortMessageFilter(
901 base::Bind(&RenderWidgetHelper::GetNextRoutingID,
902 base::Unretained(widget_helper_.get())));
903 AddFilter(message_port_message_filter_.get());
905 scoped_refptr<CacheStorageDispatcherHost> cache_storage_filter =
906 new CacheStorageDispatcherHost();
907 cache_storage_filter->Init(storage_partition_impl_->GetCacheStorageContext());
908 AddFilter(cache_storage_filter.get());
910 scoped_refptr<ServiceWorkerDispatcherHost> service_worker_filter =
911 new ServiceWorkerDispatcherHost(
912 GetID(), message_port_message_filter_.get(), resource_context);
913 service_worker_filter->Init(
914 storage_partition_impl_->GetServiceWorkerContext());
915 AddFilter(service_worker_filter.get());
917 AddFilter(new SharedWorkerMessageFilter(
918 GetID(),
919 resource_context,
920 WorkerStoragePartition(
921 storage_partition_impl_->GetURLRequestContext(),
922 storage_partition_impl_->GetMediaURLRequestContext(),
923 storage_partition_impl_->GetAppCacheService(),
924 storage_partition_impl_->GetQuotaManager(),
925 storage_partition_impl_->GetFileSystemContext(),
926 storage_partition_impl_->GetDatabaseTracker(),
927 storage_partition_impl_->GetIndexedDBContext(),
928 storage_partition_impl_->GetServiceWorkerContext()),
929 message_port_message_filter_.get()));
931 #if defined(ENABLE_WEBRTC)
932 p2p_socket_dispatcher_host_ = new P2PSocketDispatcherHost(
933 resource_context,
934 browser_context->GetRequestContextForRenderProcess(GetID()));
935 AddFilter(p2p_socket_dispatcher_host_.get());
936 #endif
938 AddFilter(new TraceMessageFilter(GetID()));
939 AddFilter(new ResolveProxyMsgHelper(
940 browser_context->GetRequestContextForRenderProcess(GetID())));
941 AddFilter(new QuotaDispatcherHost(
942 GetID(),
943 storage_partition_impl_->GetQuotaManager(),
944 GetContentClient()->browser()->CreateQuotaPermissionContext()));
946 notification_message_filter_ = new NotificationMessageFilter(
947 GetID(),
948 storage_partition_impl_->GetPlatformNotificationContext(),
949 resource_context,
950 browser_context);
951 AddFilter(notification_message_filter_.get());
953 AddFilter(new GamepadBrowserMessageFilter());
954 AddFilter(new DeviceLightMessageFilter());
955 AddFilter(new DeviceMotionMessageFilter());
956 AddFilter(new DeviceOrientationMessageFilter());
957 AddFilter(new ProfilerMessageFilter(PROCESS_TYPE_RENDERER));
958 AddFilter(new HistogramMessageFilter());
959 #if defined(USE_TCMALLOC) && (defined(OS_LINUX) || defined(OS_ANDROID))
960 if (browser_command_line.HasSwitch(switches::kEnableMemoryBenchmarking))
961 AddFilter(new MemoryBenchmarkMessageFilter());
962 #endif
963 AddFilter(new PushMessagingMessageFilter(
964 GetID(), storage_partition_impl_->GetServiceWorkerContext()));
965 #if defined(OS_ANDROID)
966 AddFilter(new ScreenOrientationMessageFilterAndroid());
967 #endif
968 AddFilter(new GeofencingDispatcherHost(
969 storage_partition_impl_->GetGeofencingManager()));
970 if (browser_command_line.HasSwitch(switches::kEnableWebBluetooth)) {
971 bluetooth_dispatcher_host_ = new BluetoothDispatcherHost(GetID());
972 AddFilter(bluetooth_dispatcher_host_.get());
976 void RenderProcessHostImpl::RegisterMojoServices() {
977 #if !defined(OS_ANDROID)
978 mojo_application_host_->service_registry()->AddService(
979 base::Bind(&device::BatteryMonitorImpl::Create));
981 mojo_application_host_->service_registry()->AddService(
982 base::Bind(&device::VibrationManagerImpl::Create));
983 #endif
985 mojo_application_host_->service_registry()->AddService(
986 base::Bind(&PermissionServiceContext::CreateService,
987 base::Unretained(permission_service_context_.get())));
989 mojo_application_host_->service_registry()->AddService(base::Bind(
990 &BackgroundSyncContextImpl::CreateService,
991 base::Unretained(storage_partition_impl_->GetBackgroundSyncContext())));
993 mojo_application_host_->service_registry()->AddService(base::Bind(
994 &content::ServicePortServiceImpl::Create,
995 make_scoped_refptr(storage_partition_impl_->GetNavigatorConnectContext()),
996 message_port_message_filter_));
998 #if defined(OS_ANDROID)
999 ServiceRegistrarAndroid::RegisterProcessHostServices(
1000 mojo_application_host_->service_registry_android());
1001 #endif
1003 GetContentClient()->browser()->RegisterRenderProcessMojoServices(
1004 mojo_application_host_->service_registry());
1007 int RenderProcessHostImpl::GetNextRoutingID() {
1008 return widget_helper_->GetNextRoutingID();
1011 void RenderProcessHostImpl::ResumeDeferredNavigation(
1012 const GlobalRequestID& request_id) {
1013 widget_helper_->ResumeDeferredNavigation(request_id);
1016 void RenderProcessHostImpl::NotifyTimezoneChange(const std::string& zone_id) {
1017 Send(new ViewMsg_TimezoneChange(zone_id));
1020 ServiceRegistry* RenderProcessHostImpl::GetServiceRegistry() {
1021 DCHECK(mojo_application_host_);
1022 return mojo_application_host_->service_registry();
1025 const base::TimeTicks& RenderProcessHostImpl::GetInitTimeForNavigationMetrics()
1026 const {
1027 return init_time_;
1030 bool RenderProcessHostImpl::SubscribeUniformEnabled() const {
1031 return subscribe_uniform_enabled_;
1034 void RenderProcessHostImpl::OnAddSubscription(unsigned int target) {
1035 DCHECK(subscribe_uniform_enabled_);
1036 subscription_set_.insert(target);
1037 const gpu::ValueState* state = pending_valuebuffer_state_->GetState(target);
1038 if (state) {
1039 SendUpdateValueState(target, *state);
1043 void RenderProcessHostImpl::OnRemoveSubscription(unsigned int target) {
1044 DCHECK(subscribe_uniform_enabled_);
1045 subscription_set_.erase(target);
1048 void RenderProcessHostImpl::SendUpdateValueState(unsigned int target,
1049 const gpu::ValueState& state) {
1050 DCHECK(subscribe_uniform_enabled_);
1051 if (subscription_set_.find(target) != subscription_set_.end()) {
1052 GpuProcessHost::SendOnIO(
1053 GpuProcessHost::GPU_PROCESS_KIND_SANDBOXED,
1054 CAUSE_FOR_GPU_LAUNCH_NO_LAUNCH,
1055 new GpuMsg_UpdateValueState(id_, target, state));
1056 } else {
1057 // Store the ValueState locally in case a Valuebuffer subscribes to it later
1058 pending_valuebuffer_state_->UpdateState(target, state);
1062 #if defined(ENABLE_BROWSER_CDMS)
1063 media::BrowserCdm* RenderProcessHostImpl::GetBrowserCdm(int render_frame_id,
1064 int cdm_id) const {
1065 DCHECK_CURRENTLY_ON(BrowserThread::UI);
1066 BrowserCdmManager* manager = BrowserCdmManager::FromProcess(GetID());
1067 if (!manager)
1068 return nullptr;
1069 return manager->GetCdm(render_frame_id, cdm_id);
1071 #endif
1073 void RenderProcessHostImpl::AddRoute(
1074 int32 routing_id,
1075 IPC::Listener* listener) {
1076 CHECK(!listeners_.Lookup(routing_id))
1077 << "Found Routing ID Conflict: " << routing_id;
1078 listeners_.AddWithID(listener, routing_id);
1081 void RenderProcessHostImpl::RemoveRoute(int32 routing_id) {
1082 DCHECK(listeners_.Lookup(routing_id) != NULL);
1083 listeners_.Remove(routing_id);
1085 // Keep the one renderer thread around forever in single process mode.
1086 if (!run_renderer_in_process())
1087 Cleanup();
1090 void RenderProcessHostImpl::AddObserver(RenderProcessHostObserver* observer) {
1091 observers_.AddObserver(observer);
1094 void RenderProcessHostImpl::RemoveObserver(
1095 RenderProcessHostObserver* observer) {
1096 observers_.RemoveObserver(observer);
1099 void RenderProcessHostImpl::ShutdownForBadMessage() {
1100 base::CommandLine* command_line = base::CommandLine::ForCurrentProcess();
1101 if (command_line->HasSwitch(switches::kDisableKillAfterBadIPC))
1102 return;
1104 if (run_renderer_in_process()) {
1105 // In single process mode it is better if we don't suicide but just
1106 // crash.
1107 CHECK(false);
1109 // We kill the renderer but don't include a NOTREACHED, because we want the
1110 // browser to try to survive when it gets illegal messages from the renderer.
1111 Shutdown(RESULT_CODE_KILLED_BAD_MESSAGE, false);
1114 void RenderProcessHostImpl::WidgetRestored() {
1115 // Verify we were properly backgrounded.
1116 DCHECK_EQ(backgrounded_, (visible_widgets_ == 0));
1117 visible_widgets_++;
1118 SetBackgrounded(false);
1121 void RenderProcessHostImpl::WidgetHidden() {
1122 // On startup, the browser will call Hide
1123 if (backgrounded_)
1124 return;
1126 DCHECK_EQ(backgrounded_, (visible_widgets_ == 0));
1127 visible_widgets_--;
1128 DCHECK_GE(visible_widgets_, 0);
1129 if (visible_widgets_ == 0) {
1130 DCHECK(!backgrounded_);
1131 SetBackgrounded(true);
1135 int RenderProcessHostImpl::VisibleWidgetCount() const {
1136 return visible_widgets_;
1139 bool RenderProcessHostImpl::IsForGuestsOnly() const {
1140 return is_for_guests_only_;
1143 StoragePartition* RenderProcessHostImpl::GetStoragePartition() const {
1144 return storage_partition_impl_;
1147 static void AppendCompositorCommandLineFlags(base::CommandLine* command_line) {
1148 if (IsPropertyTreeVerificationEnabled())
1149 command_line->AppendSwitch(cc::switches::kEnablePropertyTreeVerification);
1151 if (IsDelegatedRendererEnabled())
1152 command_line->AppendSwitch(switches::kEnableDelegatedRenderer);
1154 command_line->AppendSwitchASCII(
1155 switches::kNumRasterThreads,
1156 base::IntToString(NumberOfRendererRasterThreads()));
1158 if (IsGpuRasterizationEnabled())
1159 command_line->AppendSwitch(switches::kEnableGpuRasterization);
1161 int msaa_sample_count = GpuRasterizationMSAASampleCount();
1162 if (msaa_sample_count >= 0) {
1163 command_line->AppendSwitchASCII(
1164 switches::kGpuRasterizationMSAASampleCount,
1165 base::IntToString(msaa_sample_count));
1168 if (IsZeroCopyUploadEnabled())
1169 command_line->AppendSwitch(switches::kEnableZeroCopy);
1170 if (IsPersistentGpuMemoryBufferEnabled())
1171 command_line->AppendSwitch(switches::kEnablePersistentGpuMemoryBuffer);
1173 if (IsForceGpuRasterizationEnabled())
1174 command_line->AppendSwitch(switches::kForceGpuRasterization);
1176 gfx::BufferUsage buffer_usage = IsPersistentGpuMemoryBufferEnabled()
1177 ? gfx::BufferUsage::PERSISTENT_MAP
1178 : gfx::BufferUsage::MAP;
1179 std::vector<unsigned> image_targets(
1180 static_cast<size_t>(gfx::BufferFormat::LAST) + 1, GL_TEXTURE_2D);
1181 for (size_t format = 0;
1182 format < static_cast<size_t>(gfx::BufferFormat::LAST) + 1; format++) {
1183 image_targets[format] =
1184 BrowserGpuMemoryBufferManager::GetImageTextureTarget(
1185 static_cast<gfx::BufferFormat>(format), buffer_usage);
1187 command_line->AppendSwitchASCII(switches::kContentImageTextureTarget,
1188 UintVectorToString(image_targets));
1190 command_line->AppendSwitchASCII(
1191 switches::kVideoImageTextureTarget,
1192 base::UintToString(BrowserGpuMemoryBufferManager::GetImageTextureTarget(
1193 gfx::BufferFormat::R_8, gfx::BufferUsage::MAP)));
1195 // Appending disable-gpu-feature switches due to software rendering list.
1196 GpuDataManagerImpl* gpu_data_manager = GpuDataManagerImpl::GetInstance();
1197 DCHECK(gpu_data_manager);
1198 gpu_data_manager->AppendRendererCommandLine(command_line);
1201 void RenderProcessHostImpl::AppendRendererCommandLine(
1202 base::CommandLine* command_line) const {
1203 // Pass the process type first, so it shows first in process listings.
1204 command_line->AppendSwitchASCII(switches::kProcessType,
1205 switches::kRendererProcess);
1207 // Now send any options from our own command line we want to propagate.
1208 const base::CommandLine& browser_command_line =
1209 *base::CommandLine::ForCurrentProcess();
1210 PropagateBrowserCommandLineToRenderer(browser_command_line, command_line);
1212 // Pass on the browser locale.
1213 const std::string locale =
1214 GetContentClient()->browser()->GetApplicationLocale();
1215 command_line->AppendSwitchASCII(switches::kLang, locale);
1217 // If we run base::FieldTrials, we want to pass to their state to the
1218 // renderer so that it can act in accordance with each state, or record
1219 // histograms relating to the base::FieldTrial states.
1220 std::string field_trial_states;
1221 base::FieldTrialList::AllStatesToString(&field_trial_states);
1222 if (!field_trial_states.empty()) {
1223 command_line->AppendSwitchASCII(switches::kForceFieldTrials,
1224 field_trial_states);
1227 GetContentClient()->browser()->AppendExtraCommandLineSwitches(
1228 command_line, GetID());
1230 if (IsPinchToZoomEnabled())
1231 command_line->AppendSwitch(switches::kEnablePinch);
1233 #if defined(OS_WIN)
1234 command_line->AppendSwitchASCII(switches::kDeviceScaleFactor,
1235 base::DoubleToString(gfx::GetDPIScale()));
1236 #endif
1238 AppendCompositorCommandLineFlags(command_line);
1241 void RenderProcessHostImpl::PropagateBrowserCommandLineToRenderer(
1242 const base::CommandLine& browser_cmd,
1243 base::CommandLine* renderer_cmd) const {
1244 // Propagate the following switches to the renderer command line (along
1245 // with any associated values) if present in the browser command line.
1246 static const char* const kSwitchNames[] = {
1247 switches::kAllowLoopbackInPeerConnection,
1248 switches::kAudioBufferSize,
1249 switches::kBlinkPlatformLogChannels,
1250 switches::kBlinkSettings,
1251 switches::kDefaultTileWidth,
1252 switches::kDefaultTileHeight,
1253 switches::kDisable3DAPIs,
1254 switches::kDisableAcceleratedJpegDecoding,
1255 switches::kDisableAcceleratedVideoDecode,
1256 switches::kDisableBlinkFeatures,
1257 switches::kDisableBreakpad,
1258 switches::kDisablePreferCompositingToLCDText,
1259 switches::kDisableDatabases,
1260 switches::kDisableDelayAgnosticAec,
1261 switches::kDisableDirectNPAPIRequests,
1262 switches::kDisableDisplayList2dCanvas,
1263 switches::kDisableDistanceFieldText,
1264 switches::kDisableEncryptedMedia,
1265 switches::kDisableFileSystem,
1266 switches::kDisableGpuCompositing,
1267 switches::kDisableGpuMemoryBufferVideoFrames,
1268 switches::kDisableGpuVsync,
1269 switches::kDisableLowResTiling,
1270 switches::kDisableHistogramCustomizer,
1271 switches::kDisableIconNtp,
1272 switches::kDisableLCDText,
1273 switches::kDisableLocalStorage,
1274 switches::kDisableLogging,
1275 switches::kDisableMediaSource,
1276 switches::kDisableMojoChannel,
1277 switches::kDisableNewVideoRenderer,
1278 switches::kDisableNotifications,
1279 switches::kDisableOverlayScrollbar,
1280 switches::kDisablePermissionsAPI,
1281 switches::kDisablePresentationAPI,
1282 switches::kDisablePinch,
1283 switches::kDisableRGBA4444Textures,
1284 switches::kDisableSeccompFilterSandbox,
1285 switches::kDisableSharedWorkers,
1286 switches::kDisableSpeechAPI,
1287 switches::kDisableSVG1DOM,
1288 switches::kDisableThreadedCompositing,
1289 switches::kDisableThreadedScrolling,
1290 switches::kDisableTouchAdjustment,
1291 switches::kDisableTouchDragDrop,
1292 switches::kDisableTouchEditing,
1293 switches::kDisableV8IdleTasks,
1294 switches::kDomAutomationController,
1295 switches::kEnableBleedingEdgeRenderingFastPaths,
1296 switches::kEnableBlinkFeatures,
1297 switches::kEnableBrowserSideNavigation,
1298 switches::kEnableCompositorAnimationTimelines,
1299 switches::kEnableCredentialManagerAPI,
1300 switches::kEnableDelayAgnosticAec,
1301 switches::kEnableDisplayList2dCanvas,
1302 switches::kEnableDistanceFieldText,
1303 switches::kEnableExperimentalCanvasFeatures,
1304 switches::kEnableExperimentalWebPlatformFeatures,
1305 switches::kEnableGPUClientLogging,
1306 switches::kEnableGpuClientTracing,
1307 switches::kEnableGpuMemoryBufferVideoFrames,
1308 switches::kEnableGPUServiceLogging,
1309 switches::kEnableIconNtp,
1310 switches::kEnableLinkDisambiguationPopup,
1311 switches::kEnableLowResTiling,
1312 switches::kEnableInbandTextTracks,
1313 switches::kEnableLCDText,
1314 switches::kEnableLogging,
1315 switches::kEnableMemoryBenchmarking,
1316 switches::kEnableNetworkInformation,
1317 switches::kEnableOverlayScrollbar,
1318 switches::kEnablePinch,
1319 switches::kEnablePluginPlaceholderTesting,
1320 switches::kEnablePreciseMemoryInfo,
1321 switches::kEnablePreferCompositingToLCDText,
1322 switches::kEnablePrefixedEncryptedMedia,
1323 switches::kEnablePushMessagePayload,
1324 switches::kEnableRGBA4444Textures,
1325 switches::kEnableRendererMojoChannel,
1326 switches::kEnableRTCSmoothnessAlgorithm,
1327 switches::kEnableSeccompFilterSandbox,
1328 switches::kEnableSkiaBenchmarking,
1329 switches::kEnableSlimmingPaintV2,
1330 switches::kEnableSmoothScrolling,
1331 switches::kEnableStatsTable,
1332 switches::kEnableThreadedCompositing,
1333 switches::kEnableTouchDragDrop,
1334 switches::kEnableTouchEditing,
1335 switches::kEnableUnsafeES3APIs,
1336 switches::kEnableViewport,
1337 switches::kEnableVtune,
1338 switches::kEnableWebBluetooth,
1339 switches::kEnableWebGLDraftExtensions,
1340 switches::kEnableWebGLImageChromium,
1341 switches::kEnableWebVR,
1342 switches::kExplicitlyAllowedPorts,
1343 switches::kForceDeviceScaleFactor,
1344 switches::kForceDisplayList2dCanvas,
1345 switches::kForceOverlayFullscreenVideo,
1346 switches::kFullMemoryCrashReport,
1347 switches::kIPCConnectionTimeout,
1348 switches::kJavaScriptFlags,
1349 switches::kLoggingLevel,
1350 switches::kMainFrameResizesAreOrientationChanges,
1351 switches::kMaxUntiledLayerWidth,
1352 switches::kMaxUntiledLayerHeight,
1353 switches::kMemoryMetrics,
1354 switches::kNoReferrers,
1355 switches::kNoSandbox,
1356 switches::kOverridePluginPowerSaverForTesting,
1357 switches::kPpapiInProcess,
1358 switches::kProfilerTiming,
1359 switches::kReducedReferrerGranularity,
1360 switches::kReduceSecurityForTesting,
1361 switches::kRegisterPepperPlugins,
1362 switches::kRendererStartupDialog,
1363 switches::kRootLayerScrolls,
1364 switches::kShowPaintRects,
1365 switches::kSitePerProcess,
1366 switches::kStatsCollectionController,
1367 switches::kTestType,
1368 switches::kTouchEvents,
1369 switches::kTouchTextSelectionStrategy,
1370 switches::kTraceConfigFile,
1371 switches::kTraceToConsole,
1372 // This flag needs to be propagated to the renderer process for
1373 // --in-process-webgl.
1374 switches::kUseGL,
1375 switches::kUseMobileUserAgent,
1376 switches::kUseNormalPriorityForTileTaskWorkerThreads,
1377 switches::kV,
1378 switches::kVideoThreads,
1379 switches::kVideoUnderflowThresholdMs,
1380 switches::kVModule,
1381 // Please keep these in alphabetical order. Compositor switches here should
1382 // also be added to chrome/browser/chromeos/login/chrome_restart_request.cc.
1383 cc::switches::kCompositeToMailbox,
1384 cc::switches::kDisableCompositedAntialiasing,
1385 cc::switches::kDisableMainFrameBeforeActivation,
1386 cc::switches::kDisableThreadedAnimation,
1387 cc::switches::kEnableBeginFrameScheduling,
1388 cc::switches::kEnableGpuBenchmarking,
1389 cc::switches::kEnableMainFrameBeforeActivation,
1390 cc::switches::kShowCompositedLayerBorders,
1391 cc::switches::kShowFPSCounter,
1392 cc::switches::kShowLayerAnimationBounds,
1393 cc::switches::kShowPropertyChangedRects,
1394 cc::switches::kShowReplicaScreenSpaceRects,
1395 cc::switches::kShowScreenSpaceRects,
1396 cc::switches::kShowSurfaceDamageRects,
1397 cc::switches::kSlowDownRasterScaleFactor,
1398 cc::switches::kStrictLayerPropertyChangeChecking,
1399 cc::switches::kTopControlsHideThreshold,
1400 cc::switches::kTopControlsShowThreshold,
1402 #if defined(ENABLE_PLUGINS)
1403 switches::kEnablePepperTesting,
1404 #endif
1405 #if defined(ENABLE_WEBRTC)
1406 switches::kDisableWebRtcHWDecoding,
1407 switches::kDisableWebRtcHWEncoding,
1408 switches::kEnableWebRtcDtls12,
1409 switches::kEnableWebRtcHWH264Encoding,
1410 switches::kEnableWebRtcStunOrigin,
1411 switches::kWebRtcMaxCaptureFramerate,
1412 #endif
1413 switches::kEnableLowEndDeviceMode,
1414 switches::kDisableLowEndDeviceMode,
1415 #if defined(OS_ANDROID)
1416 switches::kDisableGestureRequirementForMediaPlayback,
1417 switches::kDisableWebAudio,
1418 switches::kRendererWaitForJavaDebugger,
1419 #endif
1420 #if defined(OS_MACOSX)
1421 // Allow this to be set when invoking the browser and relayed along.
1422 switches::kEnableSandboxLogging,
1423 #endif
1424 #if defined(OS_WIN)
1425 switches::kDisableDirectWrite,
1426 switches::kDisableWin32kRendererLockDown,
1427 switches::kTraceExportEventsToETW,
1428 #endif
1429 #if defined(USE_OZONE)
1430 switches::kOzonePlatform,
1431 #endif
1432 #if defined(OS_CHROMEOS)
1433 switches::kDisableVaapiAcceleratedVideoEncode,
1434 #endif
1436 renderer_cmd->CopySwitchesFrom(browser_cmd, kSwitchNames,
1437 arraysize(kSwitchNames));
1439 if (browser_cmd.HasSwitch(switches::kTraceStartup) &&
1440 BrowserMainLoop::GetInstance()->is_tracing_startup_for_duration()) {
1441 // Pass kTraceStartup switch to renderer only if startup tracing has not
1442 // finished.
1443 renderer_cmd->AppendSwitchASCII(
1444 switches::kTraceStartup,
1445 browser_cmd.GetSwitchValueASCII(switches::kTraceStartup));
1448 #if defined(ENABLE_WEBRTC)
1449 // Only run the Stun trials in the first renderer.
1450 if (!has_done_stun_trials &&
1451 browser_cmd.HasSwitch(switches::kWebRtcStunProbeTrialParameter)) {
1452 has_done_stun_trials = true;
1453 renderer_cmd->AppendSwitchASCII(
1454 switches::kWebRtcStunProbeTrialParameter,
1455 browser_cmd.GetSwitchValueASCII(
1456 switches::kWebRtcStunProbeTrialParameter));
1458 #endif
1460 // Disable databases in incognito mode.
1461 if (GetBrowserContext()->IsOffTheRecord() &&
1462 !browser_cmd.HasSwitch(switches::kDisableDatabases)) {
1463 renderer_cmd->AppendSwitch(switches::kDisableDatabases);
1466 // Add kWaitForDebugger to let renderer process wait for a debugger.
1467 if (browser_cmd.HasSwitch(switches::kWaitForDebuggerChildren)) {
1468 // Look to pass-on the kWaitForDebugger flag.
1469 std::string value =
1470 browser_cmd.GetSwitchValueASCII(switches::kWaitForDebuggerChildren);
1471 if (value.empty() || value == switches::kRendererProcess) {
1472 renderer_cmd->AppendSwitch(switches::kWaitForDebugger);
1477 base::ProcessHandle RenderProcessHostImpl::GetHandle() const {
1478 if (run_renderer_in_process())
1479 return base::GetCurrentProcessHandle();
1481 if (!child_process_launcher_.get() || child_process_launcher_->IsStarting())
1482 return base::kNullProcessHandle;
1484 return child_process_launcher_->GetProcess().Handle();
1487 bool RenderProcessHostImpl::Shutdown(int exit_code, bool wait) {
1488 if (run_renderer_in_process())
1489 return false; // Single process mode never shuts down the renderer.
1491 #if defined(OS_ANDROID)
1492 // Android requires a different approach for killing.
1493 StopChildProcess(GetHandle());
1494 return true;
1495 #else
1496 if (!child_process_launcher_.get() || child_process_launcher_->IsStarting())
1497 return false;
1499 return child_process_launcher_->GetProcess().Terminate(exit_code, wait);
1500 #endif
1503 bool RenderProcessHostImpl::FastShutdownIfPossible() {
1504 if (run_renderer_in_process())
1505 return false; // Single process mode never shuts down the renderer.
1507 if (!GetContentClient()->browser()->IsFastShutdownPossible())
1508 return false;
1510 if (!child_process_launcher_.get() ||
1511 child_process_launcher_->IsStarting() ||
1512 !GetHandle())
1513 return false; // Render process hasn't started or is probably crashed.
1515 // Test if there's an unload listener.
1516 // NOTE: It's possible that an onunload listener may be installed
1517 // while we're shutting down, so there's a small race here. Given that
1518 // the window is small, it's unlikely that the web page has much
1519 // state that will be lost by not calling its unload handlers properly.
1520 if (!SuddenTerminationAllowed())
1521 return false;
1523 if (worker_ref_count_ != 0) {
1524 if (survive_for_worker_start_time_.is_null())
1525 survive_for_worker_start_time_ = base::TimeTicks::Now();
1526 return false;
1529 // Set this before ProcessDied() so observers can tell if the render process
1530 // died due to fast shutdown versus another cause.
1531 fast_shutdown_started_ = true;
1533 ProcessDied(false /* already_dead */, nullptr);
1534 return true;
1537 bool RenderProcessHostImpl::Send(IPC::Message* msg) {
1538 TRACE_EVENT0("renderer_host", "RenderProcessHostImpl::Send");
1539 if (!channel_) {
1540 if (!is_initialized_) {
1541 queued_messages_.push(msg);
1542 return true;
1543 } else {
1544 delete msg;
1545 return false;
1549 if (child_process_launcher_.get() && child_process_launcher_->IsStarting()) {
1550 queued_messages_.push(msg);
1551 return true;
1554 return channel_->Send(msg);
1557 bool RenderProcessHostImpl::OnMessageReceived(const IPC::Message& msg) {
1558 // If we're about to be deleted, or have initiated the fast shutdown sequence,
1559 // we ignore incoming messages.
1561 if (deleting_soon_ || fast_shutdown_started_)
1562 return false;
1564 mark_child_process_activity_time();
1565 if (msg.routing_id() == MSG_ROUTING_CONTROL) {
1566 // Dispatch control messages.
1567 IPC_BEGIN_MESSAGE_MAP(RenderProcessHostImpl, msg)
1568 IPC_MESSAGE_HANDLER(ChildProcessHostMsg_ShutdownRequest,
1569 OnShutdownRequest)
1570 IPC_MESSAGE_HANDLER(RenderProcessHostMsg_SuddenTerminationChanged,
1571 SuddenTerminationChanged)
1572 IPC_MESSAGE_HANDLER(ViewHostMsg_UserMetricsRecordAction,
1573 OnUserMetricsRecordAction)
1574 IPC_MESSAGE_HANDLER(ViewHostMsg_SavedPageAsMHTML, OnSavedPageAsMHTML)
1575 IPC_MESSAGE_HANDLER(ViewHostMsg_Close_ACK, OnCloseACK)
1576 #if defined(ENABLE_WEBRTC)
1577 IPC_MESSAGE_HANDLER(AecDumpMsg_RegisterAecDumpConsumer,
1578 OnRegisterAecDumpConsumer)
1579 IPC_MESSAGE_HANDLER(AecDumpMsg_UnregisterAecDumpConsumer,
1580 OnUnregisterAecDumpConsumer)
1581 #endif
1582 // Adding single handlers for your service here is fine, but once your
1583 // service needs more than one handler, please extract them into a new
1584 // message filter and add that filter to CreateMessageFilters().
1585 IPC_END_MESSAGE_MAP()
1587 return true;
1590 // Dispatch incoming messages to the appropriate IPC::Listener.
1591 IPC::Listener* listener = listeners_.Lookup(msg.routing_id());
1592 if (!listener) {
1593 if (msg.is_sync()) {
1594 // The listener has gone away, so we must respond or else the caller will
1595 // hang waiting for a reply.
1596 IPC::Message* reply = IPC::SyncMessage::GenerateReply(&msg);
1597 reply->set_reply_error();
1598 Send(reply);
1600 return true;
1602 return listener->OnMessageReceived(msg);
1605 void RenderProcessHostImpl::OnChannelConnected(int32 peer_pid) {
1606 #if defined(IPC_MESSAGE_LOG_ENABLED)
1607 Send(new ChildProcessMsg_SetIPCLoggingEnabled(
1608 IPC::Logging::GetInstance()->Enabled()));
1609 #endif
1611 tracked_objects::ThreadData::Status status =
1612 tracked_objects::ThreadData::status();
1613 Send(new ChildProcessMsg_SetProfilerStatus(status));
1615 #if defined(OS_MACOSX) && !defined(OS_IOS)
1616 io_surface_manager_token_ =
1617 BrowserIOSurfaceManager::GetInstance()->GenerateChildProcessToken(
1618 GetID());
1619 Send(new ChildProcessMsg_SetIOSurfaceManagerToken(io_surface_manager_token_));
1620 #endif
1622 #if defined(USE_OZONE)
1623 Send(new ChildProcessMsg_InitializeClientNativePixmapFactory(
1624 base::FileDescriptor(
1625 ui::OzonePlatform::GetInstance()->OpenClientNativePixmapDevice())));
1626 #endif
1628 // Inform AudioInputRendererHost about the new render process PID.
1629 // AudioInputRendererHost is reference counted, so it's lifetime is
1630 // guarantueed during the lifetime of the closure.
1631 BrowserThread::PostTask(
1632 BrowserThread::IO, FROM_HERE,
1633 base::Bind(&AudioInputRendererHost::set_renderer_pid,
1634 audio_input_renderer_host_,
1635 peer_pid));
1638 void RenderProcessHostImpl::OnChannelError() {
1639 ProcessDied(true /* already_dead */, nullptr);
1642 void RenderProcessHostImpl::OnBadMessageReceived(const IPC::Message& message) {
1643 // Message de-serialization failed. We consider this a capital crime. Kill the
1644 // renderer if we have one.
1645 LOG(ERROR) << "bad message " << message.type() << " terminating renderer.";
1646 BrowserChildProcessHostImpl::HistogramBadMessageTerminated(
1647 PROCESS_TYPE_RENDERER);
1649 // Create a memory dump. This will contain enough stack frames to work out
1650 // what the bad message was.
1651 base::debug::DumpWithoutCrashing();
1653 bad_message::ReceivedBadMessage(this,
1654 bad_message::RPH_DESERIALIZATION_FAILED);
1657 BrowserContext* RenderProcessHostImpl::GetBrowserContext() const {
1658 return browser_context_;
1661 bool RenderProcessHostImpl::InSameStoragePartition(
1662 StoragePartition* partition) const {
1663 return storage_partition_impl_ == partition;
1666 int RenderProcessHostImpl::GetID() const {
1667 return id_;
1670 bool RenderProcessHostImpl::HasConnection() const {
1671 return channel_.get() != NULL;
1674 void RenderProcessHostImpl::SetIgnoreInputEvents(bool ignore_input_events) {
1675 ignore_input_events_ = ignore_input_events;
1678 bool RenderProcessHostImpl::IgnoreInputEvents() const {
1679 return ignore_input_events_;
1682 void RenderProcessHostImpl::Cleanup() {
1683 // If within_process_died_observer_ is true, one of our observers performed an
1684 // action that caused us to die (e.g. http://crbug.com/339504). Therefore,
1685 // delay the destruction until all of the observer callbacks have been made,
1686 // and guarantee that the RenderProcessHostDestroyed observer callback is
1687 // always the last callback fired.
1688 if (within_process_died_observer_) {
1689 delayed_cleanup_needed_ = true;
1690 return;
1692 delayed_cleanup_needed_ = false;
1694 // Records the time when the process starts surviving for workers for UMA.
1695 if (listeners_.IsEmpty() && worker_ref_count_ > 0 &&
1696 survive_for_worker_start_time_.is_null()) {
1697 survive_for_worker_start_time_ = base::TimeTicks::Now();
1700 // When there are no other owners of this object, we can delete ourselves.
1701 if (listeners_.IsEmpty() && worker_ref_count_ == 0) {
1702 if (!survive_for_worker_start_time_.is_null()) {
1703 UMA_HISTOGRAM_LONG_TIMES(
1704 "SharedWorker.RendererSurviveForWorkerTime",
1705 base::TimeTicks::Now() - survive_for_worker_start_time_);
1708 if (max_worker_count_ > 0) {
1709 // Record the max number of workers (SharedWorker or ServiceWorker)
1710 // that are simultaneously hosted in this renderer process.
1711 UMA_HISTOGRAM_COUNTS("Render.Workers.MaxWorkerCountInRendererProcess",
1712 max_worker_count_);
1715 // We cannot clean up twice; if this fails, there is an issue with our
1716 // control flow.
1717 DCHECK(!deleting_soon_);
1719 DCHECK_EQ(0, pending_views_);
1720 FOR_EACH_OBSERVER(RenderProcessHostObserver,
1721 observers_,
1722 RenderProcessHostDestroyed(this));
1723 NotificationService::current()->Notify(
1724 NOTIFICATION_RENDERER_PROCESS_TERMINATED,
1725 Source<RenderProcessHost>(this),
1726 NotificationService::NoDetails());
1728 #ifndef NDEBUG
1729 is_self_deleted_ = true;
1730 #endif
1731 base::MessageLoop::current()->DeleteSoon(FROM_HERE, this);
1732 deleting_soon_ = true;
1733 // It's important not to wait for the DeleteTask to delete the channel
1734 // proxy. Kill it off now. That way, in case the profile is going away, the
1735 // rest of the objects attached to this RenderProcessHost start going
1736 // away first, since deleting the channel proxy will post a
1737 // OnChannelClosed() to IPC::ChannelProxy::Context on the IO thread.
1738 channel_.reset();
1740 // The following members should be cleared in ProcessDied() as well!
1741 gpu_message_filter_ = NULL;
1742 message_port_message_filter_ = NULL;
1744 RemoveUserData(kSessionStorageHolderKey);
1746 // Remove ourself from the list of renderer processes so that we can't be
1747 // reused in between now and when the Delete task runs.
1748 UnregisterHost(GetID());
1750 #if defined(OS_MACOSX) && !defined(OS_IOS)
1751 if (!io_surface_manager_token_.IsZero()) {
1752 BrowserIOSurfaceManager::GetInstance()->InvalidateChildProcessToken(
1753 io_surface_manager_token_);
1754 io_surface_manager_token_.SetZero();
1756 #endif
1760 void RenderProcessHostImpl::AddPendingView() {
1761 pending_views_++;
1764 void RenderProcessHostImpl::RemovePendingView() {
1765 DCHECK(pending_views_);
1766 pending_views_--;
1769 void RenderProcessHostImpl::SetSuddenTerminationAllowed(bool enabled) {
1770 sudden_termination_allowed_ = enabled;
1773 bool RenderProcessHostImpl::SuddenTerminationAllowed() const {
1774 return sudden_termination_allowed_;
1777 base::TimeDelta RenderProcessHostImpl::GetChildProcessIdleTime() const {
1778 return base::TimeTicks::Now() - child_process_activity_time_;
1781 void RenderProcessHostImpl::ResumeRequestsForView(int route_id) {
1782 widget_helper_->ResumeRequestsForView(route_id);
1785 void RenderProcessHostImpl::FilterURL(bool empty_allowed, GURL* url) {
1786 FilterURL(this, empty_allowed, url);
1789 #if defined(ENABLE_WEBRTC)
1790 void RenderProcessHostImpl::EnableAudioDebugRecordings(
1791 const base::FilePath& file) {
1792 DCHECK_CURRENTLY_ON(BrowserThread::UI);
1794 // Enable AEC dump for each registered consumer.
1795 base::FilePath file_with_extensions =
1796 GetAecDumpFilePathWithExtensions(file);
1797 for (std::vector<int>::iterator it = aec_dump_consumers_.begin();
1798 it != aec_dump_consumers_.end(); ++it) {
1799 EnableAecDumpForId(file_with_extensions, *it);
1802 // Enable mic input recording. AudioInputRendererHost is reference counted, so
1803 // it's lifetime is guarantueed during the lifetime of the closure.
1804 BrowserThread::PostTask(
1805 BrowserThread::IO, FROM_HERE,
1806 base::Bind(&AudioInputRendererHost::EnableDebugRecording,
1807 audio_input_renderer_host_,
1808 file));
1811 void RenderProcessHostImpl::DisableAudioDebugRecordings() {
1812 DCHECK_CURRENTLY_ON(BrowserThread::UI);
1814 // Posting on the FILE thread and then replying back on the UI thread is only
1815 // for avoiding races between enable and disable. Nothing is done on the FILE
1816 // thread.
1817 BrowserThread::PostTaskAndReply(
1818 BrowserThread::FILE, FROM_HERE,
1819 base::Bind(&DisableAecDumpOnFileThread),
1820 base::Bind(&RenderProcessHostImpl::SendDisableAecDumpToRenderer,
1821 weak_factory_.GetWeakPtr()));
1823 // AudioInputRendererHost is reference counted, so it's lifetime is
1824 // guaranteed during the lifetime of the closure.
1825 BrowserThread::PostTask(
1826 BrowserThread::IO, FROM_HERE,
1827 base::Bind(
1828 &AudioInputRendererHost::DisableDebugRecording,
1829 audio_input_renderer_host_));
1832 void RenderProcessHostImpl::SetWebRtcLogMessageCallback(
1833 base::Callback<void(const std::string&)> callback) {
1834 webrtc_log_message_callback_ = callback;
1837 RenderProcessHostImpl::WebRtcStopRtpDumpCallback
1838 RenderProcessHostImpl::StartRtpDump(
1839 bool incoming,
1840 bool outgoing,
1841 const WebRtcRtpPacketCallback& packet_callback) {
1842 if (!p2p_socket_dispatcher_host_.get())
1843 return WebRtcStopRtpDumpCallback();
1845 BrowserThread::PostTask(BrowserThread::IO,
1846 FROM_HERE,
1847 base::Bind(&P2PSocketDispatcherHost::StartRtpDump,
1848 p2p_socket_dispatcher_host_,
1849 incoming,
1850 outgoing,
1851 packet_callback));
1853 if (stop_rtp_dump_callback_.is_null()) {
1854 stop_rtp_dump_callback_ =
1855 base::Bind(&P2PSocketDispatcherHost::StopRtpDumpOnUIThread,
1856 p2p_socket_dispatcher_host_);
1858 return stop_rtp_dump_callback_;
1860 #endif
1862 IPC::ChannelProxy* RenderProcessHostImpl::GetChannel() {
1863 return channel_.get();
1866 void RenderProcessHostImpl::AddFilter(BrowserMessageFilter* filter) {
1867 channel_->AddFilter(filter->GetFilter());
1870 bool RenderProcessHostImpl::FastShutdownForPageCount(size_t count) {
1871 if (GetActiveViewCount() == count)
1872 return FastShutdownIfPossible();
1873 return false;
1876 bool RenderProcessHostImpl::FastShutdownStarted() const {
1877 return fast_shutdown_started_;
1880 // static
1881 void RenderProcessHostImpl::RegisterHost(int host_id, RenderProcessHost* host) {
1882 g_all_hosts.Get().AddWithID(host, host_id);
1885 // static
1886 void RenderProcessHostImpl::UnregisterHost(int host_id) {
1887 RenderProcessHost* host = g_all_hosts.Get().Lookup(host_id);
1888 if (!host)
1889 return;
1891 g_all_hosts.Get().Remove(host_id);
1893 // Look up the map of site to process for the given browser_context,
1894 // in case we need to remove this process from it. It will be registered
1895 // under any sites it rendered that use process-per-site mode.
1896 SiteProcessMap* map =
1897 GetSiteProcessMapForBrowserContext(host->GetBrowserContext());
1898 map->RemoveProcess(host);
1901 // static
1902 void RenderProcessHostImpl::FilterURL(RenderProcessHost* rph,
1903 bool empty_allowed,
1904 GURL* url) {
1905 ChildProcessSecurityPolicyImpl* policy =
1906 ChildProcessSecurityPolicyImpl::GetInstance();
1908 if (empty_allowed && url->is_empty())
1909 return;
1911 // The browser process should never hear the swappedout:// URL from any
1912 // of the renderer's messages. Check for this in debug builds, but don't
1913 // let it crash a release browser.
1914 DCHECK(GURL(kSwappedOutURL) != *url);
1916 if (!url->is_valid()) {
1917 // Have to use about:blank for the denied case, instead of an empty GURL.
1918 // This is because the browser treats navigation to an empty GURL as a
1919 // navigation to the home page. This is often a privileged page
1920 // (chrome://newtab/) which is exactly what we don't want.
1921 *url = GURL(url::kAboutBlankURL);
1922 return;
1925 if (url->SchemeIs(url::kAboutScheme)) {
1926 // The renderer treats all URLs in the about: scheme as being about:blank.
1927 // Canonicalize about: URLs to about:blank.
1928 *url = GURL(url::kAboutBlankURL);
1931 // Do not allow browser plugin guests to navigate to non-web URLs, since they
1932 // cannot swap processes or grant bindings.
1933 bool non_web_url_in_guest = rph->IsForGuestsOnly() &&
1934 !(url->is_valid() && policy->IsWebSafeScheme(url->scheme()));
1936 if (non_web_url_in_guest || !policy->CanRequestURL(rph->GetID(), *url)) {
1937 // If this renderer is not permitted to request this URL, we invalidate the
1938 // URL. This prevents us from storing the blocked URL and becoming confused
1939 // later.
1940 VLOG(1) << "Blocked URL " << url->spec();
1941 *url = GURL(url::kAboutBlankURL);
1945 // static
1946 bool RenderProcessHostImpl::IsSuitableHost(
1947 RenderProcessHost* host,
1948 BrowserContext* browser_context,
1949 const GURL& site_url) {
1950 if (run_renderer_in_process())
1951 return true;
1953 if (host->GetBrowserContext() != browser_context)
1954 return false;
1956 // Do not allow sharing of guest hosts. This is to prevent bugs where guest
1957 // and non-guest storage gets mixed. In the future, we might consider enabling
1958 // the sharing of guests, in this case this check should be removed and
1959 // InSameStoragePartition should handle the possible sharing.
1960 if (host->IsForGuestsOnly())
1961 return false;
1963 // Check whether the given host and the intended site_url will be using the
1964 // same StoragePartition, since a RenderProcessHost can only support a single
1965 // StoragePartition. This is relevant for packaged apps.
1966 StoragePartition* dest_partition =
1967 BrowserContext::GetStoragePartitionForSite(browser_context, site_url);
1968 if (!host->InSameStoragePartition(dest_partition))
1969 return false;
1971 // TODO(nick): Consult the SiteIsolationPolicy here. https://crbug.com/513036
1972 if (ChildProcessSecurityPolicyImpl::GetInstance()->HasWebUIBindings(
1973 host->GetID()) !=
1974 WebUIControllerFactoryRegistry::GetInstance()->UseWebUIBindingsForURL(
1975 browser_context, site_url)) {
1976 return false;
1979 return GetContentClient()->browser()->IsSuitableHost(host, site_url);
1982 // static
1983 bool RenderProcessHost::run_renderer_in_process() {
1984 return g_run_renderer_in_process_;
1987 // static
1988 void RenderProcessHost::SetRunRendererInProcess(bool value) {
1989 g_run_renderer_in_process_ = value;
1991 base::CommandLine* command_line = base::CommandLine::ForCurrentProcess();
1992 if (value) {
1993 if (!command_line->HasSwitch(switches::kLang)) {
1994 // Modify the current process' command line to include the browser locale,
1995 // as the renderer expects this flag to be set.
1996 const std::string locale =
1997 GetContentClient()->browser()->GetApplicationLocale();
1998 command_line->AppendSwitchASCII(switches::kLang, locale);
2000 // TODO(piman): we should really send configuration through bools rather
2001 // than by parsing strings, i.e. sending an IPC rather than command line
2002 // args. crbug.com/314909
2003 AppendCompositorCommandLineFlags(command_line);
2007 // static
2008 RenderProcessHost::iterator RenderProcessHost::AllHostsIterator() {
2009 DCHECK_CURRENTLY_ON(BrowserThread::UI);
2010 return iterator(g_all_hosts.Pointer());
2013 // static
2014 RenderProcessHost* RenderProcessHost::FromID(int render_process_id) {
2015 DCHECK_CURRENTLY_ON(BrowserThread::UI);
2016 return g_all_hosts.Get().Lookup(render_process_id);
2019 // static
2020 bool RenderProcessHost::ShouldTryToUseExistingProcessHost(
2021 BrowserContext* browser_context, const GURL& url) {
2022 // If --site-per-process is enabled, do not try to reuse renderer processes
2023 // when over the limit.
2024 // TODO(nick): This is overly conservative and isn't launchable. Move this
2025 // logic into IsSuitableHost, and check |url| against the URL the process is
2026 // dedicated to. This will allow pages from the same site to share, and will
2027 // also allow non-isolated sites to share processes. https://crbug.com/513036
2028 if (SiteIsolationPolicy::AreCrossProcessFramesPossible())
2029 return false;
2031 if (run_renderer_in_process())
2032 return true;
2034 // NOTE: Sometimes it's necessary to create more render processes than
2035 // GetMaxRendererProcessCount(), for instance when we want to create
2036 // a renderer process for a browser context that has no existing
2037 // renderers. This is OK in moderation, since the
2038 // GetMaxRendererProcessCount() is conservative.
2039 if (g_all_hosts.Get().size() >= GetMaxRendererProcessCount())
2040 return true;
2042 return GetContentClient()->browser()->
2043 ShouldTryToUseExistingProcessHost(browser_context, url);
2046 // static
2047 RenderProcessHost* RenderProcessHost::GetExistingProcessHost(
2048 BrowserContext* browser_context,
2049 const GURL& site_url) {
2050 // First figure out which existing renderers we can use.
2051 std::vector<RenderProcessHost*> suitable_renderers;
2052 suitable_renderers.reserve(g_all_hosts.Get().size());
2054 iterator iter(AllHostsIterator());
2055 while (!iter.IsAtEnd()) {
2056 if (GetContentClient()->browser()->MayReuseHost(iter.GetCurrentValue()) &&
2057 RenderProcessHostImpl::IsSuitableHost(
2058 iter.GetCurrentValue(),
2059 browser_context, site_url)) {
2060 suitable_renderers.push_back(iter.GetCurrentValue());
2062 iter.Advance();
2065 // Now pick a random suitable renderer, if we have any.
2066 if (!suitable_renderers.empty()) {
2067 int suitable_count = static_cast<int>(suitable_renderers.size());
2068 int random_index = base::RandInt(0, suitable_count - 1);
2069 return suitable_renderers[random_index];
2072 return NULL;
2075 // static
2076 bool RenderProcessHost::ShouldUseProcessPerSite(
2077 BrowserContext* browser_context,
2078 const GURL& url) {
2079 // Returns true if we should use the process-per-site model. This will be
2080 // the case if the --process-per-site switch is specified, or in
2081 // process-per-site-instance for particular sites (e.g., WebUI).
2082 // Note that --single-process is handled in ShouldTryToUseExistingProcessHost.
2083 const base::CommandLine& command_line =
2084 *base::CommandLine::ForCurrentProcess();
2085 if (command_line.HasSwitch(switches::kProcessPerSite))
2086 return true;
2088 // We want to consolidate particular sites like WebUI even when we are using
2089 // the process-per-tab or process-per-site-instance models.
2090 // Note: DevTools pages have WebUI type but should not reuse the same host.
2091 if (WebUIControllerFactoryRegistry::GetInstance()->UseWebUIForURL(
2092 browser_context, url) &&
2093 !url.SchemeIs(kChromeDevToolsScheme)) {
2094 return true;
2097 // Otherwise let the content client decide, defaulting to false.
2098 return GetContentClient()->browser()->ShouldUseProcessPerSite(browser_context,
2099 url);
2102 // static
2103 RenderProcessHost* RenderProcessHostImpl::GetProcessHostForSite(
2104 BrowserContext* browser_context,
2105 const GURL& url) {
2106 // Look up the map of site to process for the given browser_context.
2107 SiteProcessMap* map =
2108 GetSiteProcessMapForBrowserContext(browser_context);
2110 // See if we have an existing process with appropriate bindings for this site.
2111 // If not, the caller should create a new process and register it.
2112 std::string site = SiteInstance::GetSiteForURL(browser_context, url)
2113 .possibly_invalid_spec();
2114 RenderProcessHost* host = map->FindProcess(site);
2115 if (host && (!GetContentClient()->browser()->MayReuseHost(host) ||
2116 !IsSuitableHost(host, browser_context, url))) {
2117 // The registered process does not have an appropriate set of bindings for
2118 // the url. Remove it from the map so we can register a better one.
2119 RecordAction(
2120 base::UserMetricsAction("BindingsMismatch_GetProcessHostPerSite"));
2121 map->RemoveProcess(host);
2122 host = NULL;
2125 return host;
2128 void RenderProcessHostImpl::RegisterProcessHostForSite(
2129 BrowserContext* browser_context,
2130 RenderProcessHost* process,
2131 const GURL& url) {
2132 // Look up the map of site to process for the given browser_context.
2133 SiteProcessMap* map =
2134 GetSiteProcessMapForBrowserContext(browser_context);
2136 // Only register valid, non-empty sites. Empty or invalid sites will not
2137 // use process-per-site mode. We cannot check whether the process has
2138 // appropriate bindings here, because the bindings have not yet been granted.
2139 std::string site = SiteInstance::GetSiteForURL(browser_context, url)
2140 .possibly_invalid_spec();
2141 if (!site.empty())
2142 map->RegisterProcess(site, process);
2145 void RenderProcessHostImpl::ProcessDied(bool already_dead,
2146 RendererClosedDetails* known_details) {
2147 // Our child process has died. If we didn't expect it, it's a crash.
2148 // In any case, we need to let everyone know it's gone.
2149 // The OnChannelError notification can fire multiple times due to nested sync
2150 // calls to a renderer. If we don't have a valid channel here it means we
2151 // already handled the error.
2153 // It should not be possible for us to be called re-entrantly.
2154 DCHECK(!within_process_died_observer_);
2156 // It should not be possible for a process death notification to come in while
2157 // we are dying.
2158 DCHECK(!deleting_soon_);
2160 // child_process_launcher_ can be NULL in single process mode or if fast
2161 // termination happened.
2162 base::TerminationStatus status = base::TERMINATION_STATUS_NORMAL_TERMINATION;
2163 int exit_code = 0;
2164 if (known_details) {
2165 status = known_details->status;
2166 exit_code = known_details->exit_code;
2167 } else if (child_process_launcher_.get()) {
2168 status = child_process_launcher_->GetChildTerminationStatus(already_dead,
2169 &exit_code);
2170 if (already_dead && status == base::TERMINATION_STATUS_STILL_RUNNING) {
2171 // May be in case of IPC error, if it takes long time for renderer
2172 // to exit. Child process will be killed in any case during
2173 // child_process_launcher_.reset(). Make sure we will not broadcast
2174 // FrameHostMsg_RenderProcessGone with status
2175 // TERMINATION_STATUS_STILL_RUNNING, since this will break WebContentsImpl
2176 // logic.
2177 status = base::TERMINATION_STATUS_PROCESS_CRASHED;
2181 RendererClosedDetails details(status, exit_code);
2182 mojo_application_host_->WillDestroySoon();
2184 child_process_launcher_.reset();
2185 channel_.reset();
2186 while (!queued_messages_.empty()) {
2187 delete queued_messages_.front();
2188 queued_messages_.pop();
2191 within_process_died_observer_ = true;
2192 NotificationService::current()->Notify(
2193 NOTIFICATION_RENDERER_PROCESS_CLOSED,
2194 Source<RenderProcessHost>(this),
2195 Details<RendererClosedDetails>(&details));
2196 FOR_EACH_OBSERVER(RenderProcessHostObserver,
2197 observers_,
2198 RenderProcessExited(this, status, exit_code));
2199 within_process_died_observer_ = false;
2201 gpu_message_filter_ = NULL;
2202 message_port_message_filter_ = NULL;
2203 RemoveUserData(kSessionStorageHolderKey);
2205 // RenderProcessGone handlers might navigate or perform other actions that
2206 // require a connection. Ensure that there is one before calling them.
2207 mojo_application_host_.reset(new MojoApplicationHost);
2209 IDMap<IPC::Listener>::iterator iter(&listeners_);
2210 while (!iter.IsAtEnd()) {
2211 iter.GetCurrentValue()->OnMessageReceived(
2212 FrameHostMsg_RenderProcessGone(iter.GetCurrentKey(),
2213 static_cast<int>(status),
2214 exit_code));
2215 iter.Advance();
2218 // It's possible that one of the calls out to the observers might have caused
2219 // this object to be no longer needed.
2220 if (delayed_cleanup_needed_)
2221 Cleanup();
2223 // This object is not deleted at this point and might be reused later.
2224 // TODO(darin): clean this up
2227 size_t RenderProcessHost::GetActiveViewCount() {
2228 size_t num_active_views = 0;
2229 scoped_ptr<RenderWidgetHostIterator> widgets(
2230 RenderWidgetHost::GetRenderWidgetHosts());
2231 while (RenderWidgetHost* widget = widgets->GetNextHost()) {
2232 // Count only RenderWidgetHosts in this process.
2233 if (widget->GetProcess()->GetID() == GetID())
2234 num_active_views++;
2236 return num_active_views;
2239 // Frame subscription API for this class is for accelerated composited path
2240 // only. These calls are redirected to GpuMessageFilter.
2241 void RenderProcessHostImpl::BeginFrameSubscription(
2242 int route_id,
2243 scoped_ptr<RenderWidgetHostViewFrameSubscriber> subscriber) {
2244 if (!gpu_message_filter_)
2245 return;
2246 BrowserThread::PostTask(BrowserThread::IO, FROM_HERE, base::Bind(
2247 &GpuMessageFilter::BeginFrameSubscription,
2248 gpu_message_filter_,
2249 route_id, base::Passed(&subscriber)));
2252 void RenderProcessHostImpl::EndFrameSubscription(int route_id) {
2253 if (!gpu_message_filter_)
2254 return;
2255 BrowserThread::PostTask(BrowserThread::IO, FROM_HERE, base::Bind(
2256 &GpuMessageFilter::EndFrameSubscription,
2257 gpu_message_filter_,
2258 route_id));
2261 #if defined(ENABLE_WEBRTC)
2262 void RenderProcessHostImpl::WebRtcLogMessage(const std::string& message) {
2263 DCHECK_CURRENTLY_ON(BrowserThread::UI);
2264 if (!webrtc_log_message_callback_.is_null())
2265 webrtc_log_message_callback_.Run(message);
2267 #endif
2269 void RenderProcessHostImpl::ReleaseOnCloseACK(
2270 RenderProcessHost* host,
2271 const SessionStorageNamespaceMap& sessions,
2272 int view_route_id) {
2273 DCHECK(host);
2274 if (sessions.empty())
2275 return;
2276 SessionStorageHolder* holder = static_cast<SessionStorageHolder*>
2277 (host->GetUserData(kSessionStorageHolderKey));
2278 if (!holder) {
2279 holder = new SessionStorageHolder();
2280 host->SetUserData(
2281 kSessionStorageHolderKey,
2282 holder);
2284 holder->Hold(sessions, view_route_id);
2287 void RenderProcessHostImpl::OnShutdownRequest() {
2288 // Don't shut down if there are active RenderViews, or if there are pending
2289 // RenderViews being swapped back in.
2290 // In single process mode, we never shutdown the renderer.
2291 if (pending_views_ || run_renderer_in_process() || GetActiveViewCount() > 0)
2292 return;
2294 // Notify any contents that might have swapped out renderers from this
2295 // process. They should not attempt to swap them back in.
2296 FOR_EACH_OBSERVER(RenderProcessHostObserver, observers_,
2297 RenderProcessWillExit(this));
2299 mojo_application_host_->WillDestroySoon();
2301 Send(new ChildProcessMsg_Shutdown());
2304 void RenderProcessHostImpl::SuddenTerminationChanged(bool enabled) {
2305 SetSuddenTerminationAllowed(enabled);
2308 void RenderProcessHostImpl::SetBackgrounded(bool backgrounded) {
2309 TRACE_EVENT1("renderer_host", "RenderProcessHostImpl::SetBackgrounded",
2310 "backgrounded", backgrounded);
2311 // Note: we always set the backgrounded_ value. If the process is NULL
2312 // (and hence hasn't been created yet), we will set the process priority
2313 // later when we create the process.
2314 backgrounded_ = backgrounded;
2315 if (!child_process_launcher_.get() || child_process_launcher_->IsStarting())
2316 return;
2318 // Don't background processes which have active audio streams.
2319 if (backgrounded_ && audio_renderer_host_->HasActiveAudio())
2320 return;
2322 const base::CommandLine* command_line =
2323 base::CommandLine::ForCurrentProcess();
2324 if (command_line->HasSwitch(switches::kDisableRendererBackgrounding))
2325 return;
2327 #if defined(OS_WIN)
2328 // The cbstext.dll loads as a global GetMessage hook in the browser process
2329 // and intercepts/unintercepts the kernel32 API SetPriorityClass in a
2330 // background thread. If the UI thread invokes this API just when it is
2331 // intercepted the stack is messed up on return from the interceptor
2332 // which causes random crashes in the browser process. Our hack for now
2333 // is to not invoke the SetPriorityClass API if the dll is loaded.
2334 if (GetModuleHandle(L"cbstext.dll"))
2335 return;
2336 #endif // OS_WIN
2338 #if defined(OS_WIN) || defined(OS_MACOSX)
2339 // Same as below, but bound to an experiment (http://crbug.com/458594 on
2340 // Windows, http://crbug.com/398103 on the Mac). Enabled by default in the
2341 // absence of field trials to get coverage on the perf waterfall.
2342 base::FieldTrial* trial =
2343 base::FieldTrialList::Find("BackgroundRendererProcesses");
2344 if (!trial || !base::StartsWith(trial->group_name(), "Disallow",
2345 base::CompareCase::SENSITIVE)) {
2346 child_process_launcher_->SetProcessBackgrounded(backgrounded);
2348 #else
2349 // Control the background state from the browser process, otherwise the task
2350 // telling the renderer to "unbackground" itself may be preempted by other
2351 // tasks executing at lowered priority ahead of it or simply by not being
2352 // swiftly scheduled by the OS per the low process priority
2353 // (http://crbug.com/398103).
2354 child_process_launcher_->SetProcessBackgrounded(backgrounded);
2355 #endif // OS_WIN
2357 // Notify the child process of background state.
2358 Send(new ChildProcessMsg_SetProcessBackgrounded(backgrounded));
2361 void RenderProcessHostImpl::OnProcessLaunched() {
2362 // TODO(erikchen): Remove ScopedTracker below once http://crbug.com/465841
2363 // is fixed.
2364 tracked_objects::ScopedTracker tracking_profile1(
2365 FROM_HERE_WITH_EXPLICIT_FUNCTION(
2366 "465841 RenderProcessHostImpl::OnProcessLaunched::Start"));
2367 // No point doing anything, since this object will be destructed soon. We
2368 // especially don't want to send the RENDERER_PROCESS_CREATED notification,
2369 // since some clients might expect a RENDERER_PROCESS_TERMINATED afterwards to
2370 // properly cleanup.
2371 if (deleting_soon_)
2372 return;
2374 if (child_process_launcher_) {
2375 // TODO(erikchen): Remove ScopedTracker below once http://crbug.com/465841
2376 // is fixed.
2377 tracked_objects::ScopedTracker tracking_profile2(
2378 FROM_HERE_WITH_EXPLICIT_FUNCTION(
2379 "465841 RenderProcessHostImpl::OnProcessLaunched::Backgrounded"));
2380 DCHECK(child_process_launcher_->GetProcess().IsValid());
2381 SetBackgrounded(backgrounded_);
2384 // TODO(erikchen): Remove ScopedTracker below once http://crbug.com/465841
2385 // is fixed.
2386 tracked_objects::ScopedTracker tracking_profile3(
2387 FROM_HERE_WITH_EXPLICIT_FUNCTION(
2388 "465841 RenderProcessHostImpl::OnProcessLaunched::Notify"));
2389 // NOTE: This needs to be before sending queued messages because
2390 // ExtensionService uses this notification to initialize the renderer process
2391 // with state that must be there before any JavaScript executes.
2393 // The queued messages contain such things as "navigate". If this notification
2394 // was after, we can end up executing JavaScript before the initialization
2395 // happens.
2396 NotificationService::current()->Notify(
2397 NOTIFICATION_RENDERER_PROCESS_CREATED,
2398 Source<RenderProcessHost>(this),
2399 NotificationService::NoDetails());
2401 // TODO(erikchen): Remove ScopedTracker below once http://crbug.com/465841
2402 // is fixed.
2403 tracked_objects::ScopedTracker tracking_profile4(
2404 FROM_HERE_WITH_EXPLICIT_FUNCTION(
2405 "465841 RenderProcessHostImpl::OnProcessLaunched::MojoActivate"));
2406 // Allow Mojo to be setup before the renderer sees any Chrome IPC messages.
2407 // This way, Mojo can be safely used from the renderer in response to any
2408 // Chrome IPC message.
2409 mojo_application_host_->Activate(this, GetHandle());
2411 // TODO(erikchen): Remove ScopedTracker below once http://crbug.com/465841
2412 // is fixed.
2413 tracked_objects::ScopedTracker tracking_profile5(
2414 FROM_HERE_WITH_EXPLICIT_FUNCTION(
2415 "465841 RenderProcessHostImpl::OnProcessLaunched::MojoClientLaunch"));
2417 // TODO(erikchen): Remove ScopedTracker below once http://crbug.com/465841
2418 // is fixed.
2419 tracked_objects::ScopedTracker tracking_profile6(
2420 FROM_HERE_WITH_EXPLICIT_FUNCTION(
2421 "465841 "
2422 "RenderProcessHostImpl::OnProcessLaunched::SendQueuedMessages"));
2423 while (!queued_messages_.empty()) {
2424 Send(queued_messages_.front());
2425 queued_messages_.pop();
2428 #if defined(ENABLE_WEBRTC)
2429 // TODO(erikchen): Remove ScopedTracker below once http://crbug.com/465841
2430 // is fixed.
2431 tracked_objects::ScopedTracker tracking_profile7(
2432 FROM_HERE_WITH_EXPLICIT_FUNCTION(
2433 "465841 RenderProcessHostImpl::OnProcessLaunched::EnableAec"));
2434 if (WebRTCInternals::GetInstance()->IsAudioDebugRecordingsEnabled()) {
2435 EnableAudioDebugRecordings(
2436 WebRTCInternals::GetInstance()->GetAudioDebugRecordingsFilePath());
2438 #endif
2441 void RenderProcessHostImpl::OnProcessLaunchFailed() {
2442 // If this object will be destructed soon, then observers have already been
2443 // sent a RenderProcessHostDestroyed notification, and we must observe our
2444 // contract that says that will be the last call.
2445 if (deleting_soon_)
2446 return;
2448 // TODO(wfh): Fill in the real error code here see crbug.com/526198.
2449 RendererClosedDetails details { base::TERMINATION_STATUS_LAUNCH_FAILED,
2450 -1 };
2451 ProcessDied(true, &details);
2454 scoped_refptr<AudioRendererHost>
2455 RenderProcessHostImpl::audio_renderer_host() const {
2456 return audio_renderer_host_;
2459 void RenderProcessHostImpl::OnUserMetricsRecordAction(
2460 const std::string& action) {
2461 RecordComputedAction(action);
2464 void RenderProcessHostImpl::OnCloseACK(int old_route_id) {
2465 SessionStorageHolder* holder = static_cast<SessionStorageHolder*>
2466 (GetUserData(kSessionStorageHolderKey));
2467 if (!holder)
2468 return;
2469 holder->Release(old_route_id);
2472 void RenderProcessHostImpl::OnSavedPageAsMHTML(int job_id, int64 data_size) {
2473 MHTMLGenerationManager::GetInstance()->MHTMLGenerated(job_id, data_size);
2476 void RenderProcessHostImpl::OnGpuSwitched() {
2477 // We are updating all widgets including swapped out ones.
2478 scoped_ptr<RenderWidgetHostIterator> widgets(
2479 RenderWidgetHostImpl::GetAllRenderWidgetHosts());
2480 while (RenderWidgetHost* widget = widgets->GetNextHost()) {
2481 if (!widget->IsRenderView())
2482 continue;
2484 // Skip widgets in other processes.
2485 if (widget->GetProcess()->GetID() != GetID())
2486 continue;
2488 RenderViewHost* rvh = RenderViewHost::From(widget);
2489 rvh->OnWebkitPreferencesChanged();
2493 #if defined(ENABLE_WEBRTC)
2494 void RenderProcessHostImpl::OnRegisterAecDumpConsumer(int id) {
2495 BrowserThread::PostTask(
2496 BrowserThread::UI,
2497 FROM_HERE,
2498 base::Bind(
2499 &RenderProcessHostImpl::RegisterAecDumpConsumerOnUIThread,
2500 weak_factory_.GetWeakPtr(),
2501 id));
2504 void RenderProcessHostImpl::OnUnregisterAecDumpConsumer(int id) {
2505 BrowserThread::PostTask(
2506 BrowserThread::UI,
2507 FROM_HERE,
2508 base::Bind(
2509 &RenderProcessHostImpl::UnregisterAecDumpConsumerOnUIThread,
2510 weak_factory_.GetWeakPtr(),
2511 id));
2514 void RenderProcessHostImpl::RegisterAecDumpConsumerOnUIThread(int id) {
2515 DCHECK_CURRENTLY_ON(BrowserThread::UI);
2516 aec_dump_consumers_.push_back(id);
2518 if (WebRTCInternals::GetInstance()->IsAudioDebugRecordingsEnabled()) {
2519 base::FilePath file_with_extensions = GetAecDumpFilePathWithExtensions(
2520 WebRTCInternals::GetInstance()->GetAudioDebugRecordingsFilePath());
2521 EnableAecDumpForId(file_with_extensions, id);
2525 void RenderProcessHostImpl::UnregisterAecDumpConsumerOnUIThread(int id) {
2526 DCHECK_CURRENTLY_ON(BrowserThread::UI);
2527 for (std::vector<int>::iterator it = aec_dump_consumers_.begin();
2528 it != aec_dump_consumers_.end(); ++it) {
2529 if (*it == id) {
2530 aec_dump_consumers_.erase(it);
2531 break;
2536 void RenderProcessHostImpl::EnableAecDumpForId(const base::FilePath& file,
2537 int id) {
2538 DCHECK_CURRENTLY_ON(BrowserThread::UI);
2539 BrowserThread::PostTaskAndReplyWithResult(
2540 BrowserThread::FILE, FROM_HERE,
2541 base::Bind(&CreateAecDumpFileForProcess,
2542 file.AddExtension(IntToStringType(id)),
2543 GetHandle()),
2544 base::Bind(&RenderProcessHostImpl::SendAecDumpFileToRenderer,
2545 weak_factory_.GetWeakPtr(),
2546 id));
2549 void RenderProcessHostImpl::SendAecDumpFileToRenderer(
2550 int id,
2551 IPC::PlatformFileForTransit file_for_transit) {
2552 if (file_for_transit == IPC::InvalidPlatformFileForTransit())
2553 return;
2554 Send(new AecDumpMsg_EnableAecDump(id, file_for_transit));
2557 void RenderProcessHostImpl::SendDisableAecDumpToRenderer() {
2558 Send(new AecDumpMsg_DisableAecDump());
2561 base::FilePath RenderProcessHostImpl::GetAecDumpFilePathWithExtensions(
2562 const base::FilePath& file) {
2563 return file.AddExtension(IntToStringType(base::GetProcId(GetHandle())))
2564 .AddExtension(kAecDumpFileNameAddition);
2566 #endif // defined(ENABLE_WEBRTC)
2568 void RenderProcessHostImpl::IncrementWorkerRefCount() {
2569 DCHECK_CURRENTLY_ON(BrowserThread::UI);
2570 ++worker_ref_count_;
2571 if (worker_ref_count_ > max_worker_count_)
2572 max_worker_count_ = worker_ref_count_;
2575 void RenderProcessHostImpl::DecrementWorkerRefCount() {
2576 DCHECK_CURRENTLY_ON(BrowserThread::UI);
2577 DCHECK_GT(worker_ref_count_, 0);
2578 --worker_ref_count_;
2579 if (worker_ref_count_ == 0)
2580 Cleanup();
2583 void RenderProcessHostImpl::GetAudioOutputControllers(
2584 const GetAudioOutputControllersCallback& callback) const {
2585 audio_renderer_host()->GetOutputControllers(callback);
2588 BluetoothDispatcherHost* RenderProcessHostImpl::GetBluetoothDispatcherHost() {
2589 return bluetooth_dispatcher_host_.get();
2592 } // namespace content