1 // Copyright (c) 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 #ifndef CONTENT_BROWSER_RENDERER_HOST_RENDER_PROCESS_HOST_IMPL_H_
6 #define CONTENT_BROWSER_RENDERER_HOST_RENDER_PROCESS_HOST_IMPL_H_
12 #include "base/memory/scoped_ptr.h"
13 #include "base/observer_list.h"
14 #include "base/process/process.h"
15 #include "content/browser/child_process_launcher.h"
16 #include "content/browser/dom_storage/session_storage_namespace_impl.h"
17 #include "content/browser/power_monitor_message_broadcaster.h"
18 #include "content/common/content_export.h"
19 #include "content/common/mojo/service_registry_impl.h"
20 #include "content/public/browser/render_process_host.h"
21 #include "ipc/ipc_channel_proxy.h"
22 #include "ipc/ipc_platform_file.h"
23 #include "third_party/mojo/src/mojo/public/cpp/bindings/interface_ptr.h"
24 #include "ui/gfx/gpu_memory_buffer.h"
25 #include "ui/gl/gpu_switching_observer.h"
41 class ChannelMojoHost
;
45 class AudioRendererHost
;
46 class BrowserCdmManager
;
47 class BrowserDemuxerAndroid
;
48 class GpuMessageFilter
;
49 class MessagePortMessageFilter
;
50 class MojoApplicationHost
;
51 class NotificationMessageFilter
;
52 #if defined(ENABLE_WEBRTC)
53 class P2PSocketDispatcherHost
;
55 class PermissionServiceContext
;
56 class PeerConnectionTrackerHost
;
57 class RendererMainThread
;
58 class RenderWidgetHelper
;
59 class RenderWidgetHost
;
60 class RenderWidgetHostImpl
;
61 class RenderWidgetHostViewFrameSubscriber
;
62 class StoragePartition
;
63 class StoragePartitionImpl
;
65 typedef base::Thread
* (*RendererMainThreadFactoryFunction
)(
66 const std::string
& id
);
68 // Implements a concrete RenderProcessHost for the browser process for talking
69 // to actual renderer processes (as opposed to mocks).
71 // Represents the browser side of the browser <--> renderer communication
72 // channel. There will be one RenderProcessHost per renderer process.
74 // This object is refcounted so that it can release its resources when all
75 // hosts using it go away.
77 // This object communicates back and forth with the RenderProcess object
78 // running in the renderer process. Each RenderProcessHost and RenderProcess
79 // keeps a list of RenderView (renderer) and WebContentsImpl (browser) which
80 // are correlated with IDs. This way, the Views and the corresponding ViewHosts
81 // communicate through the two process objects.
83 // A RenderProcessHost is also associated with one and only one
84 // StoragePartition. This allows us to implement strong storage isolation
85 // because all the IPCs from the RenderViews (renderer) will only ever be able
86 // to access the partition they are assigned to.
87 class CONTENT_EXPORT RenderProcessHostImpl
88 : public RenderProcessHost
,
89 public ChildProcessLauncher::Client
,
90 public ui::GpuSwitchingObserver
{
92 RenderProcessHostImpl(BrowserContext
* browser_context
,
93 StoragePartitionImpl
* storage_partition_impl
,
94 bool is_isolated_guest
);
95 ~RenderProcessHostImpl() override
;
97 // RenderProcessHost implementation (public portion).
98 void EnableSendQueue() override
;
100 int GetNextRoutingID() override
;
101 void AddRoute(int32 routing_id
, IPC::Listener
* listener
) override
;
102 void RemoveRoute(int32 routing_id
) override
;
103 void AddObserver(RenderProcessHostObserver
* observer
) override
;
104 void RemoveObserver(RenderProcessHostObserver
* observer
) override
;
105 void ReceivedBadMessage() override
;
106 void WidgetRestored() override
;
107 void WidgetHidden() override
;
108 int VisibleWidgetCount() const override
;
109 bool IsIsolatedGuest() const override
;
110 StoragePartition
* GetStoragePartition() const override
;
111 bool Shutdown(int exit_code
, bool wait
) override
;
112 bool FastShutdownIfPossible() override
;
113 void DumpHandles() override
;
114 base::ProcessHandle
GetHandle() const override
;
115 BrowserContext
* GetBrowserContext() const override
;
116 bool InSameStoragePartition(StoragePartition
* partition
) const override
;
117 int GetID() const override
;
118 bool HasConnection() const override
;
119 void SetIgnoreInputEvents(bool ignore_input_events
) override
;
120 bool IgnoreInputEvents() const override
;
121 void Cleanup() override
;
122 void AddPendingView() override
;
123 void RemovePendingView() override
;
124 bool SuddenTerminationAllowed() const override
;
125 IPC::ChannelProxy
* GetChannel() override
;
126 void AddFilter(BrowserMessageFilter
* filter
) override
;
127 bool FastShutdownForPageCount(size_t count
) override
;
128 bool FastShutdownStarted() const override
;
129 base::TimeDelta
GetChildProcessIdleTime() const override
;
130 void ResumeRequestsForView(int route_id
) override
;
131 void FilterURL(bool empty_allowed
, GURL
* url
) override
;
132 #if defined(ENABLE_WEBRTC)
133 void EnableAecDump(const base::FilePath
& file
) override
;
134 void DisableAecDump() override
;
135 void SetWebRtcLogMessageCallback(
136 base::Callback
<void(const std::string
&)> callback
) override
;
137 WebRtcStopRtpDumpCallback
StartRtpDump(
140 const WebRtcRtpPacketCallback
& packet_callback
) override
;
142 void ResumeDeferredNavigation(const GlobalRequestID
& request_id
) override
;
143 void NotifyTimezoneChange() override
;
144 ServiceRegistry
* GetServiceRegistry() override
;
145 const base::TimeTicks
& GetInitTimeForNavigationMetrics() const override
;
146 bool SubscribeUniformEnabled() const override
;
147 void OnAddSubscription(unsigned int target
) override
;
148 void OnRemoveSubscription(unsigned int target
) override
;
149 void SendUpdateValueState(
150 unsigned int target
, const gpu::ValueState
& state
) override
;
151 #if defined(ENABLE_BROWSER_CDMS)
152 media::BrowserCdm
* GetBrowserCdm(int render_frame_id
,
153 int cdm_id
) const override
;
156 // IPC::Sender via RenderProcessHost.
157 bool Send(IPC::Message
* msg
) override
;
159 // IPC::Listener via RenderProcessHost.
160 bool OnMessageReceived(const IPC::Message
& msg
) override
;
161 void OnChannelConnected(int32 peer_pid
) override
;
162 void OnChannelError() override
;
163 void OnBadMessageReceived(const IPC::Message
& message
) override
;
165 // ChildProcessLauncher::Client implementation.
166 void OnProcessLaunched() override
;
167 void OnProcessLaunchFailed() override
;
169 scoped_refptr
<AudioRendererHost
> audio_renderer_host() const;
171 // Call this function when it is evident that the child process is actively
172 // performing some operation, for example if we just received an IPC message.
173 void mark_child_process_activity_time() {
174 child_process_activity_time_
= base::TimeTicks::Now();
177 // Start and end frame subscription for a specific renderer.
178 // This API only supports subscription to accelerated composited frames.
179 void BeginFrameSubscription(
181 scoped_ptr
<RenderWidgetHostViewFrameSubscriber
> subscriber
);
182 void EndFrameSubscription(int route_id
);
184 #if defined(ENABLE_WEBRTC)
185 // Fires the webrtc log message callback with |message|, if callback is set.
186 void WebRtcLogMessage(const std::string
& message
);
189 // Used to extend the lifetime of the sessions until the render view
190 // in the renderer is fully closed. This is static because its also called
191 // with mock hosts as input in test cases.
192 static void ReleaseOnCloseACK(
193 RenderProcessHost
* host
,
194 const SessionStorageNamespaceMap
& sessions
,
197 // Register/unregister the host identified by the host id in the global host
199 static void RegisterHost(int host_id
, RenderProcessHost
* host
);
200 static void UnregisterHost(int host_id
);
202 // Implementation of FilterURL below that can be shared with the mock class.
203 static void FilterURL(RenderProcessHost
* rph
, bool empty_allowed
, GURL
* url
);
205 // Returns true if |host| is suitable for launching a new view with |site_url|
206 // in the given |browser_context|.
207 static bool IsSuitableHost(RenderProcessHost
* host
,
208 BrowserContext
* browser_context
,
209 const GURL
& site_url
);
211 // Returns an existing RenderProcessHost for |url| in |browser_context|,
212 // if one exists. Otherwise a new RenderProcessHost should be created and
213 // registered using RegisterProcessHostForSite().
214 // This should only be used for process-per-site mode, which can be enabled
215 // globally with a command line flag or per-site, as determined by
216 // SiteInstanceImpl::ShouldUseProcessPerSite.
217 static RenderProcessHost
* GetProcessHostForSite(
218 BrowserContext
* browser_context
,
221 // Registers the given |process| to be used for any instance of |url|
222 // within |browser_context|.
223 // This should only be used for process-per-site mode, which can be enabled
224 // globally with a command line flag or per-site, as determined by
225 // SiteInstanceImpl::ShouldUseProcessPerSite.
226 static void RegisterProcessHostForSite(
227 BrowserContext
* browser_context
,
228 RenderProcessHost
* process
,
231 static base::MessageLoop
* GetInProcessRendererThreadForTesting();
233 // This forces a renderer that is running "in process" to shut down.
234 static void ShutDownInProcessRenderer();
236 static void RegisterRendererMainThreadFactory(
237 RendererMainThreadFactoryFunction create
);
239 #if defined(OS_ANDROID)
240 const scoped_refptr
<BrowserDemuxerAndroid
>& browser_demuxer_android() {
241 return browser_demuxer_android_
;
245 #if defined(ENABLE_BROWSER_CDMS)
246 const scoped_refptr
<BrowserCdmManager
>& browser_cdm_manager() {
247 return browser_cdm_manager_
;
251 MessagePortMessageFilter
* message_port_message_filter() const {
252 return message_port_message_filter_
.get();
255 NotificationMessageFilter
* notification_message_filter() const {
256 return notification_message_filter_
.get();
259 void set_is_isolated_guest_for_testing(bool is_isolated_guest
) {
260 is_isolated_guest_
= is_isolated_guest
;
263 // Called when the existence of the other renderer process which is connected
264 // to the Worker in this renderer process has changed.
265 // It is only called when "enable-embedded-shared-worker" flag is set.
266 void IncrementWorkerRefCount();
267 void DecrementWorkerRefCount();
269 // Call this function to resume the navigation when it was deferred
270 // immediately after receiving response headers.
271 void ResumeResponseDeferredAtStart(const GlobalRequestID
& request_id
);
273 void GetAudioOutputControllers(
274 const GetAudioOutputControllersCallback
& callback
) const override
;
277 // A proxy for our IPC::Channel that lives on the IO thread (see
278 // browser_process.h)
279 scoped_ptr
<IPC::ChannelProxy
> channel_
;
281 // A host object ChannelMojo needs. The lifetime is bound to
282 // the RenderProcessHostImpl, not the channel.
283 scoped_ptr
<IPC::ChannelMojoHost
> channel_mojo_host_
;
285 // True if fast shutdown has been performed on this RPH.
286 bool fast_shutdown_started_
;
288 // True if we've posted a DeleteTask and will be deleted soon.
292 // True if this object has deleted itself.
293 bool is_self_deleted_
;
296 // The count of currently swapped out but pending RenderViews. We have
297 // started to swap these in, so the renderer process should not exit if
298 // this count is non-zero.
299 int32 pending_views_
;
302 friend class VisitRelayingRenderProcessHost
;
304 scoped_ptr
<IPC::ChannelProxy
> CreateChannelProxy(
305 const std::string
& channel_id
);
307 // Creates and adds the IO thread message filters.
308 void CreateMessageFilters();
310 // Registers Mojo services to be exposed to the renderer.
311 void RegisterMojoServices();
313 // Control message handlers.
314 void OnShutdownRequest();
315 void OnDumpHandlesDone();
316 void OnSuddenTerminationChanged(bool enabled
);
317 void OnUserMetricsRecordAction(const std::string
& action
);
318 void OnSavedPageAsMHTML(int job_id
, int64 mhtml_file_size
);
319 void OnCloseACK(int old_route_id
);
321 // Generates a command line to be used to spawn a renderer and appends the
322 // results to |*command_line|.
323 void AppendRendererCommandLine(base::CommandLine
* command_line
) const;
325 // Copies applicable command line switches from the given |browser_cmd| line
326 // flags to the output |renderer_cmd| line flags. Not all switches will be
328 void PropagateBrowserCommandLineToRenderer(
329 const base::CommandLine
& browser_cmd
,
330 base::CommandLine
* renderer_cmd
) const;
332 // Callers can reduce the RenderProcess' priority.
333 void SetBackgrounded(bool backgrounded
);
335 // Handle termination of our process.
336 void ProcessDied(bool already_dead
, RendererClosedDetails
* known_details
);
338 // GpuSwitchingObserver implementation.
339 void OnGpuSwitched() override
;
341 #if defined(ENABLE_WEBRTC)
342 void OnRegisterAecDumpConsumer(int id
);
343 void OnUnregisterAecDumpConsumer(int id
);
344 void RegisterAecDumpConsumerOnUIThread(int id
);
345 void UnregisterAecDumpConsumerOnUIThread(int id
);
346 void EnableAecDumpForId(const base::FilePath
& file
, int id
);
347 // Sends |file_for_transit| to the render process.
348 void SendAecDumpFileToRenderer(int id
,
349 IPC::PlatformFileForTransit file_for_transit
);
350 void SendDisableAecDumpToRenderer();
353 scoped_ptr
<MojoApplicationHost
> mojo_application_host_
;
355 // The registered IPC listener objects. When this list is empty, we should
357 IDMap
<IPC::Listener
> listeners_
;
359 // The count of currently visible widgets. Since the host can be a container
360 // for multiple widgets, it uses this count to determine when it should be
362 int32 visible_widgets_
;
364 // Does this process have backgrounded priority.
367 // Used to allow a RenderWidgetHost to intercept various messages on the
369 scoped_refptr
<RenderWidgetHelper
> widget_helper_
;
371 // The filter for GPU-related messages coming from the renderer.
372 // Thread safety note: this field is to be accessed from the UI thread.
373 // We don't keep a reference to it, to avoid it being destroyed on the UI
374 // thread, but we clear this field when we clear channel_. When channel_ goes
375 // away, it posts a task to the IO thread to destroy it there, so we know that
376 // it's valid if non-NULL.
377 GpuMessageFilter
* gpu_message_filter_
;
379 // The filter for MessagePort messages coming from the renderer.
380 scoped_refptr
<MessagePortMessageFilter
> message_port_message_filter_
;
382 // The filter for Web Notification messages coming from the renderer. Holds a
383 // closure per notification that must be freed when the notification closes.
384 scoped_refptr
<NotificationMessageFilter
> notification_message_filter_
;
386 // Used in single-process mode.
387 scoped_ptr
<base::Thread
> in_process_renderer_
;
389 // True after Init() has been called. We can't just check channel_ because we
390 // also reset that in the case of process termination.
391 bool is_initialized_
;
394 // Stores the time at which the first call to Init happened.
395 base::TimeTicks init_time_
;
397 // Used to launch and terminate the process without blocking the UI thread.
398 scoped_ptr
<ChildProcessLauncher
> child_process_launcher_
;
400 // Messages we queue while waiting for the process handle. We queue them here
401 // instead of in the channel so that we ensure they're sent after init related
402 // messages that are sent once the process handle is available. This is
403 // because the queued messages may have dependencies on the init messages.
404 std::queue
<IPC::Message
*> queued_messages_
;
406 // The globally-unique identifier for this RPH.
409 BrowserContext
* browser_context_
;
411 // Owned by |browser_context_|.
412 StoragePartitionImpl
* storage_partition_impl_
;
414 // The observers watching our lifetime.
415 ObserverList
<RenderProcessHostObserver
> observers_
;
417 // True if the process can be shut down suddenly. If this is true, then it's
418 // sure that all the RenderFrames in the process can be shutdown suddenly. If
419 // it's false, then specific RenderFrames might still be allowed to be
420 // shutdown suddenly by checking their SuddenTerminationAllowed() flag. This
421 // can occur when a RenderFrame has an unload/beforeUnload event listener
422 // registered but another RenderFrame in the same process doesn't.
423 bool sudden_termination_allowed_
;
425 // Set to true if we shouldn't send input events. We actually do the
426 // filtering for this at the render widget level.
427 bool ignore_input_events_
;
429 // Records the last time we regarded the child process active.
430 base::TimeTicks child_process_activity_time_
;
432 // Indicates whether this is a RenderProcessHost of a Browser Plugin guest
434 bool is_isolated_guest_
;
436 // Forwards messages between WebRTCInternals in the browser process
437 // and PeerConnectionTracker in the renderer process.
438 scoped_refptr
<PeerConnectionTrackerHost
> peer_connection_tracker_host_
;
440 // Prevents the class from being added as a GpuDataManagerImpl observer more
442 bool gpu_observer_registered_
;
444 // Set if a call to Cleanup is required once the RenderProcessHostImpl is no
445 // longer within the RenderProcessHostObserver::RenderProcessExited callbacks.
446 bool delayed_cleanup_needed_
;
448 // Indicates whether RenderProcessHostImpl is currently iterating and calling
449 // through RenderProcessHostObserver::RenderProcessExited.
450 bool within_process_died_observer_
;
452 // Forwards power state messages to the renderer process.
453 PowerMonitorMessageBroadcaster power_monitor_broadcaster_
;
455 scoped_refptr
<AudioRendererHost
> audio_renderer_host_
;
457 #if defined(OS_ANDROID)
458 scoped_refptr
<BrowserDemuxerAndroid
> browser_demuxer_android_
;
461 #if defined(ENABLE_BROWSER_CDMS)
462 scoped_refptr
<BrowserCdmManager
> browser_cdm_manager_
;
465 #if defined(ENABLE_WEBRTC)
466 base::Callback
<void(const std::string
&)> webrtc_log_message_callback_
;
468 scoped_refptr
<P2PSocketDispatcherHost
> p2p_socket_dispatcher_host_
;
470 // Must be accessed on UI thread.
471 std::vector
<int> aec_dump_consumers_
;
473 WebRtcStopRtpDumpCallback stop_rtp_dump_callback_
;
476 int worker_ref_count_
;
478 // Records the time when the process starts surviving for workers for UMA.
479 base::TimeTicks survive_for_worker_start_time_
;
481 // Records the maximum # of workers simultaneously hosted in this process
483 int max_worker_count_
;
485 // Context shared for each PermissionService instance created for this RPH.
486 scoped_ptr
<PermissionServiceContext
> permission_service_context_
;
488 // This is a set of all subscription targets valuebuffers in the GPU process
489 // are currently subscribed too. Used to prevent sending unnecessary
490 // ValueState updates.
491 typedef base::hash_set
<unsigned int> SubscriptionSet
;
492 SubscriptionSet subscription_set_
;
494 // Maintains ValueStates which are not currently subscribed too so we can
495 // pass them to the GpuService if a Valuebuffer ever subscribes to the
496 // respective subscription target
497 scoped_refptr
<gpu::ValueStateMap
> pending_valuebuffer_state_
;
499 // Whether or not the CHROMIUM_subscribe_uniform WebGL extension is enabled
500 bool subscribe_uniform_enabled_
;
502 base::WeakPtrFactory
<RenderProcessHostImpl
> weak_factory_
;
504 DISALLOW_COPY_AND_ASSIGN(RenderProcessHostImpl
);
507 } // namespace content
509 #endif // CONTENT_BROWSER_RENDERER_HOST_RENDER_PROCESS_HOST_IMPL_H_