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