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/gpu_data_manager_observer.h"
21 #include "content/public/browser/render_process_host.h"
22 #include "ipc/ipc_channel_proxy.h"
23 #include "ipc/ipc_platform_file.h"
24 #include "ui/surface/transport_dib.h"
27 struct ViewHostMsg_CompositorSurfaceBuffersSwapped_Params;
38 class AudioRendererHost;
39 class BrowserDemuxerAndroid;
40 class GeolocationDispatcherHost;
41 class GpuMessageFilter;
42 class MessagePortMessageFilter;
43 class PeerConnectionTrackerHost;
44 class RendererMainThread;
45 class RenderWidgetHelper;
46 class RenderWidgetHost;
47 class RenderWidgetHostImpl;
48 class RenderWidgetHostViewFrameSubscriber;
49 class StoragePartition;
50 class StoragePartitionImpl;
52 // Implements a concrete RenderProcessHost for the browser process for talking
53 // to actual renderer processes (as opposed to mocks).
55 // Represents the browser side of the browser <--> renderer communication
56 // channel. There will be one RenderProcessHost per renderer process.
58 // This object is refcounted so that it can release its resources when all
59 // hosts using it go away.
61 // This object communicates back and forth with the RenderProcess object
62 // running in the renderer process. Each RenderProcessHost and RenderProcess
63 // keeps a list of RenderView (renderer) and WebContentsImpl (browser) which
64 // are correlated with IDs. This way, the Views and the corresponding ViewHosts
65 // communicate through the two process objects.
67 // A RenderProcessHost is also associated with one and only one
68 // StoragePartition. This allows us to implement strong storage isolation
69 // because all the IPCs from the RenderViews (renderer) will only ever be able
70 // to access the partition they are assigned to.
71 class CONTENT_EXPORT RenderProcessHostImpl
72 : public RenderProcessHost,
73 public ChildProcessLauncher::Client,
74 public GpuDataManagerObserver {
76 RenderProcessHostImpl(BrowserContext* browser_context,
77 StoragePartitionImpl* storage_partition_impl,
78 bool supports_browser_plugin,
80 virtual ~RenderProcessHostImpl();
82 // RenderProcessHost implementation (public portion).
83 virtual void EnableSendQueue() OVERRIDE;
84 virtual bool Init() OVERRIDE;
85 virtual int GetNextRoutingID() OVERRIDE;
86 virtual void AddRoute(int32 routing_id, IPC::Listener* listener) OVERRIDE;
87 virtual void RemoveRoute(int32 routing_id) OVERRIDE;
88 virtual void AddObserver(RenderProcessHostObserver* observer) OVERRIDE;
89 virtual void RemoveObserver(RenderProcessHostObserver* observer) OVERRIDE;
90 virtual bool WaitForBackingStoreMsg(int render_widget_id,
91 const base::TimeDelta& max_delay,
92 IPC::Message* msg) OVERRIDE;
93 virtual void ReceivedBadMessage() OVERRIDE;
94 virtual void WidgetRestored() OVERRIDE;
95 virtual void WidgetHidden() OVERRIDE;
96 virtual int VisibleWidgetCount() const OVERRIDE;
97 virtual bool IsGuest() const OVERRIDE;
98 virtual StoragePartition* GetStoragePartition() const OVERRIDE;
99 virtual bool FastShutdownIfPossible() OVERRIDE;
100 virtual void DumpHandles() OVERRIDE;
101 virtual base::ProcessHandle GetHandle() const OVERRIDE;
102 virtual TransportDIB* GetTransportDIB(TransportDIB::Id dib_id) OVERRIDE;
103 virtual TransportDIB* MapTransportDIB(TransportDIB::Id dib_id) 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;
129 virtual void ResumeDeferredNavigation(const GlobalRequestID& request_id)
132 // IPC::Sender via RenderProcessHost.
133 virtual bool Send(IPC::Message* msg) OVERRIDE;
135 // IPC::Listener via RenderProcessHost.
136 virtual bool OnMessageReceived(const IPC::Message& msg) OVERRIDE;
137 virtual void OnChannelConnected(int32 peer_pid) OVERRIDE;
138 virtual void OnChannelError() OVERRIDE;
140 // ChildProcessLauncher::Client implementation.
141 virtual void OnProcessLaunched() OVERRIDE;
143 scoped_refptr<AudioRendererHost> audio_renderer_host() const;
145 // Call this function when it is evident that the child process is actively
146 // performing some operation, for example if we just received an IPC message.
147 void mark_child_process_activity_time() {
148 child_process_activity_time_ = base::TimeTicks::Now();
151 // Returns the current number of active views in this process. Excludes
152 // any RenderViewHosts that are swapped out.
153 int GetActiveViewCount();
155 // Start and end frame subscription for a specific renderer.
156 // This API only supports subscription to accelerated composited frames.
157 void BeginFrameSubscription(
159 scoped_ptr<RenderWidgetHostViewFrameSubscriber> subscriber);
160 void EndFrameSubscription(int route_id);
162 scoped_refptr<GeolocationDispatcherHost>
163 geolocation_dispatcher_host() const {
164 return make_scoped_refptr(geolocation_dispatcher_host_);
167 #if defined(ENABLE_WEBRTC)
168 // Fires the webrtc log message callback with |message|, if callback is set.
169 void WebRtcLogMessage(const std::string& message);
172 // Register/unregister the host identified by the host id in the global host
174 static void RegisterHost(int host_id, RenderProcessHost* host);
175 static void UnregisterHost(int host_id);
177 // Implementation of FilterURL below that can be shared with the mock class.
178 static void FilterURL(RenderProcessHost* rph, bool empty_allowed, GURL* url);
180 // Returns true if |host| is suitable for launching a new view with |site_url|
181 // in the given |browser_context|.
182 static bool IsSuitableHost(RenderProcessHost* host,
183 BrowserContext* browser_context,
184 const GURL& site_url);
186 // Returns an existing RenderProcessHost for |url| in |browser_context|,
187 // if one exists. Otherwise a new RenderProcessHost should be created and
188 // registered using RegisterProcessHostForSite().
189 // This should only be used for process-per-site mode, which can be enabled
190 // globally with a command line flag or per-site, as determined by
191 // SiteInstanceImpl::ShouldUseProcessPerSite.
192 static RenderProcessHost* GetProcessHostForSite(
193 BrowserContext* browser_context,
196 // Registers the given |process| to be used for any instance of |url|
197 // within |browser_context|.
198 // This should only be used for process-per-site mode, which can be enabled
199 // globally with a command line flag or per-site, as determined by
200 // SiteInstanceImpl::ShouldUseProcessPerSite.
201 static void RegisterProcessHostForSite(
202 BrowserContext* browser_context,
203 RenderProcessHost* process,
206 static base::MessageLoop* GetInProcessRendererThreadForTesting();
208 // This forces a renderer that is running "in process" to shut down.
209 static void ShutDownInProcessRenderer();
211 #if defined(OS_ANDROID)
212 const scoped_refptr<BrowserDemuxerAndroid>& browser_demuxer_android() {
213 return browser_demuxer_android_;
217 MessagePortMessageFilter* message_port_message_filter() const {
218 return message_port_message_filter_;
221 void SetIsGuestForTesting(bool is_guest) {
222 is_guest_ = is_guest;
226 // A proxy for our IPC::Channel that lives on the IO thread (see
227 // browser_process.h)
228 scoped_ptr<IPC::ChannelProxy> channel_;
230 // True if fast shutdown has been performed on this RPH.
231 bool fast_shutdown_started_;
233 // True if we've posted a DeleteTask and will be deleted soon.
237 // True if this object has deleted itself.
238 bool is_self_deleted_;
241 // The count of currently swapped out but pending RenderViews. We have
242 // started to swap these in, so the renderer process should not exit if
243 // this count is non-zero.
244 int32 pending_views_;
247 friend class VisitRelayingRenderProcessHost;
249 // Creates and adds the IO thread message filters.
250 void CreateMessageFilters();
252 // Control message handlers.
253 void OnShutdownRequest();
254 void OnDumpHandlesDone();
255 void SuddenTerminationChanged(bool enabled);
256 void OnUserMetricsRecordAction(const std::string& action);
257 void OnSavedPageAsMHTML(int job_id, int64 mhtml_file_size);
259 // CompositorSurfaceBuffersSwapped handler when there's no RWH.
260 void OnCompositorSurfaceBuffersSwappedNoHost(
261 const ViewHostMsg_CompositorSurfaceBuffersSwapped_Params& params);
263 // Generates a command line to be used to spawn a renderer and appends the
264 // results to |*command_line|.
265 void AppendRendererCommandLine(CommandLine* command_line) const;
267 // Copies applicable command line switches from the given |browser_cmd| line
268 // flags to the output |renderer_cmd| line flags. Not all switches will be
270 void PropagateBrowserCommandLineToRenderer(const CommandLine& browser_cmd,
271 CommandLine* renderer_cmd) const;
273 // Callers can reduce the RenderProcess' priority.
274 void SetBackgrounded(bool backgrounded);
276 // Handle termination of our process.
277 void ProcessDied(bool already_dead);
279 virtual void OnGpuSwitching() OVERRIDE;
281 #if defined(ENABLE_WEBRTC)
282 // Sends |file_for_transit| to the render process.
283 void SendAecDumpFileToRenderer(IPC::PlatformFileForTransit file_for_transit);
284 void SendDisableAecDumpToRenderer();
287 // The registered IPC listener objects. When this list is empty, we should
289 IDMap<IPC::Listener> listeners_;
291 // The count of currently visible widgets. Since the host can be a container
292 // for multiple widgets, it uses this count to determine when it should be
294 int32 visible_widgets_;
296 // Does this process have backgrounded priority.
299 // Used to allow a RenderWidgetHost to intercept various messages on the
301 scoped_refptr<RenderWidgetHelper> widget_helper_;
303 // The filter for GPU-related messages coming from the renderer.
304 // Thread safety note: this field is to be accessed from the UI thread.
305 // We don't keep a reference to it, to avoid it being destroyed on the UI
306 // thread, but we clear this field when we clear channel_. When channel_ goes
307 // away, it posts a task to the IO thread to destroy it there, so we know that
308 // it's valid if non-NULL.
309 GpuMessageFilter* gpu_message_filter_;
311 // The filter for MessagePort messages coming from the renderer.
312 scoped_refptr<MessagePortMessageFilter> message_port_message_filter_;
314 // A map of transport DIB ids to cached TransportDIBs
315 std::map<TransportDIB::Id, TransportDIB*> cached_dibs_;
318 // This is the maximum size of |cached_dibs_|
319 MAX_MAPPED_TRANSPORT_DIBS = 3,
322 void ClearTransportDIBCache();
323 // This is used to clear our cache five seconds after the last use.
324 base::DelayTimer<RenderProcessHostImpl> cached_dibs_cleaner_;
326 // Used in single-process mode.
327 scoped_ptr<base::Thread> in_process_renderer_;
329 // True after Init() has been called. We can't just check channel_ because we
330 // also reset that in the case of process termination.
331 bool is_initialized_;
333 // Used to launch and terminate the process without blocking the UI thread.
334 scoped_ptr<ChildProcessLauncher> child_process_launcher_;
336 // Messages we queue while waiting for the process handle. We queue them here
337 // instead of in the channel so that we ensure they're sent after init related
338 // messages that are sent once the process handle is available. This is
339 // because the queued messages may have dependencies on the init messages.
340 std::queue<IPC::Message*> queued_messages_;
342 // The globally-unique identifier for this RPH.
345 BrowserContext* browser_context_;
347 // Owned by |browser_context_|.
348 StoragePartitionImpl* storage_partition_impl_;
350 // The observers watching our lifetime.
351 ObserverList<RenderProcessHostObserver> observers_;
353 // True if the process can be shut down suddenly. If this is true, then we're
354 // sure that all the RenderViews in the process can be shutdown suddenly. If
355 // it's false, then specific RenderViews might still be allowed to be shutdown
356 // suddenly by checking their SuddenTerminationAllowed() flag. This can occur
357 // if one WebContents has an unload event listener but another WebContents in
358 // the same process doesn't.
359 bool sudden_termination_allowed_;
361 // Set to true if we shouldn't send input events. We actually do the
362 // filtering for this at the render widget level.
363 bool ignore_input_events_;
365 // Records the last time we regarded the child process active.
366 base::TimeTicks child_process_activity_time_;
368 // Indicates whether this is a RenderProcessHost that has permission to embed
370 bool supports_browser_plugin_;
372 // Indicates whether this is a RenderProcessHost of a Browser Plugin guest
376 // Forwards messages between WebRTCInternals in the browser process
377 // and PeerConnectionTracker in the renderer process.
378 scoped_refptr<PeerConnectionTrackerHost> peer_connection_tracker_host_;
380 // Prevents the class from being added as a GpuDataManagerImpl observer more
382 bool gpu_observer_registered_;
384 // Set if a call to Cleanup is required once the RenderProcessHostImpl is no
385 // longer within the RenderProcessHostObserver::RenderProcessExited callbacks.
386 bool delayed_cleanup_needed_;
388 // Indicates whether RenderProcessHostImpl is currently iterating and calling
389 // through RenderProcessHostObserver::RenderProcessExited.
390 bool within_process_died_observer_;
392 // Forwards power state messages to the renderer process.
393 PowerMonitorMessageBroadcaster power_monitor_broadcaster_;
395 scoped_refptr<AudioRendererHost> audio_renderer_host_;
397 #if defined(OS_ANDROID)
398 scoped_refptr<BrowserDemuxerAndroid> browser_demuxer_android_;
401 // Message filter for geolocation messages.
402 GeolocationDispatcherHost* geolocation_dispatcher_host_;
404 #if defined(ENABLE_WEBRTC)
405 base::Callback<void(const std::string&)> webrtc_log_message_callback_;
408 // Lives on the browser's ChildThread.
409 base::WeakPtrFactory<RenderProcessHostImpl> weak_factory_;
411 DISALLOW_COPY_AND_ASSIGN(RenderProcessHostImpl);
414 } // namespace content
416 #endif // CONTENT_BROWSER_RENDERER_HOST_BROWSER_RENDER_PROCESS_HOST_IMPL_H_