cc: Make picture pile base thread safe.
[chromium-blink-merge.git] / content / browser / renderer_host / render_process_host_impl.h
blob233039b2a53afe136a079a7b4813a47264a9a20e
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_
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 "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/render_process_host.h"
22 #include "ipc/ipc_channel_proxy.h"
23 #include "ipc/ipc_platform_file.h"
24 #include "mojo/public/cpp/bindings/interface_ptr.h"
25 #include "ui/gfx/gpu_memory_buffer.h"
26 #include "ui/gl/gpu_switching_observer.h"
28 namespace base {
29 class CommandLine;
30 class MessageLoop;
33 namespace gfx {
34 class Size;
37 namespace IPC {
38 class ChannelMojoHost;
41 namespace content {
42 class AudioRendererHost;
43 class BrowserCdmManager;
44 class BrowserDemuxerAndroid;
45 class GpuMessageFilter;
46 class MessagePortMessageFilter;
47 class MojoApplicationHost;
48 #if defined(ENABLE_WEBRTC)
49 class P2PSocketDispatcherHost;
50 #endif
51 class PeerConnectionTrackerHost;
52 class RendererMainThread;
53 class RenderWidgetHelper;
54 class RenderWidgetHost;
55 class RenderWidgetHostImpl;
56 class RenderWidgetHostViewFrameSubscriber;
57 class StoragePartition;
58 class StoragePartitionImpl;
60 typedef base::Thread* (*RendererMainThreadFactoryFunction)(
61 const std::string& id);
63 // Implements a concrete RenderProcessHost for the browser process for talking
64 // to actual renderer processes (as opposed to mocks).
66 // Represents the browser side of the browser <--> renderer communication
67 // channel. There will be one RenderProcessHost per renderer process.
69 // This object is refcounted so that it can release its resources when all
70 // hosts using it go away.
72 // This object communicates back and forth with the RenderProcess object
73 // running in the renderer process. Each RenderProcessHost and RenderProcess
74 // keeps a list of RenderView (renderer) and WebContentsImpl (browser) which
75 // are correlated with IDs. This way, the Views and the corresponding ViewHosts
76 // communicate through the two process objects.
78 // A RenderProcessHost is also associated with one and only one
79 // StoragePartition. This allows us to implement strong storage isolation
80 // because all the IPCs from the RenderViews (renderer) will only ever be able
81 // to access the partition they are assigned to.
82 class CONTENT_EXPORT RenderProcessHostImpl
83 : public RenderProcessHost,
84 public ChildProcessLauncher::Client,
85 public ui::GpuSwitchingObserver {
86 public:
87 RenderProcessHostImpl(BrowserContext* browser_context,
88 StoragePartitionImpl* storage_partition_impl,
89 bool is_isolated_guest);
90 ~RenderProcessHostImpl() override;
92 // RenderProcessHost implementation (public portion).
93 void EnableSendQueue() override;
94 bool Init() override;
95 int GetNextRoutingID() override;
96 void AddRoute(int32 routing_id, IPC::Listener* listener) override;
97 void RemoveRoute(int32 routing_id) override;
98 void AddObserver(RenderProcessHostObserver* observer) override;
99 void RemoveObserver(RenderProcessHostObserver* observer) override;
100 void ReceivedBadMessage() override;
101 void WidgetRestored() override;
102 void WidgetHidden() override;
103 int VisibleWidgetCount() const override;
104 bool IsIsolatedGuest() const override;
105 StoragePartition* GetStoragePartition() const override;
106 bool FastShutdownIfPossible() override;
107 void DumpHandles() override;
108 base::ProcessHandle GetHandle() const override;
109 BrowserContext* GetBrowserContext() const override;
110 bool InSameStoragePartition(StoragePartition* partition) const override;
111 int GetID() const override;
112 bool HasConnection() const override;
113 void SetIgnoreInputEvents(bool ignore_input_events) override;
114 bool IgnoreInputEvents() const override;
115 void Cleanup() override;
116 void AddPendingView() override;
117 void RemovePendingView() override;
118 void SetSuddenTerminationAllowed(bool enabled) override;
119 bool SuddenTerminationAllowed() const override;
120 IPC::ChannelProxy* GetChannel() override;
121 void AddFilter(BrowserMessageFilter* filter) override;
122 bool FastShutdownForPageCount(size_t count) override;
123 bool FastShutdownStarted() const override;
124 base::TimeDelta GetChildProcessIdleTime() const override;
125 void ResumeRequestsForView(int route_id) override;
126 void FilterURL(bool empty_allowed, GURL* url) override;
127 #if defined(ENABLE_WEBRTC)
128 void EnableAecDump(const base::FilePath& file) override;
129 void DisableAecDump() override;
130 void SetWebRtcLogMessageCallback(
131 base::Callback<void(const std::string&)> callback) override;
132 WebRtcStopRtpDumpCallback StartRtpDump(
133 bool incoming,
134 bool outgoing,
135 const WebRtcRtpPacketCallback& packet_callback) override;
136 #endif
137 void ResumeDeferredNavigation(const GlobalRequestID& request_id) override;
138 void NotifyTimezoneChange() override;
139 ServiceRegistry* GetServiceRegistry() override;
140 const base::TimeTicks& GetInitTimeForNavigationMetrics() const override;
142 // IPC::Sender via RenderProcessHost.
143 bool Send(IPC::Message* msg) override;
145 // IPC::Listener via RenderProcessHost.
146 bool OnMessageReceived(const IPC::Message& msg) override;
147 void OnChannelConnected(int32 peer_pid) override;
148 void OnChannelError() override;
149 void OnBadMessageReceived(const IPC::Message& message) override;
151 // ChildProcessLauncher::Client implementation.
152 void OnProcessLaunched() override;
154 scoped_refptr<AudioRendererHost> audio_renderer_host() const;
156 // Call this function when it is evident that the child process is actively
157 // performing some operation, for example if we just received an IPC message.
158 void mark_child_process_activity_time() {
159 child_process_activity_time_ = base::TimeTicks::Now();
162 // Returns the current number of active views in this process. Excludes
163 // any RenderViewHosts that are swapped out.
164 int GetActiveViewCount();
166 // Start and end frame subscription for a specific renderer.
167 // This API only supports subscription to accelerated composited frames.
168 void BeginFrameSubscription(
169 int route_id,
170 scoped_ptr<RenderWidgetHostViewFrameSubscriber> subscriber);
171 void EndFrameSubscription(int route_id);
173 #if defined(ENABLE_WEBRTC)
174 // Fires the webrtc log message callback with |message|, if callback is set.
175 void WebRtcLogMessage(const std::string& message);
176 #endif
178 // Used to extend the lifetime of the sessions until the render view
179 // in the renderer is fully closed. This is static because its also called
180 // with mock hosts as input in test cases.
181 static void ReleaseOnCloseACK(
182 RenderProcessHost* host,
183 const SessionStorageNamespaceMap& sessions,
184 int view_route_id);
186 // Register/unregister the host identified by the host id in the global host
187 // list.
188 static void RegisterHost(int host_id, RenderProcessHost* host);
189 static void UnregisterHost(int host_id);
191 // Implementation of FilterURL below that can be shared with the mock class.
192 static void FilterURL(RenderProcessHost* rph, bool empty_allowed, GURL* url);
194 // Returns true if |host| is suitable for launching a new view with |site_url|
195 // in the given |browser_context|.
196 static bool IsSuitableHost(RenderProcessHost* host,
197 BrowserContext* browser_context,
198 const GURL& site_url);
200 // Returns an existing RenderProcessHost for |url| in |browser_context|,
201 // if one exists. Otherwise a new RenderProcessHost should be created and
202 // registered using RegisterProcessHostForSite().
203 // This should only be used for process-per-site mode, which can be enabled
204 // globally with a command line flag or per-site, as determined by
205 // SiteInstanceImpl::ShouldUseProcessPerSite.
206 static RenderProcessHost* GetProcessHostForSite(
207 BrowserContext* browser_context,
208 const GURL& url);
210 // Registers the given |process| to be used for any instance of |url|
211 // within |browser_context|.
212 // This should only be used for process-per-site mode, which can be enabled
213 // globally with a command line flag or per-site, as determined by
214 // SiteInstanceImpl::ShouldUseProcessPerSite.
215 static void RegisterProcessHostForSite(
216 BrowserContext* browser_context,
217 RenderProcessHost* process,
218 const GURL& url);
220 static base::MessageLoop* GetInProcessRendererThreadForTesting();
222 // This forces a renderer that is running "in process" to shut down.
223 static void ShutDownInProcessRenderer();
225 static void RegisterRendererMainThreadFactory(
226 RendererMainThreadFactoryFunction create);
228 #if defined(OS_ANDROID)
229 const scoped_refptr<BrowserDemuxerAndroid>& browser_demuxer_android() {
230 return browser_demuxer_android_;
232 #endif
234 #if defined(ENABLE_BROWSER_CDMS)
235 const scoped_refptr<BrowserCdmManager>& browser_cdm_manager() {
236 return browser_cdm_manager_;
238 #endif
240 MessagePortMessageFilter* message_port_message_filter() const {
241 return message_port_message_filter_.get();
244 void set_is_isolated_guest_for_testing(bool is_isolated_guest) {
245 is_isolated_guest_ = is_isolated_guest;
248 // Called when the existence of the other renderer process which is connected
249 // to the Worker in this renderer process has changed.
250 // It is only called when "enable-embedded-shared-worker" flag is set.
251 void IncrementWorkerRefCount();
252 void DecrementWorkerRefCount();
254 // Call this function to resume the navigation when it was deferred
255 // immediately after receiving response headers.
256 void ResumeResponseDeferredAtStart(const GlobalRequestID& request_id);
258 protected:
259 // A proxy for our IPC::Channel that lives on the IO thread (see
260 // browser_process.h)
261 scoped_ptr<IPC::ChannelProxy> channel_;
263 // A host object ChannelMojo needs. The lifetime is bound to
264 // the RenderProcessHostImpl, not the channel.
265 scoped_ptr<IPC::ChannelMojoHost> channel_mojo_host_;
267 // True if fast shutdown has been performed on this RPH.
268 bool fast_shutdown_started_;
270 // True if we've posted a DeleteTask and will be deleted soon.
271 bool deleting_soon_;
273 #ifndef NDEBUG
274 // True if this object has deleted itself.
275 bool is_self_deleted_;
276 #endif
278 // The count of currently swapped out but pending RenderViews. We have
279 // started to swap these in, so the renderer process should not exit if
280 // this count is non-zero.
281 int32 pending_views_;
283 private:
284 friend class VisitRelayingRenderProcessHost;
286 bool ShouldUseMojoChannel() const;
287 scoped_ptr<IPC::ChannelProxy> CreateChannelProxy(
288 const std::string& channel_id);
290 // Creates and adds the IO thread message filters.
291 void CreateMessageFilters();
293 // Control message handlers.
294 void OnShutdownRequest();
295 void OnDumpHandlesDone();
296 void SuddenTerminationChanged(bool enabled);
297 void OnUserMetricsRecordAction(const std::string& action);
298 void OnSavedPageAsMHTML(int job_id, int64 mhtml_file_size);
299 void OnCloseACK(int old_route_id);
301 // Generates a command line to be used to spawn a renderer and appends the
302 // results to |*command_line|.
303 void AppendRendererCommandLine(base::CommandLine* command_line) const;
305 // Copies applicable command line switches from the given |browser_cmd| line
306 // flags to the output |renderer_cmd| line flags. Not all switches will be
307 // copied over.
308 void PropagateBrowserCommandLineToRenderer(
309 const base::CommandLine& browser_cmd,
310 base::CommandLine* renderer_cmd) const;
312 // Callers can reduce the RenderProcess' priority.
313 void SetBackgrounded(bool backgrounded);
315 // Handle termination of our process.
316 void ProcessDied(bool already_dead);
318 // GpuSwitchingObserver implementation.
319 void OnGpuSwitched() override;
321 #if defined(ENABLE_WEBRTC)
322 void OnRegisterAecDumpConsumer(int id);
323 void OnUnregisterAecDumpConsumer(int id);
324 void RegisterAecDumpConsumerOnUIThread(int id);
325 void UnregisterAecDumpConsumerOnUIThread(int id);
326 void EnableAecDumpForId(const base::FilePath& file, int id);
327 // Sends |file_for_transit| to the render process.
328 void SendAecDumpFileToRenderer(int id,
329 IPC::PlatformFileForTransit file_for_transit);
330 void SendDisableAecDumpToRenderer();
331 #endif
333 scoped_ptr<MojoApplicationHost> mojo_application_host_;
335 // The registered IPC listener objects. When this list is empty, we should
336 // delete ourselves.
337 IDMap<IPC::Listener> listeners_;
339 // The count of currently visible widgets. Since the host can be a container
340 // for multiple widgets, it uses this count to determine when it should be
341 // backgrounded.
342 int32 visible_widgets_;
344 // Does this process have backgrounded priority.
345 bool backgrounded_;
347 // Used to allow a RenderWidgetHost to intercept various messages on the
348 // IO thread.
349 scoped_refptr<RenderWidgetHelper> widget_helper_;
351 // The filter for GPU-related messages coming from the renderer.
352 // Thread safety note: this field is to be accessed from the UI thread.
353 // We don't keep a reference to it, to avoid it being destroyed on the UI
354 // thread, but we clear this field when we clear channel_. When channel_ goes
355 // away, it posts a task to the IO thread to destroy it there, so we know that
356 // it's valid if non-NULL.
357 GpuMessageFilter* gpu_message_filter_;
359 // The filter for MessagePort messages coming from the renderer.
360 scoped_refptr<MessagePortMessageFilter> message_port_message_filter_;
362 // Used in single-process mode.
363 scoped_ptr<base::Thread> in_process_renderer_;
365 // True after Init() has been called. We can't just check channel_ because we
366 // also reset that in the case of process termination.
367 bool is_initialized_;
369 // PlzNavigate
370 // Stores the time at which the first call to Init happened.
371 base::TimeTicks init_time_;
373 // Used to launch and terminate the process without blocking the UI thread.
374 scoped_ptr<ChildProcessLauncher> child_process_launcher_;
376 // Messages we queue while waiting for the process handle. We queue them here
377 // instead of in the channel so that we ensure they're sent after init related
378 // messages that are sent once the process handle is available. This is
379 // because the queued messages may have dependencies on the init messages.
380 std::queue<IPC::Message*> queued_messages_;
382 // The globally-unique identifier for this RPH.
383 int id_;
385 BrowserContext* browser_context_;
387 // Owned by |browser_context_|.
388 StoragePartitionImpl* storage_partition_impl_;
390 // The observers watching our lifetime.
391 ObserverList<RenderProcessHostObserver> observers_;
393 // True if the process can be shut down suddenly. If this is true, then we're
394 // sure that all the RenderViews in the process can be shutdown suddenly. If
395 // it's false, then specific RenderViews might still be allowed to be shutdown
396 // suddenly by checking their SuddenTerminationAllowed() flag. This can occur
397 // if one WebContents has an unload event listener but another WebContents in
398 // the same process doesn't.
399 bool sudden_termination_allowed_;
401 // Set to true if we shouldn't send input events. We actually do the
402 // filtering for this at the render widget level.
403 bool ignore_input_events_;
405 // Records the last time we regarded the child process active.
406 base::TimeTicks child_process_activity_time_;
408 // Indicates whether this is a RenderProcessHost of a Browser Plugin guest
409 // renderer.
410 bool is_isolated_guest_;
412 // Forwards messages between WebRTCInternals in the browser process
413 // and PeerConnectionTracker in the renderer process.
414 scoped_refptr<PeerConnectionTrackerHost> peer_connection_tracker_host_;
416 // Prevents the class from being added as a GpuDataManagerImpl observer more
417 // than once.
418 bool gpu_observer_registered_;
420 // Set if a call to Cleanup is required once the RenderProcessHostImpl is no
421 // longer within the RenderProcessHostObserver::RenderProcessExited callbacks.
422 bool delayed_cleanup_needed_;
424 // Indicates whether RenderProcessHostImpl is currently iterating and calling
425 // through RenderProcessHostObserver::RenderProcessExited.
426 bool within_process_died_observer_;
428 // Forwards power state messages to the renderer process.
429 PowerMonitorMessageBroadcaster power_monitor_broadcaster_;
431 scoped_refptr<AudioRendererHost> audio_renderer_host_;
433 #if defined(OS_ANDROID)
434 scoped_refptr<BrowserDemuxerAndroid> browser_demuxer_android_;
435 #endif
437 #if defined(ENABLE_BROWSER_CDMS)
438 scoped_refptr<BrowserCdmManager> browser_cdm_manager_;
439 #endif
441 #if defined(ENABLE_WEBRTC)
442 base::Callback<void(const std::string&)> webrtc_log_message_callback_;
444 scoped_refptr<P2PSocketDispatcherHost> p2p_socket_dispatcher_host_;
446 // Must be accessed on UI thread.
447 std::vector<int> aec_dump_consumers_;
449 WebRtcStopRtpDumpCallback stop_rtp_dump_callback_;
450 #endif
452 int worker_ref_count_;
454 // Records the time when the process starts surviving for workers for UMA.
455 base::TimeTicks survive_for_worker_start_time_;
457 base::WeakPtrFactory<RenderProcessHostImpl> weak_factory_;
459 DISALLOW_COPY_AND_ASSIGN(RenderProcessHostImpl);
462 } // namespace content
464 #endif // CONTENT_BROWSER_RENDERER_HOST_BROWSER_RENDER_PROCESS_HOST_IMPL_H_