Simplify ChildProcessLauncher
[chromium-blink-merge.git] / content / browser / renderer_host / render_process_host_impl.h
blob93b7aa542f183dae50ead2786cf6783d31891534
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_
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 "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 namespace base {
28 class CommandLine;
29 class MessageLoop;
32 namespace gfx {
33 class Size;
36 namespace gpu {
37 class ValueStateMap;
40 namespace IPC {
41 class ChannelMojoHost;
44 namespace content {
45 class AudioRendererHost;
46 class BrowserCdmManager;
47 class BrowserDemuxerAndroid;
48 class GpuMessageFilter;
49 class InProcessChildThreadParams;
50 class MessagePortMessageFilter;
51 class MojoApplicationHost;
52 class NotificationMessageFilter;
53 #if defined(ENABLE_WEBRTC)
54 class P2PSocketDispatcherHost;
55 #endif
56 class PermissionServiceContext;
57 class PeerConnectionTrackerHost;
58 class RendererMainThread;
59 class RenderWidgetHelper;
60 class RenderWidgetHost;
61 class RenderWidgetHostImpl;
62 class RenderWidgetHostViewFrameSubscriber;
63 class StoragePartition;
64 class StoragePartitionImpl;
66 typedef base::Thread* (*RendererMainThreadFactoryFunction)(
67 const InProcessChildThreadParams& params);
69 // Implements a concrete RenderProcessHost for the browser process for talking
70 // to actual renderer processes (as opposed to mocks).
72 // Represents the browser side of the browser <--> renderer communication
73 // channel. There will be one RenderProcessHost per renderer process.
75 // This object is refcounted so that it can release its resources when all
76 // hosts using it go away.
78 // This object communicates back and forth with the RenderProcess object
79 // running in the renderer process. Each RenderProcessHost and RenderProcess
80 // keeps a list of RenderView (renderer) and WebContentsImpl (browser) which
81 // are correlated with IDs. This way, the Views and the corresponding ViewHosts
82 // communicate through the two process objects.
84 // A RenderProcessHost is also associated with one and only one
85 // StoragePartition. This allows us to implement strong storage isolation
86 // because all the IPCs from the RenderViews (renderer) will only ever be able
87 // to access the partition they are assigned to.
88 class CONTENT_EXPORT RenderProcessHostImpl
89 : public RenderProcessHost,
90 public ChildProcessLauncher::Client,
91 public ui::GpuSwitchingObserver {
92 public:
93 RenderProcessHostImpl(BrowserContext* browser_context,
94 StoragePartitionImpl* storage_partition_impl,
95 bool is_isolated_guest);
96 ~RenderProcessHostImpl() override;
98 // RenderProcessHost implementation (public portion).
99 void EnableSendQueue() override;
100 bool Init() override;
101 int GetNextRoutingID() override;
102 void AddRoute(int32 routing_id, IPC::Listener* listener) override;
103 void RemoveRoute(int32 routing_id) override;
104 void AddObserver(RenderProcessHostObserver* observer) override;
105 void RemoveObserver(RenderProcessHostObserver* observer) override;
106 void ShutdownForBadMessage() override;
107 void WidgetRestored() override;
108 void WidgetHidden() override;
109 int VisibleWidgetCount() const override;
110 bool IsIsolatedGuest() const override;
111 StoragePartition* GetStoragePartition() const override;
112 bool Shutdown(int exit_code, bool wait) override;
113 bool FastShutdownIfPossible() override;
114 void DumpHandles() override;
115 base::ProcessHandle GetHandle() const override;
116 BrowserContext* GetBrowserContext() const override;
117 bool InSameStoragePartition(StoragePartition* partition) const override;
118 int GetID() const override;
119 bool HasConnection() const override;
120 void SetIgnoreInputEvents(bool ignore_input_events) override;
121 bool IgnoreInputEvents() const override;
122 void Cleanup() override;
123 void AddPendingView() override;
124 void RemovePendingView() override;
125 void SetSuddenTerminationAllowed(bool enabled) override;
126 bool SuddenTerminationAllowed() const override;
127 IPC::ChannelProxy* GetChannel() override;
128 void AddFilter(BrowserMessageFilter* filter) override;
129 bool FastShutdownForPageCount(size_t count) override;
130 bool FastShutdownStarted() const override;
131 base::TimeDelta GetChildProcessIdleTime() const override;
132 void ResumeRequestsForView(int route_id) override;
133 void FilterURL(bool empty_allowed, GURL* url) override;
134 #if defined(ENABLE_WEBRTC)
135 void EnableAecDump(const base::FilePath& file) override;
136 void DisableAecDump() override;
137 void SetWebRtcLogMessageCallback(
138 base::Callback<void(const std::string&)> callback) override;
139 WebRtcStopRtpDumpCallback StartRtpDump(
140 bool incoming,
141 bool outgoing,
142 const WebRtcRtpPacketCallback& packet_callback) override;
143 #endif
144 void ResumeDeferredNavigation(const GlobalRequestID& request_id) override;
145 void NotifyTimezoneChange() override;
146 ServiceRegistry* GetServiceRegistry() override;
147 const base::TimeTicks& GetInitTimeForNavigationMetrics() const override;
148 bool SubscribeUniformEnabled() const override;
149 void OnAddSubscription(unsigned int target) override;
150 void OnRemoveSubscription(unsigned int target) override;
151 void SendUpdateValueState(
152 unsigned int target, const gpu::ValueState& state) override;
153 #if defined(ENABLE_BROWSER_CDMS)
154 media::BrowserCdm* GetBrowserCdm(int render_frame_id,
155 int cdm_id) const override;
156 #endif
158 // IPC::Sender via RenderProcessHost. SendHelper() can be used to ensure
159 // allocated messages are not leaked after RPHI is destructed.
160 bool Send(IPC::Message* msg) override;
161 bool SendHelper(scoped_ptr<IPC::Message> msg);
163 // IPC::Listener via RenderProcessHost.
164 bool OnMessageReceived(const IPC::Message& msg) override;
165 void OnChannelConnected(int32 peer_pid) override;
166 void OnChannelError() override;
167 void OnBadMessageReceived(const IPC::Message& message) override;
169 // ChildProcessLauncher::Client implementation.
170 void OnProcessLaunched() override;
171 void OnProcessLaunchFailed() override;
173 scoped_refptr<AudioRendererHost> audio_renderer_host() const;
175 // Call this function when it is evident that the child process is actively
176 // performing some operation, for example if we just received an IPC message.
177 void mark_child_process_activity_time() {
178 child_process_activity_time_ = base::TimeTicks::Now();
181 // Start and end frame subscription for a specific renderer.
182 // This API only supports subscription to accelerated composited frames.
183 void BeginFrameSubscription(
184 int route_id,
185 scoped_ptr<RenderWidgetHostViewFrameSubscriber> subscriber);
186 void EndFrameSubscription(int route_id);
188 #if defined(ENABLE_WEBRTC)
189 // Fires the webrtc log message callback with |message|, if callback is set.
190 void WebRtcLogMessage(const std::string& message);
191 #endif
193 // Used to extend the lifetime of the sessions until the render view
194 // in the renderer is fully closed. This is static because its also called
195 // with mock hosts as input in test cases.
196 static void ReleaseOnCloseACK(
197 RenderProcessHost* host,
198 const SessionStorageNamespaceMap& sessions,
199 int view_route_id);
201 // Register/unregister the host identified by the host id in the global host
202 // list.
203 static void RegisterHost(int host_id, RenderProcessHost* host);
204 static void UnregisterHost(int host_id);
206 // Implementation of FilterURL below that can be shared with the mock class.
207 static void FilterURL(RenderProcessHost* rph, bool empty_allowed, GURL* url);
209 // Returns true if |host| is suitable for launching a new view with |site_url|
210 // in the given |browser_context|.
211 static bool IsSuitableHost(RenderProcessHost* host,
212 BrowserContext* browser_context,
213 const GURL& site_url);
215 // Returns an existing RenderProcessHost for |url| in |browser_context|,
216 // if one exists. Otherwise a new RenderProcessHost should be created and
217 // registered using RegisterProcessHostForSite().
218 // This should only be used for process-per-site mode, which can be enabled
219 // globally with a command line flag or per-site, as determined by
220 // SiteInstanceImpl::ShouldUseProcessPerSite.
221 static RenderProcessHost* GetProcessHostForSite(
222 BrowserContext* browser_context,
223 const GURL& url);
225 // Registers the given |process| to be used for any instance of |url|
226 // within |browser_context|.
227 // This should only be used for process-per-site mode, which can be enabled
228 // globally with a command line flag or per-site, as determined by
229 // SiteInstanceImpl::ShouldUseProcessPerSite.
230 static void RegisterProcessHostForSite(
231 BrowserContext* browser_context,
232 RenderProcessHost* process,
233 const GURL& url);
235 static base::MessageLoop* GetInProcessRendererThreadForTesting();
237 // This forces a renderer that is running "in process" to shut down.
238 static void ShutDownInProcessRenderer();
240 static void RegisterRendererMainThreadFactory(
241 RendererMainThreadFactoryFunction create);
243 #if defined(OS_ANDROID)
244 const scoped_refptr<BrowserDemuxerAndroid>& browser_demuxer_android() {
245 return browser_demuxer_android_;
247 #endif
249 #if defined(ENABLE_BROWSER_CDMS)
250 const scoped_refptr<BrowserCdmManager>& browser_cdm_manager() {
251 return browser_cdm_manager_;
253 #endif
255 MessagePortMessageFilter* message_port_message_filter() const {
256 return message_port_message_filter_.get();
259 NotificationMessageFilter* notification_message_filter() const {
260 return notification_message_filter_.get();
263 void set_is_isolated_guest_for_testing(bool is_isolated_guest) {
264 is_isolated_guest_ = is_isolated_guest;
267 // Called when the existence of the other renderer process which is connected
268 // to the Worker in this renderer process has changed.
269 // It is only called when "enable-embedded-shared-worker" flag is set.
270 void IncrementWorkerRefCount();
271 void DecrementWorkerRefCount();
273 // Call this function to resume the navigation when it was deferred
274 // immediately after receiving response headers.
275 void ResumeResponseDeferredAtStart(const GlobalRequestID& request_id);
277 void GetAudioOutputControllers(
278 const GetAudioOutputControllersCallback& callback) const override;
280 protected:
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.
293 bool deleting_soon_;
295 #ifndef NDEBUG
296 // True if this object has deleted itself.
297 bool is_self_deleted_;
298 #endif
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_;
305 private:
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 OnDumpHandlesDone();
321 void SuddenTerminationChanged(bool enabled);
322 void OnUserMetricsRecordAction(const std::string& action);
323 void OnSavedPageAsMHTML(int job_id, int64 mhtml_file_size);
324 void OnCloseACK(int old_route_id);
326 // Generates a command line to be used to spawn a renderer and appends the
327 // results to |*command_line|.
328 void AppendRendererCommandLine(base::CommandLine* command_line) const;
330 // Copies applicable command line switches from the given |browser_cmd| line
331 // flags to the output |renderer_cmd| line flags. Not all switches will be
332 // copied over.
333 void PropagateBrowserCommandLineToRenderer(
334 const base::CommandLine& browser_cmd,
335 base::CommandLine* renderer_cmd) const;
337 // Callers can reduce the RenderProcess' priority.
338 void SetBackgrounded(bool backgrounded);
340 // Handle termination of our process.
341 void ProcessDied(bool already_dead, RendererClosedDetails* known_details);
343 // GpuSwitchingObserver implementation.
344 void OnGpuSwitched() override;
346 #if defined(ENABLE_WEBRTC)
347 void OnRegisterAecDumpConsumer(int id);
348 void OnUnregisterAecDumpConsumer(int id);
349 void RegisterAecDumpConsumerOnUIThread(int id);
350 void UnregisterAecDumpConsumerOnUIThread(int id);
351 void EnableAecDumpForId(const base::FilePath& file, int id);
352 // Sends |file_for_transit| to the render process.
353 void SendAecDumpFileToRenderer(int id,
354 IPC::PlatformFileForTransit file_for_transit);
355 void SendDisableAecDumpToRenderer();
356 #endif
358 scoped_ptr<MojoApplicationHost> mojo_application_host_;
360 // The registered IPC listener objects. When this list is empty, we should
361 // delete ourselves.
362 IDMap<IPC::Listener> listeners_;
364 // The count of currently visible widgets. Since the host can be a container
365 // for multiple widgets, it uses this count to determine when it should be
366 // backgrounded.
367 int32 visible_widgets_;
369 // Does this process have backgrounded priority.
370 bool backgrounded_;
372 // Used to allow a RenderWidgetHost to intercept various messages on the
373 // IO thread.
374 scoped_refptr<RenderWidgetHelper> widget_helper_;
376 // The filter for GPU-related messages coming from the renderer.
377 // Thread safety note: this field is to be accessed from the UI thread.
378 // We don't keep a reference to it, to avoid it being destroyed on the UI
379 // thread, but we clear this field when we clear channel_. When channel_ goes
380 // away, it posts a task to the IO thread to destroy it there, so we know that
381 // it's valid if non-NULL.
382 GpuMessageFilter* gpu_message_filter_;
384 // The filter for MessagePort messages coming from the renderer.
385 scoped_refptr<MessagePortMessageFilter> message_port_message_filter_;
387 // The filter for Web Notification messages coming from the renderer. Holds a
388 // closure per notification that must be freed when the notification closes.
389 scoped_refptr<NotificationMessageFilter> notification_message_filter_;
391 // Used in single-process mode.
392 scoped_ptr<base::Thread> in_process_renderer_;
394 // True after Init() has been called. We can't just check channel_ because we
395 // also reset that in the case of process termination.
396 bool is_initialized_;
398 // PlzNavigate
399 // Stores the time at which the first call to Init happened.
400 base::TimeTicks init_time_;
402 // Used to launch and terminate the process without blocking the UI thread.
403 scoped_ptr<ChildProcessLauncher> child_process_launcher_;
405 // Messages we queue while waiting for the process handle. We queue them here
406 // instead of in the channel so that we ensure they're sent after init related
407 // messages that are sent once the process handle is available. This is
408 // because the queued messages may have dependencies on the init messages.
409 std::queue<IPC::Message*> queued_messages_;
411 // The globally-unique identifier for this RPH.
412 int id_;
414 BrowserContext* browser_context_;
416 // Owned by |browser_context_|.
417 StoragePartitionImpl* storage_partition_impl_;
419 // The observers watching our lifetime.
420 ObserverList<RenderProcessHostObserver> observers_;
422 // True if the process can be shut down suddenly. If this is true, then we're
423 // sure that all the RenderViews in the process can be shutdown suddenly. If
424 // it's false, then specific RenderViews might still be allowed to be shutdown
425 // suddenly by checking their SuddenTerminationAllowed() flag. This can occur
426 // if one WebContents has an unload event listener but another WebContents in
427 // the same process doesn't.
428 bool sudden_termination_allowed_;
430 // Set to true if we shouldn't send input events. We actually do the
431 // filtering for this at the render widget level.
432 bool ignore_input_events_;
434 // Records the last time we regarded the child process active.
435 base::TimeTicks child_process_activity_time_;
437 // Indicates whether this is a RenderProcessHost of a Browser Plugin guest
438 // renderer.
439 bool is_isolated_guest_;
441 // Forwards messages between WebRTCInternals in the browser process
442 // and PeerConnectionTracker in the renderer process.
443 scoped_refptr<PeerConnectionTrackerHost> peer_connection_tracker_host_;
445 // Prevents the class from being added as a GpuDataManagerImpl observer more
446 // than once.
447 bool gpu_observer_registered_;
449 // Set if a call to Cleanup is required once the RenderProcessHostImpl is no
450 // longer within the RenderProcessHostObserver::RenderProcessExited callbacks.
451 bool delayed_cleanup_needed_;
453 // Indicates whether RenderProcessHostImpl is currently iterating and calling
454 // through RenderProcessHostObserver::RenderProcessExited.
455 bool within_process_died_observer_;
457 // Forwards power state messages to the renderer process.
458 PowerMonitorMessageBroadcaster power_monitor_broadcaster_;
460 scoped_refptr<AudioRendererHost> audio_renderer_host_;
462 #if defined(OS_ANDROID)
463 scoped_refptr<BrowserDemuxerAndroid> browser_demuxer_android_;
464 #endif
466 #if defined(ENABLE_BROWSER_CDMS)
467 scoped_refptr<BrowserCdmManager> browser_cdm_manager_;
468 #endif
470 #if defined(ENABLE_WEBRTC)
471 base::Callback<void(const std::string&)> webrtc_log_message_callback_;
473 scoped_refptr<P2PSocketDispatcherHost> p2p_socket_dispatcher_host_;
475 // Must be accessed on UI thread.
476 std::vector<int> aec_dump_consumers_;
478 WebRtcStopRtpDumpCallback stop_rtp_dump_callback_;
479 #endif
481 int worker_ref_count_;
483 // Records the time when the process starts surviving for workers for UMA.
484 base::TimeTicks survive_for_worker_start_time_;
486 // Records the maximum # of workers simultaneously hosted in this process
487 // for UMA.
488 int max_worker_count_;
490 // Context shared for each PermissionService instance created for this RPH.
491 scoped_ptr<PermissionServiceContext> permission_service_context_;
493 // This is a set of all subscription targets valuebuffers in the GPU process
494 // are currently subscribed too. Used to prevent sending unnecessary
495 // ValueState updates.
496 typedef base::hash_set<unsigned int> SubscriptionSet;
497 SubscriptionSet subscription_set_;
499 // Maintains ValueStates which are not currently subscribed too so we can
500 // pass them to the GpuService if a Valuebuffer ever subscribes to the
501 // respective subscription target
502 scoped_refptr<gpu::ValueStateMap> pending_valuebuffer_state_;
504 // Whether or not the CHROMIUM_subscribe_uniform WebGL extension is enabled
505 bool subscribe_uniform_enabled_;
507 base::WeakPtrFactory<RenderProcessHostImpl> weak_factory_;
509 DISALLOW_COPY_AND_ASSIGN(RenderProcessHostImpl);
512 } // namespace content
514 #endif // CONTENT_BROWSER_RENDERER_HOST_RENDER_PROCESS_HOST_IMPL_H_