Clean up check for dependency_info.
[chromium-blink-merge.git] / content / browser / renderer_host / render_process_host_impl.cc
blob4411451af02c73ff1856cfc3aa0d9f68c8ebdfa3
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::kDisableNotifications,
1278 switches::kDisableOverlayScrollbar,
1279 switches::kDisablePermissionsAPI,
1280 switches::kDisablePresentationAPI,
1281 switches::kDisablePinch,
1282 switches::kDisableRGBA4444Textures,
1283 switches::kDisableSeccompFilterSandbox,
1284 switches::kDisableSharedWorkers,
1285 switches::kDisableSpeechAPI,
1286 switches::kDisableSVG1DOM,
1287 switches::kDisableThreadedCompositing,
1288 switches::kDisableThreadedScrolling,
1289 switches::kDisableTouchAdjustment,
1290 switches::kDisableTouchDragDrop,
1291 switches::kDisableTouchEditing,
1292 switches::kDisableV8IdleTasks,
1293 switches::kDomAutomationController,
1294 switches::kEnableBleedingEdgeRenderingFastPaths,
1295 switches::kEnableBlinkFeatures,
1296 switches::kEnableBrowserSideNavigation,
1297 switches::kEnableCompositorAnimationTimelines,
1298 switches::kEnableCredentialManagerAPI,
1299 switches::kEnableDelayAgnosticAec,
1300 switches::kEnableDisplayList2dCanvas,
1301 switches::kEnableDistanceFieldText,
1302 switches::kEnableExperimentalCanvasFeatures,
1303 switches::kEnableExperimentalWebPlatformFeatures,
1304 switches::kEnableGPUClientLogging,
1305 switches::kEnableGpuClientTracing,
1306 switches::kEnableGpuMemoryBufferVideoFrames,
1307 switches::kEnableGPUServiceLogging,
1308 switches::kEnableIconNtp,
1309 switches::kEnableLinkDisambiguationPopup,
1310 switches::kEnableLowResTiling,
1311 switches::kEnableInbandTextTracks,
1312 switches::kEnableLCDText,
1313 switches::kEnableLogging,
1314 switches::kEnableMemoryBenchmarking,
1315 switches::kEnableNetworkInformation,
1316 switches::kEnableOverlayScrollbar,
1317 switches::kEnablePinch,
1318 switches::kEnablePluginPlaceholderTesting,
1319 switches::kEnablePreciseMemoryInfo,
1320 switches::kEnablePreferCompositingToLCDText,
1321 switches::kEnablePrefixedEncryptedMedia,
1322 switches::kEnablePushMessagePayload,
1323 switches::kEnableRGBA4444Textures,
1324 switches::kEnableRendererMojoChannel,
1325 switches::kEnableRTCSmoothnessAlgorithm,
1326 switches::kEnableSeccompFilterSandbox,
1327 switches::kEnableSkiaBenchmarking,
1328 switches::kEnableSlimmingPaintV2,
1329 switches::kEnableSmoothScrolling,
1330 switches::kEnableStatsTable,
1331 switches::kEnableThreadedCompositing,
1332 switches::kEnableTouchDragDrop,
1333 switches::kEnableTouchEditing,
1334 switches::kEnableUnsafeES3APIs,
1335 switches::kEnableViewport,
1336 switches::kEnableVtune,
1337 switches::kEnableWebBluetooth,
1338 switches::kEnableWebGLDraftExtensions,
1339 switches::kEnableWebGLImageChromium,
1340 switches::kEnableWebVR,
1341 switches::kExplicitlyAllowedPorts,
1342 switches::kForceDeviceScaleFactor,
1343 switches::kForceDisplayList2dCanvas,
1344 switches::kForceOverlayFullscreenVideo,
1345 switches::kFullMemoryCrashReport,
1346 switches::kIPCConnectionTimeout,
1347 switches::kJavaScriptFlags,
1348 switches::kLoggingLevel,
1349 switches::kMainFrameResizesAreOrientationChanges,
1350 switches::kMaxUntiledLayerWidth,
1351 switches::kMaxUntiledLayerHeight,
1352 switches::kMemoryMetrics,
1353 switches::kNoReferrers,
1354 switches::kNoSandbox,
1355 switches::kOverridePluginPowerSaverForTesting,
1356 switches::kPpapiInProcess,
1357 switches::kProfilerTiming,
1358 switches::kReducedReferrerGranularity,
1359 switches::kReduceSecurityForTesting,
1360 switches::kRegisterPepperPlugins,
1361 switches::kRendererStartupDialog,
1362 switches::kRootLayerScrolls,
1363 switches::kShowPaintRects,
1364 switches::kSitePerProcess,
1365 switches::kStatsCollectionController,
1366 switches::kTestType,
1367 switches::kTouchEvents,
1368 switches::kTouchTextSelectionStrategy,
1369 switches::kTraceConfigFile,
1370 switches::kTraceToConsole,
1371 // This flag needs to be propagated to the renderer process for
1372 // --in-process-webgl.
1373 switches::kUseGL,
1374 switches::kUseMobileUserAgent,
1375 switches::kUseNormalPriorityForTileTaskWorkerThreads,
1376 switches::kV,
1377 switches::kVideoThreads,
1378 switches::kVideoUnderflowThresholdMs,
1379 switches::kVModule,
1380 // Please keep these in alphabetical order. Compositor switches here should
1381 // also be added to chrome/browser/chromeos/login/chrome_restart_request.cc.
1382 cc::switches::kCompositeToMailbox,
1383 cc::switches::kDisableCompositedAntialiasing,
1384 cc::switches::kDisableMainFrameBeforeActivation,
1385 cc::switches::kDisableThreadedAnimation,
1386 cc::switches::kEnableBeginFrameScheduling,
1387 cc::switches::kEnableGpuBenchmarking,
1388 cc::switches::kEnableMainFrameBeforeActivation,
1389 cc::switches::kShowCompositedLayerBorders,
1390 cc::switches::kShowFPSCounter,
1391 cc::switches::kShowLayerAnimationBounds,
1392 cc::switches::kShowPropertyChangedRects,
1393 cc::switches::kShowReplicaScreenSpaceRects,
1394 cc::switches::kShowScreenSpaceRects,
1395 cc::switches::kShowSurfaceDamageRects,
1396 cc::switches::kSlowDownRasterScaleFactor,
1397 cc::switches::kStrictLayerPropertyChangeChecking,
1398 cc::switches::kTopControlsHideThreshold,
1399 cc::switches::kTopControlsShowThreshold,
1401 #if defined(ENABLE_PLUGINS)
1402 switches::kEnablePepperTesting,
1403 #endif
1404 #if defined(ENABLE_WEBRTC)
1405 switches::kDisableWebRtcHWDecoding,
1406 switches::kDisableWebRtcHWEncoding,
1407 switches::kEnableWebRtcDtls12,
1408 switches::kEnableWebRtcHWH264Encoding,
1409 switches::kEnableWebRtcStunOrigin,
1410 switches::kWebRtcMaxCaptureFramerate,
1411 #endif
1412 switches::kEnableLowEndDeviceMode,
1413 switches::kDisableLowEndDeviceMode,
1414 #if defined(OS_ANDROID)
1415 switches::kDisableGestureRequirementForMediaPlayback,
1416 switches::kDisableWebAudio,
1417 switches::kRendererWaitForJavaDebugger,
1418 #endif
1419 #if defined(OS_MACOSX)
1420 // Allow this to be set when invoking the browser and relayed along.
1421 switches::kEnableSandboxLogging,
1422 #endif
1423 #if defined(OS_WIN)
1424 switches::kDisableDirectWrite,
1425 switches::kDisableWin32kRendererLockDown,
1426 switches::kTraceExportEventsToETW,
1427 #endif
1428 #if defined(USE_OZONE)
1429 switches::kOzonePlatform,
1430 #endif
1431 #if defined(OS_CHROMEOS)
1432 switches::kDisableVaapiAcceleratedVideoEncode,
1433 #endif
1435 renderer_cmd->CopySwitchesFrom(browser_cmd, kSwitchNames,
1436 arraysize(kSwitchNames));
1438 if (browser_cmd.HasSwitch(switches::kTraceStartup) &&
1439 BrowserMainLoop::GetInstance()->is_tracing_startup_for_duration()) {
1440 // Pass kTraceStartup switch to renderer only if startup tracing has not
1441 // finished.
1442 renderer_cmd->AppendSwitchASCII(
1443 switches::kTraceStartup,
1444 browser_cmd.GetSwitchValueASCII(switches::kTraceStartup));
1447 #if defined(ENABLE_WEBRTC)
1448 // Only run the Stun trials in the first renderer.
1449 if (!has_done_stun_trials &&
1450 browser_cmd.HasSwitch(switches::kWebRtcStunProbeTrialParameter)) {
1451 has_done_stun_trials = true;
1452 renderer_cmd->AppendSwitchASCII(
1453 switches::kWebRtcStunProbeTrialParameter,
1454 browser_cmd.GetSwitchValueASCII(
1455 switches::kWebRtcStunProbeTrialParameter));
1457 #endif
1459 // Disable databases in incognito mode.
1460 if (GetBrowserContext()->IsOffTheRecord() &&
1461 !browser_cmd.HasSwitch(switches::kDisableDatabases)) {
1462 renderer_cmd->AppendSwitch(switches::kDisableDatabases);
1465 // Add kWaitForDebugger to let renderer process wait for a debugger.
1466 if (browser_cmd.HasSwitch(switches::kWaitForDebuggerChildren)) {
1467 // Look to pass-on the kWaitForDebugger flag.
1468 std::string value =
1469 browser_cmd.GetSwitchValueASCII(switches::kWaitForDebuggerChildren);
1470 if (value.empty() || value == switches::kRendererProcess) {
1471 renderer_cmd->AppendSwitch(switches::kWaitForDebugger);
1476 base::ProcessHandle RenderProcessHostImpl::GetHandle() const {
1477 if (run_renderer_in_process())
1478 return base::GetCurrentProcessHandle();
1480 if (!child_process_launcher_.get() || child_process_launcher_->IsStarting())
1481 return base::kNullProcessHandle;
1483 return child_process_launcher_->GetProcess().Handle();
1486 bool RenderProcessHostImpl::Shutdown(int exit_code, bool wait) {
1487 if (run_renderer_in_process())
1488 return false; // Single process mode never shuts down the renderer.
1490 #if defined(OS_ANDROID)
1491 // Android requires a different approach for killing.
1492 StopChildProcess(GetHandle());
1493 return true;
1494 #else
1495 if (!child_process_launcher_.get() || child_process_launcher_->IsStarting())
1496 return false;
1498 return child_process_launcher_->GetProcess().Terminate(exit_code, wait);
1499 #endif
1502 bool RenderProcessHostImpl::FastShutdownIfPossible() {
1503 if (run_renderer_in_process())
1504 return false; // Single process mode never shuts down the renderer.
1506 if (!GetContentClient()->browser()->IsFastShutdownPossible())
1507 return false;
1509 if (!child_process_launcher_.get() ||
1510 child_process_launcher_->IsStarting() ||
1511 !GetHandle())
1512 return false; // Render process hasn't started or is probably crashed.
1514 // Test if there's an unload listener.
1515 // NOTE: It's possible that an onunload listener may be installed
1516 // while we're shutting down, so there's a small race here. Given that
1517 // the window is small, it's unlikely that the web page has much
1518 // state that will be lost by not calling its unload handlers properly.
1519 if (!SuddenTerminationAllowed())
1520 return false;
1522 if (worker_ref_count_ != 0) {
1523 if (survive_for_worker_start_time_.is_null())
1524 survive_for_worker_start_time_ = base::TimeTicks::Now();
1525 return false;
1528 // Set this before ProcessDied() so observers can tell if the render process
1529 // died due to fast shutdown versus another cause.
1530 fast_shutdown_started_ = true;
1532 ProcessDied(false /* already_dead */, nullptr);
1533 return true;
1536 bool RenderProcessHostImpl::Send(IPC::Message* msg) {
1537 TRACE_EVENT0("renderer_host", "RenderProcessHostImpl::Send");
1538 if (!channel_) {
1539 if (!is_initialized_) {
1540 queued_messages_.push(msg);
1541 return true;
1542 } else {
1543 delete msg;
1544 return false;
1548 if (child_process_launcher_.get() && child_process_launcher_->IsStarting()) {
1549 queued_messages_.push(msg);
1550 return true;
1553 return channel_->Send(msg);
1556 bool RenderProcessHostImpl::OnMessageReceived(const IPC::Message& msg) {
1557 // If we're about to be deleted, or have initiated the fast shutdown sequence,
1558 // we ignore incoming messages.
1560 if (deleting_soon_ || fast_shutdown_started_)
1561 return false;
1563 mark_child_process_activity_time();
1564 if (msg.routing_id() == MSG_ROUTING_CONTROL) {
1565 // Dispatch control messages.
1566 IPC_BEGIN_MESSAGE_MAP(RenderProcessHostImpl, msg)
1567 IPC_MESSAGE_HANDLER(ChildProcessHostMsg_ShutdownRequest,
1568 OnShutdownRequest)
1569 IPC_MESSAGE_HANDLER(RenderProcessHostMsg_SuddenTerminationChanged,
1570 SuddenTerminationChanged)
1571 IPC_MESSAGE_HANDLER(ViewHostMsg_UserMetricsRecordAction,
1572 OnUserMetricsRecordAction)
1573 IPC_MESSAGE_HANDLER(ViewHostMsg_SavedPageAsMHTML, OnSavedPageAsMHTML)
1574 IPC_MESSAGE_HANDLER(ViewHostMsg_Close_ACK, OnCloseACK)
1575 #if defined(ENABLE_WEBRTC)
1576 IPC_MESSAGE_HANDLER(AecDumpMsg_RegisterAecDumpConsumer,
1577 OnRegisterAecDumpConsumer)
1578 IPC_MESSAGE_HANDLER(AecDumpMsg_UnregisterAecDumpConsumer,
1579 OnUnregisterAecDumpConsumer)
1580 #endif
1581 // Adding single handlers for your service here is fine, but once your
1582 // service needs more than one handler, please extract them into a new
1583 // message filter and add that filter to CreateMessageFilters().
1584 IPC_END_MESSAGE_MAP()
1586 return true;
1589 // Dispatch incoming messages to the appropriate IPC::Listener.
1590 IPC::Listener* listener = listeners_.Lookup(msg.routing_id());
1591 if (!listener) {
1592 if (msg.is_sync()) {
1593 // The listener has gone away, so we must respond or else the caller will
1594 // hang waiting for a reply.
1595 IPC::Message* reply = IPC::SyncMessage::GenerateReply(&msg);
1596 reply->set_reply_error();
1597 Send(reply);
1599 return true;
1601 return listener->OnMessageReceived(msg);
1604 void RenderProcessHostImpl::OnChannelConnected(int32 peer_pid) {
1605 #if defined(IPC_MESSAGE_LOG_ENABLED)
1606 Send(new ChildProcessMsg_SetIPCLoggingEnabled(
1607 IPC::Logging::GetInstance()->Enabled()));
1608 #endif
1610 tracked_objects::ThreadData::Status status =
1611 tracked_objects::ThreadData::status();
1612 Send(new ChildProcessMsg_SetProfilerStatus(status));
1614 #if defined(OS_MACOSX) && !defined(OS_IOS)
1615 io_surface_manager_token_ =
1616 BrowserIOSurfaceManager::GetInstance()->GenerateChildProcessToken(
1617 GetID());
1618 Send(new ChildProcessMsg_SetIOSurfaceManagerToken(io_surface_manager_token_));
1619 #endif
1621 #if defined(USE_OZONE)
1622 Send(new ChildProcessMsg_InitializeClientNativePixmapFactory(
1623 base::FileDescriptor(
1624 ui::OzonePlatform::GetInstance()->OpenClientNativePixmapDevice())));
1625 #endif
1627 // Inform AudioInputRendererHost about the new render process PID.
1628 // AudioInputRendererHost is reference counted, so it's lifetime is
1629 // guarantueed during the lifetime of the closure.
1630 BrowserThread::PostTask(
1631 BrowserThread::IO, FROM_HERE,
1632 base::Bind(&AudioInputRendererHost::set_renderer_pid,
1633 audio_input_renderer_host_,
1634 peer_pid));
1637 void RenderProcessHostImpl::OnChannelError() {
1638 ProcessDied(true /* already_dead */, nullptr);
1641 void RenderProcessHostImpl::OnBadMessageReceived(const IPC::Message& message) {
1642 // Message de-serialization failed. We consider this a capital crime. Kill the
1643 // renderer if we have one.
1644 auto type = message.type();
1645 LOG(ERROR) << "bad 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::Alias(&type);
1652 base::debug::DumpWithoutCrashing();
1654 bad_message::ReceivedBadMessage(this,
1655 bad_message::RPH_DESERIALIZATION_FAILED);
1658 BrowserContext* RenderProcessHostImpl::GetBrowserContext() const {
1659 return browser_context_;
1662 bool RenderProcessHostImpl::InSameStoragePartition(
1663 StoragePartition* partition) const {
1664 return storage_partition_impl_ == partition;
1667 int RenderProcessHostImpl::GetID() const {
1668 return id_;
1671 bool RenderProcessHostImpl::HasConnection() const {
1672 return channel_.get() != NULL;
1675 void RenderProcessHostImpl::SetIgnoreInputEvents(bool ignore_input_events) {
1676 ignore_input_events_ = ignore_input_events;
1679 bool RenderProcessHostImpl::IgnoreInputEvents() const {
1680 return ignore_input_events_;
1683 void RenderProcessHostImpl::Cleanup() {
1684 // If within_process_died_observer_ is true, one of our observers performed an
1685 // action that caused us to die (e.g. http://crbug.com/339504). Therefore,
1686 // delay the destruction until all of the observer callbacks have been made,
1687 // and guarantee that the RenderProcessHostDestroyed observer callback is
1688 // always the last callback fired.
1689 if (within_process_died_observer_) {
1690 delayed_cleanup_needed_ = true;
1691 return;
1693 delayed_cleanup_needed_ = false;
1695 // Records the time when the process starts surviving for workers for UMA.
1696 if (listeners_.IsEmpty() && worker_ref_count_ > 0 &&
1697 survive_for_worker_start_time_.is_null()) {
1698 survive_for_worker_start_time_ = base::TimeTicks::Now();
1701 // When there are no other owners of this object, we can delete ourselves.
1702 if (listeners_.IsEmpty() && worker_ref_count_ == 0) {
1703 if (!survive_for_worker_start_time_.is_null()) {
1704 UMA_HISTOGRAM_LONG_TIMES(
1705 "SharedWorker.RendererSurviveForWorkerTime",
1706 base::TimeTicks::Now() - survive_for_worker_start_time_);
1709 if (max_worker_count_ > 0) {
1710 // Record the max number of workers (SharedWorker or ServiceWorker)
1711 // that are simultaneously hosted in this renderer process.
1712 UMA_HISTOGRAM_COUNTS("Render.Workers.MaxWorkerCountInRendererProcess",
1713 max_worker_count_);
1716 // We cannot clean up twice; if this fails, there is an issue with our
1717 // control flow.
1718 DCHECK(!deleting_soon_);
1720 DCHECK_EQ(0, pending_views_);
1721 FOR_EACH_OBSERVER(RenderProcessHostObserver,
1722 observers_,
1723 RenderProcessHostDestroyed(this));
1724 NotificationService::current()->Notify(
1725 NOTIFICATION_RENDERER_PROCESS_TERMINATED,
1726 Source<RenderProcessHost>(this),
1727 NotificationService::NoDetails());
1729 #ifndef NDEBUG
1730 is_self_deleted_ = true;
1731 #endif
1732 base::MessageLoop::current()->DeleteSoon(FROM_HERE, this);
1733 deleting_soon_ = true;
1734 // It's important not to wait for the DeleteTask to delete the channel
1735 // proxy. Kill it off now. That way, in case the profile is going away, the
1736 // rest of the objects attached to this RenderProcessHost start going
1737 // away first, since deleting the channel proxy will post a
1738 // OnChannelClosed() to IPC::ChannelProxy::Context on the IO thread.
1739 channel_.reset();
1741 // The following members should be cleared in ProcessDied() as well!
1742 gpu_message_filter_ = NULL;
1743 message_port_message_filter_ = NULL;
1745 RemoveUserData(kSessionStorageHolderKey);
1747 // Remove ourself from the list of renderer processes so that we can't be
1748 // reused in between now and when the Delete task runs.
1749 UnregisterHost(GetID());
1751 #if defined(OS_MACOSX) && !defined(OS_IOS)
1752 if (!io_surface_manager_token_.IsZero()) {
1753 BrowserIOSurfaceManager::GetInstance()->InvalidateChildProcessToken(
1754 io_surface_manager_token_);
1755 io_surface_manager_token_.SetZero();
1757 #endif
1761 void RenderProcessHostImpl::AddPendingView() {
1762 pending_views_++;
1765 void RenderProcessHostImpl::RemovePendingView() {
1766 DCHECK(pending_views_);
1767 pending_views_--;
1770 void RenderProcessHostImpl::SetSuddenTerminationAllowed(bool enabled) {
1771 sudden_termination_allowed_ = enabled;
1774 bool RenderProcessHostImpl::SuddenTerminationAllowed() const {
1775 return sudden_termination_allowed_;
1778 base::TimeDelta RenderProcessHostImpl::GetChildProcessIdleTime() const {
1779 return base::TimeTicks::Now() - child_process_activity_time_;
1782 void RenderProcessHostImpl::ResumeRequestsForView(int route_id) {
1783 widget_helper_->ResumeRequestsForView(route_id);
1786 void RenderProcessHostImpl::FilterURL(bool empty_allowed, GURL* url) {
1787 FilterURL(this, empty_allowed, url);
1790 #if defined(ENABLE_WEBRTC)
1791 void RenderProcessHostImpl::EnableAudioDebugRecordings(
1792 const base::FilePath& file) {
1793 DCHECK_CURRENTLY_ON(BrowserThread::UI);
1795 // Enable AEC dump for each registered consumer.
1796 base::FilePath file_with_extensions =
1797 GetAecDumpFilePathWithExtensions(file);
1798 for (std::vector<int>::iterator it = aec_dump_consumers_.begin();
1799 it != aec_dump_consumers_.end(); ++it) {
1800 EnableAecDumpForId(file_with_extensions, *it);
1803 // Enable mic input recording. AudioInputRendererHost is reference counted, so
1804 // it's lifetime is guarantueed during the lifetime of the closure.
1805 BrowserThread::PostTask(
1806 BrowserThread::IO, FROM_HERE,
1807 base::Bind(&AudioInputRendererHost::EnableDebugRecording,
1808 audio_input_renderer_host_,
1809 file));
1812 void RenderProcessHostImpl::DisableAudioDebugRecordings() {
1813 DCHECK_CURRENTLY_ON(BrowserThread::UI);
1815 // Posting on the FILE thread and then replying back on the UI thread is only
1816 // for avoiding races between enable and disable. Nothing is done on the FILE
1817 // thread.
1818 BrowserThread::PostTaskAndReply(
1819 BrowserThread::FILE, FROM_HERE,
1820 base::Bind(&DisableAecDumpOnFileThread),
1821 base::Bind(&RenderProcessHostImpl::SendDisableAecDumpToRenderer,
1822 weak_factory_.GetWeakPtr()));
1824 // AudioInputRendererHost is reference counted, so it's lifetime is
1825 // guaranteed during the lifetime of the closure.
1826 BrowserThread::PostTask(
1827 BrowserThread::IO, FROM_HERE,
1828 base::Bind(
1829 &AudioInputRendererHost::DisableDebugRecording,
1830 audio_input_renderer_host_));
1833 void RenderProcessHostImpl::SetWebRtcLogMessageCallback(
1834 base::Callback<void(const std::string&)> callback) {
1835 webrtc_log_message_callback_ = callback;
1838 RenderProcessHostImpl::WebRtcStopRtpDumpCallback
1839 RenderProcessHostImpl::StartRtpDump(
1840 bool incoming,
1841 bool outgoing,
1842 const WebRtcRtpPacketCallback& packet_callback) {
1843 if (!p2p_socket_dispatcher_host_.get())
1844 return WebRtcStopRtpDumpCallback();
1846 BrowserThread::PostTask(BrowserThread::IO,
1847 FROM_HERE,
1848 base::Bind(&P2PSocketDispatcherHost::StartRtpDump,
1849 p2p_socket_dispatcher_host_,
1850 incoming,
1851 outgoing,
1852 packet_callback));
1854 if (stop_rtp_dump_callback_.is_null()) {
1855 stop_rtp_dump_callback_ =
1856 base::Bind(&P2PSocketDispatcherHost::StopRtpDumpOnUIThread,
1857 p2p_socket_dispatcher_host_);
1859 return stop_rtp_dump_callback_;
1861 #endif
1863 IPC::ChannelProxy* RenderProcessHostImpl::GetChannel() {
1864 return channel_.get();
1867 void RenderProcessHostImpl::AddFilter(BrowserMessageFilter* filter) {
1868 channel_->AddFilter(filter->GetFilter());
1871 bool RenderProcessHostImpl::FastShutdownForPageCount(size_t count) {
1872 if (GetActiveViewCount() == count)
1873 return FastShutdownIfPossible();
1874 return false;
1877 bool RenderProcessHostImpl::FastShutdownStarted() const {
1878 return fast_shutdown_started_;
1881 // static
1882 void RenderProcessHostImpl::RegisterHost(int host_id, RenderProcessHost* host) {
1883 g_all_hosts.Get().AddWithID(host, host_id);
1886 // static
1887 void RenderProcessHostImpl::UnregisterHost(int host_id) {
1888 RenderProcessHost* host = g_all_hosts.Get().Lookup(host_id);
1889 if (!host)
1890 return;
1892 g_all_hosts.Get().Remove(host_id);
1894 // Look up the map of site to process for the given browser_context,
1895 // in case we need to remove this process from it. It will be registered
1896 // under any sites it rendered that use process-per-site mode.
1897 SiteProcessMap* map =
1898 GetSiteProcessMapForBrowserContext(host->GetBrowserContext());
1899 map->RemoveProcess(host);
1902 // static
1903 void RenderProcessHostImpl::FilterURL(RenderProcessHost* rph,
1904 bool empty_allowed,
1905 GURL* url) {
1906 ChildProcessSecurityPolicyImpl* policy =
1907 ChildProcessSecurityPolicyImpl::GetInstance();
1909 if (empty_allowed && url->is_empty())
1910 return;
1912 // The browser process should never hear the swappedout:// URL from any
1913 // of the renderer's messages. Check for this in debug builds, but don't
1914 // let it crash a release browser.
1915 DCHECK(GURL(kSwappedOutURL) != *url);
1917 if (!url->is_valid()) {
1918 // Have to use about:blank for the denied case, instead of an empty GURL.
1919 // This is because the browser treats navigation to an empty GURL as a
1920 // navigation to the home page. This is often a privileged page
1921 // (chrome://newtab/) which is exactly what we don't want.
1922 *url = GURL(url::kAboutBlankURL);
1923 return;
1926 if (url->SchemeIs(url::kAboutScheme)) {
1927 // The renderer treats all URLs in the about: scheme as being about:blank.
1928 // Canonicalize about: URLs to about:blank.
1929 *url = GURL(url::kAboutBlankURL);
1932 // Do not allow browser plugin guests to navigate to non-web URLs, since they
1933 // cannot swap processes or grant bindings.
1934 bool non_web_url_in_guest = rph->IsForGuestsOnly() &&
1935 !(url->is_valid() && policy->IsWebSafeScheme(url->scheme()));
1937 if (non_web_url_in_guest || !policy->CanRequestURL(rph->GetID(), *url)) {
1938 // If this renderer is not permitted to request this URL, we invalidate the
1939 // URL. This prevents us from storing the blocked URL and becoming confused
1940 // later.
1941 VLOG(1) << "Blocked URL " << url->spec();
1942 *url = GURL(url::kAboutBlankURL);
1946 // static
1947 bool RenderProcessHostImpl::IsSuitableHost(
1948 RenderProcessHost* host,
1949 BrowserContext* browser_context,
1950 const GURL& site_url) {
1951 if (run_renderer_in_process())
1952 return true;
1954 if (host->GetBrowserContext() != browser_context)
1955 return false;
1957 // Do not allow sharing of guest hosts. This is to prevent bugs where guest
1958 // and non-guest storage gets mixed. In the future, we might consider enabling
1959 // the sharing of guests, in this case this check should be removed and
1960 // InSameStoragePartition should handle the possible sharing.
1961 if (host->IsForGuestsOnly())
1962 return false;
1964 // Check whether the given host and the intended site_url will be using the
1965 // same StoragePartition, since a RenderProcessHost can only support a single
1966 // StoragePartition. This is relevant for packaged apps.
1967 StoragePartition* dest_partition =
1968 BrowserContext::GetStoragePartitionForSite(browser_context, site_url);
1969 if (!host->InSameStoragePartition(dest_partition))
1970 return false;
1972 // TODO(nick): Consult the SiteIsolationPolicy here. https://crbug.com/513036
1973 if (ChildProcessSecurityPolicyImpl::GetInstance()->HasWebUIBindings(
1974 host->GetID()) !=
1975 WebUIControllerFactoryRegistry::GetInstance()->UseWebUIBindingsForURL(
1976 browser_context, site_url)) {
1977 return false;
1980 return GetContentClient()->browser()->IsSuitableHost(host, site_url);
1983 // static
1984 bool RenderProcessHost::run_renderer_in_process() {
1985 return g_run_renderer_in_process_;
1988 // static
1989 void RenderProcessHost::SetRunRendererInProcess(bool value) {
1990 g_run_renderer_in_process_ = value;
1992 base::CommandLine* command_line = base::CommandLine::ForCurrentProcess();
1993 if (value) {
1994 if (!command_line->HasSwitch(switches::kLang)) {
1995 // Modify the current process' command line to include the browser locale,
1996 // as the renderer expects this flag to be set.
1997 const std::string locale =
1998 GetContentClient()->browser()->GetApplicationLocale();
1999 command_line->AppendSwitchASCII(switches::kLang, locale);
2001 // TODO(piman): we should really send configuration through bools rather
2002 // than by parsing strings, i.e. sending an IPC rather than command line
2003 // args. crbug.com/314909
2004 AppendCompositorCommandLineFlags(command_line);
2008 // static
2009 RenderProcessHost::iterator RenderProcessHost::AllHostsIterator() {
2010 DCHECK_CURRENTLY_ON(BrowserThread::UI);
2011 return iterator(g_all_hosts.Pointer());
2014 // static
2015 RenderProcessHost* RenderProcessHost::FromID(int render_process_id) {
2016 DCHECK_CURRENTLY_ON(BrowserThread::UI);
2017 return g_all_hosts.Get().Lookup(render_process_id);
2020 // static
2021 bool RenderProcessHost::ShouldTryToUseExistingProcessHost(
2022 BrowserContext* browser_context, const GURL& url) {
2023 // If --site-per-process is enabled, do not try to reuse renderer processes
2024 // when over the limit.
2025 // TODO(nick): This is overly conservative and isn't launchable. Move this
2026 // logic into IsSuitableHost, and check |url| against the URL the process is
2027 // dedicated to. This will allow pages from the same site to share, and will
2028 // also allow non-isolated sites to share processes. https://crbug.com/513036
2029 if (SiteIsolationPolicy::AreCrossProcessFramesPossible())
2030 return false;
2032 if (run_renderer_in_process())
2033 return true;
2035 // NOTE: Sometimes it's necessary to create more render processes than
2036 // GetMaxRendererProcessCount(), for instance when we want to create
2037 // a renderer process for a browser context that has no existing
2038 // renderers. This is OK in moderation, since the
2039 // GetMaxRendererProcessCount() is conservative.
2040 if (g_all_hosts.Get().size() >= GetMaxRendererProcessCount())
2041 return true;
2043 return GetContentClient()->browser()->
2044 ShouldTryToUseExistingProcessHost(browser_context, url);
2047 // static
2048 RenderProcessHost* RenderProcessHost::GetExistingProcessHost(
2049 BrowserContext* browser_context,
2050 const GURL& site_url) {
2051 // First figure out which existing renderers we can use.
2052 std::vector<RenderProcessHost*> suitable_renderers;
2053 suitable_renderers.reserve(g_all_hosts.Get().size());
2055 iterator iter(AllHostsIterator());
2056 while (!iter.IsAtEnd()) {
2057 if (GetContentClient()->browser()->MayReuseHost(iter.GetCurrentValue()) &&
2058 RenderProcessHostImpl::IsSuitableHost(
2059 iter.GetCurrentValue(),
2060 browser_context, site_url)) {
2061 suitable_renderers.push_back(iter.GetCurrentValue());
2063 iter.Advance();
2066 // Now pick a random suitable renderer, if we have any.
2067 if (!suitable_renderers.empty()) {
2068 int suitable_count = static_cast<int>(suitable_renderers.size());
2069 int random_index = base::RandInt(0, suitable_count - 1);
2070 return suitable_renderers[random_index];
2073 return NULL;
2076 // static
2077 bool RenderProcessHost::ShouldUseProcessPerSite(
2078 BrowserContext* browser_context,
2079 const GURL& url) {
2080 // Returns true if we should use the process-per-site model. This will be
2081 // the case if the --process-per-site switch is specified, or in
2082 // process-per-site-instance for particular sites (e.g., WebUI).
2083 // Note that --single-process is handled in ShouldTryToUseExistingProcessHost.
2084 const base::CommandLine& command_line =
2085 *base::CommandLine::ForCurrentProcess();
2086 if (command_line.HasSwitch(switches::kProcessPerSite))
2087 return true;
2089 // We want to consolidate particular sites like WebUI even when we are using
2090 // the process-per-tab or process-per-site-instance models.
2091 // Note: DevTools pages have WebUI type but should not reuse the same host.
2092 if (WebUIControllerFactoryRegistry::GetInstance()->UseWebUIForURL(
2093 browser_context, url) &&
2094 !url.SchemeIs(kChromeDevToolsScheme)) {
2095 return true;
2098 // Otherwise let the content client decide, defaulting to false.
2099 return GetContentClient()->browser()->ShouldUseProcessPerSite(browser_context,
2100 url);
2103 // static
2104 RenderProcessHost* RenderProcessHostImpl::GetProcessHostForSite(
2105 BrowserContext* browser_context,
2106 const GURL& url) {
2107 // Look up the map of site to process for the given browser_context.
2108 SiteProcessMap* map =
2109 GetSiteProcessMapForBrowserContext(browser_context);
2111 // See if we have an existing process with appropriate bindings for this site.
2112 // If not, the caller should create a new process and register it.
2113 std::string site = SiteInstance::GetSiteForURL(browser_context, url)
2114 .possibly_invalid_spec();
2115 RenderProcessHost* host = map->FindProcess(site);
2116 if (host && (!GetContentClient()->browser()->MayReuseHost(host) ||
2117 !IsSuitableHost(host, browser_context, url))) {
2118 // The registered process does not have an appropriate set of bindings for
2119 // the url. Remove it from the map so we can register a better one.
2120 RecordAction(
2121 base::UserMetricsAction("BindingsMismatch_GetProcessHostPerSite"));
2122 map->RemoveProcess(host);
2123 host = NULL;
2126 return host;
2129 void RenderProcessHostImpl::RegisterProcessHostForSite(
2130 BrowserContext* browser_context,
2131 RenderProcessHost* process,
2132 const GURL& url) {
2133 // Look up the map of site to process for the given browser_context.
2134 SiteProcessMap* map =
2135 GetSiteProcessMapForBrowserContext(browser_context);
2137 // Only register valid, non-empty sites. Empty or invalid sites will not
2138 // use process-per-site mode. We cannot check whether the process has
2139 // appropriate bindings here, because the bindings have not yet been granted.
2140 std::string site = SiteInstance::GetSiteForURL(browser_context, url)
2141 .possibly_invalid_spec();
2142 if (!site.empty())
2143 map->RegisterProcess(site, process);
2146 void RenderProcessHostImpl::ProcessDied(bool already_dead,
2147 RendererClosedDetails* known_details) {
2148 // Our child process has died. If we didn't expect it, it's a crash.
2149 // In any case, we need to let everyone know it's gone.
2150 // The OnChannelError notification can fire multiple times due to nested sync
2151 // calls to a renderer. If we don't have a valid channel here it means we
2152 // already handled the error.
2154 // It should not be possible for us to be called re-entrantly.
2155 DCHECK(!within_process_died_observer_);
2157 // It should not be possible for a process death notification to come in while
2158 // we are dying.
2159 DCHECK(!deleting_soon_);
2161 // child_process_launcher_ can be NULL in single process mode or if fast
2162 // termination happened.
2163 base::TerminationStatus status = base::TERMINATION_STATUS_NORMAL_TERMINATION;
2164 int exit_code = 0;
2165 if (known_details) {
2166 status = known_details->status;
2167 exit_code = known_details->exit_code;
2168 } else if (child_process_launcher_.get()) {
2169 status = child_process_launcher_->GetChildTerminationStatus(already_dead,
2170 &exit_code);
2171 if (already_dead && status == base::TERMINATION_STATUS_STILL_RUNNING) {
2172 // May be in case of IPC error, if it takes long time for renderer
2173 // to exit. Child process will be killed in any case during
2174 // child_process_launcher_.reset(). Make sure we will not broadcast
2175 // FrameHostMsg_RenderProcessGone with status
2176 // TERMINATION_STATUS_STILL_RUNNING, since this will break WebContentsImpl
2177 // logic.
2178 status = base::TERMINATION_STATUS_PROCESS_CRASHED;
2182 RendererClosedDetails details(status, exit_code);
2183 mojo_application_host_->WillDestroySoon();
2185 child_process_launcher_.reset();
2186 channel_.reset();
2187 while (!queued_messages_.empty()) {
2188 delete queued_messages_.front();
2189 queued_messages_.pop();
2192 within_process_died_observer_ = true;
2193 NotificationService::current()->Notify(
2194 NOTIFICATION_RENDERER_PROCESS_CLOSED,
2195 Source<RenderProcessHost>(this),
2196 Details<RendererClosedDetails>(&details));
2197 FOR_EACH_OBSERVER(RenderProcessHostObserver,
2198 observers_,
2199 RenderProcessExited(this, status, exit_code));
2200 within_process_died_observer_ = false;
2202 gpu_message_filter_ = NULL;
2203 message_port_message_filter_ = NULL;
2204 RemoveUserData(kSessionStorageHolderKey);
2206 // RenderProcessGone handlers might navigate or perform other actions that
2207 // require a connection. Ensure that there is one before calling them.
2208 mojo_application_host_.reset(new MojoApplicationHost);
2210 IDMap<IPC::Listener>::iterator iter(&listeners_);
2211 while (!iter.IsAtEnd()) {
2212 iter.GetCurrentValue()->OnMessageReceived(
2213 FrameHostMsg_RenderProcessGone(iter.GetCurrentKey(),
2214 static_cast<int>(status),
2215 exit_code));
2216 iter.Advance();
2219 // It's possible that one of the calls out to the observers might have caused
2220 // this object to be no longer needed.
2221 if (delayed_cleanup_needed_)
2222 Cleanup();
2224 // This object is not deleted at this point and might be reused later.
2225 // TODO(darin): clean this up
2228 size_t RenderProcessHost::GetActiveViewCount() {
2229 size_t num_active_views = 0;
2230 scoped_ptr<RenderWidgetHostIterator> widgets(
2231 RenderWidgetHost::GetRenderWidgetHosts());
2232 while (RenderWidgetHost* widget = widgets->GetNextHost()) {
2233 // Count only RenderWidgetHosts in this process.
2234 if (widget->GetProcess()->GetID() == GetID())
2235 num_active_views++;
2237 return num_active_views;
2240 #if defined(ENABLE_WEBRTC)
2241 void RenderProcessHostImpl::WebRtcLogMessage(const std::string& message) {
2242 DCHECK_CURRENTLY_ON(BrowserThread::UI);
2243 if (!webrtc_log_message_callback_.is_null())
2244 webrtc_log_message_callback_.Run(message);
2246 #endif
2248 void RenderProcessHostImpl::ReleaseOnCloseACK(
2249 RenderProcessHost* host,
2250 const SessionStorageNamespaceMap& sessions,
2251 int view_route_id) {
2252 DCHECK(host);
2253 if (sessions.empty())
2254 return;
2255 SessionStorageHolder* holder = static_cast<SessionStorageHolder*>
2256 (host->GetUserData(kSessionStorageHolderKey));
2257 if (!holder) {
2258 holder = new SessionStorageHolder();
2259 host->SetUserData(
2260 kSessionStorageHolderKey,
2261 holder);
2263 holder->Hold(sessions, view_route_id);
2266 void RenderProcessHostImpl::OnShutdownRequest() {
2267 // Don't shut down if there are active RenderViews, or if there are pending
2268 // RenderViews being swapped back in.
2269 // In single process mode, we never shutdown the renderer.
2270 if (pending_views_ || run_renderer_in_process() || GetActiveViewCount() > 0)
2271 return;
2273 // Notify any contents that might have swapped out renderers from this
2274 // process. They should not attempt to swap them back in.
2275 FOR_EACH_OBSERVER(RenderProcessHostObserver, observers_,
2276 RenderProcessWillExit(this));
2278 mojo_application_host_->WillDestroySoon();
2280 Send(new ChildProcessMsg_Shutdown());
2283 void RenderProcessHostImpl::SuddenTerminationChanged(bool enabled) {
2284 SetSuddenTerminationAllowed(enabled);
2287 void RenderProcessHostImpl::SetBackgrounded(bool backgrounded) {
2288 TRACE_EVENT1("renderer_host", "RenderProcessHostImpl::SetBackgrounded",
2289 "backgrounded", backgrounded);
2290 // Note: we always set the backgrounded_ value. If the process is NULL
2291 // (and hence hasn't been created yet), we will set the process priority
2292 // later when we create the process.
2293 backgrounded_ = backgrounded;
2294 if (!child_process_launcher_.get() || child_process_launcher_->IsStarting())
2295 return;
2297 // Don't background processes which have active audio streams.
2298 if (backgrounded_ && audio_renderer_host_->HasActiveAudio())
2299 return;
2301 const base::CommandLine* command_line =
2302 base::CommandLine::ForCurrentProcess();
2303 if (command_line->HasSwitch(switches::kDisableRendererBackgrounding))
2304 return;
2306 #if defined(OS_WIN)
2307 // The cbstext.dll loads as a global GetMessage hook in the browser process
2308 // and intercepts/unintercepts the kernel32 API SetPriorityClass in a
2309 // background thread. If the UI thread invokes this API just when it is
2310 // intercepted the stack is messed up on return from the interceptor
2311 // which causes random crashes in the browser process. Our hack for now
2312 // is to not invoke the SetPriorityClass API if the dll is loaded.
2313 if (GetModuleHandle(L"cbstext.dll"))
2314 return;
2315 #endif // OS_WIN
2317 #if defined(OS_WIN) || defined(OS_MACOSX)
2318 // Same as below, but bound to an experiment (http://crbug.com/458594 on
2319 // Windows, http://crbug.com/398103 on the Mac). Enabled by default in the
2320 // absence of field trials to get coverage on the perf waterfall.
2321 base::FieldTrial* trial =
2322 base::FieldTrialList::Find("BackgroundRendererProcesses");
2323 if (!trial || !base::StartsWith(trial->group_name(), "Disallow",
2324 base::CompareCase::SENSITIVE)) {
2325 child_process_launcher_->SetProcessBackgrounded(backgrounded);
2327 #else
2328 // Control the background state from the browser process, otherwise the task
2329 // telling the renderer to "unbackground" itself may be preempted by other
2330 // tasks executing at lowered priority ahead of it or simply by not being
2331 // swiftly scheduled by the OS per the low process priority
2332 // (http://crbug.com/398103).
2333 child_process_launcher_->SetProcessBackgrounded(backgrounded);
2334 #endif // OS_WIN
2336 // Notify the child process of background state.
2337 Send(new ChildProcessMsg_SetProcessBackgrounded(backgrounded));
2340 void RenderProcessHostImpl::OnProcessLaunched() {
2341 // TODO(erikchen): Remove ScopedTracker below once http://crbug.com/465841
2342 // is fixed.
2343 tracked_objects::ScopedTracker tracking_profile1(
2344 FROM_HERE_WITH_EXPLICIT_FUNCTION(
2345 "465841 RenderProcessHostImpl::OnProcessLaunched::Start"));
2346 // No point doing anything, since this object will be destructed soon. We
2347 // especially don't want to send the RENDERER_PROCESS_CREATED notification,
2348 // since some clients might expect a RENDERER_PROCESS_TERMINATED afterwards to
2349 // properly cleanup.
2350 if (deleting_soon_)
2351 return;
2353 if (child_process_launcher_) {
2354 // TODO(erikchen): Remove ScopedTracker below once http://crbug.com/465841
2355 // is fixed.
2356 tracked_objects::ScopedTracker tracking_profile2(
2357 FROM_HERE_WITH_EXPLICIT_FUNCTION(
2358 "465841 RenderProcessHostImpl::OnProcessLaunched::Backgrounded"));
2359 DCHECK(child_process_launcher_->GetProcess().IsValid());
2360 SetBackgrounded(backgrounded_);
2363 // TODO(erikchen): Remove ScopedTracker below once http://crbug.com/465841
2364 // is fixed.
2365 tracked_objects::ScopedTracker tracking_profile3(
2366 FROM_HERE_WITH_EXPLICIT_FUNCTION(
2367 "465841 RenderProcessHostImpl::OnProcessLaunched::Notify"));
2368 // NOTE: This needs to be before sending queued messages because
2369 // ExtensionService uses this notification to initialize the renderer process
2370 // with state that must be there before any JavaScript executes.
2372 // The queued messages contain such things as "navigate". If this notification
2373 // was after, we can end up executing JavaScript before the initialization
2374 // happens.
2375 NotificationService::current()->Notify(
2376 NOTIFICATION_RENDERER_PROCESS_CREATED,
2377 Source<RenderProcessHost>(this),
2378 NotificationService::NoDetails());
2380 // TODO(erikchen): Remove ScopedTracker below once http://crbug.com/465841
2381 // is fixed.
2382 tracked_objects::ScopedTracker tracking_profile4(
2383 FROM_HERE_WITH_EXPLICIT_FUNCTION(
2384 "465841 RenderProcessHostImpl::OnProcessLaunched::MojoActivate"));
2385 // Allow Mojo to be setup before the renderer sees any Chrome IPC messages.
2386 // This way, Mojo can be safely used from the renderer in response to any
2387 // Chrome IPC message.
2388 mojo_application_host_->Activate(this, GetHandle());
2390 // TODO(erikchen): Remove ScopedTracker below once http://crbug.com/465841
2391 // is fixed.
2392 tracked_objects::ScopedTracker tracking_profile5(
2393 FROM_HERE_WITH_EXPLICIT_FUNCTION(
2394 "465841 RenderProcessHostImpl::OnProcessLaunched::MojoClientLaunch"));
2396 // TODO(erikchen): Remove ScopedTracker below once http://crbug.com/465841
2397 // is fixed.
2398 tracked_objects::ScopedTracker tracking_profile6(
2399 FROM_HERE_WITH_EXPLICIT_FUNCTION(
2400 "465841 "
2401 "RenderProcessHostImpl::OnProcessLaunched::SendQueuedMessages"));
2402 while (!queued_messages_.empty()) {
2403 Send(queued_messages_.front());
2404 queued_messages_.pop();
2407 #if defined(ENABLE_WEBRTC)
2408 // TODO(erikchen): Remove ScopedTracker below once http://crbug.com/465841
2409 // is fixed.
2410 tracked_objects::ScopedTracker tracking_profile7(
2411 FROM_HERE_WITH_EXPLICIT_FUNCTION(
2412 "465841 RenderProcessHostImpl::OnProcessLaunched::EnableAec"));
2413 if (WebRTCInternals::GetInstance()->IsAudioDebugRecordingsEnabled()) {
2414 EnableAudioDebugRecordings(
2415 WebRTCInternals::GetInstance()->GetAudioDebugRecordingsFilePath());
2417 #endif
2420 void RenderProcessHostImpl::OnProcessLaunchFailed() {
2421 // If this object will be destructed soon, then observers have already been
2422 // sent a RenderProcessHostDestroyed notification, and we must observe our
2423 // contract that says that will be the last call.
2424 if (deleting_soon_)
2425 return;
2427 // TODO(wfh): Fill in the real error code here see crbug.com/526198.
2428 RendererClosedDetails details { base::TERMINATION_STATUS_LAUNCH_FAILED,
2429 -1 };
2430 ProcessDied(true, &details);
2433 scoped_refptr<AudioRendererHost>
2434 RenderProcessHostImpl::audio_renderer_host() const {
2435 return audio_renderer_host_;
2438 void RenderProcessHostImpl::OnUserMetricsRecordAction(
2439 const std::string& action) {
2440 RecordComputedAction(action);
2443 void RenderProcessHostImpl::OnCloseACK(int old_route_id) {
2444 SessionStorageHolder* holder = static_cast<SessionStorageHolder*>
2445 (GetUserData(kSessionStorageHolderKey));
2446 if (!holder)
2447 return;
2448 holder->Release(old_route_id);
2451 void RenderProcessHostImpl::OnSavedPageAsMHTML(int job_id, int64 data_size) {
2452 MHTMLGenerationManager::GetInstance()->MHTMLGenerated(job_id, data_size);
2455 void RenderProcessHostImpl::OnGpuSwitched() {
2456 // We are updating all widgets including swapped out ones.
2457 scoped_ptr<RenderWidgetHostIterator> widgets(
2458 RenderWidgetHostImpl::GetAllRenderWidgetHosts());
2459 while (RenderWidgetHost* widget = widgets->GetNextHost()) {
2460 if (!widget->IsRenderView())
2461 continue;
2463 // Skip widgets in other processes.
2464 if (widget->GetProcess()->GetID() != GetID())
2465 continue;
2467 RenderViewHost* rvh = RenderViewHost::From(widget);
2468 rvh->OnWebkitPreferencesChanged();
2472 #if defined(ENABLE_WEBRTC)
2473 void RenderProcessHostImpl::OnRegisterAecDumpConsumer(int id) {
2474 BrowserThread::PostTask(
2475 BrowserThread::UI,
2476 FROM_HERE,
2477 base::Bind(
2478 &RenderProcessHostImpl::RegisterAecDumpConsumerOnUIThread,
2479 weak_factory_.GetWeakPtr(),
2480 id));
2483 void RenderProcessHostImpl::OnUnregisterAecDumpConsumer(int id) {
2484 BrowserThread::PostTask(
2485 BrowserThread::UI,
2486 FROM_HERE,
2487 base::Bind(
2488 &RenderProcessHostImpl::UnregisterAecDumpConsumerOnUIThread,
2489 weak_factory_.GetWeakPtr(),
2490 id));
2493 void RenderProcessHostImpl::RegisterAecDumpConsumerOnUIThread(int id) {
2494 DCHECK_CURRENTLY_ON(BrowserThread::UI);
2495 aec_dump_consumers_.push_back(id);
2497 if (WebRTCInternals::GetInstance()->IsAudioDebugRecordingsEnabled()) {
2498 base::FilePath file_with_extensions = GetAecDumpFilePathWithExtensions(
2499 WebRTCInternals::GetInstance()->GetAudioDebugRecordingsFilePath());
2500 EnableAecDumpForId(file_with_extensions, id);
2504 void RenderProcessHostImpl::UnregisterAecDumpConsumerOnUIThread(int id) {
2505 DCHECK_CURRENTLY_ON(BrowserThread::UI);
2506 for (std::vector<int>::iterator it = aec_dump_consumers_.begin();
2507 it != aec_dump_consumers_.end(); ++it) {
2508 if (*it == id) {
2509 aec_dump_consumers_.erase(it);
2510 break;
2515 void RenderProcessHostImpl::EnableAecDumpForId(const base::FilePath& file,
2516 int id) {
2517 DCHECK_CURRENTLY_ON(BrowserThread::UI);
2518 BrowserThread::PostTaskAndReplyWithResult(
2519 BrowserThread::FILE, FROM_HERE,
2520 base::Bind(&CreateAecDumpFileForProcess,
2521 file.AddExtension(IntToStringType(id)),
2522 GetHandle()),
2523 base::Bind(&RenderProcessHostImpl::SendAecDumpFileToRenderer,
2524 weak_factory_.GetWeakPtr(),
2525 id));
2528 void RenderProcessHostImpl::SendAecDumpFileToRenderer(
2529 int id,
2530 IPC::PlatformFileForTransit file_for_transit) {
2531 if (file_for_transit == IPC::InvalidPlatformFileForTransit())
2532 return;
2533 Send(new AecDumpMsg_EnableAecDump(id, file_for_transit));
2536 void RenderProcessHostImpl::SendDisableAecDumpToRenderer() {
2537 Send(new AecDumpMsg_DisableAecDump());
2540 base::FilePath RenderProcessHostImpl::GetAecDumpFilePathWithExtensions(
2541 const base::FilePath& file) {
2542 return file.AddExtension(IntToStringType(base::GetProcId(GetHandle())))
2543 .AddExtension(kAecDumpFileNameAddition);
2545 #endif // defined(ENABLE_WEBRTC)
2547 void RenderProcessHostImpl::IncrementWorkerRefCount() {
2548 DCHECK_CURRENTLY_ON(BrowserThread::UI);
2549 ++worker_ref_count_;
2550 if (worker_ref_count_ > max_worker_count_)
2551 max_worker_count_ = worker_ref_count_;
2554 void RenderProcessHostImpl::DecrementWorkerRefCount() {
2555 DCHECK_CURRENTLY_ON(BrowserThread::UI);
2556 DCHECK_GT(worker_ref_count_, 0);
2557 --worker_ref_count_;
2558 if (worker_ref_count_ == 0)
2559 Cleanup();
2562 void RenderProcessHostImpl::GetAudioOutputControllers(
2563 const GetAudioOutputControllersCallback& callback) const {
2564 audio_renderer_host()->GetOutputControllers(callback);
2567 BluetoothDispatcherHost* RenderProcessHostImpl::GetBluetoothDispatcherHost() {
2568 return bluetooth_dispatcher_host_.get();
2571 } // namespace content