Upstream version 5.34.104.0
[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/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"
25
26 class CommandLine;
27 struct ViewHostMsg_CompositorSurfaceBuffersSwapped_Params;
28
29 namespace base {
30 class MessageLoop;
31 }
32
33 namespace gfx {
34 class Size;
35 }
36
37 namespace content {
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;
51
52 // Implements a concrete RenderProcessHost for the browser process for talking
53 // to actual renderer processes (as opposed to mocks).
54 //
55 // Represents the browser side of the browser <--> renderer communication
56 // channel. There will be one RenderProcessHost per renderer process.
57 //
58 // This object is refcounted so that it can release its resources when all
59 // hosts using it go away.
60 //
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.
66 //
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 {
75  public:
76   RenderProcessHostImpl(BrowserContext* browser_context,
77                         StoragePartitionImpl* storage_partition_impl,
78                         bool supports_browser_plugin,
79                         bool is_guest);
80   virtual ~RenderProcessHostImpl();
81
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;
128 #endif
129   virtual void ResumeDeferredNavigation(const GlobalRequestID& request_id)
130       OVERRIDE;
131
132   // IPC::Sender via RenderProcessHost.
133   virtual bool Send(IPC::Message* msg) OVERRIDE;
134
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;
139
140   // ChildProcessLauncher::Client implementation.
141   virtual void OnProcessLaunched() OVERRIDE;
142
143   scoped_refptr<AudioRendererHost> audio_renderer_host() const;
144
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();
149   }
150
151   // Returns the current number of active views in this process.  Excludes
152   // any RenderViewHosts that are swapped out.
153   int GetActiveViewCount();
154
155   // Start and end frame subscription for a specific renderer.
156   // This API only supports subscription to accelerated composited frames.
157   void BeginFrameSubscription(
158       int route_id,
159       scoped_ptr<RenderWidgetHostViewFrameSubscriber> subscriber);
160   void EndFrameSubscription(int route_id);
161
162   scoped_refptr<GeolocationDispatcherHost>
163       geolocation_dispatcher_host() const {
164     return make_scoped_refptr(geolocation_dispatcher_host_);
165   }
166
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);
170 #endif
171
172   // Register/unregister the host identified by the host id in the global host
173   // list.
174   static void RegisterHost(int host_id, RenderProcessHost* host);
175   static void UnregisterHost(int host_id);
176
177   // Implementation of FilterURL below that can be shared with the mock class.
178   static void FilterURL(RenderProcessHost* rph, bool empty_allowed, GURL* url);
179
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);
185
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,
194       const GURL& url);
195
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,
204       const GURL& url);
205
206   static base::MessageLoop* GetInProcessRendererThreadForTesting();
207
208   // This forces a renderer that is running "in process" to shut down.
209   static void ShutDownInProcessRenderer();
210
211 #if defined(OS_ANDROID)
212   const scoped_refptr<BrowserDemuxerAndroid>& browser_demuxer_android() {
213     return browser_demuxer_android_;
214   }
215 #endif
216
217   MessagePortMessageFilter* message_port_message_filter() const {
218     return message_port_message_filter_;
219   }
220
221   void SetIsGuestForTesting(bool is_guest) {
222     is_guest_ = is_guest;
223   }
224
225  protected:
226   // A proxy for our IPC::Channel that lives on the IO thread (see
227   // browser_process.h)
228   scoped_ptr<IPC::ChannelProxy> channel_;
229
230   // True if fast shutdown has been performed on this RPH.
231   bool fast_shutdown_started_;
232
233   // True if we've posted a DeleteTask and will be deleted soon.
234   bool deleting_soon_;
235
236 #ifndef NDEBUG
237   // True if this object has deleted itself.
238   bool is_self_deleted_;
239 #endif
240
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_;
245
246  private:
247   friend class VisitRelayingRenderProcessHost;
248
249   // Creates and adds the IO thread message filters.
250   void CreateMessageFilters();
251
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);
258
259   // CompositorSurfaceBuffersSwapped handler when there's no RWH.
260   void OnCompositorSurfaceBuffersSwappedNoHost(
261       const ViewHostMsg_CompositorSurfaceBuffersSwapped_Params& params);
262
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;
266
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
269   // copied over.
270   void PropagateBrowserCommandLineToRenderer(const CommandLine& browser_cmd,
271                                              CommandLine* renderer_cmd) const;
272
273   // Callers can reduce the RenderProcess' priority.
274   void SetBackgrounded(bool backgrounded);
275
276   // Handle termination of our process.
277   void ProcessDied(bool already_dead);
278
279   virtual void OnGpuSwitching() OVERRIDE;
280
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();
285 #endif
286
287   // The registered IPC listener objects. When this list is empty, we should
288   // delete ourselves.
289   IDMap<IPC::Listener> listeners_;
290
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
293   // backgrounded.
294   int32 visible_widgets_;
295
296   // Does this process have backgrounded priority.
297   bool backgrounded_;
298
299   // Used to allow a RenderWidgetHost to intercept various messages on the
300   // IO thread.
301   scoped_refptr<RenderWidgetHelper> widget_helper_;
302
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_;
310
311   // The filter for MessagePort messages coming from the renderer.
312   scoped_refptr<MessagePortMessageFilter> message_port_message_filter_;
313
314   // A map of transport DIB ids to cached TransportDIBs
315   std::map<TransportDIB::Id, TransportDIB*> cached_dibs_;
316
317   enum {
318     // This is the maximum size of |cached_dibs_|
319     MAX_MAPPED_TRANSPORT_DIBS = 3,
320   };
321
322   void ClearTransportDIBCache();
323   // This is used to clear our cache five seconds after the last use.
324   base::DelayTimer<RenderProcessHostImpl> cached_dibs_cleaner_;
325
326   // Used in single-process mode.
327   scoped_ptr<base::Thread> in_process_renderer_;
328
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_;
332
333   // Used to launch and terminate the process without blocking the UI thread.
334   scoped_ptr<ChildProcessLauncher> child_process_launcher_;
335
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_;
341
342   // The globally-unique identifier for this RPH.
343   int id_;
344
345   BrowserContext* browser_context_;
346
347   // Owned by |browser_context_|.
348   StoragePartitionImpl* storage_partition_impl_;
349
350   // The observers watching our lifetime.
351   ObserverList<RenderProcessHostObserver> observers_;
352
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_;
360
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_;
364
365   // Records the last time we regarded the child process active.
366   base::TimeTicks child_process_activity_time_;
367
368   // Indicates whether this is a RenderProcessHost that has permission to embed
369   // Browser Plugins.
370   bool supports_browser_plugin_;
371
372   // Indicates whether this is a RenderProcessHost of a Browser Plugin guest
373   // renderer.
374   bool is_guest_;
375
376   // Forwards messages between WebRTCInternals in the browser process
377   // and PeerConnectionTracker in the renderer process.
378   scoped_refptr<PeerConnectionTrackerHost> peer_connection_tracker_host_;
379
380   // Prevents the class from being added as a GpuDataManagerImpl observer more
381   // than once.
382   bool gpu_observer_registered_;
383
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_;
387
388   // Indicates whether RenderProcessHostImpl is currently iterating and calling
389   // through RenderProcessHostObserver::RenderProcessExited.
390   bool within_process_died_observer_;
391
392   // Forwards power state messages to the renderer process.
393   PowerMonitorMessageBroadcaster power_monitor_broadcaster_;
394
395   scoped_refptr<AudioRendererHost> audio_renderer_host_;
396
397 #if defined(OS_ANDROID)
398   scoped_refptr<BrowserDemuxerAndroid> browser_demuxer_android_;
399 #endif
400
401   // Message filter for geolocation messages.
402   GeolocationDispatcherHost* geolocation_dispatcher_host_;
403
404 #if defined(ENABLE_WEBRTC)
405   base::Callback<void(const std::string&)> webrtc_log_message_callback_;
406 #endif
407
408   // Lives on the browser's ChildThread.
409   base::WeakPtrFactory<RenderProcessHostImpl> weak_factory_;
410
411   DISALLOW_COPY_AND_ASSIGN(RenderProcessHostImpl);
412 };
413
414 }  // namespace content
415
416 #endif  // CONTENT_BROWSER_RENDERER_HOST_BROWSER_RENDER_PROCESS_HOST_IMPL_H_