Revert 268405 "Make sure that ScratchBuffer::Allocate() always r..."
[chromium-blink-merge.git] / content / browser / renderer_host / render_process_host_impl.h
blobcddc4dc115d97db62e3ed1a8be458399fab22994
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/geolocation/geolocation_dispatcher_host.h"
18 #include "content/browser/power_monitor_message_broadcaster.h"
19 #include "content/common/content_export.h"
20 #include "content/public/browser/gpu_data_manager_observer.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/embedder/scoped_platform_handle.h"
25 #include "mojo/public/cpp/bindings/remote_ptr.h"
26 #include "mojo/public/interfaces/shell/shell.mojom.h"
28 struct ViewHostMsg_CompositorSurfaceBuffersSwapped_Params;
30 namespace base {
31 class CommandLine;
32 class MessageLoop;
35 namespace gfx {
36 class Size;
39 namespace content {
40 class AudioRendererHost;
41 class BrowserDemuxerAndroid;
42 class GeolocationDispatcherHost;
43 class GpuMessageFilter;
44 class MessagePortMessageFilter;
45 class MojoApplicationHost;
46 class PeerConnectionTrackerHost;
47 class RendererMainThread;
48 class RenderProcessHostMojoImpl;
49 class RenderWidgetHelper;
50 class RenderWidgetHost;
51 class RenderWidgetHostImpl;
52 class RenderWidgetHostViewFrameSubscriber;
53 class ScreenOrientationDispatcherHost;
54 class StoragePartition;
55 class StoragePartitionImpl;
57 typedef base::Thread* (*RendererMainThreadFactoryFunction)(
58 const std::string& id);
60 // Implements a concrete RenderProcessHost for the browser process for talking
61 // to actual renderer processes (as opposed to mocks).
63 // Represents the browser side of the browser <--> renderer communication
64 // channel. There will be one RenderProcessHost per renderer process.
66 // This object is refcounted so that it can release its resources when all
67 // hosts using it go away.
69 // This object communicates back and forth with the RenderProcess object
70 // running in the renderer process. Each RenderProcessHost and RenderProcess
71 // keeps a list of RenderView (renderer) and WebContentsImpl (browser) which
72 // are correlated with IDs. This way, the Views and the corresponding ViewHosts
73 // communicate through the two process objects.
75 // A RenderProcessHost is also associated with one and only one
76 // StoragePartition. This allows us to implement strong storage isolation
77 // because all the IPCs from the RenderViews (renderer) will only ever be able
78 // to access the partition they are assigned to.
79 class CONTENT_EXPORT RenderProcessHostImpl
80 : public RenderProcessHost,
81 public ChildProcessLauncher::Client,
82 public GpuDataManagerObserver {
83 public:
84 RenderProcessHostImpl(BrowserContext* browser_context,
85 StoragePartitionImpl* storage_partition_impl,
86 bool is_guest);
87 virtual ~RenderProcessHostImpl();
89 // RenderProcessHost implementation (public portion).
90 virtual void EnableSendQueue() OVERRIDE;
91 virtual bool Init() OVERRIDE;
92 virtual int GetNextRoutingID() OVERRIDE;
93 virtual void AddRoute(int32 routing_id, IPC::Listener* listener) OVERRIDE;
94 virtual void RemoveRoute(int32 routing_id) OVERRIDE;
95 virtual void AddObserver(RenderProcessHostObserver* observer) OVERRIDE;
96 virtual void RemoveObserver(RenderProcessHostObserver* observer) OVERRIDE;
97 virtual bool WaitForBackingStoreMsg(int render_widget_id,
98 const base::TimeDelta& max_delay,
99 IPC::Message* msg) OVERRIDE;
100 virtual void ReceivedBadMessage() OVERRIDE;
101 virtual void WidgetRestored() OVERRIDE;
102 virtual void WidgetHidden() OVERRIDE;
103 virtual int VisibleWidgetCount() const OVERRIDE;
104 virtual bool IsGuest() const OVERRIDE;
105 virtual StoragePartition* GetStoragePartition() const OVERRIDE;
106 virtual bool FastShutdownIfPossible() OVERRIDE;
107 virtual void DumpHandles() OVERRIDE;
108 virtual base::ProcessHandle GetHandle() const OVERRIDE;
109 virtual BrowserContext* GetBrowserContext() const OVERRIDE;
110 virtual bool InSameStoragePartition(
111 StoragePartition* partition) const OVERRIDE;
112 virtual int GetID() const OVERRIDE;
113 virtual bool HasConnection() const OVERRIDE;
114 virtual void SetIgnoreInputEvents(bool ignore_input_events) OVERRIDE;
115 virtual bool IgnoreInputEvents() const OVERRIDE;
116 virtual void Cleanup() OVERRIDE;
117 virtual void AddPendingView() OVERRIDE;
118 virtual void RemovePendingView() OVERRIDE;
119 virtual void SetSuddenTerminationAllowed(bool enabled) OVERRIDE;
120 virtual bool SuddenTerminationAllowed() const OVERRIDE;
121 virtual IPC::ChannelProxy* GetChannel() OVERRIDE;
122 virtual void AddFilter(BrowserMessageFilter* filter) OVERRIDE;
123 virtual bool FastShutdownForPageCount(size_t count) OVERRIDE;
124 virtual bool FastShutdownStarted() const OVERRIDE;
125 virtual base::TimeDelta GetChildProcessIdleTime() const OVERRIDE;
126 virtual void ResumeRequestsForView(int route_id) OVERRIDE;
127 virtual void FilterURL(bool empty_allowed, GURL* url) OVERRIDE;
128 #if defined(ENABLE_WEBRTC)
129 virtual void EnableAecDump(const base::FilePath& file) OVERRIDE;
130 virtual void DisableAecDump() OVERRIDE;
131 virtual void SetWebRtcLogMessageCallback(
132 base::Callback<void(const std::string&)> callback) OVERRIDE;
133 #endif
134 virtual void ResumeDeferredNavigation(const GlobalRequestID& request_id)
135 OVERRIDE;
136 virtual void NotifyTimezoneChange() OVERRIDE;
138 // IPC::Sender via RenderProcessHost.
139 virtual bool Send(IPC::Message* msg) OVERRIDE;
141 // IPC::Listener via RenderProcessHost.
142 virtual bool OnMessageReceived(const IPC::Message& msg) OVERRIDE;
143 virtual void OnChannelConnected(int32 peer_pid) OVERRIDE;
144 virtual void OnChannelError() OVERRIDE;
146 // ChildProcessLauncher::Client implementation.
147 virtual void OnProcessLaunched() OVERRIDE;
149 scoped_refptr<AudioRendererHost> audio_renderer_host() const;
151 // Call this function when it is evident that the child process is actively
152 // performing some operation, for example if we just received an IPC message.
153 void mark_child_process_activity_time() {
154 child_process_activity_time_ = base::TimeTicks::Now();
157 // Returns the current number of active views in this process. Excludes
158 // any RenderViewHosts that are swapped out.
159 int GetActiveViewCount();
161 // Start and end frame subscription for a specific renderer.
162 // This API only supports subscription to accelerated composited frames.
163 void BeginFrameSubscription(
164 int route_id,
165 scoped_ptr<RenderWidgetHostViewFrameSubscriber> subscriber);
166 void EndFrameSubscription(int route_id);
168 scoped_refptr<GeolocationDispatcherHost>
169 geolocation_dispatcher_host() const {
170 return make_scoped_refptr(geolocation_dispatcher_host_);
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 scoped_refptr<ScreenOrientationDispatcherHost>
179 screen_orientation_dispatcher_host() const;
181 // Register/unregister the host identified by the host id in the global host
182 // list.
183 static void RegisterHost(int host_id, RenderProcessHost* host);
184 static void UnregisterHost(int host_id);
186 // Implementation of FilterURL below that can be shared with the mock class.
187 static void FilterURL(RenderProcessHost* rph, bool empty_allowed, GURL* url);
189 // Returns true if |host| is suitable for launching a new view with |site_url|
190 // in the given |browser_context|.
191 static bool IsSuitableHost(RenderProcessHost* host,
192 BrowserContext* browser_context,
193 const GURL& site_url);
195 // Returns an existing RenderProcessHost for |url| in |browser_context|,
196 // if one exists. Otherwise a new RenderProcessHost should be created and
197 // registered using RegisterProcessHostForSite().
198 // This should only be used for process-per-site mode, which can be enabled
199 // globally with a command line flag or per-site, as determined by
200 // SiteInstanceImpl::ShouldUseProcessPerSite.
201 static RenderProcessHost* GetProcessHostForSite(
202 BrowserContext* browser_context,
203 const GURL& url);
205 // Registers the given |process| to be used for any instance of |url|
206 // within |browser_context|.
207 // This should only be used for process-per-site mode, which can be enabled
208 // globally with a command line flag or per-site, as determined by
209 // SiteInstanceImpl::ShouldUseProcessPerSite.
210 static void RegisterProcessHostForSite(
211 BrowserContext* browser_context,
212 RenderProcessHost* process,
213 const GURL& url);
215 static base::MessageLoop* GetInProcessRendererThreadForTesting();
217 // This forces a renderer that is running "in process" to shut down.
218 static void ShutDownInProcessRenderer();
220 static void RegisterRendererMainThreadFactory(
221 RendererMainThreadFactoryFunction create);
223 #if defined(OS_ANDROID)
224 const scoped_refptr<BrowserDemuxerAndroid>& browser_demuxer_android() {
225 return browser_demuxer_android_;
227 #endif
229 MessagePortMessageFilter* message_port_message_filter() const {
230 return message_port_message_filter_;
233 void SetIsGuestForTesting(bool is_guest) {
234 is_guest_ = is_guest;
237 // Called when the existence of the other renderer process which is connected
238 // to the Worker in this renderer process has changed.
239 // It is only called when "enable-embedded-shared-worker" flag is set.
240 void IncrementWorkerRefCount();
241 void DecrementWorkerRefCount();
243 // Establish a connection to a renderer-provided service. See
244 // content/common/mojo/mojo_service_names.h for a list of services.
245 void ConnectTo(const base::StringPiece& service_name,
246 mojo::ScopedMessagePipeHandle handle);
248 protected:
249 // A proxy for our IPC::Channel that lives on the IO thread (see
250 // browser_process.h)
251 scoped_ptr<IPC::ChannelProxy> channel_;
253 // True if fast shutdown has been performed on this RPH.
254 bool fast_shutdown_started_;
256 // True if we've posted a DeleteTask and will be deleted soon.
257 bool deleting_soon_;
259 #ifndef NDEBUG
260 // True if this object has deleted itself.
261 bool is_self_deleted_;
262 #endif
264 // The count of currently swapped out but pending RenderViews. We have
265 // started to swap these in, so the renderer process should not exit if
266 // this count is non-zero.
267 int32 pending_views_;
269 private:
270 friend class VisitRelayingRenderProcessHost;
272 void MaybeActivateMojo();
274 // Creates and adds the IO thread message filters.
275 void CreateMessageFilters();
277 // Control message handlers.
278 void OnShutdownRequest();
279 void OnDumpHandlesDone();
280 void SuddenTerminationChanged(bool enabled);
281 void OnUserMetricsRecordAction(const std::string& action);
282 void OnSavedPageAsMHTML(int job_id, int64 mhtml_file_size);
284 // CompositorSurfaceBuffersSwapped handler when there's no RWH.
285 void OnCompositorSurfaceBuffersSwappedNoHost(
286 const ViewHostMsg_CompositorSurfaceBuffersSwapped_Params& params);
288 // Generates a command line to be used to spawn a renderer and appends the
289 // results to |*command_line|.
290 void AppendRendererCommandLine(base::CommandLine* command_line) const;
292 // Copies applicable command line switches from the given |browser_cmd| line
293 // flags to the output |renderer_cmd| line flags. Not all switches will be
294 // copied over.
295 void PropagateBrowserCommandLineToRenderer(
296 const base::CommandLine& browser_cmd,
297 base::CommandLine* renderer_cmd) const;
299 // Callers can reduce the RenderProcess' priority.
300 void SetBackgrounded(bool backgrounded);
302 // Handle termination of our process.
303 void ProcessDied(bool already_dead);
305 virtual void OnGpuSwitching() OVERRIDE;
307 #if defined(ENABLE_WEBRTC)
308 // Sends |file_for_transit| to the render process.
309 void SendAecDumpFileToRenderer(IPC::PlatformFileForTransit file_for_transit);
310 void SendDisableAecDumpToRenderer();
311 #endif
313 scoped_ptr<MojoApplicationHost> mojo_application_host_;
314 bool mojo_activation_required_;
316 // The registered IPC listener objects. When this list is empty, we should
317 // delete ourselves.
318 IDMap<IPC::Listener> listeners_;
320 // The count of currently visible widgets. Since the host can be a container
321 // for multiple widgets, it uses this count to determine when it should be
322 // backgrounded.
323 int32 visible_widgets_;
325 // Does this process have backgrounded priority.
326 bool backgrounded_;
328 // Used to allow a RenderWidgetHost to intercept various messages on the
329 // IO thread.
330 scoped_refptr<RenderWidgetHelper> widget_helper_;
332 // The filter for GPU-related messages coming from the renderer.
333 // Thread safety note: this field is to be accessed from the UI thread.
334 // We don't keep a reference to it, to avoid it being destroyed on the UI
335 // thread, but we clear this field when we clear channel_. When channel_ goes
336 // away, it posts a task to the IO thread to destroy it there, so we know that
337 // it's valid if non-NULL.
338 GpuMessageFilter* gpu_message_filter_;
340 // The filter for MessagePort messages coming from the renderer.
341 scoped_refptr<MessagePortMessageFilter> message_port_message_filter_;
343 // Used in single-process mode.
344 scoped_ptr<base::Thread> in_process_renderer_;
346 // True after Init() has been called. We can't just check channel_ because we
347 // also reset that in the case of process termination.
348 bool is_initialized_;
350 // Used to launch and terminate the process without blocking the UI thread.
351 scoped_ptr<ChildProcessLauncher> child_process_launcher_;
353 // Messages we queue while waiting for the process handle. We queue them here
354 // instead of in the channel so that we ensure they're sent after init related
355 // messages that are sent once the process handle is available. This is
356 // because the queued messages may have dependencies on the init messages.
357 std::queue<IPC::Message*> queued_messages_;
359 // The globally-unique identifier for this RPH.
360 int id_;
362 BrowserContext* browser_context_;
364 // Owned by |browser_context_|.
365 StoragePartitionImpl* storage_partition_impl_;
367 // The observers watching our lifetime.
368 ObserverList<RenderProcessHostObserver> observers_;
370 // True if the process can be shut down suddenly. If this is true, then we're
371 // sure that all the RenderViews in the process can be shutdown suddenly. If
372 // it's false, then specific RenderViews might still be allowed to be shutdown
373 // suddenly by checking their SuddenTerminationAllowed() flag. This can occur
374 // if one WebContents has an unload event listener but another WebContents in
375 // the same process doesn't.
376 bool sudden_termination_allowed_;
378 // Set to true if we shouldn't send input events. We actually do the
379 // filtering for this at the render widget level.
380 bool ignore_input_events_;
382 // Records the last time we regarded the child process active.
383 base::TimeTicks child_process_activity_time_;
385 // Indicates whether this is a RenderProcessHost of a Browser Plugin guest
386 // renderer.
387 bool is_guest_;
389 // Forwards messages between WebRTCInternals in the browser process
390 // and PeerConnectionTracker in the renderer process.
391 scoped_refptr<PeerConnectionTrackerHost> peer_connection_tracker_host_;
393 // Prevents the class from being added as a GpuDataManagerImpl observer more
394 // than once.
395 bool gpu_observer_registered_;
397 // Set if a call to Cleanup is required once the RenderProcessHostImpl is no
398 // longer within the RenderProcessHostObserver::RenderProcessExited callbacks.
399 bool delayed_cleanup_needed_;
401 // Indicates whether RenderProcessHostImpl is currently iterating and calling
402 // through RenderProcessHostObserver::RenderProcessExited.
403 bool within_process_died_observer_;
405 // Forwards power state messages to the renderer process.
406 PowerMonitorMessageBroadcaster power_monitor_broadcaster_;
408 scoped_refptr<AudioRendererHost> audio_renderer_host_;
410 #if defined(OS_ANDROID)
411 scoped_refptr<BrowserDemuxerAndroid> browser_demuxer_android_;
412 #endif
414 // Message filter for geolocation messages.
415 GeolocationDispatcherHost* geolocation_dispatcher_host_;
417 #if defined(ENABLE_WEBRTC)
418 base::Callback<void(const std::string&)> webrtc_log_message_callback_;
419 #endif
421 // Message filter and dispatcher for screen orientation.
422 ScreenOrientationDispatcherHost* screen_orientation_dispatcher_host_;
424 int worker_ref_count_;
426 // Records the time when the process starts surviving for workers for UMA.
427 base::TimeTicks survive_for_worker_start_time_;
429 base::WeakPtrFactory<RenderProcessHostImpl> weak_factory_;
431 DISALLOW_COPY_AND_ASSIGN(RenderProcessHostImpl);
434 } // namespace content
436 #endif // CONTENT_BROWSER_RENDERER_HOST_BROWSER_RENDER_PROCESS_HOST_IMPL_H_