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/geolocation/geolocation_dispatcher_host.h"
18 #include "content/browser/power_monitor_message_broadcaster.h"
19 #include "content/common/content_export.h"
20 #include "content/public/browser/global_request_id.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 "ui/surface/transport_dib.h"
28 struct ViewHostMsg_CompositorSurfaceBuffersSwapped_Params;
39 class AudioRendererHost;
40 class BrowserDemuxerAndroid;
41 class GeolocationDispatcherHost;
42 class GpuMessageFilter;
43 class MessagePortMessageFilter;
44 class PeerConnectionTrackerHost;
45 class RendererMainThread;
46 class RenderWidgetHelper;
47 class RenderWidgetHost;
48 class RenderWidgetHostImpl;
49 class RenderWidgetHostViewFrameSubscriber;
50 class StoragePartition;
51 class StoragePartitionImpl;
53 // Implements a concrete RenderProcessHost for the browser process for talking
54 // to actual renderer processes (as opposed to mocks).
56 // Represents the browser side of the browser <--> renderer communication
57 // channel. There will be one RenderProcessHost per renderer process.
59 // This object is refcounted so that it can release its resources when all
60 // hosts using it go away.
62 // This object communicates back and forth with the RenderProcess object
63 // running in the renderer process. Each RenderProcessHost and RenderProcess
64 // keeps a list of RenderView (renderer) and WebContentsImpl (browser) which
65 // are correlated with IDs. This way, the Views and the corresponding ViewHosts
66 // communicate through the two process objects.
68 // A RenderProcessHost is also associated with one and only one
69 // StoragePartition. This allows us to implement strong storage isolation
70 // because all the IPCs from the RenderViews (renderer) will only ever be able
71 // to access the partition they are assigned to.
72 class CONTENT_EXPORT RenderProcessHostImpl
73 : public RenderProcessHost,
74 public ChildProcessLauncher::Client,
75 public GpuDataManagerObserver {
77 RenderProcessHostImpl(BrowserContext* browser_context,
78 StoragePartitionImpl* storage_partition_impl,
79 bool supports_browser_plugin,
81 virtual ~RenderProcessHostImpl();
83 // RenderProcessHost implementation (public portion).
84 virtual void EnableSendQueue() OVERRIDE;
85 virtual bool Init() OVERRIDE;
86 virtual int GetNextRoutingID() OVERRIDE;
87 virtual void AddRoute(int32 routing_id, IPC::Listener* listener) OVERRIDE;
88 virtual void RemoveRoute(int32 routing_id) OVERRIDE;
89 virtual void AddObserver(RenderProcessHostObserver* observer) OVERRIDE;
90 virtual void RemoveObserver(RenderProcessHostObserver* observer) OVERRIDE;
91 virtual bool WaitForBackingStoreMsg(int render_widget_id,
92 const base::TimeDelta& max_delay,
93 IPC::Message* msg) OVERRIDE;
94 virtual void ReceivedBadMessage() OVERRIDE;
95 virtual void WidgetRestored() OVERRIDE;
96 virtual void WidgetHidden() OVERRIDE;
97 virtual int VisibleWidgetCount() const OVERRIDE;
98 virtual bool IsGuest() const OVERRIDE;
99 virtual StoragePartition* GetStoragePartition() const OVERRIDE;
100 virtual bool FastShutdownIfPossible() OVERRIDE;
101 virtual void DumpHandles() OVERRIDE;
102 virtual base::ProcessHandle GetHandle() const OVERRIDE;
103 virtual TransportDIB* GetTransportDIB(TransportDIB::Id dib_id) OVERRIDE;
104 virtual TransportDIB* MapTransportDIB(TransportDIB::Id dib_id) OVERRIDE;
105 virtual BrowserContext* GetBrowserContext() const OVERRIDE;
106 virtual bool InSameStoragePartition(
107 StoragePartition* partition) const OVERRIDE;
108 virtual int GetID() const OVERRIDE;
109 virtual bool HasConnection() const OVERRIDE;
110 virtual void SetIgnoreInputEvents(bool ignore_input_events) OVERRIDE;
111 virtual bool IgnoreInputEvents() const OVERRIDE;
112 virtual void Cleanup() OVERRIDE;
113 virtual void AddPendingView() OVERRIDE;
114 virtual void RemovePendingView() OVERRIDE;
115 virtual void SetSuddenTerminationAllowed(bool enabled) OVERRIDE;
116 virtual bool SuddenTerminationAllowed() const OVERRIDE;
117 virtual IPC::ChannelProxy* GetChannel() OVERRIDE;
118 virtual void AddFilter(BrowserMessageFilter* filter) OVERRIDE;
119 virtual bool FastShutdownForPageCount(size_t count) OVERRIDE;
120 virtual bool FastShutdownStarted() const OVERRIDE;
121 virtual base::TimeDelta GetChildProcessIdleTime() const OVERRIDE;
122 virtual void ResumeRequestsForView(int route_id) OVERRIDE;
123 virtual void FilterURL(bool empty_allowed, GURL* url) OVERRIDE;
124 #if defined(ENABLE_WEBRTC)
125 virtual void EnableAecDump(const base::FilePath& file) OVERRIDE;
126 virtual void DisableAecDump() OVERRIDE;
127 virtual void SetWebRtcLogMessageCallback(
128 base::Callback<void(const std::string&)> callback) OVERRIDE;
131 // IPC::Sender via RenderProcessHost.
132 virtual bool Send(IPC::Message* msg) OVERRIDE;
134 // IPC::Listener via RenderProcessHost.
135 virtual bool OnMessageReceived(const IPC::Message& msg) OVERRIDE;
136 virtual void OnChannelConnected(int32 peer_pid) OVERRIDE;
137 virtual void OnChannelError() OVERRIDE;
139 // ChildProcessLauncher::Client implementation.
140 virtual void OnProcessLaunched() OVERRIDE;
142 scoped_refptr<AudioRendererHost> audio_renderer_host() const;
144 // Tells the ResourceDispatcherHost to resume a deferred navigation without
145 // transferring it to a new renderer process.
146 void ResumeDeferredNavigation(const GlobalRequestID& request_id);
148 // Call this function when it is evident that the child process is actively
149 // performing some operation, for example if we just received an IPC message.
150 void mark_child_process_activity_time() {
151 child_process_activity_time_ = base::TimeTicks::Now();
154 // Returns the current number of active views in this process. Excludes
155 // any RenderViewHosts that are swapped out.
156 int GetActiveViewCount();
158 // Start and end frame subscription for a specific renderer.
159 // This API only supports subscription to accelerated composited frames.
160 void BeginFrameSubscription(
162 scoped_ptr<RenderWidgetHostViewFrameSubscriber> subscriber);
163 void EndFrameSubscription(int route_id);
165 scoped_refptr<GeolocationDispatcherHost>
166 geolocation_dispatcher_host() const {
167 return make_scoped_refptr(geolocation_dispatcher_host_);
170 #if defined(ENABLE_WEBRTC)
171 // Fires the webrtc log message callback with |message|, if callback is set.
172 void WebRtcLogMessage(const std::string& message);
175 // Register/unregister the host identified by the host id in the global host
177 static void RegisterHost(int host_id, RenderProcessHost* host);
178 static void UnregisterHost(int host_id);
180 // Implementation of FilterURL below that can be shared with the mock class.
181 static void FilterURL(RenderProcessHost* rph, bool empty_allowed, GURL* url);
183 // Returns true if |host| is suitable for launching a new view with |site_url|
184 // in the given |browser_context|.
185 static bool IsSuitableHost(RenderProcessHost* host,
186 BrowserContext* browser_context,
187 const GURL& site_url);
189 // Returns an existing RenderProcessHost for |url| in |browser_context|,
190 // if one exists. Otherwise a new RenderProcessHost should be created and
191 // registered using RegisterProcessHostForSite().
192 // This should only be used for process-per-site mode, which can be enabled
193 // globally with a command line flag or per-site, as determined by
194 // SiteInstanceImpl::ShouldUseProcessPerSite.
195 static RenderProcessHost* GetProcessHostForSite(
196 BrowserContext* browser_context,
199 // Registers the given |process| to be used for any instance of |url|
200 // within |browser_context|.
201 // This should only be used for process-per-site mode, which can be enabled
202 // globally with a command line flag or per-site, as determined by
203 // SiteInstanceImpl::ShouldUseProcessPerSite.
204 static void RegisterProcessHostForSite(
205 BrowserContext* browser_context,
206 RenderProcessHost* process,
209 static base::MessageLoop* GetInProcessRendererThreadForTesting();
211 // This forces a renderer that is running "in process" to shut down.
212 static void ShutDownInProcessRenderer();
214 #if defined(OS_ANDROID)
215 const scoped_refptr<BrowserDemuxerAndroid>& browser_demuxer_android() {
216 return browser_demuxer_android_;
220 MessagePortMessageFilter* message_port_message_filter() const {
221 return message_port_message_filter_;
224 void SetIsGuestForTesting(bool is_guest) {
225 is_guest_ = is_guest;
229 // A proxy for our IPC::Channel that lives on the IO thread (see
230 // browser_process.h)
231 scoped_ptr<IPC::ChannelProxy> channel_;
233 // True if fast shutdown has been performed on this RPH.
234 bool fast_shutdown_started_;
236 // True if we've posted a DeleteTask and will be deleted soon.
240 // True if this object has deleted itself.
241 bool is_self_deleted_;
244 // The count of currently swapped out but pending RenderViews. We have
245 // started to swap these in, so the renderer process should not exit if
246 // this count is non-zero.
247 int32 pending_views_;
250 friend class VisitRelayingRenderProcessHost;
252 // Creates and adds the IO thread message filters.
253 void CreateMessageFilters();
255 // Control message handlers.
256 void OnShutdownRequest();
257 void OnDumpHandlesDone();
258 void SuddenTerminationChanged(bool enabled);
259 void OnUserMetricsRecordAction(const std::string& action);
260 void OnSavedPageAsMHTML(int job_id, int64 mhtml_file_size);
262 // CompositorSurfaceBuffersSwapped handler when there's no RWH.
263 void OnCompositorSurfaceBuffersSwappedNoHost(
264 const ViewHostMsg_CompositorSurfaceBuffersSwapped_Params& params);
266 // Generates a command line to be used to spawn a renderer and appends the
267 // results to |*command_line|.
268 void AppendRendererCommandLine(CommandLine* command_line) const;
270 // Copies applicable command line switches from the given |browser_cmd| line
271 // flags to the output |renderer_cmd| line flags. Not all switches will be
273 void PropagateBrowserCommandLineToRenderer(const CommandLine& browser_cmd,
274 CommandLine* renderer_cmd) const;
276 // Callers can reduce the RenderProcess' priority.
277 void SetBackgrounded(bool backgrounded);
279 // Handle termination of our process.
280 void ProcessDied(bool already_dead);
282 virtual void OnGpuSwitching() OVERRIDE;
284 #if defined(ENABLE_WEBRTC)
285 // Sends |file_for_transit| to the render process.
286 void SendAecDumpFileToRenderer(IPC::PlatformFileForTransit file_for_transit);
287 void SendDisableAecDumpToRenderer();
290 // The registered IPC listener objects. When this list is empty, we should
292 IDMap<IPC::Listener> listeners_;
294 // The count of currently visible widgets. Since the host can be a container
295 // for multiple widgets, it uses this count to determine when it should be
297 int32 visible_widgets_;
299 // Does this process have backgrounded priority.
302 // Used to allow a RenderWidgetHost to intercept various messages on the
304 scoped_refptr<RenderWidgetHelper> widget_helper_;
306 // The filter for GPU-related messages coming from the renderer.
307 // Thread safety note: this field is to be accessed from the UI thread.
308 // We don't keep a reference to it, to avoid it being destroyed on the UI
309 // thread, but we clear this field when we clear channel_. When channel_ goes
310 // away, it posts a task to the IO thread to destroy it there, so we know that
311 // it's valid if non-NULL.
312 GpuMessageFilter* gpu_message_filter_;
314 // The filter for MessagePort messages coming from the renderer.
315 scoped_refptr<MessagePortMessageFilter> message_port_message_filter_;
317 // A map of transport DIB ids to cached TransportDIBs
318 std::map<TransportDIB::Id, TransportDIB*> cached_dibs_;
321 // This is the maximum size of |cached_dibs_|
322 MAX_MAPPED_TRANSPORT_DIBS = 3,
325 void ClearTransportDIBCache();
326 // This is used to clear our cache five seconds after the last use.
327 base::DelayTimer<RenderProcessHostImpl> cached_dibs_cleaner_;
329 // Used in single-process mode.
330 scoped_ptr<base::Thread> in_process_renderer_;
332 // True after Init() has been called. We can't just check channel_ because we
333 // also reset that in the case of process termination.
334 bool is_initialized_;
336 // Used to launch and terminate the process without blocking the UI thread.
337 scoped_ptr<ChildProcessLauncher> child_process_launcher_;
339 // Messages we queue while waiting for the process handle. We queue them here
340 // instead of in the channel so that we ensure they're sent after init related
341 // messages that are sent once the process handle is available. This is
342 // because the queued messages may have dependencies on the init messages.
343 std::queue<IPC::Message*> queued_messages_;
345 // The globally-unique identifier for this RPH.
348 BrowserContext* browser_context_;
350 // Owned by |browser_context_|.
351 StoragePartitionImpl* storage_partition_impl_;
353 // The observers watching our lifetime.
354 ObserverList<RenderProcessHostObserver> observers_;
356 // True if the process can be shut down suddenly. If this is true, then we're
357 // sure that all the RenderViews in the process can be shutdown suddenly. If
358 // it's false, then specific RenderViews might still be allowed to be shutdown
359 // suddenly by checking their SuddenTerminationAllowed() flag. This can occur
360 // if one WebContents has an unload event listener but another WebContents in
361 // the same process doesn't.
362 bool sudden_termination_allowed_;
364 // Set to true if we shouldn't send input events. We actually do the
365 // filtering for this at the render widget level.
366 bool ignore_input_events_;
368 // Records the last time we regarded the child process active.
369 base::TimeTicks child_process_activity_time_;
371 // Indicates whether this is a RenderProcessHost that has permission to embed
373 bool supports_browser_plugin_;
375 // Indicates whether this is a RenderProcessHost of a Browser Plugin guest
379 // Forwards messages between WebRTCInternals in the browser process
380 // and PeerConnectionTracker in the renderer process.
381 scoped_refptr<PeerConnectionTrackerHost> peer_connection_tracker_host_;
383 // Prevents the class from being added as a GpuDataManagerImpl observer more
385 bool gpu_observer_registered_;
387 // Forwards power state messages to the renderer process.
388 PowerMonitorMessageBroadcaster power_monitor_broadcaster_;
390 scoped_refptr<AudioRendererHost> audio_renderer_host_;
392 #if defined(OS_ANDROID)
393 scoped_refptr<BrowserDemuxerAndroid> browser_demuxer_android_;
396 // Message filter for geolocation messages.
397 GeolocationDispatcherHost* geolocation_dispatcher_host_;
399 #if defined(ENABLE_WEBRTC)
400 base::Callback<void(const std::string&)> webrtc_log_message_callback_;
403 // Lives on the browser's ChildThread.
404 base::WeakPtrFactory<RenderProcessHostImpl> weak_factory_;
406 DISALLOW_COPY_AND_ASSIGN(RenderProcessHostImpl);
409 } // namespace content
411 #endif // CONTENT_BROWSER_RENDERER_HOST_BROWSER_RENDER_PROCESS_HOST_IMPL_H_