Home | History | Annotate | Download | only in renderer_host
      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.
      4 
      5 #ifndef CONTENT_BROWSER_RENDERER_HOST_BROWSER_RENDER_PROCESS_HOST_IMPL_H_
      6 #define CONTENT_BROWSER_RENDERER_HOST_BROWSER_RENDER_PROCESS_HOST_IMPL_H_
      7 
      8 #include <map>
      9 #include <queue>
     10 #include <string>
     11 
     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"
     27 
     28 namespace base {
     29 class CommandLine;
     30 class MessageLoop;
     31 }
     32 
     33 namespace gfx {
     34 class Size;
     35 }
     36 
     37 namespace IPC {
     38 class ChannelMojoHost;
     39 }
     40 
     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;
     59 
     60 typedef base::Thread* (*RendererMainThreadFactoryFunction)(
     61     const std::string& id);
     62 
     63 // Implements a concrete RenderProcessHost for the browser process for talking
     64 // to actual renderer processes (as opposed to mocks).
     65 //
     66 // Represents the browser side of the browser <--> renderer communication
     67 // channel. There will be one RenderProcessHost per renderer process.
     68 //
     69 // This object is refcounted so that it can release its resources when all
     70 // hosts using it go away.
     71 //
     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.
     77 //
     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 GpuDataManagerObserver {
     86  public:
     87   RenderProcessHostImpl(BrowserContext* browser_context,
     88                         StoragePartitionImpl* storage_partition_impl,
     89                         bool is_isolated_guest);
     90   virtual ~RenderProcessHostImpl();
     91 
     92   // RenderProcessHost implementation (public portion).
     93   virtual void EnableSendQueue() OVERRIDE;
     94   virtual bool Init() OVERRIDE;
     95   virtual int GetNextRoutingID() OVERRIDE;
     96   virtual void AddRoute(int32 routing_id, IPC::Listener* listener) OVERRIDE;
     97   virtual void RemoveRoute(int32 routing_id) OVERRIDE;
     98   virtual void AddObserver(RenderProcessHostObserver* observer) OVERRIDE;
     99   virtual void RemoveObserver(RenderProcessHostObserver* observer) 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 IsIsolatedGuest() 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   virtual WebRtcStopRtpDumpCallback StartRtpDump(
    134       bool incoming,
    135       bool outgoing,
    136       const WebRtcRtpPacketCallback& packet_callback) OVERRIDE;
    137 #endif
    138   virtual void ResumeDeferredNavigation(const GlobalRequestID& request_id)
    139       OVERRIDE;
    140   virtual void NotifyTimezoneChange() OVERRIDE;
    141   virtual ServiceRegistry* GetServiceRegistry() OVERRIDE;
    142 
    143   // IPC::Sender via RenderProcessHost.
    144   virtual bool Send(IPC::Message* msg) OVERRIDE;
    145 
    146   // IPC::Listener via RenderProcessHost.
    147   virtual bool OnMessageReceived(const IPC::Message& msg) OVERRIDE;
    148   virtual void OnChannelConnected(int32 peer_pid) OVERRIDE;
    149   virtual void OnChannelError() OVERRIDE;
    150   virtual void OnBadMessageReceived(const IPC::Message& message) OVERRIDE;
    151 
    152   // ChildProcessLauncher::Client implementation.
    153   virtual void OnProcessLaunched() OVERRIDE;
    154 
    155   scoped_refptr<AudioRendererHost> audio_renderer_host() const;
    156 
    157   // Call this function when it is evident that the child process is actively
    158   // performing some operation, for example if we just received an IPC message.
    159   void mark_child_process_activity_time() {
    160     child_process_activity_time_ = base::TimeTicks::Now();
    161   }
    162 
    163   // Returns the current number of active views in this process.  Excludes
    164   // any RenderViewHosts that are swapped out.
    165   int GetActiveViewCount();
    166 
    167   // Start and end frame subscription for a specific renderer.
    168   // This API only supports subscription to accelerated composited frames.
    169   void BeginFrameSubscription(
    170       int route_id,
    171       scoped_ptr<RenderWidgetHostViewFrameSubscriber> subscriber);
    172   void EndFrameSubscription(int route_id);
    173 
    174 #if defined(ENABLE_WEBRTC)
    175   // Fires the webrtc log message callback with |message|, if callback is set.
    176   void WebRtcLogMessage(const std::string& message);
    177 #endif
    178 
    179   // Used to extend the lifetime of the sessions until the render view
    180   // in the renderer is fully closed. This is static because its also called
    181   // with mock hosts as input in test cases.
    182   static void ReleaseOnCloseACK(
    183       RenderProcessHost* host,
    184       const SessionStorageNamespaceMap& sessions,
    185       int view_route_id);
    186 
    187   // Register/unregister the host identified by the host id in the global host
    188   // list.
    189   static void RegisterHost(int host_id, RenderProcessHost* host);
    190   static void UnregisterHost(int host_id);
    191 
    192   // Implementation of FilterURL below that can be shared with the mock class.
    193   static void FilterURL(RenderProcessHost* rph, bool empty_allowed, GURL* url);
    194 
    195   // Returns true if |host| is suitable for launching a new view with |site_url|
    196   // in the given |browser_context|.
    197   static bool IsSuitableHost(RenderProcessHost* host,
    198                              BrowserContext* browser_context,
    199                              const GURL& site_url);
    200 
    201   // Returns an existing RenderProcessHost for |url| in |browser_context|,
    202   // if one exists.  Otherwise a new RenderProcessHost should be created and
    203   // registered using RegisterProcessHostForSite().
    204   // This should only be used for process-per-site mode, which can be enabled
    205   // globally with a command line flag or per-site, as determined by
    206   // SiteInstanceImpl::ShouldUseProcessPerSite.
    207   static RenderProcessHost* GetProcessHostForSite(
    208       BrowserContext* browser_context,
    209       const GURL& url);
    210 
    211   // Registers the given |process| to be used for any instance of |url|
    212   // within |browser_context|.
    213   // This should only be used for process-per-site mode, which can be enabled
    214   // globally with a command line flag or per-site, as determined by
    215   // SiteInstanceImpl::ShouldUseProcessPerSite.
    216   static void RegisterProcessHostForSite(
    217       BrowserContext* browser_context,
    218       RenderProcessHost* process,
    219       const GURL& url);
    220 
    221   static base::MessageLoop* GetInProcessRendererThreadForTesting();
    222 
    223   // This forces a renderer that is running "in process" to shut down.
    224   static void ShutDownInProcessRenderer();
    225 
    226   static void RegisterRendererMainThreadFactory(
    227       RendererMainThreadFactoryFunction create);
    228 
    229 #if defined(OS_ANDROID)
    230   const scoped_refptr<BrowserDemuxerAndroid>& browser_demuxer_android() {
    231     return browser_demuxer_android_;
    232   }
    233 #endif
    234 
    235 #if defined(ENABLE_BROWSER_CDMS)
    236   const scoped_refptr<BrowserCdmManager>& browser_cdm_manager() {
    237     return browser_cdm_manager_;
    238   }
    239 #endif
    240 
    241   MessagePortMessageFilter* message_port_message_filter() const {
    242     return message_port_message_filter_.get();
    243   }
    244 
    245   void set_is_isolated_guest_for_testing(bool is_isolated_guest) {
    246     is_isolated_guest_ = is_isolated_guest;
    247   }
    248 
    249   // Called when the existence of the other renderer process which is connected
    250   // to the Worker in this renderer process has changed.
    251   // It is only called when "enable-embedded-shared-worker" flag is set.
    252   void IncrementWorkerRefCount();
    253   void DecrementWorkerRefCount();
    254 
    255   // Call this function to resume the navigation when it was deferred
    256   // immediately after receiving response headers.
    257   void ResumeResponseDeferredAtStart(const GlobalRequestID& request_id);
    258 
    259   // Activates Mojo for this process. Does nothing if Mojo is already activated.
    260   void EnsureMojoActivated();
    261 
    262  protected:
    263   // A proxy for our IPC::Channel that lives on the IO thread (see
    264   // browser_process.h)
    265   scoped_ptr<IPC::ChannelProxy> channel_;
    266 
    267   // A host object ChannelMojo needs. The lifetime is bound to
    268   // the RenderProcessHostImpl, not the channel.
    269   scoped_ptr<IPC::ChannelMojoHost> channel_mojo_host_;
    270 
    271   // True if fast shutdown has been performed on this RPH.
    272   bool fast_shutdown_started_;
    273 
    274   // True if we've posted a DeleteTask and will be deleted soon.
    275   bool deleting_soon_;
    276 
    277 #ifndef NDEBUG
    278   // True if this object has deleted itself.
    279   bool is_self_deleted_;
    280 #endif
    281 
    282   // The count of currently swapped out but pending RenderViews.  We have
    283   // started to swap these in, so the renderer process should not exit if
    284   // this count is non-zero.
    285   int32 pending_views_;
    286 
    287  private:
    288   friend class VisitRelayingRenderProcessHost;
    289 
    290   void MaybeActivateMojo();
    291   bool ShouldUseMojoChannel() const;
    292   scoped_ptr<IPC::ChannelProxy> CreateChannelProxy(
    293       const std::string& channel_id);
    294 
    295   // Creates and adds the IO thread message filters.
    296   void CreateMessageFilters();
    297 
    298   // Control message handlers.
    299   void OnShutdownRequest();
    300   void OnDumpHandlesDone();
    301   void SuddenTerminationChanged(bool enabled);
    302   void OnUserMetricsRecordAction(const std::string& action);
    303   void OnSavedPageAsMHTML(int job_id, int64 mhtml_file_size);
    304   void OnCloseACK(int old_route_id);
    305 
    306   // Generates a command line to be used to spawn a renderer and appends the
    307   // results to |*command_line|.
    308   void AppendRendererCommandLine(base::CommandLine* command_line) const;
    309 
    310   // Copies applicable command line switches from the given |browser_cmd| line
    311   // flags to the output |renderer_cmd| line flags. Not all switches will be
    312   // copied over.
    313   void PropagateBrowserCommandLineToRenderer(
    314       const base::CommandLine& browser_cmd,
    315       base::CommandLine* renderer_cmd) const;
    316 
    317   // Callers can reduce the RenderProcess' priority.
    318   void SetBackgrounded(bool backgrounded);
    319 
    320   // Handle termination of our process.
    321   void ProcessDied(bool already_dead);
    322 
    323   virtual void OnGpuSwitching() OVERRIDE;
    324 
    325 #if defined(ENABLE_WEBRTC)
    326   void OnRegisterAecDumpConsumer(int id);
    327   void OnUnregisterAecDumpConsumer(int id);
    328   void RegisterAecDumpConsumerOnUIThread(int id);
    329   void UnregisterAecDumpConsumerOnUIThread(int id);
    330   void EnableAecDumpForId(const base::FilePath& file, int id);
    331   // Sends |file_for_transit| to the render process.
    332   void SendAecDumpFileToRenderer(int id,
    333                                  IPC::PlatformFileForTransit file_for_transit);
    334   void SendDisableAecDumpToRenderer();
    335 #endif
    336 
    337   scoped_ptr<MojoApplicationHost> mojo_application_host_;
    338   bool mojo_activation_required_;
    339 
    340   // The registered IPC listener objects. When this list is empty, we should
    341   // delete ourselves.
    342   IDMap<IPC::Listener> listeners_;
    343 
    344   // The count of currently visible widgets.  Since the host can be a container
    345   // for multiple widgets, it uses this count to determine when it should be
    346   // backgrounded.
    347   int32 visible_widgets_;
    348 
    349   // Does this process have backgrounded priority.
    350   bool backgrounded_;
    351 
    352   // Used to allow a RenderWidgetHost to intercept various messages on the
    353   // IO thread.
    354   scoped_refptr<RenderWidgetHelper> widget_helper_;
    355 
    356   // The filter for GPU-related messages coming from the renderer.
    357   // Thread safety note: this field is to be accessed from the UI thread.
    358   // We don't keep a reference to it, to avoid it being destroyed on the UI
    359   // thread, but we clear this field when we clear channel_. When channel_ goes
    360   // away, it posts a task to the IO thread to destroy it there, so we know that
    361   // it's valid if non-NULL.
    362   GpuMessageFilter* gpu_message_filter_;
    363 
    364   // The filter for MessagePort messages coming from the renderer.
    365   scoped_refptr<MessagePortMessageFilter> message_port_message_filter_;
    366 
    367   // Used in single-process mode.
    368   scoped_ptr<base::Thread> in_process_renderer_;
    369 
    370   // True after Init() has been called. We can't just check channel_ because we
    371   // also reset that in the case of process termination.
    372   bool is_initialized_;
    373 
    374   // Used to launch and terminate the process without blocking the UI thread.
    375   scoped_ptr<ChildProcessLauncher> child_process_launcher_;
    376 
    377   // Messages we queue while waiting for the process handle.  We queue them here
    378   // instead of in the channel so that we ensure they're sent after init related
    379   // messages that are sent once the process handle is available.  This is
    380   // because the queued messages may have dependencies on the init messages.
    381   std::queue<IPC::Message*> queued_messages_;
    382 
    383   // The globally-unique identifier for this RPH.
    384   int id_;
    385 
    386   BrowserContext* browser_context_;
    387 
    388   // Owned by |browser_context_|.
    389   StoragePartitionImpl* storage_partition_impl_;
    390 
    391   // The observers watching our lifetime.
    392   ObserverList<RenderProcessHostObserver> observers_;
    393 
    394   // True if the process can be shut down suddenly.  If this is true, then we're
    395   // sure that all the RenderViews in the process can be shutdown suddenly.  If
    396   // it's false, then specific RenderViews might still be allowed to be shutdown
    397   // suddenly by checking their SuddenTerminationAllowed() flag.  This can occur
    398   // if one WebContents has an unload event listener but another WebContents in
    399   // the same process doesn't.
    400   bool sudden_termination_allowed_;
    401 
    402   // Set to true if we shouldn't send input events.  We actually do the
    403   // filtering for this at the render widget level.
    404   bool ignore_input_events_;
    405 
    406   // Records the last time we regarded the child process active.
    407   base::TimeTicks child_process_activity_time_;
    408 
    409   // Indicates whether this is a RenderProcessHost of a Browser Plugin guest
    410   // renderer.
    411   bool is_isolated_guest_;
    412 
    413   // Forwards messages between WebRTCInternals in the browser process
    414   // and PeerConnectionTracker in the renderer process.
    415   scoped_refptr<PeerConnectionTrackerHost> peer_connection_tracker_host_;
    416 
    417   // Prevents the class from being added as a GpuDataManagerImpl observer more
    418   // than once.
    419   bool gpu_observer_registered_;
    420 
    421   // Set if a call to Cleanup is required once the RenderProcessHostImpl is no
    422   // longer within the RenderProcessHostObserver::RenderProcessExited callbacks.
    423   bool delayed_cleanup_needed_;
    424 
    425   // Indicates whether RenderProcessHostImpl is currently iterating and calling
    426   // through RenderProcessHostObserver::RenderProcessExited.
    427   bool within_process_died_observer_;
    428 
    429   // Forwards power state messages to the renderer process.
    430   PowerMonitorMessageBroadcaster power_monitor_broadcaster_;
    431 
    432   scoped_refptr<AudioRendererHost> audio_renderer_host_;
    433 
    434 #if defined(OS_ANDROID)
    435   scoped_refptr<BrowserDemuxerAndroid> browser_demuxer_android_;
    436 #endif
    437 
    438 #if defined(ENABLE_BROWSER_CDMS)
    439   scoped_refptr<BrowserCdmManager> browser_cdm_manager_;
    440 #endif
    441 
    442 #if defined(ENABLE_WEBRTC)
    443   base::Callback<void(const std::string&)> webrtc_log_message_callback_;
    444 
    445   scoped_refptr<P2PSocketDispatcherHost> p2p_socket_dispatcher_host_;
    446 
    447   // Must be accessed on UI thread.
    448   std::vector<int> aec_dump_consumers_;
    449 
    450   WebRtcStopRtpDumpCallback stop_rtp_dump_callback_;
    451 #endif
    452 
    453   int worker_ref_count_;
    454 
    455   // Records the time when the process starts surviving for workers for UMA.
    456   base::TimeTicks survive_for_worker_start_time_;
    457 
    458   base::WeakPtrFactory<RenderProcessHostImpl> weak_factory_;
    459 
    460   DISALLOW_COPY_AND_ASSIGN(RenderProcessHostImpl);
    461 };
    462 
    463 }  // namespace content
    464 
    465 #endif  // CONTENT_BROWSER_RENDERER_HOST_BROWSER_RENDER_PROCESS_HOST_IMPL_H_
    466