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 "mojo/public/cpp/bindings/interface_ptr.h"
26 struct ViewHostMsg_CompositorSurfaceBuffersSwapped_Params;
38 class AudioRendererHost;
39 class BrowserDemuxerAndroid;
40 class GeolocationDispatcherHost;
41 class GpuMessageFilter;
42 class MessagePortMessageFilter;
43 class MojoApplicationHost;
44 class PeerConnectionTrackerHost;
45 class RendererMainThread;
46 class RenderProcessHostMojoImpl;
47 class RenderWidgetHelper;
48 class RenderWidgetHost;
49 class RenderWidgetHostImpl;
50 class RenderWidgetHostViewFrameSubscriber;
51 class ScreenOrientationDispatcherHost;
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,
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 bool WaitForBackingStoreMsg(int render_widget_id,
96 const base::TimeDelta& max_delay,
97 IPC::Message* msg) OVERRIDE;
98 virtual void ReceivedBadMessage() OVERRIDE;
99 virtual void WidgetRestored() OVERRIDE;
100 virtual void WidgetHidden() OVERRIDE;
101 virtual int VisibleWidgetCount() const OVERRIDE;
102 virtual bool IsGuest() const OVERRIDE;
103 virtual StoragePartition* GetStoragePartition() const OVERRIDE;
104 virtual bool FastShutdownIfPossible() OVERRIDE;
105 virtual void DumpHandles() OVERRIDE;
106 virtual base::ProcessHandle GetHandle() const OVERRIDE;
107 virtual BrowserContext* GetBrowserContext() const OVERRIDE;
108 virtual bool InSameStoragePartition(
109 StoragePartition* partition) const OVERRIDE;
110 virtual int GetID() const OVERRIDE;
111 virtual bool HasConnection() const OVERRIDE;
112 virtual void SetIgnoreInputEvents(bool ignore_input_events) OVERRIDE;
113 virtual bool IgnoreInputEvents() const OVERRIDE;
114 virtual void Cleanup() OVERRIDE;
115 virtual void AddPendingView() OVERRIDE;
116 virtual void RemovePendingView() OVERRIDE;
117 virtual void SetSuddenTerminationAllowed(bool enabled) OVERRIDE;
118 virtual bool SuddenTerminationAllowed() const OVERRIDE;
119 virtual IPC::ChannelProxy* GetChannel() OVERRIDE;
120 virtual void AddFilter(BrowserMessageFilter* filter) OVERRIDE;
121 virtual bool FastShutdownForPageCount(size_t count) OVERRIDE;
122 virtual bool FastShutdownStarted() const OVERRIDE;
123 virtual base::TimeDelta GetChildProcessIdleTime() const OVERRIDE;
124 virtual void ResumeRequestsForView(int route_id) OVERRIDE;
125 virtual void FilterURL(bool empty_allowed, GURL* url) OVERRIDE;
126 #if defined(ENABLE_WEBRTC)
127 virtual void EnableAecDump(const base::FilePath& file) OVERRIDE;
128 virtual void DisableAecDump() OVERRIDE;
129 virtual void SetWebRtcLogMessageCallback(
130 base::Callback<void(const std::string&)> callback) OVERRIDE;
132 virtual void ResumeDeferredNavigation(const GlobalRequestID& request_id)
134 virtual void NotifyTimezoneChange() OVERRIDE;
136 // IPC::Sender via RenderProcessHost.
137 virtual bool Send(IPC::Message* msg) OVERRIDE;
139 // IPC::Listener via RenderProcessHost.
140 virtual bool OnMessageReceived(const IPC::Message& msg) OVERRIDE;
141 virtual void OnChannelConnected(int32 peer_pid) OVERRIDE;
142 virtual void OnChannelError() OVERRIDE;
144 // ChildProcessLauncher::Client implementation.
145 virtual void OnProcessLaunched() OVERRIDE;
147 scoped_refptr<AudioRendererHost> audio_renderer_host() const;
149 // Call this function when it is evident that the child process is actively
150 // performing some operation, for example if we just received an IPC message.
151 void mark_child_process_activity_time() {
152 child_process_activity_time_ = base::TimeTicks::Now();
155 // Returns the current number of active views in this process. Excludes
156 // any RenderViewHosts that are swapped out.
157 int GetActiveViewCount();
159 // Start and end frame subscription for a specific renderer.
160 // This API only supports subscription to accelerated composited frames.
161 void BeginFrameSubscription(
163 scoped_ptr<RenderWidgetHostViewFrameSubscriber> subscriber);
164 void EndFrameSubscription(int route_id);
166 scoped_refptr<GeolocationDispatcherHost>
167 geolocation_dispatcher_host() const {
168 return make_scoped_refptr(geolocation_dispatcher_host_);
171 #if defined(ENABLE_WEBRTC)
172 // Fires the webrtc log message callback with |message|, if callback is set.
173 void WebRtcLogMessage(const std::string& message);
176 scoped_refptr<ScreenOrientationDispatcherHost>
177 screen_orientation_dispatcher_host() const;
179 // Register/unregister the host identified by the host id in the global host
181 static void RegisterHost(int host_id, RenderProcessHost* host);
182 static void UnregisterHost(int host_id);
184 // Implementation of FilterURL below that can be shared with the mock class.
185 static void FilterURL(RenderProcessHost* rph, bool empty_allowed, GURL* url);
187 // Returns true if |host| is suitable for launching a new view with |site_url|
188 // in the given |browser_context|.
189 static bool IsSuitableHost(RenderProcessHost* host,
190 BrowserContext* browser_context,
191 const GURL& site_url);
193 // Returns an existing RenderProcessHost for |url| in |browser_context|,
194 // if one exists. Otherwise a new RenderProcessHost should be created and
195 // registered using RegisterProcessHostForSite().
196 // This should only be used for process-per-site mode, which can be enabled
197 // globally with a command line flag or per-site, as determined by
198 // SiteInstanceImpl::ShouldUseProcessPerSite.
199 static RenderProcessHost* GetProcessHostForSite(
200 BrowserContext* browser_context,
203 // Registers the given |process| to be used for any instance of |url|
204 // within |browser_context|.
205 // This should only be used for process-per-site mode, which can be enabled
206 // globally with a command line flag or per-site, as determined by
207 // SiteInstanceImpl::ShouldUseProcessPerSite.
208 static void RegisterProcessHostForSite(
209 BrowserContext* browser_context,
210 RenderProcessHost* process,
213 static base::MessageLoop* GetInProcessRendererThreadForTesting();
215 // This forces a renderer that is running "in process" to shut down.
216 static void ShutDownInProcessRenderer();
218 static void RegisterRendererMainThreadFactory(
219 RendererMainThreadFactoryFunction create);
221 #if defined(OS_ANDROID)
222 const scoped_refptr<BrowserDemuxerAndroid>& browser_demuxer_android() {
223 return browser_demuxer_android_;
227 MessagePortMessageFilter* message_port_message_filter() const {
228 return message_port_message_filter_;
231 void SetIsGuestForTesting(bool is_guest) {
232 is_guest_ = is_guest;
235 // Called when the existence of the other renderer process which is connected
236 // to the Worker in this renderer process has changed.
237 // It is only called when "enable-embedded-shared-worker" flag is set.
238 void IncrementWorkerRefCount();
239 void DecrementWorkerRefCount();
241 // Establish a connection to a renderer-provided service. See
242 // content/common/mojo/mojo_service_names.h for a list of services.
243 void ConnectTo(const base::StringPiece& service_name,
244 mojo::ScopedMessagePipeHandle handle);
246 template <typename Interface>
247 void ConnectTo(const base::StringPiece& service_name,
248 mojo::InterfacePtr<Interface>* ptr) {
249 mojo::MessagePipe pipe;
250 ptr->Bind(pipe.handle0.Pass());
251 ConnectTo(service_name, pipe.handle1.Pass());
255 // A proxy for our IPC::Channel that lives on the IO thread (see
256 // browser_process.h)
257 scoped_ptr<IPC::ChannelProxy> channel_;
259 // True if fast shutdown has been performed on this RPH.
260 bool fast_shutdown_started_;
262 // True if we've posted a DeleteTask and will be deleted soon.
266 // True if this object has deleted itself.
267 bool is_self_deleted_;
270 // The count of currently swapped out but pending RenderViews. We have
271 // started to swap these in, so the renderer process should not exit if
272 // this count is non-zero.
273 int32 pending_views_;
276 friend class VisitRelayingRenderProcessHost;
278 void MaybeActivateMojo();
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);
290 // CompositorSurfaceBuffersSwapped handler when there's no RWH.
291 void OnCompositorSurfaceBuffersSwappedNoHost(
292 const ViewHostMsg_CompositorSurfaceBuffersSwapped_Params& params);
294 // Generates a command line to be used to spawn a renderer and appends the
295 // results to |*command_line|.
296 void AppendRendererCommandLine(base::CommandLine* command_line) const;
298 // Copies applicable command line switches from the given |browser_cmd| line
299 // flags to the output |renderer_cmd| line flags. Not all switches will be
301 void PropagateBrowserCommandLineToRenderer(
302 const base::CommandLine& browser_cmd,
303 base::CommandLine* renderer_cmd) const;
305 // Callers can reduce the RenderProcess' priority.
306 void SetBackgrounded(bool backgrounded);
308 // Handle termination of our process.
309 void ProcessDied(bool already_dead);
311 virtual void OnGpuSwitching() OVERRIDE;
313 #if defined(ENABLE_WEBRTC)
314 // Sends |file_for_transit| to the render process.
315 void SendAecDumpFileToRenderer(IPC::PlatformFileForTransit file_for_transit);
316 void SendDisableAecDumpToRenderer();
319 scoped_ptr<MojoApplicationHost> mojo_application_host_;
320 bool mojo_activation_required_;
322 // The registered IPC listener objects. When this list is empty, we should
324 IDMap<IPC::Listener> listeners_;
326 // The count of currently visible widgets. Since the host can be a container
327 // for multiple widgets, it uses this count to determine when it should be
329 int32 visible_widgets_;
331 // Does this process have backgrounded priority.
334 // Used to allow a RenderWidgetHost to intercept various messages on the
336 scoped_refptr<RenderWidgetHelper> widget_helper_;
338 // The filter for GPU-related messages coming from the renderer.
339 // Thread safety note: this field is to be accessed from the UI thread.
340 // We don't keep a reference to it, to avoid it being destroyed on the UI
341 // thread, but we clear this field when we clear channel_. When channel_ goes
342 // away, it posts a task to the IO thread to destroy it there, so we know that
343 // it's valid if non-NULL.
344 GpuMessageFilter* gpu_message_filter_;
346 // The filter for MessagePort messages coming from the renderer.
347 scoped_refptr<MessagePortMessageFilter> message_port_message_filter_;
349 // Used in single-process mode.
350 scoped_ptr<base::Thread> in_process_renderer_;
352 // True after Init() has been called. We can't just check channel_ because we
353 // also reset that in the case of process termination.
354 bool is_initialized_;
356 // Used to launch and terminate the process without blocking the UI thread.
357 scoped_ptr<ChildProcessLauncher> child_process_launcher_;
359 // Messages we queue while waiting for the process handle. We queue them here
360 // instead of in the channel so that we ensure they're sent after init related
361 // messages that are sent once the process handle is available. This is
362 // because the queued messages may have dependencies on the init messages.
363 std::queue<IPC::Message*> queued_messages_;
365 // The globally-unique identifier for this RPH.
368 BrowserContext* browser_context_;
370 // Owned by |browser_context_|.
371 StoragePartitionImpl* storage_partition_impl_;
373 // The observers watching our lifetime.
374 ObserverList<RenderProcessHostObserver> observers_;
376 // True if the process can be shut down suddenly. If this is true, then we're
377 // sure that all the RenderViews in the process can be shutdown suddenly. If
378 // it's false, then specific RenderViews might still be allowed to be shutdown
379 // suddenly by checking their SuddenTerminationAllowed() flag. This can occur
380 // if one WebContents has an unload event listener but another WebContents in
381 // the same process doesn't.
382 bool sudden_termination_allowed_;
384 // Set to true if we shouldn't send input events. We actually do the
385 // filtering for this at the render widget level.
386 bool ignore_input_events_;
388 // Records the last time we regarded the child process active.
389 base::TimeTicks child_process_activity_time_;
391 // Indicates whether this is a RenderProcessHost of a Browser Plugin guest
395 // Forwards messages between WebRTCInternals in the browser process
396 // and PeerConnectionTracker in the renderer process.
397 scoped_refptr<PeerConnectionTrackerHost> peer_connection_tracker_host_;
399 // Prevents the class from being added as a GpuDataManagerImpl observer more
401 bool gpu_observer_registered_;
403 // Set if a call to Cleanup is required once the RenderProcessHostImpl is no
404 // longer within the RenderProcessHostObserver::RenderProcessExited callbacks.
405 bool delayed_cleanup_needed_;
407 // Indicates whether RenderProcessHostImpl is currently iterating and calling
408 // through RenderProcessHostObserver::RenderProcessExited.
409 bool within_process_died_observer_;
411 // Forwards power state messages to the renderer process.
412 PowerMonitorMessageBroadcaster power_monitor_broadcaster_;
414 scoped_refptr<AudioRendererHost> audio_renderer_host_;
416 #if defined(OS_ANDROID)
417 scoped_refptr<BrowserDemuxerAndroid> browser_demuxer_android_;
420 // Message filter for geolocation messages.
421 GeolocationDispatcherHost* geolocation_dispatcher_host_;
423 #if defined(ENABLE_WEBRTC)
424 base::Callback<void(const std::string&)> webrtc_log_message_callback_;
427 // Message filter and dispatcher for screen orientation.
428 ScreenOrientationDispatcherHost* screen_orientation_dispatcher_host_;
430 int worker_ref_count_;
432 // Records the time when the process starts surviving for workers for UMA.
433 base::TimeTicks survive_for_worker_start_time_;
435 base::WeakPtrFactory<RenderProcessHostImpl> weak_factory_;
437 DISALLOW_COPY_AND_ASSIGN(RenderProcessHostImpl);
440 } // namespace content
442 #endif // CONTENT_BROWSER_RENDERER_HOST_BROWSER_RENDER_PROCESS_HOST_IMPL_H_