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_isolated_guest
);
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 IsIsolatedGuest() 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 #if defined(ENABLE_BROWSER_CDMS)
252 const scoped_refptr
<BrowserCdmManager
>& browser_cdm_manager() {
253 return browser_cdm_manager_
;
257 MessagePortMessageFilter
* message_port_message_filter() const {
258 return message_port_message_filter_
.get();
261 NotificationMessageFilter
* notification_message_filter() const {
262 return notification_message_filter_
.get();
265 void set_is_isolated_guest_for_testing(bool is_isolated_guest
) {
266 is_isolated_guest_
= is_isolated_guest
;
269 // Called when the existence of the other renderer process which is connected
270 // to the Worker in this renderer process has changed.
271 // It is only called when "enable-embedded-shared-worker" flag is set.
272 void IncrementWorkerRefCount();
273 void DecrementWorkerRefCount();
275 void GetAudioOutputControllers(
276 const GetAudioOutputControllersCallback
& callback
) const override
;
278 BluetoothDispatcherHost
* GetBluetoothDispatcherHost();
281 // A proxy for our IPC::Channel that lives on the IO thread (see
282 // browser_process.h)
283 scoped_ptr
<IPC::ChannelProxy
> channel_
;
285 // A host object ChannelMojo needs. The lifetime is bound to
286 // the RenderProcessHostImpl, not the channel.
287 scoped_ptr
<IPC::ChannelMojoHost
> channel_mojo_host_
;
289 // True if fast shutdown has been performed on this RPH.
290 bool fast_shutdown_started_
;
292 // True if we've posted a DeleteTask and will be deleted soon.
296 // True if this object has deleted itself.
297 bool is_self_deleted_
;
300 // The count of currently swapped out but pending RenderViews. We have
301 // started to swap these in, so the renderer process should not exit if
302 // this count is non-zero.
303 int32 pending_views_
;
306 friend class VisitRelayingRenderProcessHost
;
307 friend class ChildProcessLauncherBrowserTest_ChildSpawnFail_Test
;
309 scoped_ptr
<IPC::ChannelProxy
> CreateChannelProxy(
310 const std::string
& channel_id
);
312 // Creates and adds the IO thread message filters.
313 void CreateMessageFilters();
315 // Registers Mojo services to be exposed to the renderer.
316 void RegisterMojoServices();
318 // Control message handlers.
319 void OnShutdownRequest();
320 void SuddenTerminationChanged(bool enabled
);
321 void OnUserMetricsRecordAction(const std::string
& action
);
322 void OnSavedPageAsMHTML(int job_id
, int64 mhtml_file_size
);
323 void OnCloseACK(int old_route_id
);
325 // Generates a command line to be used to spawn a renderer and appends the
326 // results to |*command_line|.
327 void AppendRendererCommandLine(base::CommandLine
* command_line
) const;
329 // Copies applicable command line switches from the given |browser_cmd| line
330 // flags to the output |renderer_cmd| line flags. Not all switches will be
332 void PropagateBrowserCommandLineToRenderer(
333 const base::CommandLine
& browser_cmd
,
334 base::CommandLine
* renderer_cmd
) const;
336 // Callers can reduce the RenderProcess' priority.
337 void SetBackgrounded(bool backgrounded
);
339 // Handle termination of our process.
340 void ProcessDied(bool already_dead
, RendererClosedDetails
* known_details
);
342 // GpuSwitchingObserver implementation.
343 void OnGpuSwitched() override
;
345 #if defined(ENABLE_WEBRTC)
346 void OnRegisterAecDumpConsumer(int id
);
347 void OnUnregisterAecDumpConsumer(int id
);
348 void RegisterAecDumpConsumerOnUIThread(int id
);
349 void UnregisterAecDumpConsumerOnUIThread(int id
);
350 void EnableAecDumpForId(const base::FilePath
& file
, int id
);
351 // Sends |file_for_transit| to the render process.
352 void SendAecDumpFileToRenderer(int id
,
353 IPC::PlatformFileForTransit file_for_transit
);
354 void SendDisableAecDumpToRenderer();
357 scoped_ptr
<MojoApplicationHost
> mojo_application_host_
;
359 // The registered IPC listener objects. When this list is empty, we should
361 IDMap
<IPC::Listener
> listeners_
;
363 // The count of currently visible widgets. Since the host can be a container
364 // for multiple widgets, it uses this count to determine when it should be
366 int32 visible_widgets_
;
368 // Does this process have backgrounded priority.
371 // Used to allow a RenderWidgetHost to intercept various messages on the
373 scoped_refptr
<RenderWidgetHelper
> widget_helper_
;
375 // The filter for GPU-related messages coming from the renderer.
376 // Thread safety note: this field is to be accessed from the UI thread.
377 // We don't keep a reference to it, to avoid it being destroyed on the UI
378 // thread, but we clear this field when we clear channel_. When channel_ goes
379 // away, it posts a task to the IO thread to destroy it there, so we know that
380 // it's valid if non-NULL.
381 GpuMessageFilter
* gpu_message_filter_
;
383 // The filter for MessagePort messages coming from the renderer.
384 scoped_refptr
<MessagePortMessageFilter
> message_port_message_filter_
;
386 // The filter for Web Notification messages coming from the renderer. Holds a
387 // closure per notification that must be freed when the notification closes.
388 scoped_refptr
<NotificationMessageFilter
> notification_message_filter_
;
390 // Used in single-process mode.
391 scoped_ptr
<base::Thread
> in_process_renderer_
;
393 // True after Init() has been called. We can't just check channel_ because we
394 // also reset that in the case of process termination.
395 bool is_initialized_
;
398 // Stores the time at which the first call to Init happened.
399 base::TimeTicks init_time_
;
401 // Used to launch and terminate the process without blocking the UI thread.
402 scoped_ptr
<ChildProcessLauncher
> child_process_launcher_
;
404 // Messages we queue while waiting for the process handle. We queue them here
405 // instead of in the channel so that we ensure they're sent after init related
406 // messages that are sent once the process handle is available. This is
407 // because the queued messages may have dependencies on the init messages.
408 std::queue
<IPC::Message
*> queued_messages_
;
410 // The globally-unique identifier for this RPH.
413 BrowserContext
* browser_context_
;
415 // Owned by |browser_context_|.
416 StoragePartitionImpl
* storage_partition_impl_
;
418 // The observers watching our lifetime.
419 base::ObserverList
<RenderProcessHostObserver
> observers_
;
421 // True if the process can be shut down suddenly. If this is true, then we're
422 // sure that all the RenderViews in the process can be shutdown suddenly. If
423 // it's false, then specific RenderViews might still be allowed to be shutdown
424 // suddenly by checking their SuddenTerminationAllowed() flag. This can occur
425 // if one WebContents has an unload event listener but another WebContents in
426 // the same process doesn't.
427 bool sudden_termination_allowed_
;
429 // Set to true if we shouldn't send input events. We actually do the
430 // filtering for this at the render widget level.
431 bool ignore_input_events_
;
433 // Records the last time we regarded the child process active.
434 base::TimeTicks child_process_activity_time_
;
436 // Indicates whether this is a RenderProcessHost of a Browser Plugin guest
438 bool is_isolated_guest_
;
440 // Forwards messages between WebRTCInternals in the browser process
441 // and PeerConnectionTracker in the renderer process.
442 scoped_refptr
<PeerConnectionTrackerHost
> peer_connection_tracker_host_
;
444 // Prevents the class from being added as a GpuDataManagerImpl observer more
446 bool gpu_observer_registered_
;
448 // Set if a call to Cleanup is required once the RenderProcessHostImpl is no
449 // longer within the RenderProcessHostObserver::RenderProcessExited callbacks.
450 bool delayed_cleanup_needed_
;
452 // Indicates whether RenderProcessHostImpl is currently iterating and calling
453 // through RenderProcessHostObserver::RenderProcessExited.
454 bool within_process_died_observer_
;
456 // Forwards power state messages to the renderer process.
457 PowerMonitorMessageBroadcaster power_monitor_broadcaster_
;
459 scoped_refptr
<AudioRendererHost
> audio_renderer_host_
;
461 scoped_refptr
<BluetoothDispatcherHost
> bluetooth_dispatcher_host_
;
463 #if defined(OS_ANDROID)
464 scoped_refptr
<BrowserDemuxerAndroid
> browser_demuxer_android_
;
467 #if defined(ENABLE_BROWSER_CDMS)
468 scoped_refptr
<BrowserCdmManager
> browser_cdm_manager_
;
471 #if defined(ENABLE_WEBRTC)
472 base::Callback
<void(const std::string
&)> webrtc_log_message_callback_
;
474 scoped_refptr
<P2PSocketDispatcherHost
> p2p_socket_dispatcher_host_
;
476 // Must be accessed on UI thread.
477 std::vector
<int> aec_dump_consumers_
;
479 WebRtcStopRtpDumpCallback stop_rtp_dump_callback_
;
482 int worker_ref_count_
;
484 // Records the time when the process starts surviving for workers for UMA.
485 base::TimeTicks survive_for_worker_start_time_
;
487 // Records the maximum # of workers simultaneously hosted in this process
489 int max_worker_count_
;
491 // Context shared for each PermissionService instance created for this RPH.
492 scoped_ptr
<PermissionServiceContext
> permission_service_context_
;
494 // This is a set of all subscription targets valuebuffers in the GPU process
495 // are currently subscribed too. Used to prevent sending unnecessary
496 // ValueState updates.
497 typedef base::hash_set
<unsigned int> SubscriptionSet
;
498 SubscriptionSet subscription_set_
;
500 // Maintains ValueStates which are not currently subscribed too so we can
501 // pass them to the GpuService if a Valuebuffer ever subscribes to the
502 // respective subscription target
503 scoped_refptr
<gpu::ValueStateMap
> pending_valuebuffer_state_
;
505 // Whether or not the CHROMIUM_subscribe_uniform WebGL extension is enabled
506 bool subscribe_uniform_enabled_
;
508 #if defined(OS_MACOSX) && !defined(OS_IOS)
509 // Unique unguessable token that the child process is using to acquire
510 // IOSurface references.
511 IOSurfaceManagerToken io_surface_manager_token_
;
514 base::WeakPtrFactory
<RenderProcessHostImpl
> weak_factory_
;
516 DISALLOW_COPY_AND_ASSIGN(RenderProcessHostImpl
);
519 } // namespace content
521 #endif // CONTENT_BROWSER_RENDERER_HOST_RENDER_PROCESS_HOST_IMPL_H_