Upstream version 7.36.149.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 "mojo/public/cpp/bindings/interface_ptr.h"
25
26 struct ViewHostMsg_CompositorSurfaceBuffersSwapped_Params;
27
28 namespace base {
29 class CommandLine;
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 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;
54
55 typedef base::Thread* (*RendererMainThreadFactoryFunction)(
56     const std::string& id);
57
58 // Implements a concrete RenderProcessHost for the browser process for talking
59 // to actual renderer processes (as opposed to mocks).
60 //
61 // Represents the browser side of the browser <--> renderer communication
62 // channel. There will be one RenderProcessHost per renderer process.
63 //
64 // This object is refcounted so that it can release its resources when all
65 // hosts using it go away.
66 //
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.
72 //
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 {
81  public:
82   RenderProcessHostImpl(BrowserContext* browser_context,
83                         StoragePartitionImpl* storage_partition_impl,
84                         bool is_guest);
85   virtual ~RenderProcessHostImpl();
86
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;
131 #endif
132   virtual void ResumeDeferredNavigation(const GlobalRequestID& request_id)
133       OVERRIDE;
134   virtual void NotifyTimezoneChange() OVERRIDE;
135
136   // IPC::Sender via RenderProcessHost.
137   virtual bool Send(IPC::Message* msg) OVERRIDE;
138
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;
143
144   // ChildProcessLauncher::Client implementation.
145   virtual void OnProcessLaunched() OVERRIDE;
146
147   scoped_refptr<AudioRendererHost> audio_renderer_host() const;
148
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();
153   }
154
155   // Returns the current number of active views in this process.  Excludes
156   // any RenderViewHosts that are swapped out.
157   int GetActiveViewCount();
158
159   // Start and end frame subscription for a specific renderer.
160   // This API only supports subscription to accelerated composited frames.
161   void BeginFrameSubscription(
162       int route_id,
163       scoped_ptr<RenderWidgetHostViewFrameSubscriber> subscriber);
164   void EndFrameSubscription(int route_id);
165
166   scoped_refptr<GeolocationDispatcherHost>
167       geolocation_dispatcher_host() const {
168     return make_scoped_refptr(geolocation_dispatcher_host_);
169   }
170
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);
174 #endif
175
176   scoped_refptr<ScreenOrientationDispatcherHost>
177       screen_orientation_dispatcher_host() const;
178
179   // Register/unregister the host identified by the host id in the global host
180   // list.
181   static void RegisterHost(int host_id, RenderProcessHost* host);
182   static void UnregisterHost(int host_id);
183
184   // Implementation of FilterURL below that can be shared with the mock class.
185   static void FilterURL(RenderProcessHost* rph, bool empty_allowed, GURL* url);
186
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);
192
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,
201       const GURL& url);
202
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,
211       const GURL& url);
212
213   static base::MessageLoop* GetInProcessRendererThreadForTesting();
214
215   // This forces a renderer that is running "in process" to shut down.
216   static void ShutDownInProcessRenderer();
217
218   static void RegisterRendererMainThreadFactory(
219       RendererMainThreadFactoryFunction create);
220
221 #if defined(OS_ANDROID)
222   const scoped_refptr<BrowserDemuxerAndroid>& browser_demuxer_android() {
223     return browser_demuxer_android_;
224   }
225 #endif
226
227   MessagePortMessageFilter* message_port_message_filter() const {
228     return message_port_message_filter_;
229   }
230
231   void SetIsGuestForTesting(bool is_guest) {
232     is_guest_ = is_guest;
233   }
234
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();
240
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);
245
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());
252   }
253
254  protected:
255   // A proxy for our IPC::Channel that lives on the IO thread (see
256   // browser_process.h)
257   scoped_ptr<IPC::ChannelProxy> channel_;
258
259   // True if fast shutdown has been performed on this RPH.
260   bool fast_shutdown_started_;
261
262   // True if we've posted a DeleteTask and will be deleted soon.
263   bool deleting_soon_;
264
265 #ifndef NDEBUG
266   // True if this object has deleted itself.
267   bool is_self_deleted_;
268 #endif
269
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_;
274
275  private:
276   friend class VisitRelayingRenderProcessHost;
277
278   void MaybeActivateMojo();
279
280   // Creates and adds the IO thread message filters.
281   void CreateMessageFilters();
282
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);
289
290   // CompositorSurfaceBuffersSwapped handler when there's no RWH.
291   void OnCompositorSurfaceBuffersSwappedNoHost(
292       const ViewHostMsg_CompositorSurfaceBuffersSwapped_Params& params);
293
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;
297
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
300   // copied over.
301   void PropagateBrowserCommandLineToRenderer(
302       const base::CommandLine& browser_cmd,
303       base::CommandLine* renderer_cmd) const;
304
305   // Callers can reduce the RenderProcess' priority.
306   void SetBackgrounded(bool backgrounded);
307
308   // Handle termination of our process.
309   void ProcessDied(bool already_dead);
310
311   virtual void OnGpuSwitching() OVERRIDE;
312
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();
317 #endif
318
319   scoped_ptr<MojoApplicationHost> mojo_application_host_;
320   bool mojo_activation_required_;
321
322   // The registered IPC listener objects. When this list is empty, we should
323   // delete ourselves.
324   IDMap<IPC::Listener> listeners_;
325
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
328   // backgrounded.
329   int32 visible_widgets_;
330
331   // Does this process have backgrounded priority.
332   bool backgrounded_;
333
334   // Used to allow a RenderWidgetHost to intercept various messages on the
335   // IO thread.
336   scoped_refptr<RenderWidgetHelper> widget_helper_;
337
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_;
345
346   // The filter for MessagePort messages coming from the renderer.
347   scoped_refptr<MessagePortMessageFilter> message_port_message_filter_;
348
349   // Used in single-process mode.
350   scoped_ptr<base::Thread> in_process_renderer_;
351
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_;
355
356   // Used to launch and terminate the process without blocking the UI thread.
357   scoped_ptr<ChildProcessLauncher> child_process_launcher_;
358
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_;
364
365   // The globally-unique identifier for this RPH.
366   int id_;
367
368   BrowserContext* browser_context_;
369
370   // Owned by |browser_context_|.
371   StoragePartitionImpl* storage_partition_impl_;
372
373   // The observers watching our lifetime.
374   ObserverList<RenderProcessHostObserver> observers_;
375
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_;
383
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_;
387
388   // Records the last time we regarded the child process active.
389   base::TimeTicks child_process_activity_time_;
390
391   // Indicates whether this is a RenderProcessHost of a Browser Plugin guest
392   // renderer.
393   bool is_guest_;
394
395   // Forwards messages between WebRTCInternals in the browser process
396   // and PeerConnectionTracker in the renderer process.
397   scoped_refptr<PeerConnectionTrackerHost> peer_connection_tracker_host_;
398
399   // Prevents the class from being added as a GpuDataManagerImpl observer more
400   // than once.
401   bool gpu_observer_registered_;
402
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_;
406
407   // Indicates whether RenderProcessHostImpl is currently iterating and calling
408   // through RenderProcessHostObserver::RenderProcessExited.
409   bool within_process_died_observer_;
410
411   // Forwards power state messages to the renderer process.
412   PowerMonitorMessageBroadcaster power_monitor_broadcaster_;
413
414   scoped_refptr<AudioRendererHost> audio_renderer_host_;
415
416 #if defined(OS_ANDROID)
417   scoped_refptr<BrowserDemuxerAndroid> browser_demuxer_android_;
418 #endif
419
420   // Message filter for geolocation messages.
421   GeolocationDispatcherHost* geolocation_dispatcher_host_;
422
423 #if defined(ENABLE_WEBRTC)
424   base::Callback<void(const std::string&)> webrtc_log_message_callback_;
425 #endif
426
427   // Message filter and dispatcher for screen orientation.
428   ScreenOrientationDispatcherHost* screen_orientation_dispatcher_host_;
429
430   int worker_ref_count_;
431
432   // Records the time when the process starts surviving for workers for UMA.
433   base::TimeTicks survive_for_worker_start_time_;
434
435   base::WeakPtrFactory<RenderProcessHostImpl> weak_factory_;
436
437   DISALLOW_COPY_AND_ASSIGN(RenderProcessHostImpl);
438 };
439
440 }  // namespace content
441
442 #endif  // CONTENT_BROWSER_RENDERER_HOST_BROWSER_RENDER_PROCESS_HOST_IMPL_H_