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/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/public/cpp/bindings/interface_ptr.h"
     25 
     26 #if defined(OS_MACOSX)
     27 #include <IOSurface/IOSurfaceAPI.h>
     28 #include "base/mac/scoped_cftyperef.h"
     29 #endif
     30 
     31 struct ViewHostMsg_CompositorSurfaceBuffersSwapped_Params;
     32 
     33 namespace base {
     34 class CommandLine;
     35 class MessageLoop;
     36 }
     37 
     38 namespace gfx {
     39 class Size;
     40 struct GpuMemoryBufferHandle;
     41 }
     42 
     43 namespace content {
     44 class AudioRendererHost;
     45 class BrowserDemuxerAndroid;
     46 class GpuMessageFilter;
     47 class MessagePortMessageFilter;
     48 class MojoApplicationHost;
     49 #if defined(ENABLE_WEBRTC)
     50 class P2PSocketDispatcherHost;
     51 #endif
     52 class PeerConnectionTrackerHost;
     53 class RendererMainThread;
     54 class RenderProcessHostMojoImpl;
     55 class RenderWidgetHelper;
     56 class RenderWidgetHost;
     57 class RenderWidgetHostImpl;
     58 class RenderWidgetHostViewFrameSubscriber;
     59 class StoragePartition;
     60 class StoragePartitionImpl;
     61 
     62 typedef base::Thread* (*RendererMainThreadFactoryFunction)(
     63     const std::string& id);
     64 
     65 // Implements a concrete RenderProcessHost for the browser process for talking
     66 // to actual renderer processes (as opposed to mocks).
     67 //
     68 // Represents the browser side of the browser <--> renderer communication
     69 // channel. There will be one RenderProcessHost per renderer process.
     70 //
     71 // This object is refcounted so that it can release its resources when all
     72 // hosts using it go away.
     73 //
     74 // This object communicates back and forth with the RenderProcess object
     75 // running in the renderer process. Each RenderProcessHost and RenderProcess
     76 // keeps a list of RenderView (renderer) and WebContentsImpl (browser) which
     77 // are correlated with IDs. This way, the Views and the corresponding ViewHosts
     78 // communicate through the two process objects.
     79 //
     80 // A RenderProcessHost is also associated with one and only one
     81 // StoragePartition.  This allows us to implement strong storage isolation
     82 // because all the IPCs from the RenderViews (renderer) will only ever be able
     83 // to access the partition they are assigned to.
     84 class CONTENT_EXPORT RenderProcessHostImpl
     85     : public RenderProcessHost,
     86       public ChildProcessLauncher::Client,
     87       public GpuDataManagerObserver {
     88  public:
     89   RenderProcessHostImpl(BrowserContext* browser_context,
     90                         StoragePartitionImpl* storage_partition_impl,
     91                         bool is_isolated_guest);
     92   virtual ~RenderProcessHostImpl();
     93 
     94   // RenderProcessHost implementation (public portion).
     95   virtual void EnableSendQueue() OVERRIDE;
     96   virtual bool Init() OVERRIDE;
     97   virtual int GetNextRoutingID() OVERRIDE;
     98   virtual void AddRoute(int32 routing_id, IPC::Listener* listener) OVERRIDE;
     99   virtual void RemoveRoute(int32 routing_id) OVERRIDE;
    100   virtual void AddObserver(RenderProcessHostObserver* observer) OVERRIDE;
    101   virtual void RemoveObserver(RenderProcessHostObserver* observer) OVERRIDE;
    102   virtual bool WaitForBackingStoreMsg(int render_widget_id,
    103                                       const base::TimeDelta& max_delay,
    104                                       IPC::Message* msg) OVERRIDE;
    105   virtual void ReceivedBadMessage() OVERRIDE;
    106   virtual void WidgetRestored() OVERRIDE;
    107   virtual void WidgetHidden() OVERRIDE;
    108   virtual int VisibleWidgetCount() const OVERRIDE;
    109   virtual bool IsIsolatedGuest() const OVERRIDE;
    110   virtual StoragePartition* GetStoragePartition() const OVERRIDE;
    111   virtual bool FastShutdownIfPossible() OVERRIDE;
    112   virtual void DumpHandles() OVERRIDE;
    113   virtual base::ProcessHandle GetHandle() const OVERRIDE;
    114   virtual BrowserContext* GetBrowserContext() const OVERRIDE;
    115   virtual bool InSameStoragePartition(
    116       StoragePartition* partition) const OVERRIDE;
    117   virtual int GetID() const OVERRIDE;
    118   virtual bool HasConnection() const OVERRIDE;
    119   virtual void SetIgnoreInputEvents(bool ignore_input_events) OVERRIDE;
    120   virtual bool IgnoreInputEvents() const OVERRIDE;
    121   virtual void Cleanup() OVERRIDE;
    122   virtual void AddPendingView() OVERRIDE;
    123   virtual void RemovePendingView() OVERRIDE;
    124   virtual void SetSuddenTerminationAllowed(bool enabled) OVERRIDE;
    125   virtual bool SuddenTerminationAllowed() const OVERRIDE;
    126   virtual IPC::ChannelProxy* GetChannel() OVERRIDE;
    127   virtual void AddFilter(BrowserMessageFilter* filter) OVERRIDE;
    128   virtual bool FastShutdownForPageCount(size_t count) OVERRIDE;
    129   virtual bool FastShutdownStarted() const OVERRIDE;
    130   virtual base::TimeDelta GetChildProcessIdleTime() const OVERRIDE;
    131   virtual void ResumeRequestsForView(int route_id) OVERRIDE;
    132   virtual void FilterURL(bool empty_allowed, GURL* url) OVERRIDE;
    133 #if defined(ENABLE_WEBRTC)
    134   virtual void EnableAecDump(const base::FilePath& file) OVERRIDE;
    135   virtual void DisableAecDump() OVERRIDE;
    136   virtual void SetWebRtcLogMessageCallback(
    137       base::Callback<void(const std::string&)> callback) OVERRIDE;
    138   virtual WebRtcStopRtpDumpCallback StartRtpDump(
    139       bool incoming,
    140       bool outgoing,
    141       const WebRtcRtpPacketCallback& packet_callback) OVERRIDE;
    142 #endif
    143   virtual void ResumeDeferredNavigation(const GlobalRequestID& request_id)
    144       OVERRIDE;
    145   virtual void NotifyTimezoneChange() OVERRIDE;
    146 
    147   // IPC::Sender via RenderProcessHost.
    148   virtual bool Send(IPC::Message* msg) OVERRIDE;
    149 
    150   // IPC::Listener via RenderProcessHost.
    151   virtual bool OnMessageReceived(const IPC::Message& msg) OVERRIDE;
    152   virtual void OnChannelConnected(int32 peer_pid) OVERRIDE;
    153   virtual void OnChannelError() OVERRIDE;
    154   virtual void OnBadMessageReceived(const IPC::Message& message) OVERRIDE;
    155 
    156   // ChildProcessLauncher::Client implementation.
    157   virtual void OnProcessLaunched() OVERRIDE;
    158 
    159   scoped_refptr<AudioRendererHost> audio_renderer_host() const;
    160 
    161   // Call this function when it is evident that the child process is actively
    162   // performing some operation, for example if we just received an IPC message.
    163   void mark_child_process_activity_time() {
    164     child_process_activity_time_ = base::TimeTicks::Now();
    165   }
    166 
    167   // Returns the current number of active views in this process.  Excludes
    168   // any RenderViewHosts that are swapped out.
    169   int GetActiveViewCount();
    170 
    171   // Start and end frame subscription for a specific renderer.
    172   // This API only supports subscription to accelerated composited frames.
    173   void BeginFrameSubscription(
    174       int route_id,
    175       scoped_ptr<RenderWidgetHostViewFrameSubscriber> subscriber);
    176   void EndFrameSubscription(int route_id);
    177 
    178 #if defined(ENABLE_WEBRTC)
    179   // Fires the webrtc log message callback with |message|, if callback is set.
    180   void WebRtcLogMessage(const std::string& message);
    181 #endif
    182 
    183   // Used to extend the lifetime of the sessions until the render view
    184   // in the renderer is fully closed. This is static because its also called
    185   // with mock hosts as input in test cases.
    186   static void ReleaseOnCloseACK(
    187       RenderProcessHost* host,
    188       const SessionStorageNamespaceMap& sessions,
    189       int view_route_id);
    190 
    191   // Register/unregister the host identified by the host id in the global host
    192   // list.
    193   static void RegisterHost(int host_id, RenderProcessHost* host);
    194   static void UnregisterHost(int host_id);
    195 
    196   // Implementation of FilterURL below that can be shared with the mock class.
    197   static void FilterURL(RenderProcessHost* rph, bool empty_allowed, GURL* url);
    198 
    199   // Returns true if |host| is suitable for launching a new view with |site_url|
    200   // in the given |browser_context|.
    201   static bool IsSuitableHost(RenderProcessHost* host,
    202                              BrowserContext* browser_context,
    203                              const GURL& site_url);
    204 
    205   // Returns an existing RenderProcessHost for |url| in |browser_context|,
    206   // if one exists.  Otherwise a new RenderProcessHost should be created and
    207   // registered using RegisterProcessHostForSite().
    208   // This should only be used for process-per-site mode, which can be enabled
    209   // globally with a command line flag or per-site, as determined by
    210   // SiteInstanceImpl::ShouldUseProcessPerSite.
    211   static RenderProcessHost* GetProcessHostForSite(
    212       BrowserContext* browser_context,
    213       const GURL& url);
    214 
    215   // Registers the given |process| to be used for any instance of |url|
    216   // within |browser_context|.
    217   // This should only be used for process-per-site mode, which can be enabled
    218   // globally with a command line flag or per-site, as determined by
    219   // SiteInstanceImpl::ShouldUseProcessPerSite.
    220   static void RegisterProcessHostForSite(
    221       BrowserContext* browser_context,
    222       RenderProcessHost* process,
    223       const GURL& url);
    224 
    225   static base::MessageLoop* GetInProcessRendererThreadForTesting();
    226 
    227   // This forces a renderer that is running "in process" to shut down.
    228   static void ShutDownInProcessRenderer();
    229 
    230   static void RegisterRendererMainThreadFactory(
    231       RendererMainThreadFactoryFunction create);
    232 
    233 #if defined(OS_ANDROID)
    234   const scoped_refptr<BrowserDemuxerAndroid>& browser_demuxer_android() {
    235     return browser_demuxer_android_;
    236   }
    237 #endif
    238 
    239   MessagePortMessageFilter* message_port_message_filter() const {
    240     return message_port_message_filter_;
    241   }
    242 
    243   void set_is_isolated_guest_for_testing(bool is_isolated_guest) {
    244     is_isolated_guest_ = is_isolated_guest;
    245   }
    246 
    247   // Called when the existence of the other renderer process which is connected
    248   // to the Worker in this renderer process has changed.
    249   // It is only called when "enable-embedded-shared-worker" flag is set.
    250   void IncrementWorkerRefCount();
    251   void DecrementWorkerRefCount();
    252 
    253   // Establish a connection to a renderer-provided service. See
    254   // content/common/mojo/mojo_service_names.h for a list of services.
    255   void ConnectTo(const base::StringPiece& service_name,
    256                  mojo::ScopedMessagePipeHandle handle);
    257 
    258   template <typename Interface>
    259   void ConnectTo(const base::StringPiece& service_name,
    260                  mojo::InterfacePtr<Interface>* ptr) {
    261     mojo::MessagePipe pipe;
    262     ptr->Bind(pipe.handle0.Pass());
    263     ConnectTo(service_name, pipe.handle1.Pass());
    264   }
    265 
    266  protected:
    267   // A proxy for our IPC::Channel that lives on the IO thread (see
    268   // browser_process.h)
    269   scoped_ptr<IPC::ChannelProxy> channel_;
    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 
    292   // Creates and adds the IO thread message filters.
    293   void CreateMessageFilters();
    294 
    295   // Control message handlers.
    296   void OnShutdownRequest();
    297   void OnDumpHandlesDone();
    298   void SuddenTerminationChanged(bool enabled);
    299   void OnUserMetricsRecordAction(const std::string& action);
    300   void OnSavedPageAsMHTML(int job_id, int64 mhtml_file_size);
    301   void OnCloseACK(int old_route_id);
    302 
    303   // CompositorSurfaceBuffersSwapped handler when there's no RWH.
    304   void OnCompositorSurfaceBuffersSwappedNoHost(
    305       const ViewHostMsg_CompositorSurfaceBuffersSwapped_Params& params);
    306 
    307   // Generates a command line to be used to spawn a renderer and appends the
    308   // results to |*command_line|.
    309   void AppendRendererCommandLine(base::CommandLine* command_line) const;
    310 
    311   // Copies applicable command line switches from the given |browser_cmd| line
    312   // flags to the output |renderer_cmd| line flags. Not all switches will be
    313   // copied over.
    314   void PropagateBrowserCommandLineToRenderer(
    315       const base::CommandLine& browser_cmd,
    316       base::CommandLine* renderer_cmd) const;
    317 
    318   // Callers can reduce the RenderProcess' priority.
    319   void SetBackgrounded(bool backgrounded);
    320 
    321   // Handle termination of our process.
    322   void ProcessDied(bool already_dead);
    323 
    324   virtual void OnGpuSwitching() OVERRIDE;
    325 
    326 #if defined(ENABLE_WEBRTC)
    327   void OnRegisterAecDumpConsumer(int id);
    328   void OnUnregisterAecDumpConsumer(int id);
    329   void RegisterAecDumpConsumerOnUIThread(int id);
    330   void UnregisterAecDumpConsumerOnUIThread(int id);
    331   void EnableAecDumpForId(const base::FilePath& file, int id);
    332   // Sends |file_for_transit| to the render process.
    333   void SendAecDumpFileToRenderer(int id,
    334                                  IPC::PlatformFileForTransit file_for_transit);
    335   void SendDisableAecDumpToRenderer();
    336 #endif
    337 
    338   // GpuMemoryBuffer allocation handler.
    339   void OnAllocateGpuMemoryBuffer(uint32 width,
    340                                  uint32 height,
    341                                  uint32 internalformat,
    342                                  uint32 usage,
    343                                  IPC::Message* reply);
    344   void GpuMemoryBufferAllocated(IPC::Message* reply,
    345                                 const gfx::GpuMemoryBufferHandle& handle);
    346 
    347   scoped_ptr<MojoApplicationHost> mojo_application_host_;
    348   bool mojo_activation_required_;
    349 
    350   // The registered IPC listener objects. When this list is empty, we should
    351   // delete ourselves.
    352   IDMap<IPC::Listener> listeners_;
    353 
    354   // The count of currently visible widgets.  Since the host can be a container
    355   // for multiple widgets, it uses this count to determine when it should be
    356   // backgrounded.
    357   int32 visible_widgets_;
    358 
    359   // Does this process have backgrounded priority.
    360   bool backgrounded_;
    361 
    362   // Used to allow a RenderWidgetHost to intercept various messages on the
    363   // IO thread.
    364   scoped_refptr<RenderWidgetHelper> widget_helper_;
    365 
    366   // The filter for GPU-related messages coming from the renderer.
    367   // Thread safety note: this field is to be accessed from the UI thread.
    368   // We don't keep a reference to it, to avoid it being destroyed on the UI
    369   // thread, but we clear this field when we clear channel_. When channel_ goes
    370   // away, it posts a task to the IO thread to destroy it there, so we know that
    371   // it's valid if non-NULL.
    372   GpuMessageFilter* gpu_message_filter_;
    373 
    374   // The filter for MessagePort messages coming from the renderer.
    375   scoped_refptr<MessagePortMessageFilter> message_port_message_filter_;
    376 
    377   // Used in single-process mode.
    378   scoped_ptr<base::Thread> in_process_renderer_;
    379 
    380   // True after Init() has been called. We can't just check channel_ because we
    381   // also reset that in the case of process termination.
    382   bool is_initialized_;
    383 
    384   // Used to launch and terminate the process without blocking the UI thread.
    385   scoped_ptr<ChildProcessLauncher> child_process_launcher_;
    386 
    387   // Messages we queue while waiting for the process handle.  We queue them here
    388   // instead of in the channel so that we ensure they're sent after init related
    389   // messages that are sent once the process handle is available.  This is
    390   // because the queued messages may have dependencies on the init messages.
    391   std::queue<IPC::Message*> queued_messages_;
    392 
    393   // The globally-unique identifier for this RPH.
    394   int id_;
    395 
    396   BrowserContext* browser_context_;
    397 
    398   // Owned by |browser_context_|.
    399   StoragePartitionImpl* storage_partition_impl_;
    400 
    401   // The observers watching our lifetime.
    402   ObserverList<RenderProcessHostObserver> observers_;
    403 
    404   // True if the process can be shut down suddenly.  If this is true, then we're
    405   // sure that all the RenderViews in the process can be shutdown suddenly.  If
    406   // it's false, then specific RenderViews might still be allowed to be shutdown
    407   // suddenly by checking their SuddenTerminationAllowed() flag.  This can occur
    408   // if one WebContents has an unload event listener but another WebContents in
    409   // the same process doesn't.
    410   bool sudden_termination_allowed_;
    411 
    412   // Set to true if we shouldn't send input events.  We actually do the
    413   // filtering for this at the render widget level.
    414   bool ignore_input_events_;
    415 
    416   // Records the last time we regarded the child process active.
    417   base::TimeTicks child_process_activity_time_;
    418 
    419   // Indicates whether this is a RenderProcessHost of a Browser Plugin guest
    420   // renderer.
    421   bool is_isolated_guest_;
    422 
    423   // Forwards messages between WebRTCInternals in the browser process
    424   // and PeerConnectionTracker in the renderer process.
    425   scoped_refptr<PeerConnectionTrackerHost> peer_connection_tracker_host_;
    426 
    427   // Prevents the class from being added as a GpuDataManagerImpl observer more
    428   // than once.
    429   bool gpu_observer_registered_;
    430 
    431   // Set if a call to Cleanup is required once the RenderProcessHostImpl is no
    432   // longer within the RenderProcessHostObserver::RenderProcessExited callbacks.
    433   bool delayed_cleanup_needed_;
    434 
    435   // Indicates whether RenderProcessHostImpl is currently iterating and calling
    436   // through RenderProcessHostObserver::RenderProcessExited.
    437   bool within_process_died_observer_;
    438 
    439   // Forwards power state messages to the renderer process.
    440   PowerMonitorMessageBroadcaster power_monitor_broadcaster_;
    441 
    442   scoped_refptr<AudioRendererHost> audio_renderer_host_;
    443 
    444 #if defined(OS_ANDROID)
    445   scoped_refptr<BrowserDemuxerAndroid> browser_demuxer_android_;
    446 #endif
    447 
    448 #if defined(ENABLE_WEBRTC)
    449   base::Callback<void(const std::string&)> webrtc_log_message_callback_;
    450 
    451   scoped_refptr<P2PSocketDispatcherHost> p2p_socket_dispatcher_host_;
    452 
    453   // Must be accessed on UI thread.
    454   std::vector<int> aec_dump_consumers_;
    455 
    456   WebRtcStopRtpDumpCallback stop_rtp_dump_callback_;
    457 #endif
    458 
    459   int worker_ref_count_;
    460 
    461   // Records the time when the process starts surviving for workers for UMA.
    462   base::TimeTicks survive_for_worker_start_time_;
    463 
    464   base::WeakPtrFactory<RenderProcessHostImpl> weak_factory_;
    465 
    466 #if defined(OS_MACOSX)
    467   base::ScopedCFTypeRef<IOSurfaceRef> last_io_surface_;
    468 #endif
    469 
    470   DISALLOW_COPY_AND_ASSIGN(RenderProcessHostImpl);
    471 };
    472 
    473 }  // namespace content
    474 
    475 #endif  // CONTENT_BROWSER_RENDERER_HOST_BROWSER_RENDER_PROCESS_HOST_IMPL_H_
    476