render_process_host_impl.cc revision a36e5920737c6adbddd3e43b760e5de8431db6e0
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// Represents the browser side of the browser <--> renderer communication
6// channel. There will be one RenderProcessHost per renderer process.
7
8#include "content/browser/renderer_host/render_process_host_impl.h"
9
10#include <algorithm>
11#include <limits>
12#include <vector>
13
14#if defined(OS_POSIX)
15#include <utility>  // for pair<>
16#endif
17
18#include "base/base_switches.h"
19#include "base/bind.h"
20#include "base/bind_helpers.h"
21#include "base/callback.h"
22#include "base/command_line.h"
23#include "base/debug/trace_event.h"
24#include "base/lazy_instance.h"
25#include "base/logging.h"
26#include "base/metrics/field_trial.h"
27#include "base/metrics/histogram.h"
28#include "base/path_service.h"
29#include "base/platform_file.h"
30#include "base/rand_util.h"
31#include "base/stl_util.h"
32#include "base/strings/string_util.h"
33#include "base/supports_user_data.h"
34#include "base/sys_info.h"
35#include "base/threading/thread.h"
36#include "base/threading/thread_restrictions.h"
37#include "base/tracked_objects.h"
38#include "cc/base/switches.h"
39#include "content/browser/appcache/appcache_dispatcher_host.h"
40#include "content/browser/appcache/chrome_appcache_service.h"
41#include "content/browser/browser_main.h"
42#include "content/browser/browser_main_loop.h"
43#include "content/browser/browser_plugin/browser_plugin_geolocation_permission_context.h"
44#include "content/browser/browser_plugin/browser_plugin_message_filter.h"
45#include "content/browser/child_process_security_policy_impl.h"
46#include "content/browser/device_orientation/orientation_message_filter.h"
47#include "content/browser/dom_storage/dom_storage_context_impl.h"
48#include "content/browser/dom_storage/dom_storage_message_filter.h"
49#include "content/browser/download/mhtml_generation_manager.h"
50#include "content/browser/fileapi/chrome_blob_storage_context.h"
51#include "content/browser/fileapi/fileapi_message_filter.h"
52#include "content/browser/geolocation/geolocation_dispatcher_host.h"
53#include "content/browser/gpu/gpu_data_manager_impl.h"
54#include "content/browser/gpu/gpu_process_host.h"
55#include "content/browser/gpu/shader_disk_cache.h"
56#include "content/browser/histogram_message_filter.h"
57#include "content/browser/indexed_db/indexed_db_context_impl.h"
58#include "content/browser/indexed_db/indexed_db_dispatcher_host.h"
59#include "content/browser/loader/resource_message_filter.h"
60#include "content/browser/loader/resource_scheduler_filter.h"
61#include "content/browser/media/media_internals.h"
62#include "content/browser/mime_registry_message_filter.h"
63#include "content/browser/plugin_service_impl.h"
64#include "content/browser/profiler_message_filter.h"
65#include "content/browser/quota_dispatcher_host.h"
66#include "content/browser/renderer_host/clipboard_message_filter.h"
67#include "content/browser/renderer_host/database_message_filter.h"
68#include "content/browser/renderer_host/device_motion_browser_message_filter.h"
69#include "content/browser/renderer_host/file_utilities_message_filter.h"
70#include "content/browser/renderer_host/gamepad_browser_message_filter.h"
71#include "content/browser/renderer_host/gpu_message_filter.h"
72#include "content/browser/renderer_host/media/audio_input_renderer_host.h"
73#include "content/browser/renderer_host/media/audio_mirroring_manager.h"
74#include "content/browser/renderer_host/media/audio_renderer_host.h"
75#include "content/browser/renderer_host/media/device_request_message_filter.h"
76#include "content/browser/renderer_host/media/media_stream_dispatcher_host.h"
77#include "content/browser/renderer_host/media/midi_dispatcher_host.h"
78#include "content/browser/renderer_host/media/midi_host.h"
79#include "content/browser/renderer_host/media/peer_connection_tracker_host.h"
80#include "content/browser/renderer_host/media/video_capture_host.h"
81#include "content/browser/renderer_host/memory_benchmark_message_filter.h"
82#include "content/browser/renderer_host/p2p/socket_dispatcher_host.h"
83#include "content/browser/renderer_host/pepper/pepper_message_filter.h"
84#include "content/browser/renderer_host/pepper/pepper_renderer_connection.h"
85#include "content/browser/renderer_host/render_message_filter.h"
86#include "content/browser/renderer_host/render_view_host_delegate.h"
87#include "content/browser/renderer_host/render_view_host_impl.h"
88#include "content/browser/renderer_host/render_widget_helper.h"
89#include "content/browser/renderer_host/render_widget_host_impl.h"
90#include "content/browser/renderer_host/socket_stream_dispatcher_host.h"
91#include "content/browser/renderer_host/text_input_client_message_filter.h"
92#include "content/browser/resolve_proxy_msg_helper.h"
93#include "content/browser/speech/input_tag_speech_dispatcher_host.h"
94#include "content/browser/speech/speech_recognition_dispatcher_host.h"
95#include "content/browser/storage_partition_impl.h"
96#include "content/browser/tracing/trace_message_filter.h"
97#include "content/browser/webui/web_ui_controller_factory_registry.h"
98#include "content/browser/worker_host/worker_message_filter.h"
99#include "content/browser/worker_host/worker_storage_partition.h"
100#include "content/common/child_process_host_impl.h"
101#include "content/common/child_process_messages.h"
102#include "content/common/gpu/gpu_messages.h"
103#include "content/common/resource_messages.h"
104#include "content/common/view_messages.h"
105#include "content/port/browser/render_widget_host_view_frame_subscriber.h"
106#include "content/public/browser/browser_context.h"
107#include "content/public/browser/content_browser_client.h"
108#include "content/public/browser/notification_service.h"
109#include "content/public/browser/notification_types.h"
110#include "content/public/browser/render_process_host_factory.h"
111#include "content/public/browser/render_widget_host.h"
112#include "content/public/browser/resource_context.h"
113#include "content/public/browser/user_metrics.h"
114#include "content/public/common/content_constants.h"
115#include "content/public/common/content_switches.h"
116#include "content/public/common/process_type.h"
117#include "content/public/common/result_codes.h"
118#include "content/public/common/url_constants.h"
119#include "content/renderer/render_process_impl.h"
120#include "content/renderer/render_thread_impl.h"
121#include "gpu/command_buffer/service/gpu_switches.h"
122#include "ipc/ipc_channel.h"
123#include "ipc/ipc_logging.h"
124#include "ipc/ipc_platform_file.h"
125#include "ipc/ipc_switches.h"
126#include "media/base/media_switches.h"
127#include "net/url_request/url_request_context_getter.h"
128#include "ppapi/shared_impl/ppapi_switches.h"
129#include "ui/base/ui_base_switches.h"
130#include "ui/gl/gl_switches.h"
131#include "webkit/browser/fileapi/sandbox_file_system_backend.h"
132#include "webkit/common/resource_type.h"
133#include "webkit/plugins/plugin_switches.h"
134
135#if defined(OS_ANDROID)
136#include "content/browser/android/vibration_message_filter.h"
137#endif
138
139#if defined(OS_WIN)
140#include "base/win/scoped_com_initializer.h"
141#include "content/common/font_cache_dispatcher_win.h"
142#include "content/common/sandbox_win.h"
143#include "content/public/common/sandboxed_process_launcher_delegate.h"
144#endif
145
146#if defined(ENABLE_WEBRTC)
147#include "content/browser/renderer_host/media/webrtc_identity_service_host.h"
148#endif
149
150#include "third_party/skia/include/core/SkBitmap.h"
151
152extern bool g_exited_main_message_loop;
153
154static const char* kSiteProcessMapKeyName = "content_site_process_map";
155
156namespace content {
157namespace {
158
159base::MessageLoop* g_in_process_thread;
160
161void CacheShaderInfo(int32 id, base::FilePath path) {
162  ShaderCacheFactory::GetInstance()->SetCacheInfo(id, path);
163}
164
165void RemoveShaderInfo(int32 id) {
166  ShaderCacheFactory::GetInstance()->RemoveCacheInfo(id);
167}
168
169}  // namespace
170
171#if !defined(CHROME_MULTIPLE_DLL)
172
173// This class creates the IO thread for the renderer when running in
174// single-process mode.  It's not used in multi-process mode.
175class RendererMainThread : public base::Thread {
176 public:
177  explicit RendererMainThread(const std::string& channel_id)
178      : Thread("Chrome_InProcRendererThread"),
179        channel_id_(channel_id) {
180  }
181
182  virtual ~RendererMainThread() {
183    Stop();
184  }
185
186 protected:
187  virtual void Init() OVERRIDE {
188    render_process_.reset(new RenderProcessImpl());
189    new RenderThreadImpl(channel_id_);
190    g_in_process_thread = message_loop();
191  }
192
193  virtual void CleanUp() OVERRIDE {
194    g_in_process_thread = NULL;
195    render_process_.reset();
196
197    // It's a little lame to manually set this flag.  But the single process
198    // RendererThread will receive the WM_QUIT.  We don't need to assert on
199    // this thread, so just force the flag manually.
200    // If we want to avoid this, we could create the InProcRendererThread
201    // directly with _beginthreadex() rather than using the Thread class.
202    // We used to set this flag in the Init function above. However there
203    // other threads like WebThread which are created by this thread
204    // which resets this flag. Please see Thread::StartWithOptions. Setting
205    // this flag to true in Cleanup works around these problems.
206    SetThreadWasQuitProperly(true);
207  }
208
209 private:
210  std::string channel_id_;
211  scoped_ptr<RenderProcess> render_process_;
212
213  DISALLOW_COPY_AND_ASSIGN(RendererMainThread);
214};
215
216#endif
217
218namespace {
219
220// Helper class that we pass to ResourceMessageFilter so that it can find the
221// right net::URLRequestContext for a request.
222class RendererURLRequestContextSelector
223    : public ResourceMessageFilter::URLRequestContextSelector {
224 public:
225  RendererURLRequestContextSelector(BrowserContext* browser_context,
226                                    int render_child_id)
227      : request_context_(browser_context->GetRequestContextForRenderProcess(
228                             render_child_id)),
229        media_request_context_(
230            browser_context->GetMediaRequestContextForRenderProcess(
231                render_child_id)) {
232  }
233
234  virtual net::URLRequestContext* GetRequestContext(
235      ResourceType::Type resource_type) OVERRIDE {
236    net::URLRequestContextGetter* request_context = request_context_.get();
237    // If the request has resource type of ResourceType::MEDIA, we use a request
238    // context specific to media for handling it because these resources have
239    // specific needs for caching.
240    if (resource_type == ResourceType::MEDIA)
241      request_context = media_request_context_.get();
242    return request_context->GetURLRequestContext();
243  }
244
245 private:
246  virtual ~RendererURLRequestContextSelector() {}
247
248  scoped_refptr<net::URLRequestContextGetter> request_context_;
249  scoped_refptr<net::URLRequestContextGetter> media_request_context_;
250};
251
252// the global list of all renderer processes
253base::LazyInstance<IDMap<RenderProcessHost> >::Leaky
254    g_all_hosts = LAZY_INSTANCE_INITIALIZER;
255
256base::LazyInstance<scoped_refptr<BrowserPluginGeolocationPermissionContext> >
257    g_browser_plugin_geolocation_context = LAZY_INSTANCE_INITIALIZER;
258
259// Map of site to process, to ensure we only have one RenderProcessHost per
260// site in process-per-site mode.  Each map is specific to a BrowserContext.
261class SiteProcessMap : public base::SupportsUserData::Data {
262 public:
263  typedef base::hash_map<std::string, RenderProcessHost*> SiteToProcessMap;
264  SiteProcessMap() {}
265
266  void RegisterProcess(const std::string& site, RenderProcessHost* process) {
267    map_[site] = process;
268  }
269
270  RenderProcessHost* FindProcess(const std::string& site) {
271    SiteToProcessMap::iterator i = map_.find(site);
272    if (i != map_.end())
273      return i->second;
274    return NULL;
275  }
276
277  void RemoveProcess(RenderProcessHost* host) {
278    // Find all instances of this process in the map, then separately remove
279    // them.
280    std::set<std::string> sites;
281    for (SiteToProcessMap::const_iterator i = map_.begin();
282         i != map_.end();
283         i++) {
284      if (i->second == host)
285        sites.insert(i->first);
286    }
287    for (std::set<std::string>::iterator i = sites.begin();
288         i != sites.end();
289         i++) {
290      SiteToProcessMap::iterator iter = map_.find(*i);
291      if (iter != map_.end()) {
292        DCHECK_EQ(iter->second, host);
293        map_.erase(iter);
294      }
295    }
296  }
297
298 private:
299  SiteToProcessMap map_;
300};
301
302// Find the SiteProcessMap specific to the given context.
303SiteProcessMap* GetSiteProcessMapForBrowserContext(BrowserContext* context) {
304  DCHECK(context);
305  SiteProcessMap* map = static_cast<SiteProcessMap*>(
306      context->GetUserData(kSiteProcessMapKeyName));
307  if (!map) {
308    map = new SiteProcessMap();
309    context->SetUserData(kSiteProcessMapKeyName, map);
310  }
311  return map;
312}
313
314#if defined(OS_WIN)
315// NOTE: changes to this class need to be reviewed by the security team.
316class RendererSandboxedProcessLauncherDelegate
317    : public content::SandboxedProcessLauncherDelegate {
318 public:
319  RendererSandboxedProcessLauncherDelegate() {}
320  virtual ~RendererSandboxedProcessLauncherDelegate() {}
321
322  virtual void ShouldSandbox(bool* in_sandbox) OVERRIDE {
323#if !defined (GOOGLE_CHROME_BUILD)
324    if (CommandLine::ForCurrentProcess()->HasSwitch(
325        switches::kInProcessPlugins)) {
326      *in_sandbox = false;
327    }
328#endif
329  }
330
331  virtual void PreSpawnTarget(sandbox::TargetPolicy* policy,
332                              bool* success) {
333    AddBaseHandleClosePolicy(policy);
334    GetContentClient()->browser()->PreSpawnRenderer(policy, success);
335  }
336};
337#endif  // OS_WIN
338
339}  // namespace
340
341// Stores the maximum number of renderer processes the content module can
342// create.
343static size_t g_max_renderer_count_override = 0;
344
345// static
346size_t RenderProcessHost::GetMaxRendererProcessCount() {
347  if (g_max_renderer_count_override)
348    return g_max_renderer_count_override;
349
350  // Defines the maximum number of renderer processes according to the
351  // amount of installed memory as reported by the OS. The calculation
352  // assumes that you want the renderers to use half of the installed
353  // RAM and assuming that each WebContents uses ~40MB.
354  // If you modify this assumption, you need to adjust the
355  // ThirtyFourTabs test to match the expected number of processes.
356  //
357  // With the given amounts of installed memory below on a 32-bit CPU,
358  // the maximum renderer count will roughly be as follows:
359  //
360  //   128 MB -> 3
361  //   512 MB -> 6
362  //  1024 MB -> 12
363  //  4096 MB -> 51
364  // 16384 MB -> 82 (kMaxRendererProcessCount)
365
366  static size_t max_count = 0;
367  if (!max_count) {
368    const size_t kEstimatedWebContentsMemoryUsage =
369#if defined(ARCH_CPU_64_BITS)
370        60;  // In MB
371#else
372        40;  // In MB
373#endif
374    max_count = base::SysInfo::AmountOfPhysicalMemoryMB() / 2;
375    max_count /= kEstimatedWebContentsMemoryUsage;
376
377    const size_t kMinRendererProcessCount = 3;
378    max_count = std::max(max_count, kMinRendererProcessCount);
379    max_count = std::min(max_count, kMaxRendererProcessCount);
380  }
381  return max_count;
382}
383
384// static
385bool g_run_renderer_in_process_ = false;
386
387// static
388void RenderProcessHost::SetMaxRendererProcessCount(size_t count) {
389  g_max_renderer_count_override = count;
390}
391
392RenderProcessHostImpl::RenderProcessHostImpl(
393    BrowserContext* browser_context,
394    StoragePartitionImpl* storage_partition_impl,
395    bool supports_browser_plugin,
396    bool is_guest)
397        : fast_shutdown_started_(false),
398          deleting_soon_(false),
399          pending_views_(0),
400          visible_widgets_(0),
401          backgrounded_(true),
402          cached_dibs_cleaner_(
403              FROM_HERE, base::TimeDelta::FromSeconds(5),
404              this, &RenderProcessHostImpl::ClearTransportDIBCache),
405          is_initialized_(false),
406          id_(ChildProcessHostImpl::GenerateChildProcessUniqueId()),
407          browser_context_(browser_context),
408          storage_partition_impl_(storage_partition_impl),
409          sudden_termination_allowed_(true),
410          ignore_input_events_(false),
411          supports_browser_plugin_(supports_browser_plugin),
412          is_guest_(is_guest),
413          gpu_observer_registered_(false),
414          power_monitor_broadcaster_(this) {
415  widget_helper_ = new RenderWidgetHelper();
416
417  ChildProcessSecurityPolicyImpl::GetInstance()->Add(GetID());
418
419  CHECK(!g_exited_main_message_loop);
420  RegisterHost(GetID(), this);
421  g_all_hosts.Get().set_check_on_null_data(true);
422  // Initialize |child_process_activity_time_| to a reasonable value.
423  mark_child_process_activity_time();
424
425  if (!GetBrowserContext()->IsOffTheRecord() &&
426      !CommandLine::ForCurrentProcess()->HasSwitch(
427          switches::kDisableGpuShaderDiskCache)) {
428    BrowserThread::PostTask(BrowserThread::IO, FROM_HERE,
429                            base::Bind(&CacheShaderInfo, GetID(),
430                                       storage_partition_impl_->GetPath()));
431  }
432
433  // Note: When we create the RenderProcessHostImpl, it's technically
434  //       backgrounded, because it has no visible listeners.  But the process
435  //       doesn't actually exist yet, so we'll Background it later, after
436  //       creation.
437}
438
439RenderProcessHostImpl::~RenderProcessHostImpl() {
440  DCHECK(!run_renderer_in_process());
441  ChildProcessSecurityPolicyImpl::GetInstance()->Remove(GetID());
442
443  if (gpu_observer_registered_) {
444    GpuDataManagerImpl::GetInstance()->RemoveObserver(this);
445    gpu_observer_registered_ = false;
446  }
447
448  // We may have some unsent messages at this point, but that's OK.
449  channel_.reset();
450  while (!queued_messages_.empty()) {
451    delete queued_messages_.front();
452    queued_messages_.pop();
453  }
454
455  ClearTransportDIBCache();
456  UnregisterHost(GetID());
457
458  if (!CommandLine::ForCurrentProcess()->HasSwitch(
459      switches::kDisableGpuShaderDiskCache)) {
460    BrowserThread::PostTask(BrowserThread::IO, FROM_HERE,
461                            base::Bind(&RemoveShaderInfo, GetID()));
462  }
463}
464
465void RenderProcessHostImpl::EnableSendQueue() {
466  is_initialized_ = false;
467}
468
469bool RenderProcessHostImpl::Init() {
470  // calling Init() more than once does nothing, this makes it more convenient
471  // for the view host which may not be sure in some cases
472  if (channel_)
473    return true;
474
475  CommandLine::StringType renderer_prefix;
476#if defined(OS_POSIX)
477  // A command prefix is something prepended to the command line of the spawned
478  // process. It is supported only on POSIX systems.
479  const CommandLine& browser_command_line = *CommandLine::ForCurrentProcess();
480  renderer_prefix =
481      browser_command_line.GetSwitchValueNative(switches::kRendererCmdPrefix);
482#endif  // defined(OS_POSIX)
483
484#if defined(OS_LINUX)
485  int flags = renderer_prefix.empty() ? ChildProcessHost::CHILD_ALLOW_SELF :
486                                        ChildProcessHost::CHILD_NORMAL;
487#else
488  int flags = ChildProcessHost::CHILD_NORMAL;
489#endif
490
491  // Find the renderer before creating the channel so if this fails early we
492  // return without creating the channel.
493  base::FilePath renderer_path = ChildProcessHost::GetChildPath(flags);
494  if (renderer_path.empty())
495    return false;
496
497  // Setup the IPC channel.
498  const std::string channel_id =
499      IPC::Channel::GenerateVerifiedChannelID(std::string());
500  channel_.reset(
501          new IPC::ChannelProxy(channel_id,
502                                IPC::Channel::MODE_SERVER,
503                                this,
504                                BrowserThread::GetMessageLoopProxyForThread(
505                                    BrowserThread::IO).get()));
506
507  // Call the embedder first so that their IPC filters have priority.
508  GetContentClient()->browser()->RenderProcessHostCreated(this);
509
510  CreateMessageFilters();
511
512  // Single-process mode not supported in multiple-dll mode currently.
513#if !defined(CHROME_MULTIPLE_DLL)
514  if (run_renderer_in_process()) {
515    // Crank up a thread and run the initialization there.  With the way that
516    // messages flow between the browser and renderer, this thread is required
517    // to prevent a deadlock in single-process mode.  Since the primordial
518    // thread in the renderer process runs the WebKit code and can sometimes
519    // make blocking calls to the UI thread (i.e. this thread), they need to run
520    // on separate threads.
521    in_process_renderer_.reset(new RendererMainThread(channel_id));
522
523    base::Thread::Options options;
524#if defined(OS_WIN) && !defined(OS_MACOSX)
525    // In-process plugins require this to be a UI message loop.
526    options.message_loop_type = base::MessageLoop::TYPE_UI;
527#else
528    // We can't have multiple UI loops on Linux and Android, so we don't support
529    // in-process plugins.
530    options.message_loop_type = base::MessageLoop::TYPE_DEFAULT;
531#endif
532    in_process_renderer_->StartWithOptions(options);
533
534    OnProcessLaunched();  // Fake a callback that the process is ready.
535  } else
536#endif  // !CHROME_MULTIPLE_DLL
537  {
538    // Build command line for renderer.  We call AppendRendererCommandLine()
539    // first so the process type argument will appear first.
540    CommandLine* cmd_line = new CommandLine(renderer_path);
541    if (!renderer_prefix.empty())
542      cmd_line->PrependWrapper(renderer_prefix);
543    AppendRendererCommandLine(cmd_line);
544    cmd_line->AppendSwitchASCII(switches::kProcessChannelID, channel_id);
545
546    // Spawn the child process asynchronously to avoid blocking the UI thread.
547    // As long as there's no renderer prefix, we can use the zygote process
548    // at this stage.
549    child_process_launcher_.reset(new ChildProcessLauncher(
550#if defined(OS_WIN)
551        new RendererSandboxedProcessLauncherDelegate,
552#elif defined(OS_POSIX)
553        renderer_prefix.empty(),
554        base::EnvironmentVector(),
555        channel_->TakeClientFileDescriptor(),
556#endif
557        cmd_line,
558        GetID(),
559        this));
560
561    fast_shutdown_started_ = false;
562  }
563
564  if (!gpu_observer_registered_) {
565    gpu_observer_registered_ = true;
566    GpuDataManagerImpl::GetInstance()->AddObserver(this);
567  }
568
569  is_initialized_ = true;
570  return true;
571}
572
573void RenderProcessHostImpl::CreateMessageFilters() {
574  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
575  channel_->AddFilter(new ResourceSchedulerFilter(GetID()));
576  MediaInternals* media_internals = MediaInternals::GetInstance();;
577  media::AudioManager* audio_manager =
578      BrowserMainLoop::GetInstance()->audio_manager();
579  // Add BrowserPluginMessageFilter to ensure it gets the first stab at messages
580  // from guests.
581  if (supports_browser_plugin_) {
582    scoped_refptr<BrowserPluginMessageFilter> bp_message_filter(
583        new BrowserPluginMessageFilter(GetID(), IsGuest()));
584    channel_->AddFilter(bp_message_filter.get());
585  }
586
587  scoped_refptr<RenderMessageFilter> render_message_filter(
588      new RenderMessageFilter(
589          GetID(),
590          IsGuest(),
591#if defined(ENABLE_PLUGINS)
592          PluginServiceImpl::GetInstance(),
593#else
594          NULL,
595#endif
596          GetBrowserContext(),
597          GetBrowserContext()->GetRequestContextForRenderProcess(GetID()),
598          widget_helper_.get(),
599          audio_manager,
600          media_internals,
601          storage_partition_impl_->GetDOMStorageContext()));
602  channel_->AddFilter(render_message_filter.get());
603  BrowserContext* browser_context = GetBrowserContext();
604  ResourceContext* resource_context = browser_context->GetResourceContext();
605
606  ResourceMessageFilter* resource_message_filter = new ResourceMessageFilter(
607      GetID(), PROCESS_TYPE_RENDERER, resource_context,
608      storage_partition_impl_->GetAppCacheService(),
609      ChromeBlobStorageContext::GetFor(browser_context),
610      storage_partition_impl_->GetFileSystemContext(),
611      new RendererURLRequestContextSelector(browser_context, GetID()));
612
613  channel_->AddFilter(resource_message_filter);
614  MediaStreamManager* media_stream_manager =
615      BrowserMainLoop::GetInstance()->media_stream_manager();
616  channel_->AddFilter(new AudioInputRendererHost(
617      audio_manager,
618      media_stream_manager,
619      BrowserMainLoop::GetInstance()->audio_mirroring_manager()));
620  channel_->AddFilter(new AudioRendererHost(
621      GetID(), audio_manager,
622      BrowserMainLoop::GetInstance()->audio_mirroring_manager(),
623      media_internals, media_stream_manager));
624  channel_->AddFilter(
625      new MIDIHost(BrowserMainLoop::GetInstance()->midi_manager()));
626  channel_->AddFilter(new MIDIDispatcherHost(GetID(), browser_context));
627  channel_->AddFilter(new VideoCaptureHost(media_stream_manager));
628  channel_->AddFilter(new AppCacheDispatcherHost(
629      storage_partition_impl_->GetAppCacheService(),
630      GetID()));
631  channel_->AddFilter(new ClipboardMessageFilter);
632  channel_->AddFilter(new DOMStorageMessageFilter(
633      GetID(),
634      storage_partition_impl_->GetDOMStorageContext()));
635  channel_->AddFilter(new IndexedDBDispatcherHost(
636      GetID(),
637      storage_partition_impl_->GetIndexedDBContext()));
638  if (IsGuest()) {
639    if (!g_browser_plugin_geolocation_context.Get().get()) {
640      g_browser_plugin_geolocation_context.Get() =
641          new BrowserPluginGeolocationPermissionContext();
642    }
643    channel_->AddFilter(GeolocationDispatcherHost::New(
644        GetID(), g_browser_plugin_geolocation_context.Get().get()));
645  } else {
646    channel_->AddFilter(GeolocationDispatcherHost::New(
647        GetID(), browser_context->GetGeolocationPermissionContext()));
648  }
649  gpu_message_filter_ = new GpuMessageFilter(GetID(), widget_helper_.get());
650  channel_->AddFilter(gpu_message_filter_);
651#if defined(ENABLE_WEBRTC)
652  channel_->AddFilter(new WebRTCIdentityServiceHost(
653      storage_partition_impl_->GetWebRTCIdentityStore()));
654  peer_connection_tracker_host_ = new PeerConnectionTrackerHost(GetID());
655  channel_->AddFilter(peer_connection_tracker_host_.get());
656  channel_->AddFilter(new MediaStreamDispatcherHost(
657      GetID(), media_stream_manager));
658  channel_->AddFilter(new DeviceRequestMessageFilter(media_stream_manager));
659#endif
660#if defined(ENABLE_PLUGINS)
661  // TODO(raymes): PepperMessageFilter should be removed from here.
662  channel_->AddFilter(new PepperMessageFilter(GetID(), browser_context));
663  channel_->AddFilter(new PepperRendererConnection(GetID()));
664#endif
665#if defined(ENABLE_INPUT_SPEECH)
666  channel_->AddFilter(new InputTagSpeechDispatcherHost(
667      IsGuest(), GetID(), storage_partition_impl_->GetURLRequestContext()));
668#endif
669  channel_->AddFilter(new SpeechRecognitionDispatcherHost(
670      GetID(), storage_partition_impl_->GetURLRequestContext()));
671  channel_->AddFilter(new FileAPIMessageFilter(
672      GetID(),
673      storage_partition_impl_->GetURLRequestContext(),
674      storage_partition_impl_->GetFileSystemContext(),
675      ChromeBlobStorageContext::GetFor(browser_context)));
676  channel_->AddFilter(new OrientationMessageFilter());
677  channel_->AddFilter(new FileUtilitiesMessageFilter(GetID()));
678  channel_->AddFilter(new MimeRegistryMessageFilter());
679  channel_->AddFilter(new DatabaseMessageFilter(
680      storage_partition_impl_->GetDatabaseTracker()));
681#if defined(OS_MACOSX)
682  channel_->AddFilter(new TextInputClientMessageFilter(GetID()));
683#elif defined(OS_WIN)
684  channel_->AddFilter(new FontCacheDispatcher());
685#endif
686
687  SocketStreamDispatcherHost* socket_stream_dispatcher_host =
688      new SocketStreamDispatcherHost(GetID(),
689          new RendererURLRequestContextSelector(browser_context, GetID()),
690          resource_context);
691  channel_->AddFilter(socket_stream_dispatcher_host);
692
693  channel_->AddFilter(new WorkerMessageFilter(
694      GetID(),
695      resource_context,
696      WorkerStoragePartition(
697          storage_partition_impl_->GetURLRequestContext(),
698          storage_partition_impl_->GetMediaURLRequestContext(),
699          storage_partition_impl_->GetAppCacheService(),
700          storage_partition_impl_->GetQuotaManager(),
701          storage_partition_impl_->GetFileSystemContext(),
702          storage_partition_impl_->GetDatabaseTracker(),
703          storage_partition_impl_->GetIndexedDBContext()),
704      base::Bind(&RenderWidgetHelper::GetNextRoutingID,
705                 base::Unretained(widget_helper_.get()))));
706
707#if defined(ENABLE_WEBRTC)
708  channel_->AddFilter(new P2PSocketDispatcherHost(
709      resource_context,
710      browser_context->GetRequestContextForRenderProcess(GetID())));
711#endif
712
713  channel_->AddFilter(new TraceMessageFilter());
714  channel_->AddFilter(new ResolveProxyMsgHelper(
715      browser_context->GetRequestContextForRenderProcess(GetID())));
716  channel_->AddFilter(new QuotaDispatcherHost(
717      GetID(),
718      storage_partition_impl_->GetQuotaManager(),
719      GetContentClient()->browser()->CreateQuotaPermissionContext()));
720  channel_->AddFilter(new GamepadBrowserMessageFilter());
721  channel_->AddFilter(new DeviceMotionBrowserMessageFilter());
722  channel_->AddFilter(new ProfilerMessageFilter(PROCESS_TYPE_RENDERER));
723  channel_->AddFilter(new HistogramMessageFilter());
724#if defined(USE_TCMALLOC) && (defined(OS_LINUX) || defined(OS_ANDROID))
725  if (CommandLine::ForCurrentProcess()->HasSwitch(
726      switches::kEnableMemoryBenchmarking))
727    channel_->AddFilter(new MemoryBenchmarkMessageFilter());
728#endif
729#if defined(OS_ANDROID)
730  channel_->AddFilter(new VibrationMessageFilter());
731#endif
732}
733
734int RenderProcessHostImpl::GetNextRoutingID() {
735  return widget_helper_->GetNextRoutingID();
736}
737
738
739void RenderProcessHostImpl::ResumeDeferredNavigation(
740    const GlobalRequestID& request_id) {
741  widget_helper_->ResumeDeferredNavigation(request_id);
742}
743
744void RenderProcessHostImpl::AddRoute(
745    int32 routing_id,
746    IPC::Listener* listener) {
747  listeners_.AddWithID(listener, routing_id);
748}
749
750void RenderProcessHostImpl::RemoveRoute(int32 routing_id) {
751  DCHECK(listeners_.Lookup(routing_id) != NULL);
752  listeners_.Remove(routing_id);
753
754#if defined(OS_WIN)
755  // Dump the handle table if handle auditing is enabled.
756  const CommandLine& browser_command_line =
757      *CommandLine::ForCurrentProcess();
758  if (browser_command_line.HasSwitch(switches::kAuditHandles) ||
759      browser_command_line.HasSwitch(switches::kAuditAllHandles)) {
760    DumpHandles();
761
762    // We wait to close the channels until the child process has finished
763    // dumping handles and sends us ChildProcessHostMsg_DumpHandlesDone.
764    return;
765  }
766#endif
767  // Keep the one renderer thread around forever in single process mode.
768  if (!run_renderer_in_process())
769    Cleanup();
770}
771
772bool RenderProcessHostImpl::WaitForBackingStoreMsg(
773    int render_widget_id,
774    const base::TimeDelta& max_delay,
775    IPC::Message* msg) {
776  // The post task to this thread with the process id could be in queue, and we
777  // don't want to dispatch a message before then since it will need the handle.
778  if (child_process_launcher_.get() && child_process_launcher_->IsStarting())
779    return false;
780
781  return widget_helper_->WaitForBackingStoreMsg(render_widget_id,
782                                                max_delay, msg);
783}
784
785void RenderProcessHostImpl::ReceivedBadMessage() {
786  if (run_renderer_in_process()) {
787    // In single process mode it is better if we don't suicide but just
788    // crash.
789    CHECK(false);
790  }
791  // We kill the renderer but don't include a NOTREACHED, because we want the
792  // browser to try to survive when it gets illegal messages from the renderer.
793  base::KillProcess(GetHandle(), RESULT_CODE_KILLED_BAD_MESSAGE,
794                    false);
795}
796
797void RenderProcessHostImpl::WidgetRestored() {
798  // Verify we were properly backgrounded.
799  DCHECK_EQ(backgrounded_, (visible_widgets_ == 0));
800  visible_widgets_++;
801  SetBackgrounded(false);
802}
803
804void RenderProcessHostImpl::WidgetHidden() {
805  // On startup, the browser will call Hide
806  if (backgrounded_)
807    return;
808
809  DCHECK_EQ(backgrounded_, (visible_widgets_ == 0));
810  visible_widgets_--;
811  DCHECK_GE(visible_widgets_, 0);
812  if (visible_widgets_ == 0) {
813    DCHECK(!backgrounded_);
814    SetBackgrounded(true);
815  }
816}
817
818int RenderProcessHostImpl::VisibleWidgetCount() const {
819  return visible_widgets_;
820}
821
822bool RenderProcessHostImpl::IsGuest() const {
823  return is_guest_;
824}
825
826StoragePartition* RenderProcessHostImpl::GetStoragePartition() const {
827  return storage_partition_impl_;
828}
829
830void RenderProcessHostImpl::AppendRendererCommandLine(
831    CommandLine* command_line) const {
832  // Pass the process type first, so it shows first in process listings.
833  command_line->AppendSwitchASCII(switches::kProcessType,
834                                  switches::kRendererProcess);
835
836  // Now send any options from our own command line we want to propagate.
837  const CommandLine& browser_command_line = *CommandLine::ForCurrentProcess();
838  PropagateBrowserCommandLineToRenderer(browser_command_line, command_line);
839
840  // Pass on the browser locale.
841  const std::string locale =
842      GetContentClient()->browser()->GetApplicationLocale();
843  command_line->AppendSwitchASCII(switches::kLang, locale);
844
845  // If we run base::FieldTrials, we want to pass to their state to the
846  // renderer so that it can act in accordance with each state, or record
847  // histograms relating to the base::FieldTrial states.
848  std::string field_trial_states;
849  base::FieldTrialList::StatesToString(&field_trial_states);
850  if (!field_trial_states.empty()) {
851    command_line->AppendSwitchASCII(switches::kForceFieldTrials,
852                                    field_trial_states);
853  }
854
855  GetContentClient()->browser()->AppendExtraCommandLineSwitches(
856      command_line, GetID());
857
858  // Appending disable-gpu-feature switches due to software rendering list.
859  GpuDataManagerImpl* gpu_data_manager = GpuDataManagerImpl::GetInstance();
860  DCHECK(gpu_data_manager);
861  gpu_data_manager->AppendRendererCommandLine(command_line);
862}
863
864void RenderProcessHostImpl::PropagateBrowserCommandLineToRenderer(
865    const CommandLine& browser_cmd,
866    CommandLine* renderer_cmd) const {
867  // Propagate the following switches to the renderer command line (along
868  // with any associated values) if present in the browser command line.
869  static const char* const kSwitchNames[] = {
870    switches::kAudioBufferSize,
871    switches::kAuditAllHandles,
872    switches::kAuditHandles,
873    switches::kDisable3DAPIs,
874    switches::kDisableAcceleratedCompositing,
875    switches::kDisableAcceleratedVideoDecode,
876    switches::kDisableApplicationCache,
877    switches::kDisableAudio,
878    switches::kDisableBreakpad,
879    switches::kDisableDatabases,
880    switches::kDisableDelegatedRenderer,
881    switches::kDisableDesktopNotifications,
882    switches::kDisableDeviceOrientation,
883    switches::kDisableFileSystem,
884    switches::kDisableGeolocation,
885    switches::kDisableGLMultisampling,
886    switches::kDisableGpuVsync,
887    switches::kDisableGpu,
888    switches::kDisableGpuCompositing,
889    switches::kDisableHistogramCustomizer,
890    switches::kDisableLocalStorage,
891    switches::kDisableLogging,
892    switches::kDisableNewDialogStyle,
893    switches::kDisableSeccompFilterSandbox,
894    switches::kDisableSessionStorage,
895    switches::kDisableSharedWorkers,
896    switches::kDisableSpeechInput,
897    switches::kDisableTouchDragDrop,
898    switches::kDisableTouchEditing,
899#if defined(OS_ANDROID)
900    switches::kDisableWebRTC,
901    switches::kEnableSpeechRecognition,
902#endif
903    switches::kDisableWebAudio,
904#if defined(ENABLE_WEBRTC)
905    switches::kDisableDeviceEnumeration,
906    switches::kEnableSCTPDataChannels,
907#endif
908    switches::kEnableWebAnimationsCSS,
909    switches::kEnableWebAnimationsSVG,
910    switches::kEnableWebMIDI,
911    switches::kEnableExperimentalCanvasFeatures,
912    switches::kEnableExperimentalWebSocket,
913    switches::kDomAutomationController,
914    switches::kEnableAccessibilityLogging,
915    switches::kEnableBeginFrameScheduling,
916    switches::kEnableBrowserInputController,
917    switches::kEnableBrowserPluginForAllViewTypes,
918    switches::kEnableDCHECK,
919    switches::kEnableDelegatedRenderer,
920    switches::kEnableEncryptedMedia,
921    switches::kDisableLegacyEncryptedMedia,
922    switches::kOverrideEncryptedMediaCanPlayType,
923    switches::kEnableExperimentalWebPlatformFeatures,
924    switches::kEnableFixedLayout,
925    switches::kEnableDeferredImageDecoding,
926    switches::kEnableGPUServiceLogging,
927    switches::kEnableGPUClientLogging,
928    switches::kEnableGpuClientTracing,
929    switches::kEnableGpuBenchmarking,
930    switches::kEnableMemoryBenchmarking,
931    switches::kEnableSkiaBenchmarking,
932    switches::kEnableLogging,
933    switches::kEnableSpeechSynthesis,
934    switches::kEnableTouchDragDrop,
935    switches::kEnableTouchEditing,
936#if defined(ENABLE_WEBRTC)
937    switches::kEnableWebRtcAecRecordings,
938    switches::kEnableWebRtcTcpServerSocket,
939    switches::kEnableWebRtcHWDecoding,
940#endif
941    switches::kDisableWebKitMediaSource,
942    switches::kEnableOverscrollNotifications,
943    switches::kEnableStrictSiteIsolation,
944    switches::kDisableFullScreen,
945    switches::kEnableNewDialogStyle,
946#if defined(ENABLE_PLUGINS)
947    switches::kEnablePepperTesting,
948    switches::kDisablePepper3d,
949#endif
950    switches::kEnablePreparsedJsCaching,
951    switches::kEnablePruneGpuCommandBuffers,
952    switches::kEnablePinch,
953    switches::kDisablePinch,
954#if defined(OS_MACOSX)
955    // Allow this to be set when invoking the browser and relayed along.
956    switches::kEnableSandboxLogging,
957#endif
958    switches::kEnableSoftwareCompositing,
959    switches::kEnableStatsTable,
960    switches::kEnableThreadedCompositing,
961    switches::kEnableCompositingForFixedPosition,
962    switches::kEnableHighDpiCompositingForFixedPosition,
963    switches::kDisableCompositingForFixedPosition,
964    switches::kEnableAcceleratedOverflowScroll,
965    switches::kEnableCompositingForTransition,
966    switches::kDisableCompositingForTransition,
967    switches::kEnableAcceleratedFixedRootBackground,
968    switches::kDisableAcceleratedFixedRootBackground,
969    switches::kDisableThreadedCompositing,
970    switches::kDisableTouchAdjustment,
971    switches::kDefaultTileWidth,
972    switches::kDefaultTileHeight,
973    switches::kMaxUntiledLayerWidth,
974    switches::kMaxUntiledLayerHeight,
975#if defined(OS_CHROMEOS)
976    switches::kEnableEncodedScreenCapture,
977#endif
978    switches::kEnableViewport,
979    switches::kEnableInbandTextTracks,
980    switches::kEnableOpusPlayback,
981    switches::kEnableVp8AlphaPlayback,
982    switches::kEnableEac3Playback,
983    switches::kForceDeviceScaleFactor,
984    switches::kFullMemoryCrashReport,
985#if defined(OS_ANDROID)
986    switches::kHideScrollbars,
987#endif
988#if !defined (GOOGLE_CHROME_BUILD)
989    // These are unsupported and not fully tested modes, so don't enable them
990    // for official Google Chrome builds.
991    switches::kInProcessPlugins,
992#endif  // GOOGLE_CHROME_BUILD
993    switches::kJavaScriptFlags,
994    switches::kLoggingLevel,
995    switches::kMemoryMetrics,
996#if defined(OS_ANDROID)
997    switches::kNetworkCountryIso,
998    switches::kDisableGestureRequirementForMediaPlayback,
999#endif
1000#if defined(GOOGLE_TV)
1001    switches::kUseExternalVideoSurfaceThresholdInPixels,
1002#endif
1003    switches::kNoReferrers,
1004    switches::kNoSandbox,
1005    switches::kEnableVtune,
1006    switches::kPpapiInProcess,
1007    switches::kRegisterPepperPlugins,
1008    switches::kRendererAssertTest,
1009#if defined(OS_POSIX)
1010    switches::kChildCleanExit,
1011#endif
1012    switches::kRendererStartupDialog,
1013    switches::kShowPaintRects,
1014    switches::kSitePerProcess,
1015    switches::kStatsCollectionController,
1016    switches::kTestSandbox,
1017    switches::kTouchEvents,
1018    switches::kTraceStartup,
1019    // This flag needs to be propagated to the renderer process for
1020    // --in-process-webgl.
1021    switches::kUseGL,
1022    switches::kUseMobileUserAgent,
1023    switches::kUserAgent,
1024    switches::kV,
1025    switches::kVideoThreads,
1026    switches::kVModule,
1027    switches::kWebCoreLogChannels,
1028    switches::kEnableWebGLDraftExtensions,
1029    switches::kTraceToConsole,
1030    switches::kEnableDeviceMotion,
1031#if defined(OS_ANDROID)
1032    switches::kDisableDeviceMotion,
1033#endif
1034    // Please keep these in alphabetical order. Compositor switches here should
1035    // also be added to chrome/browser/chromeos/login/chrome_restart_request.cc.
1036    cc::switches::kBackgroundColorInsteadOfCheckerboard,
1037    cc::switches::kCompositeToMailbox,
1038    cc::switches::kDisableCompositedAntialiasing,
1039    cc::switches::kDisableImplSidePainting,
1040    cc::switches::kDisableThreadedAnimation,
1041    cc::switches::kEnableImplSidePainting,
1042    cc::switches::kEnablePartialSwap,
1043    cc::switches::kEnablePerTilePainting,
1044    cc::switches::kEnablePinchVirtualViewport,
1045    cc::switches::kEnableTopControlsPositionCalculation,
1046    cc::switches::kForceDirectLayerDrawing,
1047    cc::switches::kLowResolutionContentsScaleFactor,
1048    cc::switches::kMaxTilesForInterestArea,
1049    cc::switches::kMaxUnusedResourceMemoryUsagePercentage,
1050    cc::switches::kNumRasterThreads,
1051    cc::switches::kShowCompositedLayerBorders,
1052    cc::switches::kShowFPSCounter,
1053    cc::switches::kShowNonOccludingRects,
1054    cc::switches::kShowOccludingRects,
1055    cc::switches::kShowPropertyChangedRects,
1056    cc::switches::kShowReplicaScreenSpaceRects,
1057    cc::switches::kShowScreenSpaceRects,
1058    cc::switches::kShowSurfaceDamageRects,
1059    cc::switches::kSlowDownRasterScaleFactor,
1060    cc::switches::kStrictLayerPropertyChangeChecking,
1061    cc::switches::kTopControlsHeight,
1062    cc::switches::kTopControlsHideThreshold,
1063    cc::switches::kTopControlsShowThreshold,
1064    cc::switches::kTraceOverdraw,
1065    cc::switches::kUseMapImage,
1066  };
1067  renderer_cmd->CopySwitchesFrom(browser_cmd, kSwitchNames,
1068                                 arraysize(kSwitchNames));
1069
1070  // Disable databases in incognito mode.
1071  if (GetBrowserContext()->IsOffTheRecord() &&
1072      !browser_cmd.HasSwitch(switches::kDisableDatabases)) {
1073    renderer_cmd->AppendSwitch(switches::kDisableDatabases);
1074#if defined(OS_ANDROID)
1075    renderer_cmd->AppendSwitch(switches::kDisableMediaHistoryLogging);
1076#endif
1077  }
1078
1079  // Enforce the extra command line flags for impl-side painting.
1080  if (cc::switches::IsImplSidePaintingEnabled() &&
1081      !browser_cmd.HasSwitch(switches::kEnableDeferredImageDecoding))
1082    renderer_cmd->AppendSwitch(switches::kEnableDeferredImageDecoding);
1083}
1084
1085base::ProcessHandle RenderProcessHostImpl::GetHandle() const {
1086  if (run_renderer_in_process())
1087    return base::Process::Current().handle();
1088
1089  if (!child_process_launcher_.get() || child_process_launcher_->IsStarting())
1090    return base::kNullProcessHandle;
1091
1092  return child_process_launcher_->GetHandle();
1093}
1094
1095bool RenderProcessHostImpl::FastShutdownIfPossible() {
1096  if (run_renderer_in_process())
1097    return false;  // Single process mode never shutdown the renderer.
1098
1099  if (!GetContentClient()->browser()->IsFastShutdownPossible())
1100    return false;
1101
1102  if (!child_process_launcher_.get() ||
1103      child_process_launcher_->IsStarting() ||
1104      !GetHandle())
1105    return false;  // Render process hasn't started or is probably crashed.
1106
1107  // Test if there's an unload listener.
1108  // NOTE: It's possible that an onunload listener may be installed
1109  // while we're shutting down, so there's a small race here.  Given that
1110  // the window is small, it's unlikely that the web page has much
1111  // state that will be lost by not calling its unload handlers properly.
1112  if (!SuddenTerminationAllowed())
1113    return false;
1114
1115  ProcessDied(false /* already_dead */);
1116  fast_shutdown_started_ = true;
1117  return true;
1118}
1119
1120void RenderProcessHostImpl::DumpHandles() {
1121#if defined(OS_WIN)
1122  Send(new ChildProcessMsg_DumpHandles());
1123  return;
1124#endif
1125
1126  NOTIMPLEMENTED();
1127}
1128
1129// This is a platform specific function for mapping a transport DIB given its id
1130TransportDIB* RenderProcessHostImpl::MapTransportDIB(
1131    TransportDIB::Id dib_id) {
1132#if defined(OS_WIN)
1133  // On Windows we need to duplicate the handle from the remote process
1134  HANDLE section;
1135  DuplicateHandle(GetHandle(), dib_id.handle, GetCurrentProcess(), &section,
1136                  STANDARD_RIGHTS_REQUIRED | FILE_MAP_READ | FILE_MAP_WRITE,
1137                  FALSE, 0);
1138  return TransportDIB::Map(section);
1139#elif defined(TOOLKIT_GTK)
1140  return TransportDIB::Map(dib_id.shmkey);
1141#elif defined(OS_ANDROID)
1142  return TransportDIB::Map(dib_id);
1143#else
1144  // On POSIX, the browser allocates all DIBs and keeps a file descriptor around
1145  // for each.
1146  return widget_helper_->MapTransportDIB(dib_id);
1147#endif
1148}
1149
1150TransportDIB* RenderProcessHostImpl::GetTransportDIB(
1151    TransportDIB::Id dib_id) {
1152  if (!TransportDIB::is_valid_id(dib_id))
1153    return NULL;
1154
1155  const std::map<TransportDIB::Id, TransportDIB*>::iterator
1156      i = cached_dibs_.find(dib_id);
1157  if (i != cached_dibs_.end()) {
1158    cached_dibs_cleaner_.Reset();
1159    return i->second;
1160  }
1161
1162  TransportDIB* dib = MapTransportDIB(dib_id);
1163  if (!dib)
1164    return NULL;
1165
1166  if (cached_dibs_.size() >= MAX_MAPPED_TRANSPORT_DIBS) {
1167    // Clean a single entry from the cache
1168    std::map<TransportDIB::Id, TransportDIB*>::iterator smallest_iterator;
1169    size_t smallest_size = std::numeric_limits<size_t>::max();
1170
1171    for (std::map<TransportDIB::Id, TransportDIB*>::iterator
1172         i = cached_dibs_.begin(); i != cached_dibs_.end(); ++i) {
1173      if (i->second->size() <= smallest_size) {
1174        smallest_iterator = i;
1175        smallest_size = i->second->size();
1176      }
1177    }
1178
1179#if defined(TOOLKIT_GTK)
1180    smallest_iterator->second->Detach();
1181#else
1182    delete smallest_iterator->second;
1183#endif
1184    cached_dibs_.erase(smallest_iterator);
1185  }
1186
1187  cached_dibs_[dib_id] = dib;
1188  cached_dibs_cleaner_.Reset();
1189  return dib;
1190}
1191
1192void RenderProcessHostImpl::ClearTransportDIBCache() {
1193#if defined(TOOLKIT_GTK)
1194  std::map<TransportDIB::Id, TransportDIB*>::const_iterator dib =
1195      cached_dibs_.begin();
1196  for (; dib != cached_dibs_.end(); ++dib)
1197    dib->second->Detach();
1198#else
1199  STLDeleteContainerPairSecondPointers(
1200      cached_dibs_.begin(), cached_dibs_.end());
1201#endif
1202  cached_dibs_.clear();
1203}
1204
1205bool RenderProcessHostImpl::Send(IPC::Message* msg) {
1206  if (!channel_) {
1207    if (!is_initialized_) {
1208      queued_messages_.push(msg);
1209      return true;
1210    } else {
1211      delete msg;
1212      return false;
1213    }
1214  }
1215
1216  if (child_process_launcher_.get() && child_process_launcher_->IsStarting()) {
1217    queued_messages_.push(msg);
1218    return true;
1219  }
1220
1221  return channel_->Send(msg);
1222}
1223
1224bool RenderProcessHostImpl::OnMessageReceived(const IPC::Message& msg) {
1225  // If we're about to be deleted, or have initiated the fast shutdown sequence,
1226  // we ignore incoming messages.
1227
1228  if (deleting_soon_ || fast_shutdown_started_)
1229    return false;
1230
1231  mark_child_process_activity_time();
1232  if (msg.routing_id() == MSG_ROUTING_CONTROL) {
1233    // Dispatch control messages.
1234    bool msg_is_ok = true;
1235    IPC_BEGIN_MESSAGE_MAP_EX(RenderProcessHostImpl, msg, msg_is_ok)
1236      IPC_MESSAGE_HANDLER(ChildProcessHostMsg_ShutdownRequest,
1237                          OnShutdownRequest)
1238      IPC_MESSAGE_HANDLER(ChildProcessHostMsg_DumpHandlesDone,
1239                          OnDumpHandlesDone)
1240      IPC_MESSAGE_HANDLER(ViewHostMsg_SuddenTerminationChanged,
1241                          SuddenTerminationChanged)
1242      IPC_MESSAGE_HANDLER(ViewHostMsg_UserMetricsRecordAction,
1243                          OnUserMetricsRecordAction)
1244      IPC_MESSAGE_HANDLER(ViewHostMsg_SavedPageAsMHTML, OnSavedPageAsMHTML)
1245      // Adding single handlers for your service here is fine, but once your
1246      // service needs more than one handler, please extract them into a new
1247      // message filter and add that filter to CreateMessageFilters().
1248      IPC_MESSAGE_UNHANDLED_ERROR()
1249    IPC_END_MESSAGE_MAP_EX()
1250
1251    if (!msg_is_ok) {
1252      // The message had a handler, but its de-serialization failed.
1253      // We consider this a capital crime. Kill the renderer if we have one.
1254      LOG(ERROR) << "bad message " << msg.type() << " terminating renderer.";
1255      RecordAction(UserMetricsAction("BadMessageTerminate_BRPH"));
1256      ReceivedBadMessage();
1257    }
1258    return true;
1259  }
1260
1261  // Dispatch incoming messages to the appropriate IPC::Listener.
1262  IPC::Listener* listener = listeners_.Lookup(msg.routing_id());
1263  if (!listener) {
1264    if (msg.is_sync()) {
1265      // The listener has gone away, so we must respond or else the caller will
1266      // hang waiting for a reply.
1267      IPC::Message* reply = IPC::SyncMessage::GenerateReply(&msg);
1268      reply->set_reply_error();
1269      Send(reply);
1270    }
1271
1272    // If this is a SwapBuffers, we need to ack it if we're not going to handle
1273    // it so that the GPU process doesn't get stuck in unscheduled state.
1274    bool msg_is_ok = true;
1275    IPC_BEGIN_MESSAGE_MAP_EX(RenderProcessHostImpl, msg, msg_is_ok)
1276      IPC_MESSAGE_HANDLER(ViewHostMsg_CompositorSurfaceBuffersSwapped,
1277                          OnCompositorSurfaceBuffersSwappedNoHost)
1278    IPC_END_MESSAGE_MAP_EX()
1279    return true;
1280  }
1281  return listener->OnMessageReceived(msg);
1282}
1283
1284void RenderProcessHostImpl::OnChannelConnected(int32 peer_pid) {
1285#if defined(IPC_MESSAGE_LOG_ENABLED)
1286  Send(new ChildProcessMsg_SetIPCLoggingEnabled(
1287      IPC::Logging::GetInstance()->Enabled()));
1288#endif
1289
1290  tracked_objects::ThreadData::Status status =
1291      tracked_objects::ThreadData::status();
1292  Send(new ChildProcessMsg_SetProfilerStatus(status));
1293}
1294
1295void RenderProcessHostImpl::OnChannelError() {
1296  ProcessDied(true /* already_dead */);
1297}
1298
1299BrowserContext* RenderProcessHostImpl::GetBrowserContext() const {
1300  return browser_context_;
1301}
1302
1303bool RenderProcessHostImpl::InSameStoragePartition(
1304    StoragePartition* partition) const {
1305  return storage_partition_impl_ == partition;
1306}
1307
1308int RenderProcessHostImpl::GetID() const {
1309  return id_;
1310}
1311
1312bool RenderProcessHostImpl::HasConnection() const {
1313  return channel_.get() != NULL;
1314}
1315
1316void RenderProcessHostImpl::SetIgnoreInputEvents(bool ignore_input_events) {
1317  ignore_input_events_ = ignore_input_events;
1318}
1319
1320bool RenderProcessHostImpl::IgnoreInputEvents() const {
1321  return ignore_input_events_;
1322}
1323
1324void RenderProcessHostImpl::Cleanup() {
1325  // When no other owners of this object, we can delete ourselves
1326  if (listeners_.IsEmpty()) {
1327    DCHECK_EQ(0, pending_views_);
1328    NotificationService::current()->Notify(
1329        NOTIFICATION_RENDERER_PROCESS_TERMINATED,
1330        Source<RenderProcessHost>(this),
1331        NotificationService::NoDetails());
1332
1333    base::MessageLoop::current()->DeleteSoon(FROM_HERE, this);
1334    deleting_soon_ = true;
1335    // It's important not to wait for the DeleteTask to delete the channel
1336    // proxy. Kill it off now. That way, in case the profile is going away, the
1337    // rest of the objects attached to this RenderProcessHost start going
1338    // away first, since deleting the channel proxy will post a
1339    // OnChannelClosed() to IPC::ChannelProxy::Context on the IO thread.
1340    channel_.reset();
1341    gpu_message_filter_ = NULL;
1342
1343    // Remove ourself from the list of renderer processes so that we can't be
1344    // reused in between now and when the Delete task runs.
1345    UnregisterHost(GetID());
1346  }
1347}
1348
1349void RenderProcessHostImpl::AddPendingView() {
1350  pending_views_++;
1351}
1352
1353void RenderProcessHostImpl::RemovePendingView() {
1354  DCHECK(pending_views_);
1355  pending_views_--;
1356}
1357
1358void RenderProcessHostImpl::SetSuddenTerminationAllowed(bool enabled) {
1359  sudden_termination_allowed_ = enabled;
1360}
1361
1362bool RenderProcessHostImpl::SuddenTerminationAllowed() const {
1363  return sudden_termination_allowed_;
1364}
1365
1366base::TimeDelta RenderProcessHostImpl::GetChildProcessIdleTime() const {
1367  return base::TimeTicks::Now() - child_process_activity_time_;
1368}
1369
1370void RenderProcessHostImpl::SurfaceUpdated(int32 surface_id) {
1371  if (!gpu_message_filter_)
1372    return;
1373  BrowserThread::PostTask(BrowserThread::IO, FROM_HERE, base::Bind(
1374      &GpuMessageFilter::SurfaceUpdated,
1375      gpu_message_filter_,
1376      surface_id));
1377}
1378
1379void RenderProcessHostImpl::ResumeRequestsForView(int route_id) {
1380  widget_helper_->ResumeRequestsForView(route_id);
1381}
1382
1383IPC::ChannelProxy* RenderProcessHostImpl::GetChannel() {
1384  return channel_.get();
1385}
1386
1387bool RenderProcessHostImpl::FastShutdownForPageCount(size_t count) {
1388  if (static_cast<size_t>(GetActiveViewCount()) == count)
1389    return FastShutdownIfPossible();
1390  return false;
1391}
1392
1393bool RenderProcessHostImpl::FastShutdownStarted() const {
1394  return fast_shutdown_started_;
1395}
1396
1397// static
1398void RenderProcessHostImpl::RegisterHost(int host_id, RenderProcessHost* host) {
1399  g_all_hosts.Get().AddWithID(host, host_id);
1400}
1401
1402// static
1403void RenderProcessHostImpl::UnregisterHost(int host_id) {
1404  RenderProcessHost* host = g_all_hosts.Get().Lookup(host_id);
1405  if (!host)
1406    return;
1407
1408  g_all_hosts.Get().Remove(host_id);
1409
1410  // Look up the map of site to process for the given browser_context,
1411  // in case we need to remove this process from it.  It will be registered
1412  // under any sites it rendered that use process-per-site mode.
1413  SiteProcessMap* map =
1414      GetSiteProcessMapForBrowserContext(host->GetBrowserContext());
1415  map->RemoveProcess(host);
1416}
1417
1418// static
1419bool RenderProcessHostImpl::IsSuitableHost(
1420    RenderProcessHost* host,
1421    BrowserContext* browser_context,
1422    const GURL& site_url) {
1423  if (run_renderer_in_process())
1424    return true;
1425
1426  if (host->GetBrowserContext() != browser_context)
1427    return false;
1428
1429  // Check whether the given host and the intended site_url will be using the
1430  // same StoragePartition, since a RenderProcessHost can only support a single
1431  // StoragePartition.  This is relevant for packaged apps, browser tags, and
1432  // isolated sites.
1433  StoragePartition* dest_partition =
1434      BrowserContext::GetStoragePartitionForSite(browser_context, site_url);
1435  if (!host->InSameStoragePartition(dest_partition))
1436    return false;
1437
1438  // All URLs are suitable if this is associated with a guest renderer process.
1439  // TODO(fsamuel, creis): Further validation is needed to ensure that only
1440  // normal web URLs are permitted in guest processes. We need to investigate
1441  // where this validation should happen.
1442  if (host->IsGuest())
1443    return true;
1444
1445  if (!host->IsGuest() && site_url.SchemeIs(chrome::kGuestScheme))
1446    return false;
1447
1448  if (ChildProcessSecurityPolicyImpl::GetInstance()->HasWebUIBindings(
1449          host->GetID()) !=
1450      WebUIControllerFactoryRegistry::GetInstance()->UseWebUIBindingsForURL(
1451          browser_context, site_url)) {
1452    return false;
1453  }
1454
1455  return GetContentClient()->browser()->IsSuitableHost(host, site_url);
1456}
1457
1458// static
1459bool RenderProcessHost::run_renderer_in_process() {
1460  return g_run_renderer_in_process_;
1461}
1462
1463// static
1464void RenderProcessHost::SetRunRendererInProcess(bool value) {
1465  g_run_renderer_in_process_ = value;
1466
1467  CommandLine* command_line = CommandLine::ForCurrentProcess();
1468  if (value && !command_line->HasSwitch(switches::kLang)) {
1469    // Modify the current process' command line to include the browser locale,
1470    // as the renderer expects this flag to be set.
1471    const std::string locale =
1472        GetContentClient()->browser()->GetApplicationLocale();
1473    command_line->AppendSwitchASCII(switches::kLang, locale);
1474  }
1475}
1476
1477RenderProcessHost::iterator RenderProcessHost::AllHostsIterator() {
1478  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
1479  return iterator(g_all_hosts.Pointer());
1480}
1481
1482// static
1483RenderProcessHost* RenderProcessHost::FromID(int render_process_id) {
1484  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
1485  return g_all_hosts.Get().Lookup(render_process_id);
1486}
1487
1488// static
1489bool RenderProcessHost::ShouldTryToUseExistingProcessHost(
1490    BrowserContext* browser_context, const GURL& url) {
1491  // Experimental:
1492  // If --enable-strict-site-isolation or --site-per-process is enabled, do not
1493  // try to reuse renderer processes when over the limit.  (We could allow pages
1494  // from the same site to share, if we knew what the given process was
1495  // dedicated to.  Allowing no sharing is simpler for now.)  This may cause
1496  // resource exhaustion issues if too many sites are open at once.
1497  const CommandLine& command_line = *CommandLine::ForCurrentProcess();
1498  if (command_line.HasSwitch(switches::kEnableStrictSiteIsolation) ||
1499      command_line.HasSwitch(switches::kSitePerProcess))
1500    return false;
1501
1502  if (run_renderer_in_process())
1503    return true;
1504
1505  // NOTE: Sometimes it's necessary to create more render processes than
1506  //       GetMaxRendererProcessCount(), for instance when we want to create
1507  //       a renderer process for a browser context that has no existing
1508  //       renderers. This is OK in moderation, since the
1509  //       GetMaxRendererProcessCount() is conservative.
1510  if (g_all_hosts.Get().size() >= GetMaxRendererProcessCount())
1511    return true;
1512
1513  return GetContentClient()->browser()->
1514      ShouldTryToUseExistingProcessHost(browser_context, url);
1515}
1516
1517// static
1518RenderProcessHost* RenderProcessHost::GetExistingProcessHost(
1519    BrowserContext* browser_context,
1520    const GURL& site_url) {
1521  // First figure out which existing renderers we can use.
1522  std::vector<RenderProcessHost*> suitable_renderers;
1523  suitable_renderers.reserve(g_all_hosts.Get().size());
1524
1525  iterator iter(AllHostsIterator());
1526  while (!iter.IsAtEnd()) {
1527    if (RenderProcessHostImpl::IsSuitableHost(
1528            iter.GetCurrentValue(),
1529            browser_context, site_url))
1530      suitable_renderers.push_back(iter.GetCurrentValue());
1531
1532    iter.Advance();
1533  }
1534
1535  // Now pick a random suitable renderer, if we have any.
1536  if (!suitable_renderers.empty()) {
1537    int suitable_count = static_cast<int>(suitable_renderers.size());
1538    int random_index = base::RandInt(0, suitable_count - 1);
1539    return suitable_renderers[random_index];
1540  }
1541
1542  return NULL;
1543}
1544
1545// static
1546bool RenderProcessHost::ShouldUseProcessPerSite(
1547    BrowserContext* browser_context,
1548    const GURL& url) {
1549  // Returns true if we should use the process-per-site model.  This will be
1550  // the case if the --process-per-site switch is specified, or in
1551  // process-per-site-instance for particular sites (e.g., WebUI).
1552  // Note that --single-process is handled in ShouldTryToUseExistingProcessHost.
1553  const CommandLine& command_line = *CommandLine::ForCurrentProcess();
1554  if (command_line.HasSwitch(switches::kProcessPerSite))
1555    return true;
1556
1557  // We want to consolidate particular sites like WebUI even when we are using
1558  // the process-per-tab or process-per-site-instance models.
1559  // Note: DevTools pages have WebUI type but should not reuse the same host.
1560  if (WebUIControllerFactoryRegistry::GetInstance()->UseWebUIForURL(
1561          browser_context, url) &&
1562      !url.SchemeIs(chrome::kChromeDevToolsScheme)) {
1563    return true;
1564  }
1565
1566  // Otherwise let the content client decide, defaulting to false.
1567  return GetContentClient()->browser()->ShouldUseProcessPerSite(browser_context,
1568                                                                url);
1569}
1570
1571// static
1572RenderProcessHost* RenderProcessHostImpl::GetProcessHostForSite(
1573    BrowserContext* browser_context,
1574    const GURL& url) {
1575  // Look up the map of site to process for the given browser_context.
1576  SiteProcessMap* map =
1577      GetSiteProcessMapForBrowserContext(browser_context);
1578
1579  // See if we have an existing process with appropriate bindings for this site.
1580  // If not, the caller should create a new process and register it.
1581  std::string site = SiteInstance::GetSiteForURL(browser_context, url)
1582      .possibly_invalid_spec();
1583  RenderProcessHost* host = map->FindProcess(site);
1584  if (host && !IsSuitableHost(host, browser_context, url)) {
1585    // The registered process does not have an appropriate set of bindings for
1586    // the url.  Remove it from the map so we can register a better one.
1587    RecordAction(UserMetricsAction("BindingsMismatch_GetProcessHostPerSite"));
1588    map->RemoveProcess(host);
1589    host = NULL;
1590  }
1591
1592  return host;
1593}
1594
1595void RenderProcessHostImpl::RegisterProcessHostForSite(
1596    BrowserContext* browser_context,
1597    RenderProcessHost* process,
1598    const GURL& url) {
1599  // Look up the map of site to process for the given browser_context.
1600  SiteProcessMap* map =
1601      GetSiteProcessMapForBrowserContext(browser_context);
1602
1603  // Only register valid, non-empty sites.  Empty or invalid sites will not
1604  // use process-per-site mode.  We cannot check whether the process has
1605  // appropriate bindings here, because the bindings have not yet been granted.
1606  std::string site = SiteInstance::GetSiteForURL(browser_context, url)
1607      .possibly_invalid_spec();
1608  if (!site.empty())
1609    map->RegisterProcess(site, process);
1610}
1611
1612base::MessageLoop*
1613    RenderProcessHostImpl::GetInProcessRendererThreadForTesting() {
1614  return g_in_process_thread;
1615}
1616
1617void RenderProcessHostImpl::ProcessDied(bool already_dead) {
1618  // Our child process has died.  If we didn't expect it, it's a crash.
1619  // In any case, we need to let everyone know it's gone.
1620  // The OnChannelError notification can fire multiple times due to nested sync
1621  // calls to a renderer. If we don't have a valid channel here it means we
1622  // already handled the error.
1623
1624  // child_process_launcher_ can be NULL in single process mode or if fast
1625  // termination happened.
1626  int exit_code = 0;
1627  base::TerminationStatus status =
1628      child_process_launcher_.get() ?
1629      child_process_launcher_->GetChildTerminationStatus(already_dead,
1630                                                         &exit_code) :
1631      base::TERMINATION_STATUS_NORMAL_TERMINATION;
1632
1633  RendererClosedDetails details(GetHandle(), status, exit_code);
1634  NotificationService::current()->Notify(
1635      NOTIFICATION_RENDERER_PROCESS_CLOSED,
1636      Source<RenderProcessHost>(this),
1637      Details<RendererClosedDetails>(&details));
1638
1639  child_process_launcher_.reset();
1640  channel_.reset();
1641  gpu_message_filter_ = NULL;
1642
1643  IDMap<IPC::Listener>::iterator iter(&listeners_);
1644  while (!iter.IsAtEnd()) {
1645    iter.GetCurrentValue()->OnMessageReceived(
1646        ViewHostMsg_RenderProcessGone(iter.GetCurrentKey(),
1647                                      static_cast<int>(status),
1648                                      exit_code));
1649    iter.Advance();
1650  }
1651
1652  ClearTransportDIBCache();
1653
1654  // this object is not deleted at this point and may be reused later.
1655  // TODO(darin): clean this up
1656}
1657
1658int RenderProcessHostImpl::GetActiveViewCount() {
1659  int num_active_views = 0;
1660  RenderWidgetHost::List widgets = RenderWidgetHost::GetRenderWidgetHosts();
1661  for (size_t i = 0; i < widgets.size(); ++i) {
1662    // Count only RenderWidgetHosts in this process.
1663    if (widgets[i]->GetProcess()->GetID() == GetID())
1664      num_active_views++;
1665  }
1666  return num_active_views;
1667}
1668
1669// Frame subscription API for this class is for accelerated composited path
1670// only. These calls are redirected to GpuMessageFilter.
1671void RenderProcessHostImpl::BeginFrameSubscription(
1672    int route_id,
1673    scoped_ptr<RenderWidgetHostViewFrameSubscriber> subscriber) {
1674  if (!gpu_message_filter_)
1675    return;
1676  BrowserThread::PostTask(BrowserThread::IO, FROM_HERE, base::Bind(
1677      &GpuMessageFilter::BeginFrameSubscription,
1678      gpu_message_filter_,
1679      route_id, base::Passed(&subscriber)));
1680}
1681
1682void RenderProcessHostImpl::EndFrameSubscription(int route_id) {
1683  if (!gpu_message_filter_)
1684    return;
1685  BrowserThread::PostTask(BrowserThread::IO, FROM_HERE, base::Bind(
1686      &GpuMessageFilter::EndFrameSubscription,
1687      gpu_message_filter_,
1688      route_id));
1689}
1690
1691void RenderProcessHostImpl::OnShutdownRequest() {
1692  // Don't shut down if there are active RenderViews, or if there are pending
1693  // RenderViews being swapped back in.
1694  // In single process mode, we never shutdown the renderer.
1695  int num_active_views = GetActiveViewCount();
1696  if (pending_views_ || num_active_views > 0 || run_renderer_in_process())
1697    return;
1698
1699  // Notify any contents that might have swapped out renderers from this
1700  // process. They should not attempt to swap them back in.
1701  NotificationService::current()->Notify(
1702      NOTIFICATION_RENDERER_PROCESS_CLOSING,
1703      Source<RenderProcessHost>(this),
1704      NotificationService::NoDetails());
1705
1706  Send(new ChildProcessMsg_Shutdown());
1707}
1708
1709void RenderProcessHostImpl::SuddenTerminationChanged(bool enabled) {
1710  SetSuddenTerminationAllowed(enabled);
1711}
1712
1713void RenderProcessHostImpl::OnDumpHandlesDone() {
1714  Cleanup();
1715}
1716
1717void RenderProcessHostImpl::SetBackgrounded(bool backgrounded) {
1718  // Note: we always set the backgrounded_ value.  If the process is NULL
1719  // (and hence hasn't been created yet), we will set the process priority
1720  // later when we create the process.
1721  backgrounded_ = backgrounded;
1722  if (!child_process_launcher_.get() || child_process_launcher_->IsStarting())
1723    return;
1724
1725#if defined(OS_WIN)
1726  // The cbstext.dll loads as a global GetMessage hook in the browser process
1727  // and intercepts/unintercepts the kernel32 API SetPriorityClass in a
1728  // background thread. If the UI thread invokes this API just when it is
1729  // intercepted the stack is messed up on return from the interceptor
1730  // which causes random crashes in the browser process. Our hack for now
1731  // is to not invoke the SetPriorityClass API if the dll is loaded.
1732  if (GetModuleHandle(L"cbstext.dll"))
1733    return;
1734#endif  // OS_WIN
1735
1736  child_process_launcher_->SetProcessBackgrounded(backgrounded);
1737}
1738
1739void RenderProcessHostImpl::OnProcessLaunched() {
1740  // No point doing anything, since this object will be destructed soon.  We
1741  // especially don't want to send the RENDERER_PROCESS_CREATED notification,
1742  // since some clients might expect a RENDERER_PROCESS_TERMINATED afterwards to
1743  // properly cleanup.
1744  if (deleting_soon_)
1745    return;
1746
1747  if (child_process_launcher_) {
1748    if (!child_process_launcher_->GetHandle()) {
1749      OnChannelError();
1750      return;
1751    }
1752
1753    child_process_launcher_->SetProcessBackgrounded(backgrounded_);
1754  }
1755
1756  // NOTE: This needs to be before sending queued messages because
1757  // ExtensionService uses this notification to initialize the renderer process
1758  // with state that must be there before any JavaScript executes.
1759  //
1760  // The queued messages contain such things as "navigate". If this notification
1761  // was after, we can end up executing JavaScript before the initialization
1762  // happens.
1763  NotificationService::current()->Notify(
1764      NOTIFICATION_RENDERER_PROCESS_CREATED,
1765      Source<RenderProcessHost>(this),
1766      NotificationService::NoDetails());
1767
1768  while (!queued_messages_.empty()) {
1769    Send(queued_messages_.front());
1770    queued_messages_.pop();
1771  }
1772}
1773
1774void RenderProcessHostImpl::OnUserMetricsRecordAction(
1775    const std::string& action) {
1776  RecordComputedAction(action);
1777}
1778
1779void RenderProcessHostImpl::OnSavedPageAsMHTML(int job_id, int64 data_size) {
1780  MHTMLGenerationManager::GetInstance()->MHTMLGenerated(job_id, data_size);
1781}
1782
1783void RenderProcessHostImpl::OnCompositorSurfaceBuffersSwappedNoHost(
1784      const ViewHostMsg_CompositorSurfaceBuffersSwapped_Params& params) {
1785  TRACE_EVENT0("renderer_host",
1786               "RenderWidgetHostImpl::OnCompositorSurfaceBuffersSwappedNoHost");
1787  AcceleratedSurfaceMsg_BufferPresented_Params ack_params;
1788  ack_params.sync_point = 0;
1789  RenderWidgetHostImpl::AcknowledgeBufferPresent(params.route_id,
1790                                                 params.gpu_process_host_id,
1791                                                 ack_params);
1792}
1793
1794void RenderProcessHostImpl::OnGpuSwitching() {
1795  // We are updating all widgets including swapped out ones.
1796  RenderWidgetHost::List widgets =
1797      RenderWidgetHostImpl::GetAllRenderWidgetHosts();
1798  for (size_t i = 0; i < widgets.size(); ++i) {
1799    if (!widgets[i]->IsRenderView())
1800      continue;
1801
1802    // Skip widgets in other processes.
1803    if (widgets[i]->GetProcess()->GetID() != GetID())
1804      continue;
1805
1806    RenderViewHost* rvh = RenderViewHost::From(widgets[i]);
1807    rvh->UpdateWebkitPreferences(rvh->GetWebkitPreferences());
1808  }
1809}
1810
1811}  // namespace content
1812