DevTools: cut host and port from webSocketDebuggerUrl in addition to ws:// prefix
[chromium-blink-merge.git] / content / browser / renderer_host / render_process_host_impl.h
blob8937fd1e561d188c12005ef4fa3f2161b7cfcb6d
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 #if defined(OS_MACOSX) && !defined(OS_IOS)
28 #include "content/common/mac/io_surface_manager_token.h"
29 #endif
31 namespace base {
32 class CommandLine;
33 class MessageLoop;
36 namespace gfx {
37 class Size;
40 namespace gpu {
41 class ValueStateMap;
44 namespace IPC {
45 class ChannelMojoHost;
48 namespace content {
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;
60 #endif
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 {
97 public:
98 RenderProcessHostImpl(BrowserContext* browser_context,
99 StoragePartitionImpl* storage_partition_impl,
100 bool is_for_guests_only);
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 IsForGuestsOnly() 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(
144 bool incoming,
145 bool outgoing,
146 const WebRtcRtpPacketCallback& packet_callback) override;
147 #endif
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;
160 #endif
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(
186 int route_id,
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);
193 #endif
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,
201 int view_route_id);
203 // Register/unregister the host identified by the host id in the global host
204 // list.
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,
225 const GURL& url);
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,
235 const GURL& url);
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_;
249 #endif
251 #if defined(ENABLE_BROWSER_CDMS)
252 const scoped_refptr<BrowserCdmManager>& browser_cdm_manager() {
253 return browser_cdm_manager_;
255 #endif
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_for_guests_only_for_testing(bool is_for_guests_only) {
266 is_for_guests_only_ = is_for_guests_only;
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();
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 // True if fast shutdown has been performed on this RPH.
286 bool fast_shutdown_started_;
288 // True if we've posted a DeleteTask and will be deleted soon.
289 bool deleting_soon_;
291 #ifndef NDEBUG
292 // True if this object has deleted itself.
293 bool is_self_deleted_;
294 #endif
296 // The count of currently swapped out but pending RenderViews. We have
297 // started to swap these in, so the renderer process should not exit if
298 // this count is non-zero.
299 int32 pending_views_;
301 private:
302 friend class VisitRelayingRenderProcessHost;
303 friend class ChildProcessLauncherBrowserTest_ChildSpawnFail_Test;
305 scoped_ptr<IPC::ChannelProxy> CreateChannelProxy(
306 const std::string& channel_id);
308 // Creates and adds the IO thread message filters.
309 void CreateMessageFilters();
311 // Registers Mojo services to be exposed to the renderer.
312 void RegisterMojoServices();
314 // Control message handlers.
315 void OnShutdownRequest();
316 void SuddenTerminationChanged(bool enabled);
317 void OnUserMetricsRecordAction(const std::string& action);
318 void OnSavedPageAsMHTML(int job_id, int64 mhtml_file_size);
319 void OnCloseACK(int old_route_id);
321 // Generates a command line to be used to spawn a renderer and appends the
322 // results to |*command_line|.
323 void AppendRendererCommandLine(base::CommandLine* command_line) const;
325 // Copies applicable command line switches from the given |browser_cmd| line
326 // flags to the output |renderer_cmd| line flags. Not all switches will be
327 // copied over.
328 void PropagateBrowserCommandLineToRenderer(
329 const base::CommandLine& browser_cmd,
330 base::CommandLine* renderer_cmd) const;
332 // Callers can reduce the RenderProcess' priority.
333 void SetBackgrounded(bool backgrounded);
335 // Handle termination of our process.
336 void ProcessDied(bool already_dead, RendererClosedDetails* known_details);
338 // GpuSwitchingObserver implementation.
339 void OnGpuSwitched() override;
341 #if defined(ENABLE_WEBRTC)
342 void OnRegisterAecDumpConsumer(int id);
343 void OnUnregisterAecDumpConsumer(int id);
344 void RegisterAecDumpConsumerOnUIThread(int id);
345 void UnregisterAecDumpConsumerOnUIThread(int id);
346 void EnableAecDumpForId(const base::FilePath& file, int id);
347 // Sends |file_for_transit| to the render process.
348 void SendAecDumpFileToRenderer(int id,
349 IPC::PlatformFileForTransit file_for_transit);
350 void SendDisableAecDumpToRenderer();
351 #endif
353 scoped_ptr<MojoApplicationHost> mojo_application_host_;
355 // The registered IPC listener objects. When this list is empty, we should
356 // delete ourselves.
357 IDMap<IPC::Listener> listeners_;
359 // The count of currently visible widgets. Since the host can be a container
360 // for multiple widgets, it uses this count to determine when it should be
361 // backgrounded.
362 int32 visible_widgets_;
364 // Does this process have backgrounded priority.
365 bool backgrounded_;
367 // Used to allow a RenderWidgetHost to intercept various messages on the
368 // IO thread.
369 scoped_refptr<RenderWidgetHelper> widget_helper_;
371 // The filter for GPU-related messages coming from the renderer.
372 // Thread safety note: this field is to be accessed from the UI thread.
373 // We don't keep a reference to it, to avoid it being destroyed on the UI
374 // thread, but we clear this field when we clear channel_. When channel_ goes
375 // away, it posts a task to the IO thread to destroy it there, so we know that
376 // it's valid if non-NULL.
377 GpuMessageFilter* gpu_message_filter_;
379 // The filter for MessagePort messages coming from the renderer.
380 scoped_refptr<MessagePortMessageFilter> message_port_message_filter_;
382 // The filter for Web Notification messages coming from the renderer. Holds a
383 // closure per notification that must be freed when the notification closes.
384 scoped_refptr<NotificationMessageFilter> notification_message_filter_;
386 // Used in single-process mode.
387 scoped_ptr<base::Thread> in_process_renderer_;
389 // True after Init() has been called. We can't just check channel_ because we
390 // also reset that in the case of process termination.
391 bool is_initialized_;
393 // PlzNavigate
394 // Stores the time at which the first call to Init happened.
395 base::TimeTicks init_time_;
397 // Used to launch and terminate the process without blocking the UI thread.
398 scoped_ptr<ChildProcessLauncher> child_process_launcher_;
400 // Messages we queue while waiting for the process handle. We queue them here
401 // instead of in the channel so that we ensure they're sent after init related
402 // messages that are sent once the process handle is available. This is
403 // because the queued messages may have dependencies on the init messages.
404 std::queue<IPC::Message*> queued_messages_;
406 // The globally-unique identifier for this RPH.
407 int id_;
409 BrowserContext* browser_context_;
411 // Owned by |browser_context_|.
412 StoragePartitionImpl* storage_partition_impl_;
414 // The observers watching our lifetime.
415 base::ObserverList<RenderProcessHostObserver> observers_;
417 // True if the process can be shut down suddenly. If this is true, then we're
418 // sure that all the RenderViews in the process can be shutdown suddenly. If
419 // it's false, then specific RenderViews might still be allowed to be shutdown
420 // suddenly by checking their SuddenTerminationAllowed() flag. This can occur
421 // if one WebContents has an unload event listener but another WebContents in
422 // the same process doesn't.
423 bool sudden_termination_allowed_;
425 // Set to true if we shouldn't send input events. We actually do the
426 // filtering for this at the render widget level.
427 bool ignore_input_events_;
429 // Records the last time we regarded the child process active.
430 base::TimeTicks child_process_activity_time_;
432 // Indicates whether this RenderProcessHost is exclusively hosting guest
433 // RenderFrames.
434 bool is_for_guests_only_;
436 // Forwards messages between WebRTCInternals in the browser process
437 // and PeerConnectionTracker in the renderer process.
438 scoped_refptr<PeerConnectionTrackerHost> peer_connection_tracker_host_;
440 // Prevents the class from being added as a GpuDataManagerImpl observer more
441 // than once.
442 bool gpu_observer_registered_;
444 // Set if a call to Cleanup is required once the RenderProcessHostImpl is no
445 // longer within the RenderProcessHostObserver::RenderProcessExited callbacks.
446 bool delayed_cleanup_needed_;
448 // Indicates whether RenderProcessHostImpl is currently iterating and calling
449 // through RenderProcessHostObserver::RenderProcessExited.
450 bool within_process_died_observer_;
452 // Forwards power state messages to the renderer process.
453 PowerMonitorMessageBroadcaster power_monitor_broadcaster_;
455 scoped_refptr<AudioRendererHost> audio_renderer_host_;
457 scoped_refptr<BluetoothDispatcherHost> bluetooth_dispatcher_host_;
459 #if defined(OS_ANDROID)
460 scoped_refptr<BrowserDemuxerAndroid> browser_demuxer_android_;
461 #endif
463 #if defined(ENABLE_BROWSER_CDMS)
464 scoped_refptr<BrowserCdmManager> browser_cdm_manager_;
465 #endif
467 #if defined(ENABLE_WEBRTC)
468 base::Callback<void(const std::string&)> webrtc_log_message_callback_;
470 scoped_refptr<P2PSocketDispatcherHost> p2p_socket_dispatcher_host_;
472 // Must be accessed on UI thread.
473 std::vector<int> aec_dump_consumers_;
475 WebRtcStopRtpDumpCallback stop_rtp_dump_callback_;
476 #endif
478 int worker_ref_count_;
480 // Records the time when the process starts surviving for workers for UMA.
481 base::TimeTicks survive_for_worker_start_time_;
483 // Records the maximum # of workers simultaneously hosted in this process
484 // for UMA.
485 int max_worker_count_;
487 // Context shared for each PermissionService instance created for this RPH.
488 scoped_ptr<PermissionServiceContext> permission_service_context_;
490 // This is a set of all subscription targets valuebuffers in the GPU process
491 // are currently subscribed too. Used to prevent sending unnecessary
492 // ValueState updates.
493 typedef base::hash_set<unsigned int> SubscriptionSet;
494 SubscriptionSet subscription_set_;
496 // Maintains ValueStates which are not currently subscribed too so we can
497 // pass them to the GpuService if a Valuebuffer ever subscribes to the
498 // respective subscription target
499 scoped_refptr<gpu::ValueStateMap> pending_valuebuffer_state_;
501 // Whether or not the CHROMIUM_subscribe_uniform WebGL extension is enabled
502 bool subscribe_uniform_enabled_;
504 #if defined(OS_MACOSX) && !defined(OS_IOS)
505 // Unique unguessable token that the child process is using to acquire
506 // IOSurface references.
507 IOSurfaceManagerToken io_surface_manager_token_;
508 #endif
510 base::WeakPtrFactory<RenderProcessHostImpl> weak_factory_;
512 DISALLOW_COPY_AND_ASSIGN(RenderProcessHostImpl);
515 } // namespace content
517 #endif // CONTENT_BROWSER_RENDERER_HOST_RENDER_PROCESS_HOST_IMPL_H_