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