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