Roll src/third_party/WebKit c63b89c:29324ab (svn 202546:202547)
[chromium-blink-merge.git] / content / browser / renderer_host / render_process_host_impl.h
blob8eff7f60ecfaaf98bfefced20d29ed0f64011b8f
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.
5 #ifndef CONTENT_BROWSER_RENDERER_HOST_RENDER_PROCESS_HOST_IMPL_H_
6 #define CONTENT_BROWSER_RENDERER_HOST_RENDER_PROCESS_HOST_IMPL_H_
8 #include <map>
9 #include <queue>
10 #include <string>
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 "third_party/mojo/src/mojo/public/cpp/bindings/interface_ptr.h"
24 #include "ui/gfx/gpu_memory_buffer.h"
25 #include "ui/gl/gpu_switching_observer.h"
27 #if defined(OS_MACOSX) && !defined(OS_IOS)
28 #include "content/common/mac/io_surface_manager_token.h"
29 #endif
31 namespace base {
32 class CommandLine;
33 class MessageLoop;
36 namespace gfx {
37 class Size;
40 namespace gpu {
41 class ValueStateMap;
44 namespace IPC {
45 class ChannelMojoHost;
48 namespace content {
49 class AudioInputRendererHost;
50 class AudioRendererHost;
51 class BluetoothDispatcherHost;
52 class BrowserCdmManager;
53 class BrowserDemuxerAndroid;
54 class GpuMessageFilter;
55 class InProcessChildThreadParams;
56 class MessagePortMessageFilter;
57 class MojoApplicationHost;
58 class NotificationMessageFilter;
59 #if defined(ENABLE_WEBRTC)
60 class P2PSocketDispatcherHost;
61 #endif
62 class PermissionServiceContext;
63 class PeerConnectionTrackerHost;
64 class RendererMainThread;
65 class RenderWidgetHelper;
66 class RenderWidgetHost;
67 class RenderWidgetHostImpl;
68 class RenderWidgetHostViewFrameSubscriber;
69 class StoragePartition;
70 class StoragePartitionImpl;
72 typedef base::Thread* (*RendererMainThreadFactoryFunction)(
73 const InProcessChildThreadParams& params);
75 // Implements a concrete RenderProcessHost for the browser process for talking
76 // to actual renderer processes (as opposed to mocks).
78 // Represents the browser side of the browser <--> renderer communication
79 // channel. There will be one RenderProcessHost per renderer process.
81 // This object is refcounted so that it can release its resources when all
82 // hosts using it go away.
84 // This object communicates back and forth with the RenderProcess object
85 // running in the renderer process. Each RenderProcessHost and RenderProcess
86 // keeps a list of RenderView (renderer) and WebContentsImpl (browser) which
87 // are correlated with IDs. This way, the Views and the corresponding ViewHosts
88 // communicate through the two process objects.
90 // A RenderProcessHost is also associated with one and only one
91 // StoragePartition. This allows us to implement strong storage isolation
92 // because all the IPCs from the RenderViews (renderer) will only ever be able
93 // to access the partition they are assigned to.
94 class CONTENT_EXPORT RenderProcessHostImpl
95 : public RenderProcessHost,
96 public ChildProcessLauncher::Client,
97 public ui::GpuSwitchingObserver {
98 public:
99 RenderProcessHostImpl(BrowserContext* browser_context,
100 StoragePartitionImpl* storage_partition_impl,
101 bool is_for_guests_only);
102 ~RenderProcessHostImpl() override;
104 // RenderProcessHost implementation (public portion).
105 void EnableSendQueue() override;
106 bool Init() override;
107 int GetNextRoutingID() override;
108 void AddRoute(int32 routing_id, IPC::Listener* listener) override;
109 void RemoveRoute(int32 routing_id) override;
110 void AddObserver(RenderProcessHostObserver* observer) override;
111 void RemoveObserver(RenderProcessHostObserver* observer) override;
112 void ShutdownForBadMessage() override;
113 void WidgetRestored() override;
114 void WidgetHidden() override;
115 int VisibleWidgetCount() const override;
116 bool IsForGuestsOnly() const override;
117 StoragePartition* GetStoragePartition() const override;
118 bool Shutdown(int exit_code, bool wait) override;
119 bool FastShutdownIfPossible() override;
120 base::ProcessHandle GetHandle() const override;
121 BrowserContext* GetBrowserContext() const override;
122 bool InSameStoragePartition(StoragePartition* partition) const override;
123 int GetID() const override;
124 bool HasConnection() const override;
125 void SetIgnoreInputEvents(bool ignore_input_events) override;
126 bool IgnoreInputEvents() const override;
127 void Cleanup() override;
128 void AddPendingView() override;
129 void RemovePendingView() override;
130 void SetSuddenTerminationAllowed(bool enabled) override;
131 bool SuddenTerminationAllowed() const override;
132 IPC::ChannelProxy* GetChannel() override;
133 void AddFilter(BrowserMessageFilter* filter) override;
134 bool FastShutdownForPageCount(size_t count) override;
135 bool FastShutdownStarted() const override;
136 base::TimeDelta GetChildProcessIdleTime() const override;
137 void ResumeRequestsForView(int route_id) override;
138 void FilterURL(bool empty_allowed, GURL* url) override;
139 #if defined(ENABLE_WEBRTC)
140 void EnableAudioDebugRecordings(const base::FilePath& file) override;
141 void DisableAudioDebugRecordings() override;
142 void SetWebRtcLogMessageCallback(
143 base::Callback<void(const std::string&)> callback) override;
144 WebRtcStopRtpDumpCallback StartRtpDump(
145 bool incoming,
146 bool outgoing,
147 const WebRtcRtpPacketCallback& packet_callback) override;
148 #endif
149 void ResumeDeferredNavigation(const GlobalRequestID& request_id) override;
150 void NotifyTimezoneChange(const std::string& timezone) override;
151 ServiceRegistry* GetServiceRegistry() override;
152 const base::TimeTicks& GetInitTimeForNavigationMetrics() const override;
153 bool SubscribeUniformEnabled() const override;
154 void OnAddSubscription(unsigned int target) override;
155 void OnRemoveSubscription(unsigned int target) override;
156 void SendUpdateValueState(
157 unsigned int target, const gpu::ValueState& state) override;
158 #if defined(ENABLE_BROWSER_CDMS)
159 media::BrowserCdm* GetBrowserCdm(int render_frame_id,
160 int cdm_id) const override;
161 #endif
163 // IPC::Sender via RenderProcessHost.
164 bool Send(IPC::Message* msg) override;
166 // IPC::Listener via RenderProcessHost.
167 bool OnMessageReceived(const IPC::Message& msg) override;
168 void OnChannelConnected(int32 peer_pid) override;
169 void OnChannelError() override;
170 void OnBadMessageReceived(const IPC::Message& message) override;
172 // ChildProcessLauncher::Client implementation.
173 void OnProcessLaunched() override;
174 void OnProcessLaunchFailed() override;
176 scoped_refptr<AudioRendererHost> audio_renderer_host() const;
178 // Call this function when it is evident that the child process is actively
179 // performing some operation, for example if we just received an IPC message.
180 void mark_child_process_activity_time() {
181 child_process_activity_time_ = base::TimeTicks::Now();
184 // Start and end frame subscription for a specific renderer.
185 // This API only supports subscription to accelerated composited frames.
186 void BeginFrameSubscription(
187 int route_id,
188 scoped_ptr<RenderWidgetHostViewFrameSubscriber> subscriber);
189 void EndFrameSubscription(int route_id);
191 #if defined(ENABLE_WEBRTC)
192 // Fires the webrtc log message callback with |message|, if callback is set.
193 void WebRtcLogMessage(const std::string& message);
194 #endif
196 // Used to extend the lifetime of the sessions until the render view
197 // in the renderer is fully closed. This is static because its also called
198 // with mock hosts as input in test cases.
199 static void ReleaseOnCloseACK(
200 RenderProcessHost* host,
201 const SessionStorageNamespaceMap& sessions,
202 int view_route_id);
204 // Register/unregister the host identified by the host id in the global host
205 // list.
206 static void RegisterHost(int host_id, RenderProcessHost* host);
207 static void UnregisterHost(int host_id);
209 // Implementation of FilterURL below that can be shared with the mock class.
210 static void FilterURL(RenderProcessHost* rph, bool empty_allowed, GURL* url);
212 // Returns true if |host| is suitable for launching a new view with |site_url|
213 // in the given |browser_context|.
214 static bool IsSuitableHost(RenderProcessHost* host,
215 BrowserContext* browser_context,
216 const GURL& site_url);
218 // Returns an existing RenderProcessHost for |url| in |browser_context|,
219 // if one exists. Otherwise a new RenderProcessHost should be created and
220 // registered using RegisterProcessHostForSite().
221 // This should only be used for process-per-site mode, which can be enabled
222 // globally with a command line flag or per-site, as determined by
223 // SiteInstanceImpl::ShouldUseProcessPerSite.
224 static RenderProcessHost* GetProcessHostForSite(
225 BrowserContext* browser_context,
226 const GURL& url);
228 // Registers the given |process| to be used for any instance of |url|
229 // within |browser_context|.
230 // This should only be used for process-per-site mode, which can be enabled
231 // globally with a command line flag or per-site, as determined by
232 // SiteInstanceImpl::ShouldUseProcessPerSite.
233 static void RegisterProcessHostForSite(
234 BrowserContext* browser_context,
235 RenderProcessHost* process,
236 const GURL& url);
238 static base::MessageLoop* GetInProcessRendererThreadForTesting();
240 // This forces a renderer that is running "in process" to shut down.
241 static void ShutDownInProcessRenderer();
243 static void RegisterRendererMainThreadFactory(
244 RendererMainThreadFactoryFunction create);
246 #if defined(OS_ANDROID)
247 const scoped_refptr<BrowserDemuxerAndroid>& browser_demuxer_android() {
248 return browser_demuxer_android_;
250 #endif
252 MessagePortMessageFilter* message_port_message_filter() const {
253 return message_port_message_filter_.get();
256 NotificationMessageFilter* notification_message_filter() const {
257 return notification_message_filter_.get();
260 void set_is_for_guests_only_for_testing(bool is_for_guests_only) {
261 is_for_guests_only_ = is_for_guests_only;
264 // Called when the existence of the other renderer process which is connected
265 // to the Worker in this renderer process has changed.
266 // It is only called when "enable-embedded-shared-worker" flag is set.
267 void IncrementWorkerRefCount();
268 void DecrementWorkerRefCount();
270 void GetAudioOutputControllers(
271 const GetAudioOutputControllersCallback& callback) const override;
273 BluetoothDispatcherHost* GetBluetoothDispatcherHost();
275 protected:
276 // A proxy for our IPC::Channel that lives on the IO thread (see
277 // browser_process.h)
278 scoped_ptr<IPC::ChannelProxy> channel_;
280 // True if fast shutdown has been performed on this RPH.
281 bool fast_shutdown_started_;
283 // True if we've posted a DeleteTask and will be deleted soon.
284 bool deleting_soon_;
286 #ifndef NDEBUG
287 // True if this object has deleted itself.
288 bool is_self_deleted_;
289 #endif
291 // The count of currently swapped out but pending RenderViews. We have
292 // started to swap these in, so the renderer process should not exit if
293 // this count is non-zero.
294 int32 pending_views_;
296 private:
297 friend class VisitRelayingRenderProcessHost;
298 friend class ChildProcessLauncherBrowserTest_ChildSpawnFail_Test;
300 scoped_ptr<IPC::ChannelProxy> CreateChannelProxy(
301 const std::string& channel_id);
303 // Creates and adds the IO thread message filters.
304 void CreateMessageFilters();
306 // Registers Mojo services to be exposed to the renderer.
307 void RegisterMojoServices();
309 // Control message handlers.
310 void OnShutdownRequest();
311 void SuddenTerminationChanged(bool enabled);
312 void OnUserMetricsRecordAction(const std::string& action);
313 void OnSavedPageAsMHTML(int job_id, int64 mhtml_file_size);
314 void OnCloseACK(int old_route_id);
316 // Generates a command line to be used to spawn a renderer and appends the
317 // results to |*command_line|.
318 void AppendRendererCommandLine(base::CommandLine* command_line) const;
320 // Copies applicable command line switches from the given |browser_cmd| line
321 // flags to the output |renderer_cmd| line flags. Not all switches will be
322 // copied over.
323 void PropagateBrowserCommandLineToRenderer(
324 const base::CommandLine& browser_cmd,
325 base::CommandLine* renderer_cmd) const;
327 // Callers can reduce the RenderProcess' priority.
328 void SetBackgrounded(bool backgrounded);
330 // Handle termination of our process.
331 void ProcessDied(bool already_dead, RendererClosedDetails* known_details);
333 // GpuSwitchingObserver implementation.
334 void OnGpuSwitched() override;
336 #if defined(ENABLE_WEBRTC)
337 void OnRegisterAecDumpConsumer(int id);
338 void OnUnregisterAecDumpConsumer(int id);
339 void RegisterAecDumpConsumerOnUIThread(int id);
340 void UnregisterAecDumpConsumerOnUIThread(int id);
341 void EnableAecDumpForId(const base::FilePath& file, int id);
342 // Sends |file_for_transit| to the render process.
343 void SendAecDumpFileToRenderer(int id,
344 IPC::PlatformFileForTransit file_for_transit);
345 void SendDisableAecDumpToRenderer();
346 base::FilePath GetAecDumpFilePathWithExtensions(const base::FilePath& file);
347 #endif
349 scoped_ptr<MojoApplicationHost> mojo_application_host_;
351 // The registered IPC listener objects. When this list is empty, we should
352 // delete ourselves.
353 IDMap<IPC::Listener> listeners_;
355 // The count of currently visible widgets. Since the host can be a container
356 // for multiple widgets, it uses this count to determine when it should be
357 // backgrounded.
358 int32 visible_widgets_;
360 // Does this process have backgrounded priority.
361 bool backgrounded_;
363 // Used to allow a RenderWidgetHost to intercept various messages on the
364 // IO thread.
365 scoped_refptr<RenderWidgetHelper> widget_helper_;
367 // The filter for GPU-related messages coming from the renderer.
368 // Thread safety note: this field is to be accessed from the UI thread.
369 // We don't keep a reference to it, to avoid it being destroyed on the UI
370 // thread, but we clear this field when we clear channel_. When channel_ goes
371 // away, it posts a task to the IO thread to destroy it there, so we know that
372 // it's valid if non-NULL.
373 GpuMessageFilter* gpu_message_filter_;
375 // The filter for MessagePort messages coming from the renderer.
376 scoped_refptr<MessagePortMessageFilter> message_port_message_filter_;
378 // The filter for Web Notification messages coming from the renderer. Holds a
379 // closure per notification that must be freed when the notification closes.
380 scoped_refptr<NotificationMessageFilter> notification_message_filter_;
382 // Used in single-process mode.
383 scoped_ptr<base::Thread> in_process_renderer_;
385 // True after Init() has been called. We can't just check channel_ because we
386 // also reset that in the case of process termination.
387 bool is_initialized_;
389 // PlzNavigate
390 // Stores the time at which the first call to Init happened.
391 base::TimeTicks init_time_;
393 // Used to launch and terminate the process without blocking the UI thread.
394 scoped_ptr<ChildProcessLauncher> child_process_launcher_;
396 // Messages we queue while waiting for the process handle. We queue them here
397 // instead of in the channel so that we ensure they're sent after init related
398 // messages that are sent once the process handle is available. This is
399 // because the queued messages may have dependencies on the init messages.
400 std::queue<IPC::Message*> queued_messages_;
402 // The globally-unique identifier for this RPH.
403 int id_;
405 BrowserContext* browser_context_;
407 // Owned by |browser_context_|.
408 StoragePartitionImpl* storage_partition_impl_;
410 // The observers watching our lifetime.
411 base::ObserverList<RenderProcessHostObserver> observers_;
413 // True if the process can be shut down suddenly. If this is true, then we're
414 // sure that all the RenderViews in the process can be shutdown suddenly. If
415 // it's false, then specific RenderViews might still be allowed to be shutdown
416 // suddenly by checking their SuddenTerminationAllowed() flag. This can occur
417 // if one WebContents has an unload event listener but another WebContents in
418 // the same process doesn't.
419 bool sudden_termination_allowed_;
421 // Set to true if we shouldn't send input events. We actually do the
422 // filtering for this at the render widget level.
423 bool ignore_input_events_;
425 // Records the last time we regarded the child process active.
426 base::TimeTicks child_process_activity_time_;
428 // Indicates whether this RenderProcessHost is exclusively hosting guest
429 // RenderFrames.
430 bool is_for_guests_only_;
432 // Forwards messages between WebRTCInternals in the browser process
433 // and PeerConnectionTracker in the renderer process.
434 scoped_refptr<PeerConnectionTrackerHost> peer_connection_tracker_host_;
436 // Prevents the class from being added as a GpuDataManagerImpl observer more
437 // than once.
438 bool gpu_observer_registered_;
440 // Set if a call to Cleanup is required once the RenderProcessHostImpl is no
441 // longer within the RenderProcessHostObserver::RenderProcessExited callbacks.
442 bool delayed_cleanup_needed_;
444 // Indicates whether RenderProcessHostImpl is currently iterating and calling
445 // through RenderProcessHostObserver::RenderProcessExited.
446 bool within_process_died_observer_;
448 // Forwards power state messages to the renderer process.
449 PowerMonitorMessageBroadcaster power_monitor_broadcaster_;
451 scoped_refptr<AudioRendererHost> audio_renderer_host_;
453 scoped_refptr<AudioInputRendererHost> audio_input_renderer_host_;
455 scoped_refptr<BluetoothDispatcherHost> bluetooth_dispatcher_host_;
457 #if defined(OS_ANDROID)
458 scoped_refptr<BrowserDemuxerAndroid> browser_demuxer_android_;
459 #endif
461 #if defined(ENABLE_WEBRTC)
462 base::Callback<void(const std::string&)> webrtc_log_message_callback_;
464 scoped_refptr<P2PSocketDispatcherHost> p2p_socket_dispatcher_host_;
466 // Must be accessed on UI thread.
467 std::vector<int> aec_dump_consumers_;
469 WebRtcStopRtpDumpCallback stop_rtp_dump_callback_;
470 #endif
472 int worker_ref_count_;
474 // Records the time when the process starts surviving for workers for UMA.
475 base::TimeTicks survive_for_worker_start_time_;
477 // Records the maximum # of workers simultaneously hosted in this process
478 // for UMA.
479 int max_worker_count_;
481 // Context shared for each PermissionService instance created for this RPH.
482 scoped_ptr<PermissionServiceContext> permission_service_context_;
484 // This is a set of all subscription targets valuebuffers in the GPU process
485 // are currently subscribed too. Used to prevent sending unnecessary
486 // ValueState updates.
487 typedef base::hash_set<unsigned int> SubscriptionSet;
488 SubscriptionSet subscription_set_;
490 // Maintains ValueStates which are not currently subscribed too so we can
491 // pass them to the GpuService if a Valuebuffer ever subscribes to the
492 // respective subscription target
493 scoped_refptr<gpu::ValueStateMap> pending_valuebuffer_state_;
495 // Whether or not the CHROMIUM_subscribe_uniform WebGL extension is enabled
496 bool subscribe_uniform_enabled_;
498 #if defined(OS_MACOSX) && !defined(OS_IOS)
499 // Unique unguessable token that the child process is using to acquire
500 // IOSurface references.
501 IOSurfaceManagerToken io_surface_manager_token_;
502 #endif
504 base::WeakPtrFactory<RenderProcessHostImpl> weak_factory_;
506 DISALLOW_COPY_AND_ASSIGN(RenderProcessHostImpl);
509 } // namespace content
511 #endif // CONTENT_BROWSER_RENDERER_HOST_RENDER_PROCESS_HOST_IMPL_H_