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 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
;
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
{
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(
147 const WebRtcRtpPacketCallback
& packet_callback
) override
;
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
;
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 #if defined(ENABLE_WEBRTC)
185 // Fires the webrtc log message callback with |message|, if callback is set.
186 void WebRtcLogMessage(const std::string
& message
);
189 // Used to extend the lifetime of the sessions until the render view
190 // in the renderer is fully closed. This is static because its also called
191 // with mock hosts as input in test cases.
192 static void ReleaseOnCloseACK(
193 RenderProcessHost
* host
,
194 const SessionStorageNamespaceMap
& sessions
,
197 // Register/unregister the host identified by the host id in the global host
199 static void RegisterHost(int host_id
, RenderProcessHost
* host
);
200 static void UnregisterHost(int host_id
);
202 // Implementation of FilterURL below that can be shared with the mock class.
203 static void FilterURL(RenderProcessHost
* rph
, bool empty_allowed
, GURL
* url
);
205 // Returns true if |host| is suitable for launching a new view with |site_url|
206 // in the given |browser_context|.
207 static bool IsSuitableHost(RenderProcessHost
* host
,
208 BrowserContext
* browser_context
,
209 const GURL
& site_url
);
211 // Returns an existing RenderProcessHost for |url| in |browser_context|,
212 // if one exists. Otherwise a new RenderProcessHost should be created and
213 // registered using RegisterProcessHostForSite().
214 // This should only be used for process-per-site mode, which can be enabled
215 // globally with a command line flag or per-site, as determined by
216 // SiteInstanceImpl::ShouldUseProcessPerSite.
217 static RenderProcessHost
* GetProcessHostForSite(
218 BrowserContext
* browser_context
,
221 // Registers the given |process| to be used for any instance of |url|
222 // within |browser_context|.
223 // This should only be used for process-per-site mode, which can be enabled
224 // globally with a command line flag or per-site, as determined by
225 // SiteInstanceImpl::ShouldUseProcessPerSite.
226 static void RegisterProcessHostForSite(
227 BrowserContext
* browser_context
,
228 RenderProcessHost
* process
,
231 static base::MessageLoop
* GetInProcessRendererThreadForTesting();
233 // This forces a renderer that is running "in process" to shut down.
234 static void ShutDownInProcessRenderer();
236 static void RegisterRendererMainThreadFactory(
237 RendererMainThreadFactoryFunction create
);
239 #if defined(OS_ANDROID)
240 const scoped_refptr
<BrowserDemuxerAndroid
>& browser_demuxer_android() {
241 return browser_demuxer_android_
;
245 MessagePortMessageFilter
* message_port_message_filter() const {
246 return message_port_message_filter_
.get();
249 NotificationMessageFilter
* notification_message_filter() const {
250 return notification_message_filter_
.get();
253 void set_is_for_guests_only_for_testing(bool is_for_guests_only
) {
254 is_for_guests_only_
= is_for_guests_only
;
257 // Called when the existence of the other renderer process which is connected
258 // to the Worker in this renderer process has changed.
259 // It is only called when "enable-embedded-shared-worker" flag is set.
260 void IncrementWorkerRefCount();
261 void DecrementWorkerRefCount();
263 void GetAudioOutputControllers(
264 const GetAudioOutputControllersCallback
& callback
) const override
;
266 BluetoothDispatcherHost
* GetBluetoothDispatcherHost();
269 // A proxy for our IPC::Channel that lives on the IO thread (see
270 // browser_process.h)
271 scoped_ptr
<IPC::ChannelProxy
> channel_
;
273 // True if fast shutdown has been performed on this RPH.
274 bool fast_shutdown_started_
;
276 // True if we've posted a DeleteTask and will be deleted soon.
280 // True if this object has deleted itself.
281 bool is_self_deleted_
;
284 // The count of currently swapped out but pending RenderViews. We have
285 // started to swap these in, so the renderer process should not exit if
286 // this count is non-zero.
287 int32 pending_views_
;
290 friend class VisitRelayingRenderProcessHost
;
291 friend class ChildProcessLauncherBrowserTest_ChildSpawnFail_Test
;
293 scoped_ptr
<IPC::ChannelProxy
> CreateChannelProxy(
294 const std::string
& channel_id
);
296 // Creates and adds the IO thread message filters.
297 void CreateMessageFilters();
299 // Registers Mojo services to be exposed to the renderer.
300 void RegisterMojoServices();
302 // Control message handlers.
303 void OnShutdownRequest();
304 void SuddenTerminationChanged(bool enabled
);
305 void OnUserMetricsRecordAction(const std::string
& action
);
306 void OnSavedPageAsMHTML(int job_id
, int64 mhtml_file_size
);
307 void OnCloseACK(int old_route_id
);
309 // Generates a command line to be used to spawn a renderer and appends the
310 // results to |*command_line|.
311 void AppendRendererCommandLine(base::CommandLine
* command_line
) const;
313 // Copies applicable command line switches from the given |browser_cmd| line
314 // flags to the output |renderer_cmd| line flags. Not all switches will be
316 void PropagateBrowserCommandLineToRenderer(
317 const base::CommandLine
& browser_cmd
,
318 base::CommandLine
* renderer_cmd
) const;
320 // Callers can reduce the RenderProcess' priority.
321 void SetBackgrounded(bool backgrounded
);
323 // Handle termination of our process.
324 void ProcessDied(bool already_dead
, RendererClosedDetails
* known_details
);
326 // GpuSwitchingObserver implementation.
327 void OnGpuSwitched() override
;
329 #if defined(ENABLE_WEBRTC)
330 void OnRegisterAecDumpConsumer(int id
);
331 void OnUnregisterAecDumpConsumer(int id
);
332 void RegisterAecDumpConsumerOnUIThread(int id
);
333 void UnregisterAecDumpConsumerOnUIThread(int id
);
334 void EnableAecDumpForId(const base::FilePath
& file
, int id
);
335 // Sends |file_for_transit| to the render process.
336 void SendAecDumpFileToRenderer(int id
,
337 IPC::PlatformFileForTransit file_for_transit
);
338 void SendDisableAecDumpToRenderer();
339 base::FilePath
GetAecDumpFilePathWithExtensions(const base::FilePath
& file
);
342 scoped_ptr
<MojoApplicationHost
> mojo_application_host_
;
344 // The registered IPC listener objects. When this list is empty, we should
346 IDMap
<IPC::Listener
> listeners_
;
348 // The count of currently visible widgets. Since the host can be a container
349 // for multiple widgets, it uses this count to determine when it should be
351 int32 visible_widgets_
;
353 // Does this process have backgrounded priority.
356 // Used to allow a RenderWidgetHost to intercept various messages on the
358 scoped_refptr
<RenderWidgetHelper
> widget_helper_
;
360 // The filter for GPU-related messages coming from the renderer.
361 // Thread safety note: this field is to be accessed from the UI thread.
362 // We don't keep a reference to it, to avoid it being destroyed on the UI
363 // thread, but we clear this field when we clear channel_. When channel_ goes
364 // away, it posts a task to the IO thread to destroy it there, so we know that
365 // it's valid if non-NULL.
366 GpuMessageFilter
* gpu_message_filter_
;
368 // The filter for MessagePort messages coming from the renderer.
369 scoped_refptr
<MessagePortMessageFilter
> message_port_message_filter_
;
371 // The filter for Web Notification messages coming from the renderer. Holds a
372 // closure per notification that must be freed when the notification closes.
373 scoped_refptr
<NotificationMessageFilter
> notification_message_filter_
;
375 // Used in single-process mode.
376 scoped_ptr
<base::Thread
> in_process_renderer_
;
378 // True after Init() has been called. We can't just check channel_ because we
379 // also reset that in the case of process termination.
380 bool is_initialized_
;
383 // Stores the time at which the first call to Init happened.
384 base::TimeTicks init_time_
;
386 // Used to launch and terminate the process without blocking the UI thread.
387 scoped_ptr
<ChildProcessLauncher
> child_process_launcher_
;
389 // Messages we queue while waiting for the process handle. We queue them here
390 // instead of in the channel so that we ensure they're sent after init related
391 // messages that are sent once the process handle is available. This is
392 // because the queued messages may have dependencies on the init messages.
393 std::queue
<IPC::Message
*> queued_messages_
;
395 // The globally-unique identifier for this RPH.
398 BrowserContext
* browser_context_
;
400 // Owned by |browser_context_|.
401 StoragePartitionImpl
* storage_partition_impl_
;
403 // The observers watching our lifetime.
404 base::ObserverList
<RenderProcessHostObserver
> observers_
;
406 // True if the process can be shut down suddenly. If this is true, then we're
407 // sure that all the RenderViews in the process can be shutdown suddenly. If
408 // it's false, then specific RenderViews might still be allowed to be shutdown
409 // suddenly by checking their SuddenTerminationAllowed() flag. This can occur
410 // if one WebContents has an unload event listener but another WebContents in
411 // the same process doesn't.
412 bool sudden_termination_allowed_
;
414 // Set to true if we shouldn't send input events. We actually do the
415 // filtering for this at the render widget level.
416 bool ignore_input_events_
;
418 // Records the last time we regarded the child process active.
419 base::TimeTicks child_process_activity_time_
;
421 // Indicates whether this RenderProcessHost is exclusively hosting guest
423 bool is_for_guests_only_
;
425 // Forwards messages between WebRTCInternals in the browser process
426 // and PeerConnectionTracker in the renderer process.
427 scoped_refptr
<PeerConnectionTrackerHost
> peer_connection_tracker_host_
;
429 // Prevents the class from being added as a GpuDataManagerImpl observer more
431 bool gpu_observer_registered_
;
433 // Set if a call to Cleanup is required once the RenderProcessHostImpl is no
434 // longer within the RenderProcessHostObserver::RenderProcessExited callbacks.
435 bool delayed_cleanup_needed_
;
437 // Indicates whether RenderProcessHostImpl is currently iterating and calling
438 // through RenderProcessHostObserver::RenderProcessExited.
439 bool within_process_died_observer_
;
441 // Forwards power state messages to the renderer process.
442 PowerMonitorMessageBroadcaster power_monitor_broadcaster_
;
444 scoped_refptr
<AudioRendererHost
> audio_renderer_host_
;
446 scoped_refptr
<AudioInputRendererHost
> audio_input_renderer_host_
;
448 scoped_refptr
<BluetoothDispatcherHost
> bluetooth_dispatcher_host_
;
450 #if defined(OS_ANDROID)
451 scoped_refptr
<BrowserDemuxerAndroid
> browser_demuxer_android_
;
454 #if defined(ENABLE_WEBRTC)
455 base::Callback
<void(const std::string
&)> webrtc_log_message_callback_
;
457 scoped_refptr
<P2PSocketDispatcherHost
> p2p_socket_dispatcher_host_
;
459 // Must be accessed on UI thread.
460 std::vector
<int> aec_dump_consumers_
;
462 WebRtcStopRtpDumpCallback stop_rtp_dump_callback_
;
465 int worker_ref_count_
;
467 // Records the time when the process starts surviving for workers for UMA.
468 base::TimeTicks survive_for_worker_start_time_
;
470 // Records the maximum # of workers simultaneously hosted in this process
472 int max_worker_count_
;
474 // Context shared for each PermissionService instance created for this RPH.
475 scoped_ptr
<PermissionServiceContext
> permission_service_context_
;
477 // This is a set of all subscription targets valuebuffers in the GPU process
478 // are currently subscribed too. Used to prevent sending unnecessary
479 // ValueState updates.
480 typedef base::hash_set
<unsigned int> SubscriptionSet
;
481 SubscriptionSet subscription_set_
;
483 // Maintains ValueStates which are not currently subscribed too so we can
484 // pass them to the GpuService if a Valuebuffer ever subscribes to the
485 // respective subscription target
486 scoped_refptr
<gpu::ValueStateMap
> pending_valuebuffer_state_
;
488 // Whether or not the CHROMIUM_subscribe_uniform WebGL extension is enabled
489 bool subscribe_uniform_enabled_
;
491 #if defined(OS_MACOSX) && !defined(OS_IOS)
492 // Unique unguessable token that the child process is using to acquire
493 // IOSurface references.
494 IOSurfaceManagerToken io_surface_manager_token_
;
497 base::WeakPtrFactory
<RenderProcessHostImpl
> weak_factory_
;
499 DISALLOW_COPY_AND_ASSIGN(RenderProcessHostImpl
);
502 } // namespace content
504 #endif // CONTENT_BROWSER_RENDERER_HOST_RENDER_PROCESS_HOST_IMPL_H_