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_BROWSER_RENDER_PROCESS_HOST_IMPL_H_
6 #define CONTENT_BROWSER_RENDERER_HOST_BROWSER_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 "base/timer/timer.h"
16 #include "content/browser/child_process_launcher.h"
17 #include "content/browser/dom_storage/session_storage_namespace_impl.h"
18 #include "content/browser/power_monitor_message_broadcaster.h"
19 #include "content/common/content_export.h"
20 #include "content/common/mojo/service_registry_impl.h"
21 #include "content/public/browser/gpu_data_manager_observer.h"
22 #include "content/public/browser/render_process_host.h"
23 #include "ipc/ipc_channel_proxy.h"
24 #include "ipc/ipc_platform_file.h"
25 #include "mojo/public/cpp/bindings/interface_ptr.h"
26 #include "ui/gfx/gpu_memory_buffer.h"
38 class AudioRendererHost
;
39 class BrowserDemuxerAndroid
;
40 class GpuMessageFilter
;
41 class MessagePortMessageFilter
;
42 class MojoApplicationHost
;
43 #if defined(ENABLE_WEBRTC)
44 class P2PSocketDispatcherHost
;
46 class PeerConnectionTrackerHost
;
47 class RendererMainThread
;
48 class RenderWidgetHelper
;
49 class RenderWidgetHost
;
50 class RenderWidgetHostImpl
;
51 class RenderWidgetHostViewFrameSubscriber
;
52 class StoragePartition
;
53 class StoragePartitionImpl
;
55 typedef base::Thread
* (*RendererMainThreadFactoryFunction
)(
56 const std::string
& id
);
58 // Implements a concrete RenderProcessHost for the browser process for talking
59 // to actual renderer processes (as opposed to mocks).
61 // Represents the browser side of the browser <--> renderer communication
62 // channel. There will be one RenderProcessHost per renderer process.
64 // This object is refcounted so that it can release its resources when all
65 // hosts using it go away.
67 // This object communicates back and forth with the RenderProcess object
68 // running in the renderer process. Each RenderProcessHost and RenderProcess
69 // keeps a list of RenderView (renderer) and WebContentsImpl (browser) which
70 // are correlated with IDs. This way, the Views and the corresponding ViewHosts
71 // communicate through the two process objects.
73 // A RenderProcessHost is also associated with one and only one
74 // StoragePartition. This allows us to implement strong storage isolation
75 // because all the IPCs from the RenderViews (renderer) will only ever be able
76 // to access the partition they are assigned to.
77 class CONTENT_EXPORT RenderProcessHostImpl
78 : public RenderProcessHost
,
79 public ChildProcessLauncher::Client
,
80 public GpuDataManagerObserver
{
82 RenderProcessHostImpl(BrowserContext
* browser_context
,
83 StoragePartitionImpl
* storage_partition_impl
,
84 bool is_isolated_guest
);
85 virtual ~RenderProcessHostImpl();
87 // RenderProcessHost implementation (public portion).
88 virtual void EnableSendQueue() OVERRIDE
;
89 virtual bool Init() OVERRIDE
;
90 virtual int GetNextRoutingID() OVERRIDE
;
91 virtual void AddRoute(int32 routing_id
, IPC::Listener
* listener
) OVERRIDE
;
92 virtual void RemoveRoute(int32 routing_id
) OVERRIDE
;
93 virtual void AddObserver(RenderProcessHostObserver
* observer
) OVERRIDE
;
94 virtual void RemoveObserver(RenderProcessHostObserver
* observer
) OVERRIDE
;
95 virtual void ReceivedBadMessage() OVERRIDE
;
96 virtual void WidgetRestored() OVERRIDE
;
97 virtual void WidgetHidden() OVERRIDE
;
98 virtual int VisibleWidgetCount() const OVERRIDE
;
99 virtual bool IsIsolatedGuest() const OVERRIDE
;
100 virtual StoragePartition
* GetStoragePartition() const OVERRIDE
;
101 virtual bool FastShutdownIfPossible() OVERRIDE
;
102 virtual void DumpHandles() OVERRIDE
;
103 virtual base::ProcessHandle
GetHandle() const OVERRIDE
;
104 virtual BrowserContext
* GetBrowserContext() const OVERRIDE
;
105 virtual bool InSameStoragePartition(
106 StoragePartition
* partition
) const OVERRIDE
;
107 virtual int GetID() const OVERRIDE
;
108 virtual bool HasConnection() const OVERRIDE
;
109 virtual void SetIgnoreInputEvents(bool ignore_input_events
) OVERRIDE
;
110 virtual bool IgnoreInputEvents() const OVERRIDE
;
111 virtual void Cleanup() OVERRIDE
;
112 virtual void AddPendingView() OVERRIDE
;
113 virtual void RemovePendingView() OVERRIDE
;
114 virtual void SetSuddenTerminationAllowed(bool enabled
) OVERRIDE
;
115 virtual bool SuddenTerminationAllowed() const OVERRIDE
;
116 virtual IPC::ChannelProxy
* GetChannel() OVERRIDE
;
117 virtual void AddFilter(BrowserMessageFilter
* filter
) OVERRIDE
;
118 virtual bool FastShutdownForPageCount(size_t count
) OVERRIDE
;
119 virtual bool FastShutdownStarted() const OVERRIDE
;
120 virtual base::TimeDelta
GetChildProcessIdleTime() const OVERRIDE
;
121 virtual void ResumeRequestsForView(int route_id
) OVERRIDE
;
122 virtual void FilterURL(bool empty_allowed
, GURL
* url
) OVERRIDE
;
123 #if defined(ENABLE_WEBRTC)
124 virtual void EnableAecDump(const base::FilePath
& file
) OVERRIDE
;
125 virtual void DisableAecDump() OVERRIDE
;
126 virtual void SetWebRtcLogMessageCallback(
127 base::Callback
<void(const std::string
&)> callback
) OVERRIDE
;
128 virtual WebRtcStopRtpDumpCallback
StartRtpDump(
131 const WebRtcRtpPacketCallback
& packet_callback
) OVERRIDE
;
133 virtual void ResumeDeferredNavigation(const GlobalRequestID
& request_id
)
135 virtual void NotifyTimezoneChange() OVERRIDE
;
136 virtual ServiceRegistry
* GetServiceRegistry() OVERRIDE
;
138 // IPC::Sender via RenderProcessHost.
139 virtual bool Send(IPC::Message
* msg
) OVERRIDE
;
141 // IPC::Listener via RenderProcessHost.
142 virtual bool OnMessageReceived(const IPC::Message
& msg
) OVERRIDE
;
143 virtual void OnChannelConnected(int32 peer_pid
) OVERRIDE
;
144 virtual void OnChannelError() OVERRIDE
;
145 virtual void OnBadMessageReceived(const IPC::Message
& message
) OVERRIDE
;
147 // ChildProcessLauncher::Client implementation.
148 virtual void OnProcessLaunched() OVERRIDE
;
150 scoped_refptr
<AudioRendererHost
> audio_renderer_host() const;
152 // Call this function when it is evident that the child process is actively
153 // performing some operation, for example if we just received an IPC message.
154 void mark_child_process_activity_time() {
155 child_process_activity_time_
= base::TimeTicks::Now();
158 // Returns the current number of active views in this process. Excludes
159 // any RenderViewHosts that are swapped out.
160 int GetActiveViewCount();
162 // Start and end frame subscription for a specific renderer.
163 // This API only supports subscription to accelerated composited frames.
164 void BeginFrameSubscription(
166 scoped_ptr
<RenderWidgetHostViewFrameSubscriber
> subscriber
);
167 void EndFrameSubscription(int route_id
);
169 #if defined(ENABLE_WEBRTC)
170 // Fires the webrtc log message callback with |message|, if callback is set.
171 void WebRtcLogMessage(const std::string
& message
);
174 // Used to extend the lifetime of the sessions until the render view
175 // in the renderer is fully closed. This is static because its also called
176 // with mock hosts as input in test cases.
177 static void ReleaseOnCloseACK(
178 RenderProcessHost
* host
,
179 const SessionStorageNamespaceMap
& sessions
,
182 // Register/unregister the host identified by the host id in the global host
184 static void RegisterHost(int host_id
, RenderProcessHost
* host
);
185 static void UnregisterHost(int host_id
);
187 // Implementation of FilterURL below that can be shared with the mock class.
188 static void FilterURL(RenderProcessHost
* rph
, bool empty_allowed
, GURL
* url
);
190 // Returns true if |host| is suitable for launching a new view with |site_url|
191 // in the given |browser_context|.
192 static bool IsSuitableHost(RenderProcessHost
* host
,
193 BrowserContext
* browser_context
,
194 const GURL
& site_url
);
196 // Returns an existing RenderProcessHost for |url| in |browser_context|,
197 // if one exists. Otherwise a new RenderProcessHost should be created and
198 // registered using RegisterProcessHostForSite().
199 // This should only be used for process-per-site mode, which can be enabled
200 // globally with a command line flag or per-site, as determined by
201 // SiteInstanceImpl::ShouldUseProcessPerSite.
202 static RenderProcessHost
* GetProcessHostForSite(
203 BrowserContext
* browser_context
,
206 // Registers the given |process| to be used for any instance of |url|
207 // within |browser_context|.
208 // This should only be used for process-per-site mode, which can be enabled
209 // globally with a command line flag or per-site, as determined by
210 // SiteInstanceImpl::ShouldUseProcessPerSite.
211 static void RegisterProcessHostForSite(
212 BrowserContext
* browser_context
,
213 RenderProcessHost
* process
,
216 static base::MessageLoop
* GetInProcessRendererThreadForTesting();
218 // This forces a renderer that is running "in process" to shut down.
219 static void ShutDownInProcessRenderer();
221 static void RegisterRendererMainThreadFactory(
222 RendererMainThreadFactoryFunction create
);
224 #if defined(OS_ANDROID)
225 const scoped_refptr
<BrowserDemuxerAndroid
>& browser_demuxer_android() {
226 return browser_demuxer_android_
;
230 MessagePortMessageFilter
* message_port_message_filter() const {
231 return message_port_message_filter_
.get();
234 void set_is_isolated_guest_for_testing(bool is_isolated_guest
) {
235 is_isolated_guest_
= is_isolated_guest
;
238 // Called when the existence of the other renderer process which is connected
239 // to the Worker in this renderer process has changed.
240 // It is only called when "enable-embedded-shared-worker" flag is set.
241 void IncrementWorkerRefCount();
242 void DecrementWorkerRefCount();
244 // Call this function to resume the navigation when it was deferred
245 // immediately after receiving response headers.
246 void ResumeResponseDeferredAtStart(const GlobalRequestID
& request_id
);
248 // Activates Mojo for this process. Does nothing if Mojo is already activated.
249 void EnsureMojoActivated();
252 // A proxy for our IPC::Channel that lives on the IO thread (see
253 // browser_process.h)
254 scoped_ptr
<IPC::ChannelProxy
> channel_
;
256 // True if fast shutdown has been performed on this RPH.
257 bool fast_shutdown_started_
;
259 // True if we've posted a DeleteTask and will be deleted soon.
263 // True if this object has deleted itself.
264 bool is_self_deleted_
;
267 // The count of currently swapped out but pending RenderViews. We have
268 // started to swap these in, so the renderer process should not exit if
269 // this count is non-zero.
270 int32 pending_views_
;
273 friend class VisitRelayingRenderProcessHost
;
275 void MaybeActivateMojo();
276 bool ShouldUseMojoChannel() const;
277 scoped_ptr
<IPC::ChannelProxy
> CreateChannelProxy(
278 const std::string
& channel_id
);
280 // Creates and adds the IO thread message filters.
281 void CreateMessageFilters();
283 // Control message handlers.
284 void OnShutdownRequest();
285 void OnDumpHandlesDone();
286 void SuddenTerminationChanged(bool enabled
);
287 void OnUserMetricsRecordAction(const std::string
& action
);
288 void OnSavedPageAsMHTML(int job_id
, int64 mhtml_file_size
);
289 void OnCloseACK(int old_route_id
);
291 // Generates a command line to be used to spawn a renderer and appends the
292 // results to |*command_line|.
293 void AppendRendererCommandLine(base::CommandLine
* command_line
) const;
295 // Copies applicable command line switches from the given |browser_cmd| line
296 // flags to the output |renderer_cmd| line flags. Not all switches will be
298 void PropagateBrowserCommandLineToRenderer(
299 const base::CommandLine
& browser_cmd
,
300 base::CommandLine
* renderer_cmd
) const;
302 // Callers can reduce the RenderProcess' priority.
303 void SetBackgrounded(bool backgrounded
);
305 // Handle termination of our process.
306 void ProcessDied(bool already_dead
);
308 virtual void OnGpuSwitching() OVERRIDE
;
310 #if defined(ENABLE_WEBRTC)
311 void OnRegisterAecDumpConsumer(int id
);
312 void OnUnregisterAecDumpConsumer(int id
);
313 void RegisterAecDumpConsumerOnUIThread(int id
);
314 void UnregisterAecDumpConsumerOnUIThread(int id
);
315 void EnableAecDumpForId(const base::FilePath
& file
, int id
);
316 // Sends |file_for_transit| to the render process.
317 void SendAecDumpFileToRenderer(int id
,
318 IPC::PlatformFileForTransit file_for_transit
);
319 void SendDisableAecDumpToRenderer();
322 scoped_ptr
<MojoApplicationHost
> mojo_application_host_
;
323 bool mojo_activation_required_
;
325 // The registered IPC listener objects. When this list is empty, we should
327 IDMap
<IPC::Listener
> listeners_
;
329 // The count of currently visible widgets. Since the host can be a container
330 // for multiple widgets, it uses this count to determine when it should be
332 int32 visible_widgets_
;
334 // Does this process have backgrounded priority.
337 // Used to allow a RenderWidgetHost to intercept various messages on the
339 scoped_refptr
<RenderWidgetHelper
> widget_helper_
;
341 // The filter for GPU-related messages coming from the renderer.
342 // Thread safety note: this field is to be accessed from the UI thread.
343 // We don't keep a reference to it, to avoid it being destroyed on the UI
344 // thread, but we clear this field when we clear channel_. When channel_ goes
345 // away, it posts a task to the IO thread to destroy it there, so we know that
346 // it's valid if non-NULL.
347 GpuMessageFilter
* gpu_message_filter_
;
349 // The filter for MessagePort messages coming from the renderer.
350 scoped_refptr
<MessagePortMessageFilter
> message_port_message_filter_
;
352 // Used in single-process mode.
353 scoped_ptr
<base::Thread
> in_process_renderer_
;
355 // True after Init() has been called. We can't just check channel_ because we
356 // also reset that in the case of process termination.
357 bool is_initialized_
;
359 // Used to launch and terminate the process without blocking the UI thread.
360 scoped_ptr
<ChildProcessLauncher
> child_process_launcher_
;
362 // Messages we queue while waiting for the process handle. We queue them here
363 // instead of in the channel so that we ensure they're sent after init related
364 // messages that are sent once the process handle is available. This is
365 // because the queued messages may have dependencies on the init messages.
366 std::queue
<IPC::Message
*> queued_messages_
;
368 // The globally-unique identifier for this RPH.
371 BrowserContext
* browser_context_
;
373 // Owned by |browser_context_|.
374 StoragePartitionImpl
* storage_partition_impl_
;
376 // The observers watching our lifetime.
377 ObserverList
<RenderProcessHostObserver
> observers_
;
379 // True if the process can be shut down suddenly. If this is true, then we're
380 // sure that all the RenderViews in the process can be shutdown suddenly. If
381 // it's false, then specific RenderViews might still be allowed to be shutdown
382 // suddenly by checking their SuddenTerminationAllowed() flag. This can occur
383 // if one WebContents has an unload event listener but another WebContents in
384 // the same process doesn't.
385 bool sudden_termination_allowed_
;
387 // Set to true if we shouldn't send input events. We actually do the
388 // filtering for this at the render widget level.
389 bool ignore_input_events_
;
391 // Records the last time we regarded the child process active.
392 base::TimeTicks child_process_activity_time_
;
394 // Indicates whether this is a RenderProcessHost of a Browser Plugin guest
396 bool is_isolated_guest_
;
398 // Forwards messages between WebRTCInternals in the browser process
399 // and PeerConnectionTracker in the renderer process.
400 scoped_refptr
<PeerConnectionTrackerHost
> peer_connection_tracker_host_
;
402 // Prevents the class from being added as a GpuDataManagerImpl observer more
404 bool gpu_observer_registered_
;
406 // Set if a call to Cleanup is required once the RenderProcessHostImpl is no
407 // longer within the RenderProcessHostObserver::RenderProcessExited callbacks.
408 bool delayed_cleanup_needed_
;
410 // Indicates whether RenderProcessHostImpl is currently iterating and calling
411 // through RenderProcessHostObserver::RenderProcessExited.
412 bool within_process_died_observer_
;
414 // Forwards power state messages to the renderer process.
415 PowerMonitorMessageBroadcaster power_monitor_broadcaster_
;
417 scoped_refptr
<AudioRendererHost
> audio_renderer_host_
;
419 #if defined(OS_ANDROID)
420 scoped_refptr
<BrowserDemuxerAndroid
> browser_demuxer_android_
;
423 #if defined(ENABLE_WEBRTC)
424 base::Callback
<void(const std::string
&)> webrtc_log_message_callback_
;
426 scoped_refptr
<P2PSocketDispatcherHost
> p2p_socket_dispatcher_host_
;
428 // Must be accessed on UI thread.
429 std::vector
<int> aec_dump_consumers_
;
431 WebRtcStopRtpDumpCallback stop_rtp_dump_callback_
;
434 int worker_ref_count_
;
436 // Records the time when the process starts surviving for workers for UMA.
437 base::TimeTicks survive_for_worker_start_time_
;
439 base::WeakPtrFactory
<RenderProcessHostImpl
> weak_factory_
;
441 DISALLOW_COPY_AND_ASSIGN(RenderProcessHostImpl
);
444 } // namespace content
446 #endif // CONTENT_BROWSER_RENDERER_HOST_BROWSER_RENDER_PROCESS_HOST_IMPL_H_