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_BROWSER_RENDER_PROCESS_HOST_IMPL_H_
6 #define CONTENT_BROWSER_RENDERER_HOST_BROWSER_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 "base/timer/timer.h"
16 #include "content/browser/child_process_launcher.h"
17 #include "content/browser/dom_storage/session_storage_namespace_impl.h"
18 #include "content/browser/power_monitor_message_broadcaster.h"
19 #include "content/common/content_export.h"
20 #include "content/common/mojo/service_registry_impl.h"
21 #include "content/public/browser/gpu_data_manager_observer.h"
22 #include "content/public/browser/render_process_host.h"
23 #include "ipc/ipc_channel_proxy.h"
24 #include "ipc/ipc_platform_file.h"
25 #include "mojo/public/cpp/bindings/interface_ptr.h"
26 #include "ui/gfx/gpu_memory_buffer.h"
28 #if defined(OS_MACOSX)
29 #include <IOSurface/IOSurfaceAPI.h>
30 #include "base/mac/scoped_cftyperef.h"
40 struct GpuMemoryBufferHandle
;
44 class AudioRendererHost
;
45 class BrowserDemuxerAndroid
;
46 class GpuMessageFilter
;
47 class MessagePortMessageFilter
;
48 class MojoApplicationHost
;
49 #if defined(ENABLE_WEBRTC)
50 class P2PSocketDispatcherHost
;
52 class PeerConnectionTrackerHost
;
53 class RendererMainThread
;
54 class RenderWidgetHelper
;
55 class RenderWidgetHost
;
56 class RenderWidgetHostImpl
;
57 class RenderWidgetHostViewFrameSubscriber
;
58 class StoragePartition
;
59 class StoragePartitionImpl
;
61 typedef base::Thread
* (*RendererMainThreadFactoryFunction
)(
62 const std::string
& id
);
64 // Implements a concrete RenderProcessHost for the browser process for talking
65 // to actual renderer processes (as opposed to mocks).
67 // Represents the browser side of the browser <--> renderer communication
68 // channel. There will be one RenderProcessHost per renderer process.
70 // This object is refcounted so that it can release its resources when all
71 // hosts using it go away.
73 // This object communicates back and forth with the RenderProcess object
74 // running in the renderer process. Each RenderProcessHost and RenderProcess
75 // keeps a list of RenderView (renderer) and WebContentsImpl (browser) which
76 // are correlated with IDs. This way, the Views and the corresponding ViewHosts
77 // communicate through the two process objects.
79 // A RenderProcessHost is also associated with one and only one
80 // StoragePartition. This allows us to implement strong storage isolation
81 // because all the IPCs from the RenderViews (renderer) will only ever be able
82 // to access the partition they are assigned to.
83 class CONTENT_EXPORT RenderProcessHostImpl
84 : public RenderProcessHost
,
85 public ChildProcessLauncher::Client
,
86 public GpuDataManagerObserver
{
88 RenderProcessHostImpl(BrowserContext
* browser_context
,
89 StoragePartitionImpl
* storage_partition_impl
,
90 bool is_isolated_guest
);
91 virtual ~RenderProcessHostImpl();
93 // RenderProcessHost implementation (public portion).
94 virtual void EnableSendQueue() OVERRIDE
;
95 virtual bool Init() OVERRIDE
;
96 virtual int GetNextRoutingID() OVERRIDE
;
97 virtual void AddRoute(int32 routing_id
, IPC::Listener
* listener
) OVERRIDE
;
98 virtual void RemoveRoute(int32 routing_id
) OVERRIDE
;
99 virtual void AddObserver(RenderProcessHostObserver
* observer
) OVERRIDE
;
100 virtual void RemoveObserver(RenderProcessHostObserver
* observer
) OVERRIDE
;
101 virtual void ReceivedBadMessage() OVERRIDE
;
102 virtual void WidgetRestored() OVERRIDE
;
103 virtual void WidgetHidden() OVERRIDE
;
104 virtual int VisibleWidgetCount() const OVERRIDE
;
105 virtual bool IsIsolatedGuest() const OVERRIDE
;
106 virtual StoragePartition
* GetStoragePartition() const OVERRIDE
;
107 virtual bool FastShutdownIfPossible() OVERRIDE
;
108 virtual void DumpHandles() OVERRIDE
;
109 virtual base::ProcessHandle
GetHandle() const OVERRIDE
;
110 virtual BrowserContext
* GetBrowserContext() const OVERRIDE
;
111 virtual bool InSameStoragePartition(
112 StoragePartition
* partition
) const OVERRIDE
;
113 virtual int GetID() const OVERRIDE
;
114 virtual bool HasConnection() const OVERRIDE
;
115 virtual void SetIgnoreInputEvents(bool ignore_input_events
) OVERRIDE
;
116 virtual bool IgnoreInputEvents() const OVERRIDE
;
117 virtual void Cleanup() OVERRIDE
;
118 virtual void AddPendingView() OVERRIDE
;
119 virtual void RemovePendingView() OVERRIDE
;
120 virtual void SetSuddenTerminationAllowed(bool enabled
) OVERRIDE
;
121 virtual bool SuddenTerminationAllowed() const OVERRIDE
;
122 virtual IPC::ChannelProxy
* GetChannel() OVERRIDE
;
123 virtual void AddFilter(BrowserMessageFilter
* filter
) OVERRIDE
;
124 virtual bool FastShutdownForPageCount(size_t count
) OVERRIDE
;
125 virtual bool FastShutdownStarted() const OVERRIDE
;
126 virtual base::TimeDelta
GetChildProcessIdleTime() const OVERRIDE
;
127 virtual void ResumeRequestsForView(int route_id
) OVERRIDE
;
128 virtual void FilterURL(bool empty_allowed
, GURL
* url
) OVERRIDE
;
129 #if defined(ENABLE_WEBRTC)
130 virtual void EnableAecDump(const base::FilePath
& file
) OVERRIDE
;
131 virtual void DisableAecDump() OVERRIDE
;
132 virtual void SetWebRtcLogMessageCallback(
133 base::Callback
<void(const std::string
&)> callback
) OVERRIDE
;
134 virtual WebRtcStopRtpDumpCallback
StartRtpDump(
137 const WebRtcRtpPacketCallback
& packet_callback
) OVERRIDE
;
139 virtual void ResumeDeferredNavigation(const GlobalRequestID
& request_id
)
141 virtual void NotifyTimezoneChange() OVERRIDE
;
142 virtual ServiceRegistry
* GetServiceRegistry() OVERRIDE
;
144 // IPC::Sender via RenderProcessHost.
145 virtual bool Send(IPC::Message
* msg
) OVERRIDE
;
147 // IPC::Listener via RenderProcessHost.
148 virtual bool OnMessageReceived(const IPC::Message
& msg
) OVERRIDE
;
149 virtual void OnChannelConnected(int32 peer_pid
) OVERRIDE
;
150 virtual void OnChannelError() OVERRIDE
;
151 virtual void OnBadMessageReceived(const IPC::Message
& message
) OVERRIDE
;
153 // ChildProcessLauncher::Client implementation.
154 virtual void OnProcessLaunched() OVERRIDE
;
156 scoped_refptr
<AudioRendererHost
> audio_renderer_host() const;
158 // Call this function when it is evident that the child process is actively
159 // performing some operation, for example if we just received an IPC message.
160 void mark_child_process_activity_time() {
161 child_process_activity_time_
= base::TimeTicks::Now();
164 // Returns the current number of active views in this process. Excludes
165 // any RenderViewHosts that are swapped out.
166 int GetActiveViewCount();
168 // Start and end frame subscription for a specific renderer.
169 // This API only supports subscription to accelerated composited frames.
170 void BeginFrameSubscription(
172 scoped_ptr
<RenderWidgetHostViewFrameSubscriber
> subscriber
);
173 void EndFrameSubscription(int route_id
);
175 #if defined(ENABLE_WEBRTC)
176 // Fires the webrtc log message callback with |message|, if callback is set.
177 void WebRtcLogMessage(const std::string
& message
);
180 // Used to extend the lifetime of the sessions until the render view
181 // in the renderer is fully closed. This is static because its also called
182 // with mock hosts as input in test cases.
183 static void ReleaseOnCloseACK(
184 RenderProcessHost
* host
,
185 const SessionStorageNamespaceMap
& sessions
,
188 // Register/unregister the host identified by the host id in the global host
190 static void RegisterHost(int host_id
, RenderProcessHost
* host
);
191 static void UnregisterHost(int host_id
);
193 // Implementation of FilterURL below that can be shared with the mock class.
194 static void FilterURL(RenderProcessHost
* rph
, bool empty_allowed
, GURL
* url
);
196 // Returns true if |host| is suitable for launching a new view with |site_url|
197 // in the given |browser_context|.
198 static bool IsSuitableHost(RenderProcessHost
* host
,
199 BrowserContext
* browser_context
,
200 const GURL
& site_url
);
202 // Returns an existing RenderProcessHost for |url| in |browser_context|,
203 // if one exists. Otherwise a new RenderProcessHost should be created and
204 // registered using RegisterProcessHostForSite().
205 // This should only be used for process-per-site mode, which can be enabled
206 // globally with a command line flag or per-site, as determined by
207 // SiteInstanceImpl::ShouldUseProcessPerSite.
208 static RenderProcessHost
* GetProcessHostForSite(
209 BrowserContext
* browser_context
,
212 // Registers the given |process| to be used for any instance of |url|
213 // within |browser_context|.
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 void RegisterProcessHostForSite(
218 BrowserContext
* browser_context
,
219 RenderProcessHost
* process
,
222 static base::MessageLoop
* GetInProcessRendererThreadForTesting();
224 // This forces a renderer that is running "in process" to shut down.
225 static void ShutDownInProcessRenderer();
227 static void RegisterRendererMainThreadFactory(
228 RendererMainThreadFactoryFunction create
);
230 #if defined(OS_ANDROID)
231 const scoped_refptr
<BrowserDemuxerAndroid
>& browser_demuxer_android() {
232 return browser_demuxer_android_
;
236 MessagePortMessageFilter
* message_port_message_filter() const {
237 return message_port_message_filter_
.get();
240 void set_is_isolated_guest_for_testing(bool is_isolated_guest
) {
241 is_isolated_guest_
= is_isolated_guest
;
244 // Called when the existence of the other renderer process which is connected
245 // to the Worker in this renderer process has changed.
246 // It is only called when "enable-embedded-shared-worker" flag is set.
247 void IncrementWorkerRefCount();
248 void DecrementWorkerRefCount();
250 // Call this function to resume the navigation when it was deferred
251 // immediately after receiving response headers.
252 void ResumeResponseDeferredAtStart(const GlobalRequestID
& request_id
);
254 // Activates Mojo for this process. Does nothing if Mojo is already activated.
255 void EnsureMojoActivated();
258 // A proxy for our IPC::Channel that lives on the IO thread (see
259 // browser_process.h)
260 scoped_ptr
<IPC::ChannelProxy
> channel_
;
262 // True if fast shutdown has been performed on this RPH.
263 bool fast_shutdown_started_
;
265 // True if we've posted a DeleteTask and will be deleted soon.
269 // True if this object has deleted itself.
270 bool is_self_deleted_
;
273 // The count of currently swapped out but pending RenderViews. We have
274 // started to swap these in, so the renderer process should not exit if
275 // this count is non-zero.
276 int32 pending_views_
;
279 friend class VisitRelayingRenderProcessHost
;
281 void MaybeActivateMojo();
282 bool ShouldUseMojoChannel() const;
283 scoped_ptr
<IPC::ChannelProxy
> CreateChannelProxy(
284 const std::string
& channel_id
);
286 // Creates and adds the IO thread message filters.
287 void CreateMessageFilters();
289 // Control message handlers.
290 void OnShutdownRequest();
291 void OnDumpHandlesDone();
292 void SuddenTerminationChanged(bool enabled
);
293 void OnUserMetricsRecordAction(const std::string
& action
);
294 void OnSavedPageAsMHTML(int job_id
, int64 mhtml_file_size
);
295 void OnCloseACK(int old_route_id
);
297 // Generates a command line to be used to spawn a renderer and appends the
298 // results to |*command_line|.
299 void AppendRendererCommandLine(base::CommandLine
* command_line
) const;
301 // Copies applicable command line switches from the given |browser_cmd| line
302 // flags to the output |renderer_cmd| line flags. Not all switches will be
304 void PropagateBrowserCommandLineToRenderer(
305 const base::CommandLine
& browser_cmd
,
306 base::CommandLine
* renderer_cmd
) const;
308 // Callers can reduce the RenderProcess' priority.
309 void SetBackgrounded(bool backgrounded
);
311 // Handle termination of our process.
312 void ProcessDied(bool already_dead
);
314 virtual void OnGpuSwitching() OVERRIDE
;
316 #if defined(ENABLE_WEBRTC)
317 void OnRegisterAecDumpConsumer(int id
);
318 void OnUnregisterAecDumpConsumer(int id
);
319 void RegisterAecDumpConsumerOnUIThread(int id
);
320 void UnregisterAecDumpConsumerOnUIThread(int id
);
321 void EnableAecDumpForId(const base::FilePath
& file
, int id
);
322 // Sends |file_for_transit| to the render process.
323 void SendAecDumpFileToRenderer(int id
,
324 IPC::PlatformFileForTransit file_for_transit
);
325 void SendDisableAecDumpToRenderer();
328 // GpuMemoryBuffer allocation handler.
329 void OnAllocateGpuMemoryBuffer(uint32 width
,
331 uint32 internalformat
,
333 IPC::Message
* reply
);
334 void GpuMemoryBufferAllocated(IPC::Message
* reply
,
335 const gfx::GpuMemoryBufferHandle
& handle
);
336 void OnDeletedGpuMemoryBuffer(gfx::GpuMemoryBufferType type
,
337 const gfx::GpuMemoryBufferId
& id
);
339 scoped_ptr
<MojoApplicationHost
> mojo_application_host_
;
340 bool mojo_activation_required_
;
342 // The registered IPC listener objects. When this list is empty, we should
344 IDMap
<IPC::Listener
> listeners_
;
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
349 int32 visible_widgets_
;
351 // Does this process have backgrounded priority.
354 // Used to allow a RenderWidgetHost to intercept various messages on the
356 scoped_refptr
<RenderWidgetHelper
> widget_helper_
;
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_
;
366 // The filter for MessagePort messages coming from the renderer.
367 scoped_refptr
<MessagePortMessageFilter
> message_port_message_filter_
;
369 // Used in single-process mode.
370 scoped_ptr
<base::Thread
> in_process_renderer_
;
372 // True after Init() has been called. We can't just check channel_ because we
373 // also reset that in the case of process termination.
374 bool is_initialized_
;
376 // Used to launch and terminate the process without blocking the UI thread.
377 scoped_ptr
<ChildProcessLauncher
> child_process_launcher_
;
379 // Messages we queue while waiting for the process handle. We queue them here
380 // instead of in the channel so that we ensure they're sent after init related
381 // messages that are sent once the process handle is available. This is
382 // because the queued messages may have dependencies on the init messages.
383 std::queue
<IPC::Message
*> queued_messages_
;
385 // The globally-unique identifier for this RPH.
388 BrowserContext
* browser_context_
;
390 // Owned by |browser_context_|.
391 StoragePartitionImpl
* storage_partition_impl_
;
393 // The observers watching our lifetime.
394 ObserverList
<RenderProcessHostObserver
> observers_
;
396 // True if the process can be shut down suddenly. If this is true, then we're
397 // sure that all the RenderViews in the process can be shutdown suddenly. If
398 // it's false, then specific RenderViews might still be allowed to be shutdown
399 // suddenly by checking their SuddenTerminationAllowed() flag. This can occur
400 // if one WebContents has an unload event listener but another WebContents in
401 // the same process doesn't.
402 bool sudden_termination_allowed_
;
404 // Set to true if we shouldn't send input events. We actually do the
405 // filtering for this at the render widget level.
406 bool ignore_input_events_
;
408 // Records the last time we regarded the child process active.
409 base::TimeTicks child_process_activity_time_
;
411 // Indicates whether this is a RenderProcessHost of a Browser Plugin guest
413 bool is_isolated_guest_
;
415 // Forwards messages between WebRTCInternals in the browser process
416 // and PeerConnectionTracker in the renderer process.
417 scoped_refptr
<PeerConnectionTrackerHost
> peer_connection_tracker_host_
;
419 // Prevents the class from being added as a GpuDataManagerImpl observer more
421 bool gpu_observer_registered_
;
423 // Set if a call to Cleanup is required once the RenderProcessHostImpl is no
424 // longer within the RenderProcessHostObserver::RenderProcessExited callbacks.
425 bool delayed_cleanup_needed_
;
427 // Indicates whether RenderProcessHostImpl is currently iterating and calling
428 // through RenderProcessHostObserver::RenderProcessExited.
429 bool within_process_died_observer_
;
431 // Forwards power state messages to the renderer process.
432 PowerMonitorMessageBroadcaster power_monitor_broadcaster_
;
434 scoped_refptr
<AudioRendererHost
> audio_renderer_host_
;
436 #if defined(OS_ANDROID)
437 scoped_refptr
<BrowserDemuxerAndroid
> browser_demuxer_android_
;
440 #if defined(ENABLE_WEBRTC)
441 base::Callback
<void(const std::string
&)> webrtc_log_message_callback_
;
443 scoped_refptr
<P2PSocketDispatcherHost
> p2p_socket_dispatcher_host_
;
445 // Must be accessed on UI thread.
446 std::vector
<int> aec_dump_consumers_
;
448 WebRtcStopRtpDumpCallback stop_rtp_dump_callback_
;
451 int worker_ref_count_
;
453 // Records the time when the process starts surviving for workers for UMA.
454 base::TimeTicks survive_for_worker_start_time_
;
456 base::WeakPtrFactory
<RenderProcessHostImpl
> weak_factory_
;
458 #if defined(OS_MACOSX)
459 base::ScopedCFTypeRef
<IOSurfaceRef
> last_io_surface_
;
462 DISALLOW_COPY_AND_ASSIGN(RenderProcessHostImpl
);
465 } // namespace content
467 #endif // CONTENT_BROWSER_RENDERER_HOST_BROWSER_RENDER_PROCESS_HOST_IMPL_H_