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