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_
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"
45 class ChannelMojoHost
;
49 class AudioRendererHost
;
50 class BluetoothDispatcherHost
;
51 class BrowserCdmManager
;
52 class BrowserDemuxerAndroid
;
53 class GpuMessageFilter
;
54 class InProcessChildThreadParams
;
55 class MessagePortMessageFilter
;
56 class MojoApplicationHost
;
57 class NotificationMessageFilter
;
58 #if defined(ENABLE_WEBRTC)
59 class P2PSocketDispatcherHost
;
61 class PermissionServiceContext
;
62 class PeerConnectionTrackerHost
;
63 class RendererMainThread
;
64 class RenderWidgetHelper
;
65 class RenderWidgetHost
;
66 class RenderWidgetHostImpl
;
67 class RenderWidgetHostViewFrameSubscriber
;
68 class StoragePartition
;
69 class StoragePartitionImpl
;
71 typedef base::Thread
* (*RendererMainThreadFactoryFunction
)(
72 const InProcessChildThreadParams
& params
);
74 // Implements a concrete RenderProcessHost for the browser process for talking
75 // to actual renderer processes (as opposed to mocks).
77 // Represents the browser side of the browser <--> renderer communication
78 // channel. There will be one RenderProcessHost per renderer process.
80 // This object is refcounted so that it can release its resources when all
81 // hosts using it go away.
83 // This object communicates back and forth with the RenderProcess object
84 // running in the renderer process. Each RenderProcessHost and RenderProcess
85 // keeps a list of RenderView (renderer) and WebContentsImpl (browser) which
86 // are correlated with IDs. This way, the Views and the corresponding ViewHosts
87 // communicate through the two process objects.
89 // A RenderProcessHost is also associated with one and only one
90 // StoragePartition. This allows us to implement strong storage isolation
91 // because all the IPCs from the RenderViews (renderer) will only ever be able
92 // to access the partition they are assigned to.
93 class CONTENT_EXPORT RenderProcessHostImpl
94 : public RenderProcessHost
,
95 public ChildProcessLauncher::Client
,
96 public ui::GpuSwitchingObserver
{
98 RenderProcessHostImpl(BrowserContext
* browser_context
,
99 StoragePartitionImpl
* storage_partition_impl
,
100 bool is_for_guests_only
);
101 ~RenderProcessHostImpl() override
;
103 // RenderProcessHost implementation (public portion).
104 void EnableSendQueue() override
;
105 bool Init() override
;
106 int GetNextRoutingID() override
;
107 void AddRoute(int32 routing_id
, IPC::Listener
* listener
) override
;
108 void RemoveRoute(int32 routing_id
) override
;
109 void AddObserver(RenderProcessHostObserver
* observer
) override
;
110 void RemoveObserver(RenderProcessHostObserver
* observer
) override
;
111 void ShutdownForBadMessage() override
;
112 void WidgetRestored() override
;
113 void WidgetHidden() override
;
114 int VisibleWidgetCount() const override
;
115 bool IsForGuestsOnly() const override
;
116 StoragePartition
* GetStoragePartition() const override
;
117 bool Shutdown(int exit_code
, bool wait
) override
;
118 bool FastShutdownIfPossible() override
;
119 base::ProcessHandle
GetHandle() const override
;
120 BrowserContext
* GetBrowserContext() const override
;
121 bool InSameStoragePartition(StoragePartition
* partition
) const override
;
122 int GetID() const override
;
123 bool HasConnection() const override
;
124 void SetIgnoreInputEvents(bool ignore_input_events
) override
;
125 bool IgnoreInputEvents() const override
;
126 void Cleanup() override
;
127 void AddPendingView() override
;
128 void RemovePendingView() override
;
129 void SetSuddenTerminationAllowed(bool enabled
) override
;
130 bool SuddenTerminationAllowed() const override
;
131 IPC::ChannelProxy
* GetChannel() override
;
132 void AddFilter(BrowserMessageFilter
* filter
) override
;
133 bool FastShutdownForPageCount(size_t count
) override
;
134 bool FastShutdownStarted() const override
;
135 base::TimeDelta
GetChildProcessIdleTime() const override
;
136 void ResumeRequestsForView(int route_id
) override
;
137 void FilterURL(bool empty_allowed
, GURL
* url
) override
;
138 #if defined(ENABLE_WEBRTC)
139 void EnableAecDump(const base::FilePath
& file
) override
;
140 void DisableAecDump() override
;
141 void SetWebRtcLogMessageCallback(
142 base::Callback
<void(const std::string
&)> callback
) override
;
143 WebRtcStopRtpDumpCallback
StartRtpDump(
146 const WebRtcRtpPacketCallback
& packet_callback
) override
;
148 void ResumeDeferredNavigation(const GlobalRequestID
& request_id
) override
;
149 void NotifyTimezoneChange(const std::string
& timezone
) override
;
150 ServiceRegistry
* GetServiceRegistry() override
;
151 const base::TimeTicks
& GetInitTimeForNavigationMetrics() const override
;
152 bool SubscribeUniformEnabled() const override
;
153 void OnAddSubscription(unsigned int target
) override
;
154 void OnRemoveSubscription(unsigned int target
) override
;
155 void SendUpdateValueState(
156 unsigned int target
, const gpu::ValueState
& state
) override
;
157 #if defined(ENABLE_BROWSER_CDMS)
158 media::BrowserCdm
* GetBrowserCdm(int render_frame_id
,
159 int cdm_id
) const override
;
162 // IPC::Sender via RenderProcessHost.
163 bool Send(IPC::Message
* msg
) override
;
165 // IPC::Listener via RenderProcessHost.
166 bool OnMessageReceived(const IPC::Message
& msg
) override
;
167 void OnChannelConnected(int32 peer_pid
) override
;
168 void OnChannelError() override
;
169 void OnBadMessageReceived(const IPC::Message
& message
) override
;
171 // ChildProcessLauncher::Client implementation.
172 void OnProcessLaunched() override
;
173 void OnProcessLaunchFailed() override
;
175 scoped_refptr
<AudioRendererHost
> audio_renderer_host() const;
177 // Call this function when it is evident that the child process is actively
178 // performing some operation, for example if we just received an IPC message.
179 void mark_child_process_activity_time() {
180 child_process_activity_time_
= base::TimeTicks::Now();
183 // Start and end frame subscription for a specific renderer.
184 // This API only supports subscription to accelerated composited frames.
185 void BeginFrameSubscription(
187 scoped_ptr
<RenderWidgetHostViewFrameSubscriber
> subscriber
);
188 void EndFrameSubscription(int route_id
);
190 #if defined(ENABLE_WEBRTC)
191 // Fires the webrtc log message callback with |message|, if callback is set.
192 void WebRtcLogMessage(const std::string
& message
);
195 // Used to extend the lifetime of the sessions until the render view
196 // in the renderer is fully closed. This is static because its also called
197 // with mock hosts as input in test cases.
198 static void ReleaseOnCloseACK(
199 RenderProcessHost
* host
,
200 const SessionStorageNamespaceMap
& sessions
,
203 // Register/unregister the host identified by the host id in the global host
205 static void RegisterHost(int host_id
, RenderProcessHost
* host
);
206 static void UnregisterHost(int host_id
);
208 // Implementation of FilterURL below that can be shared with the mock class.
209 static void FilterURL(RenderProcessHost
* rph
, bool empty_allowed
, GURL
* url
);
211 // Returns true if |host| is suitable for launching a new view with |site_url|
212 // in the given |browser_context|.
213 static bool IsSuitableHost(RenderProcessHost
* host
,
214 BrowserContext
* browser_context
,
215 const GURL
& site_url
);
217 // Returns an existing RenderProcessHost for |url| in |browser_context|,
218 // if one exists. Otherwise a new RenderProcessHost should be created and
219 // registered using RegisterProcessHostForSite().
220 // This should only be used for process-per-site mode, which can be enabled
221 // globally with a command line flag or per-site, as determined by
222 // SiteInstanceImpl::ShouldUseProcessPerSite.
223 static RenderProcessHost
* GetProcessHostForSite(
224 BrowserContext
* browser_context
,
227 // Registers the given |process| to be used for any instance of |url|
228 // within |browser_context|.
229 // This should only be used for process-per-site mode, which can be enabled
230 // globally with a command line flag or per-site, as determined by
231 // SiteInstanceImpl::ShouldUseProcessPerSite.
232 static void RegisterProcessHostForSite(
233 BrowserContext
* browser_context
,
234 RenderProcessHost
* process
,
237 static base::MessageLoop
* GetInProcessRendererThreadForTesting();
239 // This forces a renderer that is running "in process" to shut down.
240 static void ShutDownInProcessRenderer();
242 static void RegisterRendererMainThreadFactory(
243 RendererMainThreadFactoryFunction create
);
245 #if defined(OS_ANDROID)
246 const scoped_refptr
<BrowserDemuxerAndroid
>& browser_demuxer_android() {
247 return browser_demuxer_android_
;
251 MessagePortMessageFilter
* message_port_message_filter() const {
252 return message_port_message_filter_
.get();
255 NotificationMessageFilter
* notification_message_filter() const {
256 return notification_message_filter_
.get();
259 void set_is_for_guests_only_for_testing(bool is_for_guests_only
) {
260 is_for_guests_only_
= is_for_guests_only
;
263 // Called when the existence of the other renderer process which is connected
264 // to the Worker in this renderer process has changed.
265 // It is only called when "enable-embedded-shared-worker" flag is set.
266 void IncrementWorkerRefCount();
267 void DecrementWorkerRefCount();
269 void GetAudioOutputControllers(
270 const GetAudioOutputControllersCallback
& callback
) const override
;
272 BluetoothDispatcherHost
* GetBluetoothDispatcherHost();
275 // A proxy for our IPC::Channel that lives on the IO thread (see
276 // browser_process.h)
277 scoped_ptr
<IPC::ChannelProxy
> channel_
;
279 // True if fast shutdown has been performed on this RPH.
280 bool fast_shutdown_started_
;
282 // True if we've posted a DeleteTask and will be deleted soon.
286 // True if this object has deleted itself.
287 bool is_self_deleted_
;
290 // The count of currently swapped out but pending RenderViews. We have
291 // started to swap these in, so the renderer process should not exit if
292 // this count is non-zero.
293 int32 pending_views_
;
296 friend class VisitRelayingRenderProcessHost
;
297 friend class ChildProcessLauncherBrowserTest_ChildSpawnFail_Test
;
299 scoped_ptr
<IPC::ChannelProxy
> CreateChannelProxy(
300 const std::string
& channel_id
);
302 // Creates and adds the IO thread message filters.
303 void CreateMessageFilters();
305 // Registers Mojo services to be exposed to the renderer.
306 void RegisterMojoServices();
308 // Control message handlers.
309 void OnShutdownRequest();
310 void SuddenTerminationChanged(bool enabled
);
311 void OnUserMetricsRecordAction(const std::string
& action
);
312 void OnSavedPageAsMHTML(int job_id
, int64 mhtml_file_size
);
313 void OnCloseACK(int old_route_id
);
315 // Generates a command line to be used to spawn a renderer and appends the
316 // results to |*command_line|.
317 void AppendRendererCommandLine(base::CommandLine
* command_line
) const;
319 // Copies applicable command line switches from the given |browser_cmd| line
320 // flags to the output |renderer_cmd| line flags. Not all switches will be
322 void PropagateBrowserCommandLineToRenderer(
323 const base::CommandLine
& browser_cmd
,
324 base::CommandLine
* renderer_cmd
) const;
326 // Callers can reduce the RenderProcess' priority.
327 void SetBackgrounded(bool backgrounded
);
329 // Handle termination of our process.
330 void ProcessDied(bool already_dead
, RendererClosedDetails
* known_details
);
332 // GpuSwitchingObserver implementation.
333 void OnGpuSwitched() override
;
335 #if defined(ENABLE_WEBRTC)
336 void OnRegisterAecDumpConsumer(int id
);
337 void OnUnregisterAecDumpConsumer(int id
);
338 void RegisterAecDumpConsumerOnUIThread(int id
);
339 void UnregisterAecDumpConsumerOnUIThread(int id
);
340 void EnableAecDumpForId(const base::FilePath
& file
, int id
);
341 // Sends |file_for_transit| to the render process.
342 void SendAecDumpFileToRenderer(int id
,
343 IPC::PlatformFileForTransit file_for_transit
);
344 void SendDisableAecDumpToRenderer();
347 scoped_ptr
<MojoApplicationHost
> mojo_application_host_
;
349 // The registered IPC listener objects. When this list is empty, we should
351 IDMap
<IPC::Listener
> listeners_
;
353 // The count of currently visible widgets. Since the host can be a container
354 // for multiple widgets, it uses this count to determine when it should be
356 int32 visible_widgets_
;
358 // Does this process have backgrounded priority.
361 // Used to allow a RenderWidgetHost to intercept various messages on the
363 scoped_refptr
<RenderWidgetHelper
> widget_helper_
;
365 // The filter for GPU-related messages coming from the renderer.
366 // Thread safety note: this field is to be accessed from the UI thread.
367 // We don't keep a reference to it, to avoid it being destroyed on the UI
368 // thread, but we clear this field when we clear channel_. When channel_ goes
369 // away, it posts a task to the IO thread to destroy it there, so we know that
370 // it's valid if non-NULL.
371 GpuMessageFilter
* gpu_message_filter_
;
373 // The filter for MessagePort messages coming from the renderer.
374 scoped_refptr
<MessagePortMessageFilter
> message_port_message_filter_
;
376 // The filter for Web Notification messages coming from the renderer. Holds a
377 // closure per notification that must be freed when the notification closes.
378 scoped_refptr
<NotificationMessageFilter
> notification_message_filter_
;
380 // Used in single-process mode.
381 scoped_ptr
<base::Thread
> in_process_renderer_
;
383 // True after Init() has been called. We can't just check channel_ because we
384 // also reset that in the case of process termination.
385 bool is_initialized_
;
388 // Stores the time at which the first call to Init happened.
389 base::TimeTicks init_time_
;
391 // Used to launch and terminate the process without blocking the UI thread.
392 scoped_ptr
<ChildProcessLauncher
> child_process_launcher_
;
394 // Messages we queue while waiting for the process handle. We queue them here
395 // instead of in the channel so that we ensure they're sent after init related
396 // messages that are sent once the process handle is available. This is
397 // because the queued messages may have dependencies on the init messages.
398 std::queue
<IPC::Message
*> queued_messages_
;
400 // The globally-unique identifier for this RPH.
403 BrowserContext
* browser_context_
;
405 // Owned by |browser_context_|.
406 StoragePartitionImpl
* storage_partition_impl_
;
408 // The observers watching our lifetime.
409 base::ObserverList
<RenderProcessHostObserver
> observers_
;
411 // True if the process can be shut down suddenly. If this is true, then we're
412 // sure that all the RenderViews in the process can be shutdown suddenly. If
413 // it's false, then specific RenderViews might still be allowed to be shutdown
414 // suddenly by checking their SuddenTerminationAllowed() flag. This can occur
415 // if one WebContents has an unload event listener but another WebContents in
416 // the same process doesn't.
417 bool sudden_termination_allowed_
;
419 // Set to true if we shouldn't send input events. We actually do the
420 // filtering for this at the render widget level.
421 bool ignore_input_events_
;
423 // Records the last time we regarded the child process active.
424 base::TimeTicks child_process_activity_time_
;
426 // Indicates whether this RenderProcessHost is exclusively hosting guest
428 bool is_for_guests_only_
;
430 // Forwards messages between WebRTCInternals in the browser process
431 // and PeerConnectionTracker in the renderer process.
432 scoped_refptr
<PeerConnectionTrackerHost
> peer_connection_tracker_host_
;
434 // Prevents the class from being added as a GpuDataManagerImpl observer more
436 bool gpu_observer_registered_
;
438 // Set if a call to Cleanup is required once the RenderProcessHostImpl is no
439 // longer within the RenderProcessHostObserver::RenderProcessExited callbacks.
440 bool delayed_cleanup_needed_
;
442 // Indicates whether RenderProcessHostImpl is currently iterating and calling
443 // through RenderProcessHostObserver::RenderProcessExited.
444 bool within_process_died_observer_
;
446 // Forwards power state messages to the renderer process.
447 PowerMonitorMessageBroadcaster power_monitor_broadcaster_
;
449 scoped_refptr
<AudioRendererHost
> audio_renderer_host_
;
451 scoped_refptr
<BluetoothDispatcherHost
> bluetooth_dispatcher_host_
;
453 #if defined(OS_ANDROID)
454 scoped_refptr
<BrowserDemuxerAndroid
> browser_demuxer_android_
;
457 #if defined(ENABLE_WEBRTC)
458 base::Callback
<void(const std::string
&)> webrtc_log_message_callback_
;
460 scoped_refptr
<P2PSocketDispatcherHost
> p2p_socket_dispatcher_host_
;
462 // Must be accessed on UI thread.
463 std::vector
<int> aec_dump_consumers_
;
465 WebRtcStopRtpDumpCallback stop_rtp_dump_callback_
;
468 int worker_ref_count_
;
470 // Records the time when the process starts surviving for workers for UMA.
471 base::TimeTicks survive_for_worker_start_time_
;
473 // Records the maximum # of workers simultaneously hosted in this process
475 int max_worker_count_
;
477 // Context shared for each PermissionService instance created for this RPH.
478 scoped_ptr
<PermissionServiceContext
> permission_service_context_
;
480 // This is a set of all subscription targets valuebuffers in the GPU process
481 // are currently subscribed too. Used to prevent sending unnecessary
482 // ValueState updates.
483 typedef base::hash_set
<unsigned int> SubscriptionSet
;
484 SubscriptionSet subscription_set_
;
486 // Maintains ValueStates which are not currently subscribed too so we can
487 // pass them to the GpuService if a Valuebuffer ever subscribes to the
488 // respective subscription target
489 scoped_refptr
<gpu::ValueStateMap
> pending_valuebuffer_state_
;
491 // Whether or not the CHROMIUM_subscribe_uniform WebGL extension is enabled
492 bool subscribe_uniform_enabled_
;
494 #if defined(OS_MACOSX) && !defined(OS_IOS)
495 // Unique unguessable token that the child process is using to acquire
496 // IOSurface references.
497 IOSurfaceManagerToken io_surface_manager_token_
;
500 base::WeakPtrFactory
<RenderProcessHostImpl
> weak_factory_
;
502 DISALLOW_COPY_AND_ASSIGN(RenderProcessHostImpl
);
505 } // namespace content
507 #endif // CONTENT_BROWSER_RENDERER_HOST_RENDER_PROCESS_HOST_IMPL_H_