Update To 11.40.268.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_RENDER_PROCESS_HOST_IMPL_H_
6 #define CONTENT_BROWSER_RENDERER_HOST_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 "content/browser/child_process_launcher.h"
16 #include "content/browser/dom_storage/session_storage_namespace_impl.h"
17 #include "content/browser/power_monitor_message_broadcaster.h"
18 #include "content/common/content_export.h"
19 #include "content/common/mojo/service_registry_impl.h"
20 #include "content/public/browser/render_process_host.h"
21 #include "ipc/ipc_channel_proxy.h"
22 #include "ipc/ipc_platform_file.h"
23 #include "mojo/public/cpp/bindings/interface_ptr.h"
24 #include "ui/gfx/gpu_memory_buffer.h"
25 #include "ui/gl/gpu_switching_observer.h"
26
27 namespace base {
28 class CommandLine;
29 class MessageLoop;
30 }
31
32 namespace gfx {
33 class Size;
34 }
35
36 namespace IPC {
37 class ChannelMojoHost;
38 }
39
40 namespace content {
41 class AudioRendererHost;
42 class BrowserCdmManager;
43 class BrowserDemuxerAndroid;
44 class GpuMessageFilter;
45 class MessagePortMessageFilter;
46 class MojoApplicationHost;
47 class NotificationMessageFilter;
48 #if defined(ENABLE_WEBRTC)
49 class P2PSocketDispatcherHost;
50 #endif
51 class PeerConnectionTrackerHost;
52 class RendererMainThread;
53 class RenderWidgetHelper;
54 class RenderWidgetHost;
55 class RenderWidgetHostImpl;
56 class RenderWidgetHostViewFrameSubscriber;
57 class StoragePartition;
58 class StoragePartitionImpl;
59
60 typedef base::Thread* (*RendererMainThreadFactoryFunction)(
61     const std::string& id);
62
63 // Implements a concrete RenderProcessHost for the browser process for talking
64 // to actual renderer processes (as opposed to mocks).
65 //
66 // Represents the browser side of the browser <--> renderer communication
67 // channel. There will be one RenderProcessHost per renderer process.
68 //
69 // This object is refcounted so that it can release its resources when all
70 // hosts using it go away.
71 //
72 // This object communicates back and forth with the RenderProcess object
73 // running in the renderer process. Each RenderProcessHost and RenderProcess
74 // keeps a list of RenderView (renderer) and WebContentsImpl (browser) which
75 // are correlated with IDs. This way, the Views and the corresponding ViewHosts
76 // communicate through the two process objects.
77 //
78 // A RenderProcessHost is also associated with one and only one
79 // StoragePartition.  This allows us to implement strong storage isolation
80 // because all the IPCs from the RenderViews (renderer) will only ever be able
81 // to access the partition they are assigned to.
82 class CONTENT_EXPORT RenderProcessHostImpl
83     : public RenderProcessHost,
84       public ChildProcessLauncher::Client,
85       public ui::GpuSwitchingObserver {
86  public:
87   RenderProcessHostImpl(BrowserContext* browser_context,
88                         StoragePartitionImpl* storage_partition_impl,
89                         bool is_isolated_guest);
90   ~RenderProcessHostImpl() override;
91
92   // RenderProcessHost implementation (public portion).
93   void EnableSendQueue() override;
94   bool Init() override;
95   int GetNextRoutingID() override;
96   void AddRoute(int32 routing_id, IPC::Listener* listener) override;
97   void RemoveRoute(int32 routing_id) override;
98   void AddObserver(RenderProcessHostObserver* observer) override;
99   void RemoveObserver(RenderProcessHostObserver* observer) override;
100   void ReceivedBadMessage() override;
101   void WidgetRestored() override;
102   void WidgetHidden() override;
103   int VisibleWidgetCount() const override;
104   bool IsIsolatedGuest() const override;
105   StoragePartition* GetStoragePartition() const override;
106   bool FastShutdownIfPossible() override;
107   void DumpHandles() override;
108   base::ProcessHandle GetHandle() const override;
109   BrowserContext* GetBrowserContext() const override;
110   bool InSameStoragePartition(StoragePartition* partition) const override;
111   int GetID() const override;
112   bool HasConnection() const override;
113   void SetIgnoreInputEvents(bool ignore_input_events) override;
114   bool IgnoreInputEvents() const override;
115   void Cleanup() override;
116   void AddPendingView() override;
117   void RemovePendingView() override;
118   void SetSuddenTerminationAllowed(bool enabled) override;
119   bool SuddenTerminationAllowed() const override;
120   IPC::ChannelProxy* GetChannel() override;
121   void AddFilter(BrowserMessageFilter* filter) override;
122   bool FastShutdownForPageCount(size_t count) override;
123   bool FastShutdownStarted() const override;
124   base::TimeDelta GetChildProcessIdleTime() const override;
125   void ResumeRequestsForView(int route_id) override;
126   void FilterURL(bool empty_allowed, GURL* url) override;
127 #if defined(ENABLE_WEBRTC)
128   void EnableAecDump(const base::FilePath& file) override;
129   void DisableAecDump() override;
130   void SetWebRtcLogMessageCallback(
131       base::Callback<void(const std::string&)> callback) override;
132   WebRtcStopRtpDumpCallback StartRtpDump(
133       bool incoming,
134       bool outgoing,
135       const WebRtcRtpPacketCallback& packet_callback) override;
136 #endif
137   void ResumeDeferredNavigation(const GlobalRequestID& request_id) override;
138   void NotifyTimezoneChange() override;
139   ServiceRegistry* GetServiceRegistry() override;
140   const base::TimeTicks& GetInitTimeForNavigationMetrics() const override;
141
142   // IPC::Sender via RenderProcessHost.
143   bool Send(IPC::Message* msg) override;
144
145   // IPC::Listener via RenderProcessHost.
146   bool OnMessageReceived(const IPC::Message& msg) override;
147   void OnChannelConnected(int32 peer_pid) override;
148   void OnChannelError() override;
149   void OnBadMessageReceived(const IPC::Message& message) override;
150
151   // ChildProcessLauncher::Client implementation.
152   void OnProcessLaunched() override;
153
154   scoped_refptr<AudioRendererHost> audio_renderer_host() const;
155
156   // Call this function when it is evident that the child process is actively
157   // performing some operation, for example if we just received an IPC message.
158   void mark_child_process_activity_time() {
159     child_process_activity_time_ = base::TimeTicks::Now();
160   }
161
162   // Returns the current number of active views in this process.  Excludes
163   // any RenderViewHosts that are swapped out.
164   int GetActiveViewCount();
165
166   // Start and end frame subscription for a specific renderer.
167   // This API only supports subscription to accelerated composited frames.
168   void BeginFrameSubscription(
169       int route_id,
170       scoped_ptr<RenderWidgetHostViewFrameSubscriber> subscriber);
171   void EndFrameSubscription(int route_id);
172
173 #if defined(ENABLE_WEBRTC)
174   // Fires the webrtc log message callback with |message|, if callback is set.
175   void WebRtcLogMessage(const std::string& message);
176 #endif
177
178   // Used to extend the lifetime of the sessions until the render view
179   // in the renderer is fully closed. This is static because its also called
180   // with mock hosts as input in test cases.
181   static void ReleaseOnCloseACK(
182       RenderProcessHost* host,
183       const SessionStorageNamespaceMap& sessions,
184       int view_route_id);
185
186   // Register/unregister the host identified by the host id in the global host
187   // list.
188   static void RegisterHost(int host_id, RenderProcessHost* host);
189   static void UnregisterHost(int host_id);
190
191   // Implementation of FilterURL below that can be shared with the mock class.
192   static void FilterURL(RenderProcessHost* rph, bool empty_allowed, GURL* url);
193
194   // Returns true if |host| is suitable for launching a new view with |site_url|
195   // in the given |browser_context|.
196   static bool IsSuitableHost(RenderProcessHost* host,
197                              BrowserContext* browser_context,
198                              const GURL& site_url);
199
200   // Returns an existing RenderProcessHost for |url| in |browser_context|,
201   // if one exists.  Otherwise a new RenderProcessHost should be created and
202   // registered using RegisterProcessHostForSite().
203   // This should only be used for process-per-site mode, which can be enabled
204   // globally with a command line flag or per-site, as determined by
205   // SiteInstanceImpl::ShouldUseProcessPerSite.
206   static RenderProcessHost* GetProcessHostForSite(
207       BrowserContext* browser_context,
208       const GURL& url);
209
210   // Registers the given |process| to be used for any instance of |url|
211   // within |browser_context|.
212   // This should only be used for process-per-site mode, which can be enabled
213   // globally with a command line flag or per-site, as determined by
214   // SiteInstanceImpl::ShouldUseProcessPerSite.
215   static void RegisterProcessHostForSite(
216       BrowserContext* browser_context,
217       RenderProcessHost* process,
218       const GURL& url);
219
220   static base::MessageLoop* GetInProcessRendererThreadForTesting();
221
222   // This forces a renderer that is running "in process" to shut down.
223   static void ShutDownInProcessRenderer();
224
225   static void RegisterRendererMainThreadFactory(
226       RendererMainThreadFactoryFunction create);
227
228 #if defined(OS_ANDROID)
229   const scoped_refptr<BrowserDemuxerAndroid>& browser_demuxer_android() {
230     return browser_demuxer_android_;
231   }
232 #endif
233
234 #if defined(ENABLE_BROWSER_CDMS)
235   const scoped_refptr<BrowserCdmManager>& browser_cdm_manager() {
236     return browser_cdm_manager_;
237   }
238 #endif
239
240   MessagePortMessageFilter* message_port_message_filter() const {
241     return message_port_message_filter_.get();
242   }
243
244   NotificationMessageFilter* notification_message_filter() const {
245     return notification_message_filter_.get();
246   }
247
248   void set_is_isolated_guest_for_testing(bool is_isolated_guest) {
249     is_isolated_guest_ = is_isolated_guest;
250   }
251
252   // Called when the existence of the other renderer process which is connected
253   // to the Worker in this renderer process has changed.
254   // It is only called when "enable-embedded-shared-worker" flag is set.
255   void IncrementWorkerRefCount();
256   void DecrementWorkerRefCount();
257
258   // Call this function to resume the navigation when it was deferred
259   // immediately after receiving response headers.
260   void ResumeResponseDeferredAtStart(const GlobalRequestID& request_id);
261
262  protected:
263   // A proxy for our IPC::Channel that lives on the IO thread (see
264   // browser_process.h)
265   scoped_ptr<IPC::ChannelProxy> channel_;
266
267   // A host object ChannelMojo needs. The lifetime is bound to
268   // the RenderProcessHostImpl, not the channel.
269   scoped_ptr<IPC::ChannelMojoHost> channel_mojo_host_;
270
271   // True if fast shutdown has been performed on this RPH.
272   bool fast_shutdown_started_;
273
274   // True if we've posted a DeleteTask and will be deleted soon.
275   bool deleting_soon_;
276
277 #ifndef NDEBUG
278   // True if this object has deleted itself.
279   bool is_self_deleted_;
280 #endif
281
282   // The count of currently swapped out but pending RenderViews.  We have
283   // started to swap these in, so the renderer process should not exit if
284   // this count is non-zero.
285   int32 pending_views_;
286
287  private:
288   friend class VisitRelayingRenderProcessHost;
289
290   bool ShouldUseMojoChannel() const;
291   scoped_ptr<IPC::ChannelProxy> CreateChannelProxy(
292       const std::string& channel_id);
293
294   // Creates and adds the IO thread message filters.
295   void CreateMessageFilters();
296
297   // Registers Mojo services to be exposed to the renderer.
298   void RegisterMojoServices();
299
300   // Control message handlers.
301   void OnShutdownRequest();
302   void OnDumpHandlesDone();
303   void SuddenTerminationChanged(bool enabled);
304   void OnUserMetricsRecordAction(const std::string& action);
305   void OnSavedPageAsMHTML(int job_id, int64 mhtml_file_size);
306   void OnCloseACK(int old_route_id);
307
308   // Generates a command line to be used to spawn a renderer and appends the
309   // results to |*command_line|.
310   void AppendRendererCommandLine(base::CommandLine* command_line) const;
311
312   // Copies applicable command line switches from the given |browser_cmd| line
313   // flags to the output |renderer_cmd| line flags. Not all switches will be
314   // copied over.
315   void PropagateBrowserCommandLineToRenderer(
316       const base::CommandLine& browser_cmd,
317       base::CommandLine* renderer_cmd) const;
318
319   // Callers can reduce the RenderProcess' priority.
320   void SetBackgrounded(bool backgrounded);
321
322   // Handle termination of our process.
323   void ProcessDied(bool already_dead);
324
325   // GpuSwitchingObserver implementation.
326   void OnGpuSwitched() override;
327
328 #if defined(ENABLE_WEBRTC)
329   void OnRegisterAecDumpConsumer(int id);
330   void OnUnregisterAecDumpConsumer(int id);
331   void RegisterAecDumpConsumerOnUIThread(int id);
332   void UnregisterAecDumpConsumerOnUIThread(int id);
333   void EnableAecDumpForId(const base::FilePath& file, int id);
334   // Sends |file_for_transit| to the render process.
335   void SendAecDumpFileToRenderer(int id,
336                                  IPC::PlatformFileForTransit file_for_transit);
337   void SendDisableAecDumpToRenderer();
338 #endif
339
340   scoped_ptr<MojoApplicationHost> mojo_application_host_;
341
342   // The registered IPC listener objects. When this list is empty, we should
343   // delete ourselves.
344   IDMap<IPC::Listener> listeners_;
345
346   // The count of currently visible widgets.  Since the host can be a container
347   // for multiple widgets, it uses this count to determine when it should be
348   // backgrounded.
349   int32 visible_widgets_;
350
351   // Does this process have backgrounded priority.
352   bool backgrounded_;
353
354   // Used to allow a RenderWidgetHost to intercept various messages on the
355   // IO thread.
356   scoped_refptr<RenderWidgetHelper> widget_helper_;
357
358   // The filter for GPU-related messages coming from the renderer.
359   // Thread safety note: this field is to be accessed from the UI thread.
360   // We don't keep a reference to it, to avoid it being destroyed on the UI
361   // thread, but we clear this field when we clear channel_. When channel_ goes
362   // away, it posts a task to the IO thread to destroy it there, so we know that
363   // it's valid if non-NULL.
364   GpuMessageFilter* gpu_message_filter_;
365
366   // The filter for MessagePort messages coming from the renderer.
367   scoped_refptr<MessagePortMessageFilter> message_port_message_filter_;
368
369   // The filter for Web Notification messages coming from the renderer. Holds a
370   // closure per notification that must be freed when the notification closes.
371   scoped_refptr<NotificationMessageFilter> notification_message_filter_;
372
373   // Used in single-process mode.
374   scoped_ptr<base::Thread> in_process_renderer_;
375
376   // True after Init() has been called. We can't just check channel_ because we
377   // also reset that in the case of process termination.
378   bool is_initialized_;
379
380   // PlzNavigate
381   // Stores the time at which the first call to Init happened.
382   base::TimeTicks init_time_;
383
384   // Used to launch and terminate the process without blocking the UI thread.
385   scoped_ptr<ChildProcessLauncher> child_process_launcher_;
386
387   // Messages we queue while waiting for the process handle.  We queue them here
388   // instead of in the channel so that we ensure they're sent after init related
389   // messages that are sent once the process handle is available.  This is
390   // because the queued messages may have dependencies on the init messages.
391   std::queue<IPC::Message*> queued_messages_;
392
393   // The globally-unique identifier for this RPH.
394   int id_;
395
396   BrowserContext* browser_context_;
397
398   // Owned by |browser_context_|.
399   StoragePartitionImpl* storage_partition_impl_;
400
401   // The observers watching our lifetime.
402   ObserverList<RenderProcessHostObserver> observers_;
403
404   // True if the process can be shut down suddenly.  If this is true, then we're
405   // sure that all the RenderViews in the process can be shutdown suddenly.  If
406   // it's false, then specific RenderViews might still be allowed to be shutdown
407   // suddenly by checking their SuddenTerminationAllowed() flag.  This can occur
408   // if one WebContents has an unload event listener but another WebContents in
409   // the same process doesn't.
410   bool sudden_termination_allowed_;
411
412   // Set to true if we shouldn't send input events.  We actually do the
413   // filtering for this at the render widget level.
414   bool ignore_input_events_;
415
416   // Records the last time we regarded the child process active.
417   base::TimeTicks child_process_activity_time_;
418
419   // Indicates whether this is a RenderProcessHost of a Browser Plugin guest
420   // renderer.
421   bool is_isolated_guest_;
422
423   // Forwards messages between WebRTCInternals in the browser process
424   // and PeerConnectionTracker in the renderer process.
425   scoped_refptr<PeerConnectionTrackerHost> peer_connection_tracker_host_;
426
427   // Prevents the class from being added as a GpuDataManagerImpl observer more
428   // than once.
429   bool gpu_observer_registered_;
430
431   // Set if a call to Cleanup is required once the RenderProcessHostImpl is no
432   // longer within the RenderProcessHostObserver::RenderProcessExited callbacks.
433   bool delayed_cleanup_needed_;
434
435   // Indicates whether RenderProcessHostImpl is currently iterating and calling
436   // through RenderProcessHostObserver::RenderProcessExited.
437   bool within_process_died_observer_;
438
439   // Forwards power state messages to the renderer process.
440   PowerMonitorMessageBroadcaster power_monitor_broadcaster_;
441
442   scoped_refptr<AudioRendererHost> audio_renderer_host_;
443
444 #if defined(OS_ANDROID)
445   scoped_refptr<BrowserDemuxerAndroid> browser_demuxer_android_;
446 #endif
447
448 #if defined(ENABLE_BROWSER_CDMS)
449   scoped_refptr<BrowserCdmManager> browser_cdm_manager_;
450 #endif
451
452 #if defined(ENABLE_WEBRTC)
453   base::Callback<void(const std::string&)> webrtc_log_message_callback_;
454
455   scoped_refptr<P2PSocketDispatcherHost> p2p_socket_dispatcher_host_;
456
457   // Must be accessed on UI thread.
458   std::vector<int> aec_dump_consumers_;
459
460   WebRtcStopRtpDumpCallback stop_rtp_dump_callback_;
461 #endif
462
463   int worker_ref_count_;
464
465   // Records the time when the process starts surviving for workers for UMA.
466   base::TimeTicks survive_for_worker_start_time_;
467
468   base::WeakPtrFactory<RenderProcessHostImpl> weak_factory_;
469
470   DISALLOW_COPY_AND_ASSIGN(RenderProcessHostImpl);
471 };
472
473 }  // namespace content
474
475 #endif  // CONTENT_BROWSER_RENDERER_HOST_RENDER_PROCESS_HOST_IMPL_H_