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/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/global_request_id.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 "ui/surface/transport_dib.h"
     25 
     26 class CommandLine;
     27 struct ViewHostMsg_CompositorSurfaceBuffersSwapped_Params;
     28 
     29 namespace base {
     30 class MessageLoop;
     31 }
     32 
     33 namespace gfx {
     34 class Size;
     35 }
     36 
     37 namespace content {
     38 class AudioRendererHost;
     39 class BrowserDemuxerAndroid;
     40 class GeolocationDispatcherHost;
     41 class GpuMessageFilter;
     42 class MessagePortMessageFilter;
     43 class PeerConnectionTrackerHost;
     44 class RendererMainThread;
     45 class RenderWidgetHelper;
     46 class RenderWidgetHost;
     47 class RenderWidgetHostImpl;
     48 class RenderWidgetHostViewFrameSubscriber;
     49 class StoragePartition;
     50 class StoragePartitionImpl;
     51 
     52 // Implements a concrete RenderProcessHost for the browser process for talking
     53 // to actual renderer processes (as opposed to mocks).
     54 //
     55 // Represents the browser side of the browser <--> renderer communication
     56 // channel. There will be one RenderProcessHost per renderer process.
     57 //
     58 // This object is refcounted so that it can release its resources when all
     59 // hosts using it go away.
     60 //
     61 // This object communicates back and forth with the RenderProcess object
     62 // running in the renderer process. Each RenderProcessHost and RenderProcess
     63 // keeps a list of RenderView (renderer) and WebContentsImpl (browser) which
     64 // are correlated with IDs. This way, the Views and the corresponding ViewHosts
     65 // communicate through the two process objects.
     66 //
     67 // A RenderProcessHost is also associated with one and only one
     68 // StoragePartition.  This allows us to implement strong storage isolation
     69 // because all the IPCs from the RenderViews (renderer) will only ever be able
     70 // to access the partition they are assigned to.
     71 class CONTENT_EXPORT RenderProcessHostImpl
     72     : public RenderProcessHost,
     73       public ChildProcessLauncher::Client,
     74       public GpuDataManagerObserver {
     75  public:
     76   RenderProcessHostImpl(BrowserContext* browser_context,
     77                         StoragePartitionImpl* storage_partition_impl,
     78                         bool supports_browser_plugin,
     79                         bool is_guest);
     80   virtual ~RenderProcessHostImpl();
     81 
     82   // RenderProcessHost implementation (public portion).
     83   virtual void EnableSendQueue() OVERRIDE;
     84   virtual bool Init() OVERRIDE;
     85   virtual int GetNextRoutingID() OVERRIDE;
     86   virtual void AddRoute(int32 routing_id, IPC::Listener* listener) OVERRIDE;
     87   virtual void RemoveRoute(int32 routing_id) OVERRIDE;
     88   virtual void AddObserver(RenderProcessHostObserver* observer) OVERRIDE;
     89   virtual void RemoveObserver(RenderProcessHostObserver* observer) OVERRIDE;
     90   virtual bool WaitForBackingStoreMsg(int render_widget_id,
     91                                       const base::TimeDelta& max_delay,
     92                                       IPC::Message* msg) OVERRIDE;
     93   virtual void ReceivedBadMessage() OVERRIDE;
     94   virtual void WidgetRestored() OVERRIDE;
     95   virtual void WidgetHidden() OVERRIDE;
     96   virtual int VisibleWidgetCount() const OVERRIDE;
     97   virtual bool IsGuest() const OVERRIDE;
     98   virtual StoragePartition* GetStoragePartition() const OVERRIDE;
     99   virtual bool FastShutdownIfPossible() OVERRIDE;
    100   virtual void DumpHandles() OVERRIDE;
    101   virtual base::ProcessHandle GetHandle() const OVERRIDE;
    102   virtual TransportDIB* GetTransportDIB(TransportDIB::Id dib_id) OVERRIDE;
    103   virtual TransportDIB* MapTransportDIB(TransportDIB::Id dib_id) OVERRIDE;
    104   virtual BrowserContext* GetBrowserContext() const OVERRIDE;
    105   virtual bool InSameStoragePartition(
    106       StoragePartition* partition) const OVERRIDE;
    107   virtual int GetID() const OVERRIDE;
    108   virtual bool HasConnection() const OVERRIDE;
    109   virtual void SetIgnoreInputEvents(bool ignore_input_events) OVERRIDE;
    110   virtual bool IgnoreInputEvents() const OVERRIDE;
    111   virtual void Cleanup() OVERRIDE;
    112   virtual void AddPendingView() OVERRIDE;
    113   virtual void RemovePendingView() OVERRIDE;
    114   virtual void SetSuddenTerminationAllowed(bool enabled) OVERRIDE;
    115   virtual bool SuddenTerminationAllowed() const OVERRIDE;
    116   virtual IPC::ChannelProxy* GetChannel() OVERRIDE;
    117   virtual void AddFilter(BrowserMessageFilter* filter) OVERRIDE;
    118   virtual bool FastShutdownForPageCount(size_t count) OVERRIDE;
    119   virtual bool FastShutdownStarted() const OVERRIDE;
    120   virtual base::TimeDelta GetChildProcessIdleTime() const OVERRIDE;
    121   virtual void SurfaceUpdated(int32 surface_id) OVERRIDE;
    122   virtual void ResumeRequestsForView(int route_id) OVERRIDE;
    123 
    124   // IPC::Sender via RenderProcessHost.
    125   virtual bool Send(IPC::Message* msg) OVERRIDE;
    126 
    127   // IPC::Listener via RenderProcessHost.
    128   virtual bool OnMessageReceived(const IPC::Message& msg) OVERRIDE;
    129   virtual void OnChannelConnected(int32 peer_pid) OVERRIDE;
    130   virtual void OnChannelError() OVERRIDE;
    131 
    132   // ChildProcessLauncher::Client implementation.
    133   virtual void OnProcessLaunched() OVERRIDE;
    134 
    135   scoped_refptr<AudioRendererHost> audio_renderer_host() const;
    136 
    137   // Tells the ResourceDispatcherHost to resume a deferred navigation without
    138   // transferring it to a new renderer process.
    139   void ResumeDeferredNavigation(const GlobalRequestID& request_id);
    140 
    141   // Call this function when it is evident that the child process is actively
    142   // performing some operation, for example if we just received an IPC message.
    143   void mark_child_process_activity_time() {
    144     child_process_activity_time_ = base::TimeTicks::Now();
    145   }
    146 
    147   // Returns the current number of active views in this process.  Excludes
    148   // any RenderViewHosts that are swapped out.
    149   int GetActiveViewCount();
    150 
    151   // Start and end frame subscription for a specific renderer.
    152   // This API only supports subscription to accelerated composited frames.
    153   void BeginFrameSubscription(
    154       int route_id,
    155       scoped_ptr<RenderWidgetHostViewFrameSubscriber> subscriber);
    156   void EndFrameSubscription(int route_id);
    157 
    158   scoped_refptr<GeolocationDispatcherHost>
    159       geolocation_dispatcher_host() const {
    160     return make_scoped_refptr(geolocation_dispatcher_host_);
    161   }
    162 
    163   // Register/unregister the host identified by the host id in the global host
    164   // list.
    165   static void RegisterHost(int host_id, RenderProcessHost* host);
    166   static void UnregisterHost(int host_id);
    167 
    168   // Returns true if |host| is suitable for launching a new view with |site_url|
    169   // in the given |browser_context|.
    170   static bool IsSuitableHost(RenderProcessHost* host,
    171                              BrowserContext* browser_context,
    172                              const GURL& site_url);
    173 
    174   // Returns an existing RenderProcessHost for |url| in |browser_context|,
    175   // if one exists.  Otherwise a new RenderProcessHost should be created and
    176   // registered using RegisterProcessHostForSite().
    177   // This should only be used for process-per-site mode, which can be enabled
    178   // globally with a command line flag or per-site, as determined by
    179   // SiteInstanceImpl::ShouldUseProcessPerSite.
    180   static RenderProcessHost* GetProcessHostForSite(
    181       BrowserContext* browser_context,
    182       const GURL& url);
    183 
    184   // Registers the given |process| to be used for any instance of |url|
    185   // within |browser_context|.
    186   // This should only be used for process-per-site mode, which can be enabled
    187   // globally with a command line flag or per-site, as determined by
    188   // SiteInstanceImpl::ShouldUseProcessPerSite.
    189   static void RegisterProcessHostForSite(
    190       BrowserContext* browser_context,
    191       RenderProcessHost* process,
    192       const GURL& url);
    193 
    194   static base::MessageLoop* GetInProcessRendererThreadForTesting();
    195 
    196   // This forces a renderer that is running "in process" to shut down.
    197   static void ShutDownInProcessRenderer();
    198 
    199 #if defined(OS_ANDROID)
    200   const scoped_refptr<BrowserDemuxerAndroid>& browser_demuxer_android() {
    201     return browser_demuxer_android_;
    202   }
    203 #endif
    204 
    205   MessagePortMessageFilter* message_port_message_filter() const {
    206     return message_port_message_filter_;
    207   }
    208 
    209   void SetIsGuestForTesting(bool is_guest) {
    210     is_guest_ = is_guest;
    211   }
    212 
    213  protected:
    214   // A proxy for our IPC::Channel that lives on the IO thread (see
    215   // browser_process.h)
    216   scoped_ptr<IPC::ChannelProxy> channel_;
    217 
    218   // True if fast shutdown has been performed on this RPH.
    219   bool fast_shutdown_started_;
    220 
    221   // True if we've posted a DeleteTask and will be deleted soon.
    222   bool deleting_soon_;
    223 
    224 #ifndef NDEBUG
    225   // True if this object has deleted itself.
    226   bool is_self_deleted_;
    227 #endif
    228 
    229   // The count of currently swapped out but pending RenderViews.  We have
    230   // started to swap these in, so the renderer process should not exit if
    231   // this count is non-zero.
    232   int32 pending_views_;
    233 
    234  private:
    235   friend class VisitRelayingRenderProcessHost;
    236 
    237   // Creates and adds the IO thread message filters.
    238   void CreateMessageFilters();
    239 
    240   // Control message handlers.
    241   void OnShutdownRequest();
    242   void OnDumpHandlesDone();
    243   void SuddenTerminationChanged(bool enabled);
    244   void OnUserMetricsRecordAction(const std::string& action);
    245   void OnSavedPageAsMHTML(int job_id, int64 mhtml_file_size);
    246 
    247   // CompositorSurfaceBuffersSwapped handler when there's no RWH.
    248   void OnCompositorSurfaceBuffersSwappedNoHost(
    249       const ViewHostMsg_CompositorSurfaceBuffersSwapped_Params& params);
    250 
    251   // Generates a command line to be used to spawn a renderer and appends the
    252   // results to |*command_line|.
    253   void AppendRendererCommandLine(CommandLine* command_line) const;
    254 
    255   // Copies applicable command line switches from the given |browser_cmd| line
    256   // flags to the output |renderer_cmd| line flags. Not all switches will be
    257   // copied over.
    258   void PropagateBrowserCommandLineToRenderer(const CommandLine& browser_cmd,
    259                                              CommandLine* renderer_cmd) const;
    260 
    261   // Callers can reduce the RenderProcess' priority.
    262   void SetBackgrounded(bool backgrounded);
    263 
    264   // Handle termination of our process.
    265   void ProcessDied(bool already_dead);
    266 
    267   virtual void OnGpuSwitching() OVERRIDE;
    268 
    269   // The registered IPC listener objects. When this list is empty, we should
    270   // delete ourselves.
    271   IDMap<IPC::Listener> listeners_;
    272 
    273   // The count of currently visible widgets.  Since the host can be a container
    274   // for multiple widgets, it uses this count to determine when it should be
    275   // backgrounded.
    276   int32 visible_widgets_;
    277 
    278   // Does this process have backgrounded priority.
    279   bool backgrounded_;
    280 
    281   // Used to allow a RenderWidgetHost to intercept various messages on the
    282   // IO thread.
    283   scoped_refptr<RenderWidgetHelper> widget_helper_;
    284 
    285   // The filter for GPU-related messages coming from the renderer.
    286   // Thread safety note: this field is to be accessed from the UI thread.
    287   // We don't keep a reference to it, to avoid it being destroyed on the UI
    288   // thread, but we clear this field when we clear channel_. When channel_ goes
    289   // away, it posts a task to the IO thread to destroy it there, so we know that
    290   // it's valid if non-NULL.
    291   GpuMessageFilter* gpu_message_filter_;
    292 
    293   // The filter for MessagePort messages coming from the renderer.
    294   scoped_refptr<MessagePortMessageFilter> message_port_message_filter_;
    295 
    296   // A map of transport DIB ids to cached TransportDIBs
    297   std::map<TransportDIB::Id, TransportDIB*> cached_dibs_;
    298 
    299   enum {
    300     // This is the maximum size of |cached_dibs_|
    301     MAX_MAPPED_TRANSPORT_DIBS = 3,
    302   };
    303 
    304   void ClearTransportDIBCache();
    305   // This is used to clear our cache five seconds after the last use.
    306   base::DelayTimer<RenderProcessHostImpl> cached_dibs_cleaner_;
    307 
    308   // Used in single-process mode.
    309   scoped_ptr<base::Thread> in_process_renderer_;
    310 
    311   // True after Init() has been called. We can't just check channel_ because we
    312   // also reset that in the case of process termination.
    313   bool is_initialized_;
    314 
    315   // Used to launch and terminate the process without blocking the UI thread.
    316   scoped_ptr<ChildProcessLauncher> child_process_launcher_;
    317 
    318   // Messages we queue while waiting for the process handle.  We queue them here
    319   // instead of in the channel so that we ensure they're sent after init related
    320   // messages that are sent once the process handle is available.  This is
    321   // because the queued messages may have dependencies on the init messages.
    322   std::queue<IPC::Message*> queued_messages_;
    323 
    324   // The globally-unique identifier for this RPH.
    325   int id_;
    326 
    327   BrowserContext* browser_context_;
    328 
    329   // Owned by |browser_context_|.
    330   StoragePartitionImpl* storage_partition_impl_;
    331 
    332   // The observers watching our lifetime.
    333   ObserverList<RenderProcessHostObserver> observers_;
    334 
    335   // True if the process can be shut down suddenly.  If this is true, then we're
    336   // sure that all the RenderViews in the process can be shutdown suddenly.  If
    337   // it's false, then specific RenderViews might still be allowed to be shutdown
    338   // suddenly by checking their SuddenTerminationAllowed() flag.  This can occur
    339   // if one WebContents has an unload event listener but another WebContents in
    340   // the same process doesn't.
    341   bool sudden_termination_allowed_;
    342 
    343   // Set to true if we shouldn't send input events.  We actually do the
    344   // filtering for this at the render widget level.
    345   bool ignore_input_events_;
    346 
    347   // Records the last time we regarded the child process active.
    348   base::TimeTicks child_process_activity_time_;
    349 
    350   // Indicates whether this is a RenderProcessHost that has permission to embed
    351   // Browser Plugins.
    352   bool supports_browser_plugin_;
    353 
    354   // Indicates whether this is a RenderProcessHost of a Browser Plugin guest
    355   // renderer.
    356   bool is_guest_;
    357 
    358   // Forwards messages between WebRTCInternals in the browser process
    359   // and PeerConnectionTracker in the renderer process.
    360   scoped_refptr<PeerConnectionTrackerHost> peer_connection_tracker_host_;
    361 
    362   // Prevents the class from being added as a GpuDataManagerImpl observer more
    363   // than once.
    364   bool gpu_observer_registered_;
    365 
    366   // Forwards power state messages to the renderer process.
    367   PowerMonitorMessageBroadcaster power_monitor_broadcaster_;
    368 
    369   scoped_refptr<AudioRendererHost> audio_renderer_host_;
    370 
    371 #if defined(OS_ANDROID)
    372   scoped_refptr<BrowserDemuxerAndroid> browser_demuxer_android_;
    373 #endif
    374 
    375   // Message filter for geolocation messages.
    376   GeolocationDispatcherHost* geolocation_dispatcher_host_;
    377 
    378   DISALLOW_COPY_AND_ASSIGN(RenderProcessHostImpl);
    379 };
    380 
    381 }  // namespace content
    382 
    383 #endif  // CONTENT_BROWSER_RENDERER_HOST_BROWSER_RENDER_PROCESS_HOST_IMPL_H_
    384