Upstream version 7.36.152.0
[platform/framework/web/crosswalk.git] / src / content / browser / renderer_host / render_process_host_impl.cc
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/files/file.h"
25 #include "base/lazy_instance.h"
26 #include "base/logging.h"
27 #include "base/metrics/field_trial.h"
28 #include "base/metrics/histogram.h"
29 #include "base/path_service.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_message_filter.h"
44 #include "content/browser/child_process_security_policy_impl.h"
45 #include "content/browser/device_sensors/device_motion_message_filter.h"
46 #include "content/browser/device_sensors/device_orientation_message_filter.h"
47 #include "content/browser/dom_storage/dom_storage_context_wrapper.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/frame_host/render_frame_message_filter.h"
53 #include "content/browser/gpu/compositor_util.h"
54 #include "content/browser/gpu/gpu_data_manager_impl.h"
55 #include "content/browser/gpu/gpu_process_host.h"
56 #include "content/browser/gpu/shader_disk_cache.h"
57 #include "content/browser/histogram_message_filter.h"
58 #include "content/browser/indexed_db/indexed_db_context_impl.h"
59 #include "content/browser/indexed_db/indexed_db_dispatcher_host.h"
60 #include "content/browser/loader/resource_message_filter.h"
61 #include "content/browser/loader/resource_scheduler_filter.h"
62 #include "content/browser/media/capture/audio_mirroring_manager.h"
63 #include "content/browser/media/media_internals.h"
64 #include "content/browser/message_port_message_filter.h"
65 #include "content/browser/mime_registry_message_filter.h"
66 #include "content/browser/mojo/mojo_application_host.h"
67 #include "content/browser/plugin_service_impl.h"
68 #include "content/browser/profiler_message_filter.h"
69 #include "content/browser/push_messaging_message_filter.h"
70 #include "content/browser/quota_dispatcher_host.h"
71 #include "content/browser/renderer_host/clipboard_message_filter.h"
72 #include "content/browser/renderer_host/database_message_filter.h"
73 #include "content/browser/renderer_host/file_utilities_message_filter.h"
74 #include "content/browser/renderer_host/gamepad_browser_message_filter.h"
75 #include "content/browser/renderer_host/gpu_message_filter.h"
76 #include "content/browser/renderer_host/media/audio_input_renderer_host.h"
77 #include "content/browser/renderer_host/media/audio_renderer_host.h"
78 #include "content/browser/renderer_host/media/device_request_message_filter.h"
79 #include "content/browser/renderer_host/media/media_stream_dispatcher_host.h"
80 #include "content/browser/renderer_host/media/midi_dispatcher_host.h"
81 #include "content/browser/renderer_host/media/midi_host.h"
82 #include "content/browser/renderer_host/media/peer_connection_tracker_host.h"
83 #include "content/browser/renderer_host/media/video_capture_host.h"
84 #include "content/browser/renderer_host/memory_benchmark_message_filter.h"
85 #include "content/browser/renderer_host/p2p/socket_dispatcher_host.h"
86 #include "content/browser/renderer_host/pepper/pepper_message_filter.h"
87 #include "content/browser/renderer_host/pepper/pepper_renderer_connection.h"
88 #include "content/browser/renderer_host/render_message_filter.h"
89 #include "content/browser/renderer_host/render_view_host_delegate.h"
90 #include "content/browser/renderer_host/render_view_host_impl.h"
91 #include "content/browser/renderer_host/render_widget_helper.h"
92 #include "content/browser/renderer_host/render_widget_host_impl.h"
93 #include "content/browser/renderer_host/socket_stream_dispatcher_host.h"
94 #include "content/browser/renderer_host/text_input_client_message_filter.h"
95 #include "content/browser/renderer_host/websocket_dispatcher_host.h"
96 #include "content/browser/resolve_proxy_msg_helper.h"
97 #include "content/browser/screen_orientation/screen_orientation_dispatcher_host.h"
98 #include "content/browser/service_worker/service_worker_context_wrapper.h"
99 #include "content/browser/service_worker/service_worker_dispatcher_host.h"
100 #include "content/browser/shared_worker/shared_worker_message_filter.h"
101 #include "content/browser/speech/speech_recognition_dispatcher_host.h"
102 #include "content/browser/storage_partition_impl.h"
103 #include "content/browser/streams/stream_context.h"
104 #include "content/browser/tracing/trace_message_filter.h"
105 #include "content/browser/vibration/vibration_message_filter.h"
106 #include "content/browser/webui/web_ui_controller_factory_registry.h"
107 #include "content/browser/worker_host/worker_message_filter.h"
108 #include "content/browser/worker_host/worker_storage_partition.h"
109 #include "content/common/child_process_host_impl.h"
110 #include "content/common/child_process_messages.h"
111 #include "content/common/content_switches_internal.h"
112 #include "content/common/gpu/gpu_messages.h"
113 #include "content/common/mojo/mojo_messages.h"
114 #include "content/common/resource_messages.h"
115 #include "content/common/view_messages.h"
116 #include "content/public/browser/browser_context.h"
117 #include "content/public/browser/content_browser_client.h"
118 #include "content/public/browser/notification_service.h"
119 #include "content/public/browser/notification_types.h"
120 #include "content/public/browser/render_process_host_factory.h"
121 #include "content/public/browser/render_process_host_observer.h"
122 #include "content/public/browser/render_widget_host.h"
123 #include "content/public/browser/render_widget_host_iterator.h"
124 #include "content/public/browser/render_widget_host_view_frame_subscriber.h"
125 #include "content/public/browser/resource_context.h"
126 #include "content/public/browser/user_metrics.h"
127 #include "content/public/browser/worker_service.h"
128 #include "content/public/common/content_constants.h"
129 #include "content/public/common/content_switches.h"
130 #include "content/public/common/process_type.h"
131 #include "content/public/common/result_codes.h"
132 #include "content/public/common/sandboxed_process_launcher_delegate.h"
133 #include "content/public/common/url_constants.h"
134 #include "gpu/command_buffer/service/gpu_switches.h"
135 #include "ipc/ipc_channel.h"
136 #include "ipc/ipc_logging.h"
137 #include "ipc/ipc_switches.h"
138 #include "media/base/media_switches.h"
139 #include "mojo/common/common_type_converters.h"
140 #include "mojo/public/cpp/bindings/allocation_scope.h"
141 #include "net/url_request/url_request_context_getter.h"
142 #include "ppapi/shared_impl/ppapi_switches.h"
143 #include "third_party/skia/include/core/SkBitmap.h"
144 #include "ui/base/ui_base_switches.h"
145 #include "ui/events/event_switches.h"
146 #include "ui/gfx/switches.h"
147 #include "ui/gl/gl_switches.h"
148 #include "ui/native_theme/native_theme_switches.h"
149 #include "webkit/browser/fileapi/sandbox_file_system_backend.h"
150 #include "webkit/common/resource_type.h"
151
152 #if defined(OS_ANDROID)
153 #include "content/browser/media/android/browser_demuxer_android.h"
154 #endif
155
156 #if defined(OS_WIN)
157 #include "base/win/scoped_com_initializer.h"
158 #include "content/common/font_cache_dispatcher_win.h"
159 #include "content/common/sandbox_win.h"
160 #endif
161
162 #if defined(ENABLE_WEBRTC)
163 #include "content/browser/media/webrtc_internals.h"
164 #include "content/browser/renderer_host/media/media_stream_track_metrics_host.h"
165 #include "content/browser/renderer_host/media/webrtc_identity_service_host.h"
166 #include "content/common/media/media_stream_messages.h"
167 #endif
168
169 extern bool g_exited_main_message_loop;
170
171 static const char* kSiteProcessMapKeyName = "content_site_process_map";
172
173 namespace content {
174 namespace {
175
176 void CacheShaderInfo(int32 id, base::FilePath path) {
177   ShaderCacheFactory::GetInstance()->SetCacheInfo(id, path);
178 }
179
180 void RemoveShaderInfo(int32 id) {
181   ShaderCacheFactory::GetInstance()->RemoveCacheInfo(id);
182 }
183
184 net::URLRequestContext* GetRequestContext(
185     scoped_refptr<net::URLRequestContextGetter> request_context,
186     scoped_refptr<net::URLRequestContextGetter> media_request_context,
187     ResourceType::Type resource_type) {
188   // If the request has resource type of ResourceType::MEDIA, we use a request
189   // context specific to media for handling it because these resources have
190   // specific needs for caching.
191   if (resource_type == ResourceType::MEDIA)
192     return media_request_context->GetURLRequestContext();
193   return request_context->GetURLRequestContext();
194 }
195
196 void GetContexts(
197     ResourceContext* resource_context,
198     scoped_refptr<net::URLRequestContextGetter> request_context,
199     scoped_refptr<net::URLRequestContextGetter> media_request_context,
200     const ResourceHostMsg_Request& request,
201     ResourceContext** resource_context_out,
202     net::URLRequestContext** request_context_out) {
203   *resource_context_out = resource_context;
204   *request_context_out =
205       GetRequestContext(request_context, media_request_context,
206                         request.resource_type);
207 }
208
209 #if defined(ENABLE_WEBRTC)
210 // Creates a file used for diagnostic echo canceller recordings for handing
211 // over to the renderer.
212 IPC::PlatformFileForTransit CreateAecDumpFileForProcess(
213     base::FilePath file_path,
214     base::ProcessHandle process) {
215   DCHECK_CURRENTLY_ON(BrowserThread::FILE);
216   base::File dump_file(file_path,
217                        base::File::FLAG_OPEN_ALWAYS | base::File::FLAG_APPEND);
218   if (!dump_file.IsValid()) {
219     VLOG(1) << "Could not open AEC dump file, error=" <<
220                dump_file.error_details();
221     return IPC::InvalidPlatformFileForTransit();
222   }
223   return IPC::TakeFileHandleForProcess(dump_file.Pass(), process);
224 }
225
226 // Does nothing. Just to avoid races between enable and disable.
227 void DisableAecDumpOnFileThread() {
228   DCHECK_CURRENTLY_ON(BrowserThread::FILE);
229 }
230 #endif
231
232 // the global list of all renderer processes
233 base::LazyInstance<IDMap<RenderProcessHost> >::Leaky
234     g_all_hosts = LAZY_INSTANCE_INITIALIZER;
235
236 // Map of site to process, to ensure we only have one RenderProcessHost per
237 // site in process-per-site mode.  Each map is specific to a BrowserContext.
238 class SiteProcessMap : public base::SupportsUserData::Data {
239  public:
240   typedef base::hash_map<std::string, RenderProcessHost*> SiteToProcessMap;
241   SiteProcessMap() {}
242
243   void RegisterProcess(const std::string& site, RenderProcessHost* process) {
244     map_[site] = process;
245   }
246
247   RenderProcessHost* FindProcess(const std::string& site) {
248     SiteToProcessMap::iterator i = map_.find(site);
249     if (i != map_.end())
250       return i->second;
251     return NULL;
252   }
253
254   void RemoveProcess(RenderProcessHost* host) {
255     // Find all instances of this process in the map, then separately remove
256     // them.
257     std::set<std::string> sites;
258     for (SiteToProcessMap::const_iterator i = map_.begin();
259          i != map_.end();
260          i++) {
261       if (i->second == host)
262         sites.insert(i->first);
263     }
264     for (std::set<std::string>::iterator i = sites.begin();
265          i != sites.end();
266          i++) {
267       SiteToProcessMap::iterator iter = map_.find(*i);
268       if (iter != map_.end()) {
269         DCHECK_EQ(iter->second, host);
270         map_.erase(iter);
271       }
272     }
273   }
274
275  private:
276   SiteToProcessMap map_;
277 };
278
279 // Find the SiteProcessMap specific to the given context.
280 SiteProcessMap* GetSiteProcessMapForBrowserContext(BrowserContext* context) {
281   DCHECK(context);
282   SiteProcessMap* map = static_cast<SiteProcessMap*>(
283       context->GetUserData(kSiteProcessMapKeyName));
284   if (!map) {
285     map = new SiteProcessMap();
286     context->SetUserData(kSiteProcessMapKeyName, map);
287   }
288   return map;
289 }
290
291 // NOTE: changes to this class need to be reviewed by the security team.
292 class RendererSandboxedProcessLauncherDelegate
293     : public content::SandboxedProcessLauncherDelegate {
294  public:
295   RendererSandboxedProcessLauncherDelegate(IPC::ChannelProxy* channel)
296 #if defined(OS_POSIX)
297        : ipc_fd_(channel->TakeClientFileDescriptor())
298 #endif  // OS_POSIX
299   {}
300
301   virtual ~RendererSandboxedProcessLauncherDelegate() {}
302
303 #if defined(OS_WIN)
304   virtual void PreSpawnTarget(sandbox::TargetPolicy* policy,
305                               bool* success) {
306     AddBaseHandleClosePolicy(policy);
307     GetContentClient()->browser()->PreSpawnRenderer(policy, success);
308   }
309
310 #elif defined(OS_POSIX)
311   virtual bool ShouldUseZygote() OVERRIDE {
312     const CommandLine& browser_command_line = *CommandLine::ForCurrentProcess();
313     CommandLine::StringType renderer_prefix =
314         browser_command_line.GetSwitchValueNative(switches::kRendererCmdPrefix);
315     return renderer_prefix.empty();
316   }
317   virtual int GetIpcFd() OVERRIDE {
318     return ipc_fd_;
319   }
320 #endif  // OS_WIN
321
322  private:
323 #if defined(OS_POSIX)
324   int ipc_fd_;
325 #endif  // OS_POSIX
326 };
327
328 }  // namespace
329
330 RendererMainThreadFactoryFunction g_renderer_main_thread_factory = NULL;
331
332 base::MessageLoop* g_in_process_thread;
333
334 base::MessageLoop*
335     RenderProcessHostImpl::GetInProcessRendererThreadForTesting() {
336   return g_in_process_thread;
337 }
338
339 // Stores the maximum number of renderer processes the content module can
340 // create.
341 static size_t g_max_renderer_count_override = 0;
342
343 // static
344 size_t RenderProcessHost::GetMaxRendererProcessCount() {
345   if (g_max_renderer_count_override)
346     return g_max_renderer_count_override;
347
348   // Defines the maximum number of renderer processes according to the
349   // amount of installed memory as reported by the OS. The calculation
350   // assumes that you want the renderers to use half of the installed
351   // RAM and assuming that each WebContents uses ~40MB.
352   // If you modify this assumption, you need to adjust the
353   // ThirtyFourTabs test to match the expected number of processes.
354   //
355   // With the given amounts of installed memory below on a 32-bit CPU,
356   // the maximum renderer count will roughly be as follows:
357   //
358   //   128 MB -> 3
359   //   512 MB -> 6
360   //  1024 MB -> 12
361   //  4096 MB -> 51
362   // 16384 MB -> 82 (kMaxRendererProcessCount)
363
364   static size_t max_count = 0;
365   if (!max_count) {
366     const size_t kEstimatedWebContentsMemoryUsage =
367 #if defined(ARCH_CPU_64_BITS)
368         60;  // In MB
369 #else
370         40;  // In MB
371 #endif
372     max_count = base::SysInfo::AmountOfPhysicalMemoryMB() / 2;
373     max_count /= kEstimatedWebContentsMemoryUsage;
374
375     const size_t kMinRendererProcessCount = 3;
376     max_count = std::max(max_count, kMinRendererProcessCount);
377     max_count = std::min(max_count, kMaxRendererProcessCount);
378   }
379   return max_count;
380 }
381
382 // static
383 bool g_run_renderer_in_process_ = false;
384
385 // static
386 void RenderProcessHost::SetMaxRendererProcessCount(size_t count) {
387   g_max_renderer_count_override = count;
388 }
389
390 RenderProcessHostImpl::RenderProcessHostImpl(
391     BrowserContext* browser_context,
392     StoragePartitionImpl* storage_partition_impl,
393     bool is_guest)
394     : fast_shutdown_started_(false),
395       deleting_soon_(false),
396 #ifndef NDEBUG
397       is_self_deleted_(false),
398 #endif
399       pending_views_(0),
400       mojo_activation_required_(false),
401       visible_widgets_(0),
402       backgrounded_(true),
403       is_initialized_(false),
404       id_(ChildProcessHostImpl::GenerateChildProcessUniqueId()),
405       browser_context_(browser_context),
406       storage_partition_impl_(storage_partition_impl),
407       sudden_termination_allowed_(true),
408       ignore_input_events_(false),
409       is_guest_(is_guest),
410       gpu_observer_registered_(false),
411       delayed_cleanup_needed_(false),
412       within_process_died_observer_(false),
413       power_monitor_broadcaster_(this),
414       geolocation_dispatcher_host_(NULL),
415       screen_orientation_dispatcher_host_(NULL),
416       worker_ref_count_(0),
417       weak_factory_(this) {
418   widget_helper_ = new RenderWidgetHelper();
419
420   ChildProcessSecurityPolicyImpl::GetInstance()->Add(GetID());
421
422   CHECK(!g_exited_main_message_loop);
423   RegisterHost(GetID(), this);
424   g_all_hosts.Get().set_check_on_null_data(true);
425   // Initialize |child_process_activity_time_| to a reasonable value.
426   mark_child_process_activity_time();
427
428   if (!GetBrowserContext()->IsOffTheRecord() &&
429       !CommandLine::ForCurrentProcess()->HasSwitch(
430           switches::kDisableGpuShaderDiskCache)) {
431     BrowserThread::PostTask(BrowserThread::IO, FROM_HERE,
432                             base::Bind(&CacheShaderInfo, GetID(),
433                                        storage_partition_impl_->GetPath()));
434   }
435
436   // Note: When we create the RenderProcessHostImpl, it's technically
437   //       backgrounded, because it has no visible listeners.  But the process
438   //       doesn't actually exist yet, so we'll Background it later, after
439   //       creation.
440 }
441
442 // static
443 void RenderProcessHostImpl::ShutDownInProcessRenderer() {
444   DCHECK(g_run_renderer_in_process_);
445
446   switch (g_all_hosts.Pointer()->size()) {
447     case 0:
448       return;
449     case 1: {
450       RenderProcessHostImpl* host = static_cast<RenderProcessHostImpl*>(
451           AllHostsIterator().GetCurrentValue());
452       FOR_EACH_OBSERVER(RenderProcessHostObserver,
453                         host->observers_,
454                         RenderProcessHostDestroyed(host));
455 #ifndef NDEBUG
456       host->is_self_deleted_ = true;
457 #endif
458       delete host;
459       return;
460     }
461     default:
462       NOTREACHED() << "There should be only one RenderProcessHost when running "
463                    << "in-process.";
464   }
465 }
466
467 void RenderProcessHostImpl::RegisterRendererMainThreadFactory(
468     RendererMainThreadFactoryFunction create) {
469   g_renderer_main_thread_factory = create;
470 }
471
472 RenderProcessHostImpl::~RenderProcessHostImpl() {
473 #ifndef NDEBUG
474   DCHECK(is_self_deleted_)
475       << "RenderProcessHostImpl is destroyed by something other than itself";
476 #endif
477
478   // Make sure to clean up the in-process renderer before the channel, otherwise
479   // it may still run and have its IPCs fail, causing asserts.
480   in_process_renderer_.reset();
481
482   ChildProcessSecurityPolicyImpl::GetInstance()->Remove(GetID());
483
484   if (gpu_observer_registered_) {
485     GpuDataManagerImpl::GetInstance()->RemoveObserver(this);
486     gpu_observer_registered_ = false;
487   }
488
489   // We may have some unsent messages at this point, but that's OK.
490   channel_.reset();
491   while (!queued_messages_.empty()) {
492     delete queued_messages_.front();
493     queued_messages_.pop();
494   }
495
496   UnregisterHost(GetID());
497
498   if (!CommandLine::ForCurrentProcess()->HasSwitch(
499       switches::kDisableGpuShaderDiskCache)) {
500     BrowserThread::PostTask(BrowserThread::IO, FROM_HERE,
501                             base::Bind(&RemoveShaderInfo, GetID()));
502   }
503 }
504
505 void RenderProcessHostImpl::EnableSendQueue() {
506   is_initialized_ = false;
507 }
508
509 bool RenderProcessHostImpl::Init() {
510   // calling Init() more than once does nothing, this makes it more convenient
511   // for the view host which may not be sure in some cases
512   if (channel_)
513     return true;
514
515   CommandLine::StringType renderer_prefix;
516 #if defined(OS_POSIX)
517   // A command prefix is something prepended to the command line of the spawned
518   // process. It is supported only on POSIX systems.
519   const CommandLine& browser_command_line = *CommandLine::ForCurrentProcess();
520   renderer_prefix =
521       browser_command_line.GetSwitchValueNative(switches::kRendererCmdPrefix);
522 #endif  // defined(OS_POSIX)
523
524 #if defined(OS_LINUX)
525   int flags = renderer_prefix.empty() ? ChildProcessHost::CHILD_ALLOW_SELF :
526                                         ChildProcessHost::CHILD_NORMAL;
527 #else
528   int flags = ChildProcessHost::CHILD_NORMAL;
529 #endif
530
531   // Find the renderer before creating the channel so if this fails early we
532   // return without creating the channel.
533   base::FilePath renderer_path = ChildProcessHost::GetChildPath(flags);
534   if (renderer_path.empty())
535     return false;
536
537   // Setup the IPC channel.
538   const std::string channel_id =
539       IPC::Channel::GenerateVerifiedChannelID(std::string());
540   channel_.reset(
541           new IPC::ChannelProxy(channel_id,
542                                 IPC::Channel::MODE_SERVER,
543                                 this,
544                                 BrowserThread::GetMessageLoopProxyForThread(
545                                     BrowserThread::IO).get()));
546
547   // Setup the Mojo channel.
548   mojo_application_host_.reset(new MojoApplicationHost());
549   mojo_application_host_->Init();
550
551   // Call the embedder first so that their IPC filters have priority.
552   GetContentClient()->browser()->RenderProcessWillLaunch(this);
553
554   CreateMessageFilters();
555
556   if (run_renderer_in_process()) {
557     DCHECK(g_renderer_main_thread_factory);
558     // Crank up a thread and run the initialization there.  With the way that
559     // messages flow between the browser and renderer, this thread is required
560     // to prevent a deadlock in single-process mode.  Since the primordial
561     // thread in the renderer process runs the WebKit code and can sometimes
562     // make blocking calls to the UI thread (i.e. this thread), they need to run
563     // on separate threads.
564     in_process_renderer_.reset(g_renderer_main_thread_factory(channel_id));
565
566     base::Thread::Options options;
567 #if defined(OS_WIN) && !defined(OS_MACOSX)
568     // In-process plugins require this to be a UI message loop.
569     options.message_loop_type = base::MessageLoop::TYPE_UI;
570 #else
571     // We can't have multiple UI loops on Linux and Android, so we don't support
572     // in-process plugins.
573     options.message_loop_type = base::MessageLoop::TYPE_DEFAULT;
574 #endif
575     in_process_renderer_->StartWithOptions(options);
576
577     g_in_process_thread = in_process_renderer_->message_loop();
578
579     OnProcessLaunched();  // Fake a callback that the process is ready.
580   } else {
581     // Build command line for renderer.  We call AppendRendererCommandLine()
582     // first so the process type argument will appear first.
583     CommandLine* cmd_line = new CommandLine(renderer_path);
584     if (!renderer_prefix.empty())
585       cmd_line->PrependWrapper(renderer_prefix);
586     AppendRendererCommandLine(cmd_line);
587     cmd_line->AppendSwitchASCII(switches::kProcessChannelID, channel_id);
588
589     // Spawn the child process asynchronously to avoid blocking the UI thread.
590     // As long as there's no renderer prefix, we can use the zygote process
591     // at this stage.
592     child_process_launcher_.reset(new ChildProcessLauncher(
593         new RendererSandboxedProcessLauncherDelegate(channel_.get()),
594         cmd_line,
595         GetID(),
596         this));
597
598     fast_shutdown_started_ = false;
599   }
600
601   if (!gpu_observer_registered_) {
602     gpu_observer_registered_ = true;
603     GpuDataManagerImpl::GetInstance()->AddObserver(this);
604   }
605
606   is_initialized_ = true;
607   return true;
608 }
609
610 void RenderProcessHostImpl::MaybeActivateMojo() {
611   // TODO(darin): Following security review, we can unconditionally initialize
612   // Mojo in all renderers. We will then be able to directly call Activate()
613   // from OnProcessLaunched.
614   if (!mojo_activation_required_)
615     return;  // Waiting on someone to require Mojo.
616
617   if (!GetHandle())
618     return;  // Waiting on renderer startup.
619
620   if (!mojo_application_host_->did_activate())
621     mojo_application_host_->Activate(this, GetHandle());
622 }
623
624 void RenderProcessHostImpl::CreateMessageFilters() {
625   DCHECK_CURRENTLY_ON(BrowserThread::UI);
626   AddFilter(new ResourceSchedulerFilter(GetID()));
627   MediaInternals* media_internals = MediaInternals::GetInstance();
628   media::AudioManager* audio_manager =
629       BrowserMainLoop::GetInstance()->audio_manager();
630   // Add BrowserPluginMessageFilter to ensure it gets the first stab at messages
631   // from guests.
632   scoped_refptr<BrowserPluginMessageFilter> bp_message_filter(
633       new BrowserPluginMessageFilter(GetID(), IsGuest()));
634   AddFilter(bp_message_filter.get());
635
636   scoped_refptr<RenderMessageFilter> render_message_filter(
637       new RenderMessageFilter(
638           GetID(),
639           IsGuest(),
640 #if defined(ENABLE_PLUGINS)
641           PluginServiceImpl::GetInstance(),
642 #else
643           NULL,
644 #endif
645           GetBrowserContext(),
646           GetBrowserContext()->GetRequestContextForRenderProcess(GetID()),
647           widget_helper_.get(),
648           audio_manager,
649           media_internals,
650           storage_partition_impl_->GetDOMStorageContext()));
651   AddFilter(render_message_filter.get());
652   AddFilter(
653       new RenderFrameMessageFilter(GetID(), widget_helper_.get()));
654   BrowserContext* browser_context = GetBrowserContext();
655   ResourceContext* resource_context = browser_context->GetResourceContext();
656
657   scoped_refptr<net::URLRequestContextGetter> request_context(
658       browser_context->GetRequestContextForRenderProcess(GetID()));
659   scoped_refptr<net::URLRequestContextGetter> media_request_context(
660       browser_context->GetMediaRequestContextForRenderProcess(GetID()));
661
662   ResourceMessageFilter::GetContextsCallback get_contexts_callback(
663       base::Bind(&GetContexts, browser_context->GetResourceContext(),
664                  request_context, media_request_context));
665
666   ResourceMessageFilter* resource_message_filter = new ResourceMessageFilter(
667       GetID(), PROCESS_TYPE_RENDERER,
668       storage_partition_impl_->GetAppCacheService(),
669       ChromeBlobStorageContext::GetFor(browser_context),
670       storage_partition_impl_->GetFileSystemContext(),
671       storage_partition_impl_->GetServiceWorkerContext(),
672       get_contexts_callback);
673
674   AddFilter(resource_message_filter);
675   MediaStreamManager* media_stream_manager =
676       BrowserMainLoop::GetInstance()->media_stream_manager();
677   AddFilter(new AudioInputRendererHost(
678       audio_manager,
679       media_stream_manager,
680       BrowserMainLoop::GetInstance()->audio_mirroring_manager(),
681       BrowserMainLoop::GetInstance()->user_input_monitor()));
682   // The AudioRendererHost needs to be available for lookup, so it's
683   // stashed in a member variable.
684   audio_renderer_host_ = new AudioRendererHost(
685       GetID(),
686       audio_manager,
687       BrowserMainLoop::GetInstance()->audio_mirroring_manager(),
688       media_internals,
689       media_stream_manager);
690   AddFilter(audio_renderer_host_);
691   AddFilter(
692       new MidiHost(GetID(), BrowserMainLoop::GetInstance()->midi_manager()));
693   AddFilter(new MidiDispatcherHost(GetID(), browser_context));
694   AddFilter(new VideoCaptureHost(media_stream_manager));
695   AddFilter(new AppCacheDispatcherHost(
696       storage_partition_impl_->GetAppCacheService(),
697       GetID()));
698   AddFilter(new ClipboardMessageFilter);
699   AddFilter(new DOMStorageMessageFilter(
700       GetID(),
701       storage_partition_impl_->GetDOMStorageContext()));
702   AddFilter(new IndexedDBDispatcherHost(
703       GetID(),
704       storage_partition_impl_->GetURLRequestContext(),
705       storage_partition_impl_->GetIndexedDBContext(),
706       ChromeBlobStorageContext::GetFor(browser_context)));
707
708   geolocation_dispatcher_host_ = new GeolocationDispatcherHost(
709       GetID(), browser_context->GetGeolocationPermissionContext());
710   AddFilter(geolocation_dispatcher_host_);
711   gpu_message_filter_ = new GpuMessageFilter(GetID(), widget_helper_.get());
712   AddFilter(gpu_message_filter_);
713 #if defined(ENABLE_WEBRTC)
714   AddFilter(new WebRTCIdentityServiceHost(
715       GetID(), storage_partition_impl_->GetWebRTCIdentityStore()));
716   peer_connection_tracker_host_ = new PeerConnectionTrackerHost(GetID());
717   AddFilter(peer_connection_tracker_host_.get());
718   AddFilter(new MediaStreamDispatcherHost(
719       GetID(),
720       browser_context->GetResourceContext()->GetMediaDeviceIDSalt(),
721       media_stream_manager));
722   AddFilter(new DeviceRequestMessageFilter(
723       resource_context, media_stream_manager, GetID()));
724   AddFilter(new MediaStreamTrackMetricsHost());
725 #endif
726 #if defined(ENABLE_PLUGINS)
727   AddFilter(new PepperRendererConnection(GetID()));
728 #endif
729   AddFilter(new SpeechRecognitionDispatcherHost(
730       IsGuest(), GetID(), storage_partition_impl_->GetURLRequestContext()));
731   AddFilter(new FileAPIMessageFilter(
732       GetID(),
733       storage_partition_impl_->GetURLRequestContext(),
734       storage_partition_impl_->GetFileSystemContext(),
735       ChromeBlobStorageContext::GetFor(browser_context),
736       StreamContext::GetFor(browser_context)));
737   AddFilter(new FileUtilitiesMessageFilter(GetID()));
738   AddFilter(new MimeRegistryMessageFilter());
739   AddFilter(new DatabaseMessageFilter(
740       storage_partition_impl_->GetDatabaseTracker()));
741 #if defined(OS_MACOSX)
742   AddFilter(new TextInputClientMessageFilter(GetID()));
743 #elif defined(OS_WIN)
744   // The FontCacheDispatcher is required only when we're using GDI rendering.
745   if (!ShouldUseDirectWrite())
746     channel_->AddFilter(new FontCacheDispatcher());
747 #elif defined(OS_ANDROID)
748   browser_demuxer_android_ = new BrowserDemuxerAndroid();
749   AddFilter(browser_demuxer_android_);
750 #endif
751
752   SocketStreamDispatcherHost::GetRequestContextCallback
753       request_context_callback(
754           base::Bind(&GetRequestContext, request_context,
755                      media_request_context));
756
757   SocketStreamDispatcherHost* socket_stream_dispatcher_host =
758       new SocketStreamDispatcherHost(
759           GetID(), request_context_callback, resource_context);
760   AddFilter(socket_stream_dispatcher_host);
761
762   WebSocketDispatcherHost::GetRequestContextCallback
763       websocket_request_context_callback(
764           base::Bind(&GetRequestContext, request_context,
765                      media_request_context, ResourceType::SUB_RESOURCE));
766
767   AddFilter(
768       new WebSocketDispatcherHost(GetID(), websocket_request_context_callback));
769
770   message_port_message_filter_ = new MessagePortMessageFilter(
771       base::Bind(&RenderWidgetHelper::GetNextRoutingID,
772                  base::Unretained(widget_helper_.get())));
773   AddFilter(message_port_message_filter_);
774
775   scoped_refptr<ServiceWorkerDispatcherHost> service_worker_filter =
776       new ServiceWorkerDispatcherHost(GetID(), message_port_message_filter_);
777   service_worker_filter->Init(
778       storage_partition_impl_->GetServiceWorkerContext());
779   AddFilter(service_worker_filter);
780
781   // If "--enable-embedded-shared-worker" is set, we use
782   // SharedWorkerMessageFilter in stead of WorkerMessageFilter.
783   if (WorkerService::EmbeddedSharedWorkerEnabled()) {
784     AddFilter(new SharedWorkerMessageFilter(
785         GetID(),
786         resource_context,
787         WorkerStoragePartition(
788             storage_partition_impl_->GetURLRequestContext(),
789             storage_partition_impl_->GetMediaURLRequestContext(),
790             storage_partition_impl_->GetAppCacheService(),
791             storage_partition_impl_->GetQuotaManager(),
792             storage_partition_impl_->GetFileSystemContext(),
793             storage_partition_impl_->GetDatabaseTracker(),
794             storage_partition_impl_->GetIndexedDBContext(),
795             storage_partition_impl_->GetServiceWorkerContext()),
796         message_port_message_filter_));
797   } else {
798     AddFilter(new WorkerMessageFilter(
799         GetID(),
800         resource_context,
801         WorkerStoragePartition(
802             storage_partition_impl_->GetURLRequestContext(),
803             storage_partition_impl_->GetMediaURLRequestContext(),
804             storage_partition_impl_->GetAppCacheService(),
805             storage_partition_impl_->GetQuotaManager(),
806             storage_partition_impl_->GetFileSystemContext(),
807             storage_partition_impl_->GetDatabaseTracker(),
808             storage_partition_impl_->GetIndexedDBContext(),
809             storage_partition_impl_->GetServiceWorkerContext()),
810         message_port_message_filter_));
811   }
812
813 #if defined(ENABLE_WEBRTC)
814   AddFilter(new P2PSocketDispatcherHost(
815       resource_context,
816       browser_context->GetRequestContextForRenderProcess(GetID())));
817 #endif
818
819   AddFilter(new TraceMessageFilter());
820   AddFilter(new ResolveProxyMsgHelper(
821       browser_context->GetRequestContextForRenderProcess(GetID())));
822   AddFilter(new QuotaDispatcherHost(
823       GetID(),
824       storage_partition_impl_->GetQuotaManager(),
825       GetContentClient()->browser()->CreateQuotaPermissionContext()));
826   AddFilter(new GamepadBrowserMessageFilter());
827   AddFilter(new DeviceMotionMessageFilter());
828   AddFilter(new DeviceOrientationMessageFilter());
829   AddFilter(new ProfilerMessageFilter(PROCESS_TYPE_RENDERER));
830   AddFilter(new HistogramMessageFilter());
831 #if defined(USE_TCMALLOC) && (defined(OS_LINUX) || defined(OS_ANDROID))
832   if (CommandLine::ForCurrentProcess()->HasSwitch(
833       switches::kEnableMemoryBenchmarking))
834     AddFilter(new MemoryBenchmarkMessageFilter());
835 #endif
836   AddFilter(new VibrationMessageFilter());
837   screen_orientation_dispatcher_host_ = new ScreenOrientationDispatcherHost();
838   AddFilter(screen_orientation_dispatcher_host_);
839   AddFilter(new PushMessagingMessageFilter());
840 }
841
842 int RenderProcessHostImpl::GetNextRoutingID() {
843   return widget_helper_->GetNextRoutingID();
844 }
845
846
847 void RenderProcessHostImpl::ResumeDeferredNavigation(
848     const GlobalRequestID& request_id) {
849   widget_helper_->ResumeDeferredNavigation(request_id);
850 }
851
852 void RenderProcessHostImpl::NotifyTimezoneChange() {
853   Send(new ViewMsg_TimezoneChange());
854 }
855
856 ScreenOrientationDispatcherHost* RenderProcessHostImpl
857     ::GetScreenOrientationDispatcherHost() {
858   return screen_orientation_dispatcher_host_;
859 }
860
861 void RenderProcessHostImpl::AddRoute(
862     int32 routing_id,
863     IPC::Listener* listener) {
864   listeners_.AddWithID(listener, routing_id);
865 }
866
867 void RenderProcessHostImpl::RemoveRoute(int32 routing_id) {
868   DCHECK(listeners_.Lookup(routing_id) != NULL);
869   listeners_.Remove(routing_id);
870
871 #if defined(OS_WIN)
872   // Dump the handle table if handle auditing is enabled.
873   const CommandLine& browser_command_line =
874       *CommandLine::ForCurrentProcess();
875   if (browser_command_line.HasSwitch(switches::kAuditHandles) ||
876       browser_command_line.HasSwitch(switches::kAuditAllHandles)) {
877     DumpHandles();
878
879     // We wait to close the channels until the child process has finished
880     // dumping handles and sends us ChildProcessHostMsg_DumpHandlesDone.
881     return;
882   }
883 #endif
884   // Keep the one renderer thread around forever in single process mode.
885   if (!run_renderer_in_process())
886     Cleanup();
887 }
888
889 void RenderProcessHostImpl::AddObserver(RenderProcessHostObserver* observer) {
890   observers_.AddObserver(observer);
891 }
892
893 void RenderProcessHostImpl::RemoveObserver(
894     RenderProcessHostObserver* observer) {
895   observers_.RemoveObserver(observer);
896 }
897
898 bool RenderProcessHostImpl::WaitForBackingStoreMsg(
899     int render_widget_id,
900     const base::TimeDelta& max_delay,
901     IPC::Message* msg) {
902   // The post task to this thread with the process id could be in queue, and we
903   // don't want to dispatch a message before then since it will need the handle.
904   if (child_process_launcher_.get() && child_process_launcher_->IsStarting())
905     return false;
906
907   return widget_helper_->WaitForBackingStoreMsg(render_widget_id,
908                                                 max_delay, msg);
909 }
910
911 void RenderProcessHostImpl::ReceivedBadMessage() {
912   CommandLine* command_line = CommandLine::ForCurrentProcess();
913   if (command_line->HasSwitch(switches::kDisableKillAfterBadIPC))
914     return;
915
916   if (run_renderer_in_process()) {
917     // In single process mode it is better if we don't suicide but just
918     // crash.
919     CHECK(false);
920   }
921   // We kill the renderer but don't include a NOTREACHED, because we want the
922   // browser to try to survive when it gets illegal messages from the renderer.
923   base::KillProcess(GetHandle(), RESULT_CODE_KILLED_BAD_MESSAGE,
924                     false);
925 }
926
927 void RenderProcessHostImpl::WidgetRestored() {
928   // Verify we were properly backgrounded.
929   DCHECK_EQ(backgrounded_, (visible_widgets_ == 0));
930   visible_widgets_++;
931   SetBackgrounded(false);
932 }
933
934 void RenderProcessHostImpl::WidgetHidden() {
935   // On startup, the browser will call Hide
936   if (backgrounded_)
937     return;
938
939   DCHECK_EQ(backgrounded_, (visible_widgets_ == 0));
940   visible_widgets_--;
941   DCHECK_GE(visible_widgets_, 0);
942   if (visible_widgets_ == 0) {
943     DCHECK(!backgrounded_);
944     SetBackgrounded(true);
945   }
946 }
947
948 int RenderProcessHostImpl::VisibleWidgetCount() const {
949   return visible_widgets_;
950 }
951
952 bool RenderProcessHostImpl::IsGuest() const {
953   return is_guest_;
954 }
955
956 StoragePartition* RenderProcessHostImpl::GetStoragePartition() const {
957   return storage_partition_impl_;
958 }
959
960 static void AppendCompositorCommandLineFlags(CommandLine* command_line) {
961   if (IsPinchVirtualViewportEnabled())
962     command_line->AppendSwitch(cc::switches::kEnablePinchVirtualViewport);
963
964   if (IsThreadedCompositingEnabled())
965     command_line->AppendSwitch(switches::kEnableThreadedCompositing);
966
967   if (IsDelegatedRendererEnabled())
968     command_line->AppendSwitch(switches::kEnableDelegatedRenderer);
969
970   if (IsImplSidePaintingEnabled())
971     command_line->AppendSwitch(switches::kEnableImplSidePainting);
972
973   if (content::IsGpuRasterizationEnabled())
974     command_line->AppendSwitch(switches::kEnableGpuRasterization);
975
976   if (content::IsForceGpuRasterizationEnabled())
977     command_line->AppendSwitch(switches::kForceGpuRasterization);
978
979   // Appending disable-gpu-feature switches due to software rendering list.
980   GpuDataManagerImpl* gpu_data_manager = GpuDataManagerImpl::GetInstance();
981   DCHECK(gpu_data_manager);
982   gpu_data_manager->AppendRendererCommandLine(command_line);
983 }
984
985 void RenderProcessHostImpl::AppendRendererCommandLine(
986     CommandLine* command_line) const {
987   // Pass the process type first, so it shows first in process listings.
988   command_line->AppendSwitchASCII(switches::kProcessType,
989                                   switches::kRendererProcess);
990
991   // Now send any options from our own command line we want to propagate.
992   const CommandLine& browser_command_line = *CommandLine::ForCurrentProcess();
993   PropagateBrowserCommandLineToRenderer(browser_command_line, command_line);
994
995   // Pass on the browser locale.
996   const std::string locale =
997       GetContentClient()->browser()->GetApplicationLocale();
998   command_line->AppendSwitchASCII(switches::kLang, locale);
999
1000   // If we run base::FieldTrials, we want to pass to their state to the
1001   // renderer so that it can act in accordance with each state, or record
1002   // histograms relating to the base::FieldTrial states.
1003   std::string field_trial_states;
1004   base::FieldTrialList::StatesToString(&field_trial_states);
1005   if (!field_trial_states.empty()) {
1006     command_line->AppendSwitchASCII(switches::kForceFieldTrials,
1007                                     field_trial_states);
1008   }
1009
1010   GetContentClient()->browser()->AppendExtraCommandLineSwitches(
1011       command_line, GetID());
1012
1013   if (content::IsPinchToZoomEnabled())
1014     command_line->AppendSwitch(switches::kEnablePinch);
1015
1016   AppendCompositorCommandLineFlags(command_line);
1017 }
1018
1019 void RenderProcessHostImpl::PropagateBrowserCommandLineToRenderer(
1020     const CommandLine& browser_cmd,
1021     CommandLine* renderer_cmd) const {
1022   // Propagate the following switches to the renderer command line (along
1023   // with any associated values) if present in the browser command line.
1024   static const char* const kSwitchNames[] = {
1025     switches::kAllowInsecureWebSocketFromHttpsOrigin,
1026     switches::kAllowLoopbackInPeerConnection,
1027     switches::kAudioBufferSize,
1028     switches::kAuditAllHandles,
1029     switches::kAuditHandles,
1030     switches::kBlinkPlatformLogChannels,
1031     switches::kBlockCrossSiteDocuments,
1032     switches::kDefaultTileWidth,
1033     switches::kDefaultTileHeight,
1034     switches::kDisable3DAPIs,
1035     switches::kDisableAcceleratedFixedRootBackground,
1036     switches::kDisableAcceleratedVideoDecode,
1037     switches::kDisableApplicationCache,
1038     switches::kDisableBreakpad,
1039     switches::kDisableCompositingForFixedPosition,
1040     switches::kDisableCompositingForTransition,
1041     switches::kDisableDatabases,
1042     switches::kDisableDesktopNotifications,
1043     switches::kDisableDirectNPAPIRequests,
1044     switches::kDisableDistanceFieldText,
1045     switches::kDisableFastTextAutosizing,
1046     switches::kDisableFileSystem,
1047     switches::kDisableFiltersOverIPC,
1048     switches::kDisableGpuCompositing,
1049     switches::kDisableGpuVsync,
1050     switches::kDisableLowResTiling,
1051     switches::kDisableHistogramCustomizer,
1052     switches::kDisableLCDText,
1053     switches::kDisableLayerSquashing,
1054     switches::kDisableLocalStorage,
1055     switches::kDisableLogging,
1056     switches::kDisableMediaSource,
1057     switches::kDisableOverlayScrollbar,
1058     switches::kDisablePinch,
1059     switches::kDisablePrefixedEncryptedMedia,
1060     switches::kDisableRepaintAfterLayout,
1061     switches::kDisableSeccompFilterSandbox,
1062     switches::kDisableSessionStorage,
1063     switches::kDisableSharedWorkers,
1064     switches::kDisableTouchAdjustment,
1065     switches::kDisableTouchDragDrop,
1066     switches::kDisableTouchEditing,
1067     switches::kDisableUniversalAcceleratedOverflowScroll,
1068     switches::kDisableZeroCopy,
1069     switches::kDomAutomationController,
1070     switches::kEnableAcceleratedFixedRootBackground,
1071     switches::kEnableAcceleratedOverflowScroll,
1072     switches::kEnableAccessibilityLogging,
1073     switches::kEnableADTSStreamParser,
1074     switches::kEnableBeginFrameScheduling,
1075     switches::kEnableBleedingEdgeRenderingFastPaths,
1076     switches::kEnableCompositingForFixedPosition,
1077     switches::kEnableCompositingForTransition,
1078     switches::kEnableDeferredImageDecoding,
1079     switches::kEnableDistanceFieldText,
1080     switches::kEnableEncryptedMedia,
1081     switches::kEnableExperimentalCanvasFeatures,
1082     switches::kEnableExperimentalWebPlatformFeatures,
1083     switches::kEnableFastTextAutosizing,
1084     switches::kEnableGPUClientLogging,
1085     switches::kEnableGpuClientTracing,
1086     switches::kEnableGPUServiceLogging,
1087     switches::kEnableHighDpiCompositingForFixedPosition,
1088     switches::kEnableLowResTiling,
1089     switches::kEnableInbandTextTracks,
1090     switches::kEnableLCDText,
1091     switches::kEnableLayerSquashing,
1092     switches::kEnableLogging,
1093     switches::kEnableMemoryBenchmarking,
1094     switches::kEnableOneCopy,
1095     switches::kEnableOverlayFullscreenVideo,
1096     switches::kEnableOverlayScrollbar,
1097     switches::kEnableOverscrollNotifications,
1098     switches::kEnablePinch,
1099     switches::kEnablePreciseMemoryInfo,
1100     switches::kEnablePreparsedJsCaching,
1101     switches::kEnableRepaintAfterLayout,
1102     switches::kEnableSeccompFilterSandbox,
1103     switches::kEnableServiceWorker,
1104     switches::kEnableSkiaBenchmarking,
1105     switches::kEnableSpeechSynthesis,
1106     switches::kEnableStatsTable,
1107     switches::kEnableStrictSiteIsolation,
1108     switches::kEnableTargetedStyleRecalc,
1109     switches::kEnableUniversalAcceleratedOverflowScroll,
1110     switches::kEnableTouchDragDrop,
1111     switches::kEnableTouchEditing,
1112     switches::kEnableViewport,
1113     switches::kEnableViewportMeta,
1114     switches::kMainFrameResizesAreOrientationChanges,
1115     switches::kEnableVtune,
1116     switches::kEnableWebAnimationsSVG,
1117     switches::kEnableWebGLDraftExtensions,
1118     switches::kEnableWebMIDI,
1119     switches::kEnableZeroCopy,
1120     switches::kForceCompositingMode,
1121     switches::kForceDeviceScaleFactor,
1122     switches::kFullMemoryCrashReport,
1123     switches::kJavaScriptFlags,
1124     switches::kLoggingLevel,
1125     switches::kMaxUntiledLayerWidth,
1126     switches::kMaxUntiledLayerHeight,
1127     switches::kMemoryMetrics,
1128     switches::kNoReferrers,
1129     switches::kNoSandbox,
1130     switches::kNumRasterThreads,
1131     switches::kPpapiInProcess,
1132     switches::kProfilerTiming,
1133     switches::kReduceSecurityForTesting,
1134     switches::kRegisterPepperPlugins,
1135     switches::kRendererAssertTest,
1136     switches::kRendererStartupDialog,
1137     switches::kShowPaintRects,
1138     switches::kSitePerProcess,
1139     switches::kStatsCollectionController,
1140     switches::kTestSandbox,
1141     switches::kTestType,
1142     switches::kTouchEvents,
1143     switches::kTraceToConsole,
1144     switches::kUseDiscardableMemory,
1145     // This flag needs to be propagated to the renderer process for
1146     // --in-process-webgl.
1147     switches::kUseGL,
1148     switches::kUseMobileUserAgent,
1149     switches::kV,
1150     switches::kVideoThreads,
1151     switches::kVModule,
1152     switches::kWebGLCommandBufferSizeKb,
1153     // Please keep these in alphabetical order. Compositor switches here should
1154     // also be added to chrome/browser/chromeos/login/chrome_restart_request.cc.
1155     cc::switches::kCompositeToMailbox,
1156     cc::switches::kDisableCompositedAntialiasing,
1157     cc::switches::kDisableCompositorTouchHitTesting,
1158     cc::switches::kDisableMainFrameBeforeActivation,
1159     cc::switches::kDisableMainFrameBeforeDraw,
1160     cc::switches::kDisableThreadedAnimation,
1161     cc::switches::kEnableGpuBenchmarking,
1162     cc::switches::kEnableMainFrameBeforeActivation,
1163     cc::switches::kEnableTopControlsPositionCalculation,
1164     cc::switches::kMaxTilesForInterestArea,
1165     cc::switches::kMaxUnusedResourceMemoryUsagePercentage,
1166     cc::switches::kShowCompositedLayerBorders,
1167     cc::switches::kShowFPSCounter,
1168     cc::switches::kShowLayerAnimationBounds,
1169     cc::switches::kShowNonOccludingRects,
1170     cc::switches::kShowOccludingRects,
1171     cc::switches::kShowPropertyChangedRects,
1172     cc::switches::kShowReplicaScreenSpaceRects,
1173     cc::switches::kShowScreenSpaceRects,
1174     cc::switches::kShowSurfaceDamageRects,
1175     cc::switches::kSlowDownRasterScaleFactor,
1176     cc::switches::kStrictLayerPropertyChangeChecking,
1177     cc::switches::kTopControlsHeight,
1178     cc::switches::kTopControlsHideThreshold,
1179     cc::switches::kTopControlsShowThreshold,
1180 #if defined(ENABLE_PLUGINS)
1181     switches::kEnablePepperTesting,
1182 #endif
1183 #if defined(ENABLE_WEBRTC)
1184     switches::kEnableAudioTrackProcessing,
1185     switches::kDisableDeviceEnumeration,
1186     switches::kDisableWebRtcHWDecoding,
1187     switches::kDisableWebRtcHWEncoding,
1188     switches::kEnableWebRtcHWVp8Encoding,
1189     switches::kEnableWebRtcTcpServerSocket,
1190 #endif
1191 #if defined(OS_ANDROID)
1192     switches::kDisableGestureRequirementForMediaPlayback,
1193     switches::kDisableLowEndDeviceMode,
1194     switches::kDisableWebRTC,
1195     switches::kEnableLowEndDeviceMode,
1196     switches::kEnableSpeechRecognition,
1197     switches::kMediaDrmEnableNonCompositing,
1198     switches::kNetworkCountryIso,
1199     switches::kDisableWebAudio,
1200 #endif
1201 #if defined(OS_MACOSX)
1202     // Allow this to be set when invoking the browser and relayed along.
1203     switches::kEnableSandboxLogging,
1204 #endif
1205 #if defined(OS_WIN)
1206     switches::kEnableDirectWrite,
1207     switches::kEnableHighResolutionTime,
1208     switches::kHighDPISupport,
1209 #endif
1210   };
1211   renderer_cmd->CopySwitchesFrom(browser_cmd, kSwitchNames,
1212                                  arraysize(kSwitchNames));
1213
1214   if (browser_cmd.HasSwitch(switches::kTraceStartup) &&
1215       BrowserMainLoop::GetInstance()->is_tracing_startup()) {
1216     // Pass kTraceStartup switch to renderer only if startup tracing has not
1217     // finished.
1218     renderer_cmd->AppendSwitchASCII(
1219         switches::kTraceStartup,
1220         browser_cmd.GetSwitchValueASCII(switches::kTraceStartup));
1221   }
1222
1223   // Disable databases in incognito mode.
1224   if (GetBrowserContext()->IsOffTheRecord() &&
1225       !browser_cmd.HasSwitch(switches::kDisableDatabases)) {
1226     renderer_cmd->AppendSwitch(switches::kDisableDatabases);
1227 #if defined(OS_ANDROID)
1228     renderer_cmd->AppendSwitch(switches::kDisableMediaHistoryLogging);
1229 #endif
1230   }
1231
1232   // Enforce the extra command line flags for impl-side painting.
1233   if (IsImplSidePaintingEnabled() &&
1234       !browser_cmd.HasSwitch(switches::kEnableDeferredImageDecoding))
1235     renderer_cmd->AppendSwitch(switches::kEnableDeferredImageDecoding);
1236 }
1237
1238 base::ProcessHandle RenderProcessHostImpl::GetHandle() const {
1239   if (run_renderer_in_process())
1240     return base::Process::Current().handle();
1241
1242   if (!child_process_launcher_.get() || child_process_launcher_->IsStarting())
1243     return base::kNullProcessHandle;
1244
1245   return child_process_launcher_->GetHandle();
1246 }
1247
1248 bool RenderProcessHostImpl::FastShutdownIfPossible() {
1249   if (run_renderer_in_process())
1250     return false;  // Single process mode never shutdown the renderer.
1251
1252   if (!GetContentClient()->browser()->IsFastShutdownPossible())
1253     return false;
1254
1255   if (!child_process_launcher_.get() ||
1256       child_process_launcher_->IsStarting() ||
1257       !GetHandle())
1258     return false;  // Render process hasn't started or is probably crashed.
1259
1260   // Test if there's an unload listener.
1261   // NOTE: It's possible that an onunload listener may be installed
1262   // while we're shutting down, so there's a small race here.  Given that
1263   // the window is small, it's unlikely that the web page has much
1264   // state that will be lost by not calling its unload handlers properly.
1265   if (!SuddenTerminationAllowed())
1266     return false;
1267
1268   if (worker_ref_count_ != 0) {
1269     if (survive_for_worker_start_time_.is_null())
1270       survive_for_worker_start_time_ = base::TimeTicks::Now();
1271     return false;
1272   }
1273
1274   // Set this before ProcessDied() so observers can tell if the render process
1275   // died due to fast shutdown versus another cause.
1276   fast_shutdown_started_ = true;
1277
1278   ProcessDied(false /* already_dead */);
1279   return true;
1280 }
1281
1282 void RenderProcessHostImpl::DumpHandles() {
1283 #if defined(OS_WIN)
1284   Send(new ChildProcessMsg_DumpHandles());
1285 #else
1286   NOTIMPLEMENTED();
1287 #endif
1288 }
1289
1290 bool RenderProcessHostImpl::Send(IPC::Message* msg) {
1291   TRACE_EVENT0("renderer_host", "RenderProcessHostImpl::Send");
1292   if (!channel_) {
1293     if (!is_initialized_) {
1294       queued_messages_.push(msg);
1295       return true;
1296     } else {
1297       delete msg;
1298       return false;
1299     }
1300   }
1301
1302   if (child_process_launcher_.get() && child_process_launcher_->IsStarting()) {
1303     queued_messages_.push(msg);
1304     return true;
1305   }
1306
1307   return channel_->Send(msg);
1308 }
1309
1310 bool RenderProcessHostImpl::OnMessageReceived(const IPC::Message& msg) {
1311   // If we're about to be deleted, or have initiated the fast shutdown sequence,
1312   // we ignore incoming messages.
1313
1314   if (deleting_soon_ || fast_shutdown_started_)
1315     return false;
1316
1317   mark_child_process_activity_time();
1318   if (msg.routing_id() == MSG_ROUTING_CONTROL) {
1319     // Dispatch control messages.
1320     bool msg_is_ok = true;
1321     IPC_BEGIN_MESSAGE_MAP_EX(RenderProcessHostImpl, msg, msg_is_ok)
1322       IPC_MESSAGE_HANDLER(ChildProcessHostMsg_ShutdownRequest,
1323                           OnShutdownRequest)
1324       IPC_MESSAGE_HANDLER(ChildProcessHostMsg_DumpHandlesDone,
1325                           OnDumpHandlesDone)
1326       IPC_MESSAGE_HANDLER(ViewHostMsg_SuddenTerminationChanged,
1327                           SuddenTerminationChanged)
1328       IPC_MESSAGE_HANDLER(ViewHostMsg_UserMetricsRecordAction,
1329                           OnUserMetricsRecordAction)
1330       IPC_MESSAGE_HANDLER(ViewHostMsg_SavedPageAsMHTML, OnSavedPageAsMHTML)
1331       // Adding single handlers for your service here is fine, but once your
1332       // service needs more than one handler, please extract them into a new
1333       // message filter and add that filter to CreateMessageFilters().
1334     IPC_END_MESSAGE_MAP_EX()
1335
1336     if (!msg_is_ok) {
1337       // The message had a handler, but its de-serialization failed.
1338       // We consider this a capital crime. Kill the renderer if we have one.
1339       LOG(ERROR) << "bad message " << msg.type() << " terminating renderer.";
1340       RecordAction(base::UserMetricsAction("BadMessageTerminate_BRPH"));
1341       ReceivedBadMessage();
1342     }
1343     return true;
1344   }
1345
1346   // Dispatch incoming messages to the appropriate IPC::Listener.
1347   IPC::Listener* listener = listeners_.Lookup(msg.routing_id());
1348   if (!listener) {
1349     if (msg.is_sync()) {
1350       // The listener has gone away, so we must respond or else the caller will
1351       // hang waiting for a reply.
1352       IPC::Message* reply = IPC::SyncMessage::GenerateReply(&msg);
1353       reply->set_reply_error();
1354       Send(reply);
1355     }
1356
1357     // If this is a SwapBuffers, we need to ack it if we're not going to handle
1358     // it so that the GPU process doesn't get stuck in unscheduled state.
1359     bool msg_is_ok = true;
1360     IPC_BEGIN_MESSAGE_MAP_EX(RenderProcessHostImpl, msg, msg_is_ok)
1361       IPC_MESSAGE_HANDLER(ViewHostMsg_CompositorSurfaceBuffersSwapped,
1362                           OnCompositorSurfaceBuffersSwappedNoHost)
1363     IPC_END_MESSAGE_MAP_EX()
1364     return true;
1365   }
1366   return listener->OnMessageReceived(msg);
1367 }
1368
1369 void RenderProcessHostImpl::OnChannelConnected(int32 peer_pid) {
1370 #if defined(IPC_MESSAGE_LOG_ENABLED)
1371   Send(new ChildProcessMsg_SetIPCLoggingEnabled(
1372       IPC::Logging::GetInstance()->Enabled()));
1373 #endif
1374
1375   tracked_objects::ThreadData::Status status =
1376       tracked_objects::ThreadData::status();
1377   Send(new ChildProcessMsg_SetProfilerStatus(status));
1378 }
1379
1380 void RenderProcessHostImpl::OnChannelError() {
1381   ProcessDied(true /* already_dead */);
1382 }
1383
1384 BrowserContext* RenderProcessHostImpl::GetBrowserContext() const {
1385   return browser_context_;
1386 }
1387
1388 bool RenderProcessHostImpl::InSameStoragePartition(
1389     StoragePartition* partition) const {
1390   return storage_partition_impl_ == partition;
1391 }
1392
1393 int RenderProcessHostImpl::GetID() const {
1394   return id_;
1395 }
1396
1397 bool RenderProcessHostImpl::HasConnection() const {
1398   return channel_.get() != NULL;
1399 }
1400
1401 void RenderProcessHostImpl::SetIgnoreInputEvents(bool ignore_input_events) {
1402   ignore_input_events_ = ignore_input_events;
1403 }
1404
1405 bool RenderProcessHostImpl::IgnoreInputEvents() const {
1406   return ignore_input_events_;
1407 }
1408
1409 void RenderProcessHostImpl::Cleanup() {
1410   // If within_process_died_observer_ is true, one of our observers performed an
1411   // action that caused us to die (e.g. http://crbug.com/339504). Therefore,
1412   // delay the destruction until all of the observer callbacks have been made,
1413   // and guarantee that the RenderProcessHostDestroyed observer callback is
1414   // always the last callback fired.
1415   if (within_process_died_observer_) {
1416     delayed_cleanup_needed_ = true;
1417     return;
1418   }
1419   delayed_cleanup_needed_ = false;
1420
1421   // Records the time when the process starts surviving for workers for UMA.
1422   if (listeners_.IsEmpty() && worker_ref_count_ > 0 &&
1423       survive_for_worker_start_time_.is_null()) {
1424     survive_for_worker_start_time_ = base::TimeTicks::Now();
1425   }
1426
1427   // When there are no other owners of this object, we can delete ourselves.
1428   if (listeners_.IsEmpty() && worker_ref_count_ == 0) {
1429     if (!survive_for_worker_start_time_.is_null()) {
1430       UMA_HISTOGRAM_LONG_TIMES(
1431           "SharedWorker.RendererSurviveForWorkerTime",
1432           base::TimeTicks::Now() - survive_for_worker_start_time_);
1433     }
1434     // We cannot clean up twice; if this fails, there is an issue with our
1435     // control flow.
1436     DCHECK(!deleting_soon_);
1437
1438     DCHECK_EQ(0, pending_views_);
1439     FOR_EACH_OBSERVER(RenderProcessHostObserver,
1440                       observers_,
1441                       RenderProcessHostDestroyed(this));
1442     NotificationService::current()->Notify(
1443         NOTIFICATION_RENDERER_PROCESS_TERMINATED,
1444         Source<RenderProcessHost>(this),
1445         NotificationService::NoDetails());
1446
1447 #ifndef NDEBUG
1448     is_self_deleted_ = true;
1449 #endif
1450     base::MessageLoop::current()->DeleteSoon(FROM_HERE, this);
1451     deleting_soon_ = true;
1452     // It's important not to wait for the DeleteTask to delete the channel
1453     // proxy. Kill it off now. That way, in case the profile is going away, the
1454     // rest of the objects attached to this RenderProcessHost start going
1455     // away first, since deleting the channel proxy will post a
1456     // OnChannelClosed() to IPC::ChannelProxy::Context on the IO thread.
1457     channel_.reset();
1458     gpu_message_filter_ = NULL;
1459     message_port_message_filter_ = NULL;
1460     geolocation_dispatcher_host_ = NULL;
1461     screen_orientation_dispatcher_host_ = NULL;
1462
1463     // Remove ourself from the list of renderer processes so that we can't be
1464     // reused in between now and when the Delete task runs.
1465     UnregisterHost(GetID());
1466   }
1467 }
1468
1469 void RenderProcessHostImpl::AddPendingView() {
1470   pending_views_++;
1471 }
1472
1473 void RenderProcessHostImpl::RemovePendingView() {
1474   DCHECK(pending_views_);
1475   pending_views_--;
1476 }
1477
1478 void RenderProcessHostImpl::SetSuddenTerminationAllowed(bool enabled) {
1479   sudden_termination_allowed_ = enabled;
1480 }
1481
1482 bool RenderProcessHostImpl::SuddenTerminationAllowed() const {
1483   return sudden_termination_allowed_;
1484 }
1485
1486 base::TimeDelta RenderProcessHostImpl::GetChildProcessIdleTime() const {
1487   return base::TimeTicks::Now() - child_process_activity_time_;
1488 }
1489
1490 void RenderProcessHostImpl::ResumeRequestsForView(int route_id) {
1491   widget_helper_->ResumeRequestsForView(route_id);
1492 }
1493
1494 void RenderProcessHostImpl::FilterURL(bool empty_allowed, GURL* url) {
1495   FilterURL(this, empty_allowed, url);
1496 }
1497
1498 #if defined(ENABLE_WEBRTC)
1499 void RenderProcessHostImpl::EnableAecDump(const base::FilePath& file) {
1500   DCHECK_CURRENTLY_ON(BrowserThread::UI);
1501   BrowserThread::PostTaskAndReplyWithResult(
1502       BrowserThread::FILE, FROM_HERE,
1503       base::Bind(&CreateAecDumpFileForProcess, file, GetHandle()),
1504       base::Bind(&RenderProcessHostImpl::SendAecDumpFileToRenderer,
1505                  weak_factory_.GetWeakPtr()));
1506 }
1507
1508 void RenderProcessHostImpl::DisableAecDump() {
1509   DCHECK_CURRENTLY_ON(BrowserThread::UI);
1510   // Posting on the FILE thread and then replying back on the UI thread is only
1511   // for avoiding races between enable and disable. Nothing is done on the FILE
1512   // thread.
1513   BrowserThread::PostTaskAndReply(
1514       BrowserThread::FILE, FROM_HERE,
1515       base::Bind(&DisableAecDumpOnFileThread),
1516       base::Bind(&RenderProcessHostImpl::SendDisableAecDumpToRenderer,
1517                  weak_factory_.GetWeakPtr()));
1518 }
1519
1520 void RenderProcessHostImpl::SetWebRtcLogMessageCallback(
1521     base::Callback<void(const std::string&)> callback) {
1522   webrtc_log_message_callback_ = callback;
1523 }
1524 #endif
1525
1526 IPC::ChannelProxy* RenderProcessHostImpl::GetChannel() {
1527   return channel_.get();
1528 }
1529
1530 void RenderProcessHostImpl::AddFilter(BrowserMessageFilter* filter) {
1531   channel_->AddFilter(filter->GetFilter());
1532 }
1533
1534 bool RenderProcessHostImpl::FastShutdownForPageCount(size_t count) {
1535   if (static_cast<size_t>(GetActiveViewCount()) == count)
1536     return FastShutdownIfPossible();
1537   return false;
1538 }
1539
1540 bool RenderProcessHostImpl::FastShutdownStarted() const {
1541   return fast_shutdown_started_;
1542 }
1543
1544 // static
1545 void RenderProcessHostImpl::RegisterHost(int host_id, RenderProcessHost* host) {
1546   g_all_hosts.Get().AddWithID(host, host_id);
1547 }
1548
1549 // static
1550 void RenderProcessHostImpl::UnregisterHost(int host_id) {
1551   RenderProcessHost* host = g_all_hosts.Get().Lookup(host_id);
1552   if (!host)
1553     return;
1554
1555   g_all_hosts.Get().Remove(host_id);
1556
1557   // Look up the map of site to process for the given browser_context,
1558   // in case we need to remove this process from it.  It will be registered
1559   // under any sites it rendered that use process-per-site mode.
1560   SiteProcessMap* map =
1561       GetSiteProcessMapForBrowserContext(host->GetBrowserContext());
1562   map->RemoveProcess(host);
1563 }
1564
1565 // static
1566 void RenderProcessHostImpl::FilterURL(RenderProcessHost* rph,
1567                                       bool empty_allowed,
1568                                       GURL* url) {
1569   ChildProcessSecurityPolicyImpl* policy =
1570       ChildProcessSecurityPolicyImpl::GetInstance();
1571
1572   if (empty_allowed && url->is_empty())
1573     return;
1574
1575   // The browser process should never hear the swappedout:// URL from any
1576   // of the renderer's messages.  Check for this in debug builds, but don't
1577   // let it crash a release browser.
1578   DCHECK(GURL(kSwappedOutURL) != *url);
1579
1580   if (!url->is_valid()) {
1581     // Have to use about:blank for the denied case, instead of an empty GURL.
1582     // This is because the browser treats navigation to an empty GURL as a
1583     // navigation to the home page. This is often a privileged page
1584     // (chrome://newtab/) which is exactly what we don't want.
1585     *url = GURL(kAboutBlankURL);
1586     RecordAction(base::UserMetricsAction("FilterURLTermiate_Invalid"));
1587     return;
1588   }
1589
1590   if (url->SchemeIs(kAboutScheme)) {
1591     // The renderer treats all URLs in the about: scheme as being about:blank.
1592     // Canonicalize about: URLs to about:blank.
1593     *url = GURL(kAboutBlankURL);
1594     RecordAction(base::UserMetricsAction("FilterURLTermiate_About"));
1595   }
1596
1597   // Do not allow browser plugin guests to navigate to non-web URLs, since they
1598   // cannot swap processes or grant bindings.
1599   bool non_web_url_in_guest = rph->IsGuest() &&
1600       !(url->is_valid() && policy->IsWebSafeScheme(url->scheme()));
1601
1602   if (non_web_url_in_guest || !policy->CanRequestURL(rph->GetID(), *url)) {
1603     // If this renderer is not permitted to request this URL, we invalidate the
1604     // URL.  This prevents us from storing the blocked URL and becoming confused
1605     // later.
1606     VLOG(1) << "Blocked URL " << url->spec();
1607     *url = GURL(kAboutBlankURL);
1608     RecordAction(base::UserMetricsAction("FilterURLTermiate_Blocked"));
1609   }
1610 }
1611
1612 // static
1613 bool RenderProcessHostImpl::IsSuitableHost(
1614     RenderProcessHost* host,
1615     BrowserContext* browser_context,
1616     const GURL& site_url) {
1617   if (run_renderer_in_process())
1618     return true;
1619
1620   if (host->GetBrowserContext() != browser_context)
1621     return false;
1622
1623   // Do not allow sharing of guest hosts. This is to prevent bugs where guest
1624   // and non-guest storage gets mixed. In the future, we might consider enabling
1625   // the sharing of guests, in this case this check should be removed and
1626   // InSameStoragePartition should handle the possible sharing.
1627   if (host->IsGuest())
1628     return false;
1629
1630   // Check whether the given host and the intended site_url will be using the
1631   // same StoragePartition, since a RenderProcessHost can only support a single
1632   // StoragePartition.  This is relevant for packaged apps and isolated sites.
1633   StoragePartition* dest_partition =
1634       BrowserContext::GetStoragePartitionForSite(browser_context, site_url);
1635   if (!host->InSameStoragePartition(dest_partition))
1636     return false;
1637
1638   if (ChildProcessSecurityPolicyImpl::GetInstance()->HasWebUIBindings(
1639           host->GetID()) !=
1640       WebUIControllerFactoryRegistry::GetInstance()->UseWebUIBindingsForURL(
1641           browser_context, site_url)) {
1642     return false;
1643   }
1644
1645   return GetContentClient()->browser()->IsSuitableHost(host, site_url);
1646 }
1647
1648 // static
1649 bool RenderProcessHost::run_renderer_in_process() {
1650   return g_run_renderer_in_process_;
1651 }
1652
1653 // static
1654 void RenderProcessHost::SetRunRendererInProcess(bool value) {
1655   g_run_renderer_in_process_ = value;
1656
1657   CommandLine* command_line = CommandLine::ForCurrentProcess();
1658   if (value) {
1659     if (!command_line->HasSwitch(switches::kLang)) {
1660       // Modify the current process' command line to include the browser locale,
1661       // as the renderer expects this flag to be set.
1662       const std::string locale =
1663           GetContentClient()->browser()->GetApplicationLocale();
1664       command_line->AppendSwitchASCII(switches::kLang, locale);
1665     }
1666     // TODO(piman): we should really send configuration through bools rather
1667     // than by parsing strings, i.e. sending an IPC rather than command line
1668     // args. crbug.com/314909
1669     AppendCompositorCommandLineFlags(command_line);
1670   }
1671 }
1672
1673 // static
1674 RenderProcessHost::iterator RenderProcessHost::AllHostsIterator() {
1675   DCHECK_CURRENTLY_ON(BrowserThread::UI);
1676   return iterator(g_all_hosts.Pointer());
1677 }
1678
1679 // static
1680 RenderProcessHost* RenderProcessHost::FromID(int render_process_id) {
1681   DCHECK_CURRENTLY_ON(BrowserThread::UI);
1682   return g_all_hosts.Get().Lookup(render_process_id);
1683 }
1684
1685 // static
1686 bool RenderProcessHost::ShouldTryToUseExistingProcessHost(
1687     BrowserContext* browser_context, const GURL& url) {
1688   // Experimental:
1689   // If --enable-strict-site-isolation or --site-per-process is enabled, do not
1690   // try to reuse renderer processes when over the limit.  (We could allow pages
1691   // from the same site to share, if we knew what the given process was
1692   // dedicated to.  Allowing no sharing is simpler for now.)  This may cause
1693   // resource exhaustion issues if too many sites are open at once.
1694   const CommandLine& command_line = *CommandLine::ForCurrentProcess();
1695   if (command_line.HasSwitch(switches::kEnableStrictSiteIsolation) ||
1696       command_line.HasSwitch(switches::kSitePerProcess))
1697     return false;
1698
1699   if (run_renderer_in_process())
1700     return true;
1701
1702   // NOTE: Sometimes it's necessary to create more render processes than
1703   //       GetMaxRendererProcessCount(), for instance when we want to create
1704   //       a renderer process for a browser context that has no existing
1705   //       renderers. This is OK in moderation, since the
1706   //       GetMaxRendererProcessCount() is conservative.
1707   if (g_all_hosts.Get().size() >= GetMaxRendererProcessCount())
1708     return true;
1709
1710   return GetContentClient()->browser()->
1711       ShouldTryToUseExistingProcessHost(browser_context, url);
1712 }
1713
1714 // static
1715 RenderProcessHost* RenderProcessHost::GetExistingProcessHost(
1716     BrowserContext* browser_context,
1717     const GURL& site_url) {
1718   // First figure out which existing renderers we can use.
1719   std::vector<RenderProcessHost*> suitable_renderers;
1720   suitable_renderers.reserve(g_all_hosts.Get().size());
1721
1722   iterator iter(AllHostsIterator());
1723   while (!iter.IsAtEnd()) {
1724     if (RenderProcessHostImpl::IsSuitableHost(
1725             iter.GetCurrentValue(),
1726             browser_context, site_url))
1727       suitable_renderers.push_back(iter.GetCurrentValue());
1728
1729     iter.Advance();
1730   }
1731
1732   // Now pick a random suitable renderer, if we have any.
1733   if (!suitable_renderers.empty()) {
1734     int suitable_count = static_cast<int>(suitable_renderers.size());
1735     int random_index = base::RandInt(0, suitable_count - 1);
1736     return suitable_renderers[random_index];
1737   }
1738
1739   return NULL;
1740 }
1741
1742 // static
1743 bool RenderProcessHost::ShouldUseProcessPerSite(
1744     BrowserContext* browser_context,
1745     const GURL& url) {
1746   // Returns true if we should use the process-per-site model.  This will be
1747   // the case if the --process-per-site switch is specified, or in
1748   // process-per-site-instance for particular sites (e.g., WebUI).
1749   // Note that --single-process is handled in ShouldTryToUseExistingProcessHost.
1750   const CommandLine& command_line = *CommandLine::ForCurrentProcess();
1751   if (command_line.HasSwitch(switches::kProcessPerSite))
1752     return true;
1753
1754   // We want to consolidate particular sites like WebUI even when we are using
1755   // the process-per-tab or process-per-site-instance models.
1756   // Note: DevTools pages have WebUI type but should not reuse the same host.
1757   if (WebUIControllerFactoryRegistry::GetInstance()->UseWebUIForURL(
1758           browser_context, url) &&
1759       !url.SchemeIs(kChromeDevToolsScheme)) {
1760     return true;
1761   }
1762
1763   // Otherwise let the content client decide, defaulting to false.
1764   return GetContentClient()->browser()->ShouldUseProcessPerSite(browser_context,
1765                                                                 url);
1766 }
1767
1768 // static
1769 RenderProcessHost* RenderProcessHostImpl::GetProcessHostForSite(
1770     BrowserContext* browser_context,
1771     const GURL& url) {
1772   // Look up the map of site to process for the given browser_context.
1773   SiteProcessMap* map =
1774       GetSiteProcessMapForBrowserContext(browser_context);
1775
1776   // See if we have an existing process with appropriate bindings for this site.
1777   // If not, the caller should create a new process and register it.
1778   std::string site = SiteInstance::GetSiteForURL(browser_context, url)
1779       .possibly_invalid_spec();
1780   RenderProcessHost* host = map->FindProcess(site);
1781   if (host && !IsSuitableHost(host, browser_context, url)) {
1782     // The registered process does not have an appropriate set of bindings for
1783     // the url.  Remove it from the map so we can register a better one.
1784     RecordAction(
1785         base::UserMetricsAction("BindingsMismatch_GetProcessHostPerSite"));
1786     map->RemoveProcess(host);
1787     host = NULL;
1788   }
1789
1790   return host;
1791 }
1792
1793 void RenderProcessHostImpl::RegisterProcessHostForSite(
1794     BrowserContext* browser_context,
1795     RenderProcessHost* process,
1796     const GURL& url) {
1797   // Look up the map of site to process for the given browser_context.
1798   SiteProcessMap* map =
1799       GetSiteProcessMapForBrowserContext(browser_context);
1800
1801   // Only register valid, non-empty sites.  Empty or invalid sites will not
1802   // use process-per-site mode.  We cannot check whether the process has
1803   // appropriate bindings here, because the bindings have not yet been granted.
1804   std::string site = SiteInstance::GetSiteForURL(browser_context, url)
1805       .possibly_invalid_spec();
1806   if (!site.empty())
1807     map->RegisterProcess(site, process);
1808 }
1809
1810 void RenderProcessHostImpl::ProcessDied(bool already_dead) {
1811   // Our child process has died.  If we didn't expect it, it's a crash.
1812   // In any case, we need to let everyone know it's gone.
1813   // The OnChannelError notification can fire multiple times due to nested sync
1814   // calls to a renderer. If we don't have a valid channel here it means we
1815   // already handled the error.
1816
1817   // It should not be possible for us to be called re-entrantly.
1818   DCHECK(!within_process_died_observer_);
1819
1820   // It should not be possible for a process death notification to come in while
1821   // we are dying.
1822   DCHECK(!deleting_soon_);
1823
1824   // child_process_launcher_ can be NULL in single process mode or if fast
1825   // termination happened.
1826   int exit_code = 0;
1827   base::TerminationStatus status =
1828       child_process_launcher_.get() ?
1829       child_process_launcher_->GetChildTerminationStatus(already_dead,
1830                                                          &exit_code) :
1831       base::TERMINATION_STATUS_NORMAL_TERMINATION;
1832
1833   RendererClosedDetails details(GetHandle(), status, exit_code);
1834   within_process_died_observer_ = true;
1835   NotificationService::current()->Notify(
1836       NOTIFICATION_RENDERER_PROCESS_CLOSED,
1837       Source<RenderProcessHost>(this),
1838       Details<RendererClosedDetails>(&details));
1839   FOR_EACH_OBSERVER(RenderProcessHostObserver,
1840                     observers_,
1841                     RenderProcessExited(this, GetHandle(), status, exit_code));
1842   within_process_died_observer_ = false;
1843
1844   child_process_launcher_.reset();
1845   channel_.reset();
1846   gpu_message_filter_ = NULL;
1847   message_port_message_filter_ = NULL;
1848   geolocation_dispatcher_host_ = NULL;
1849   screen_orientation_dispatcher_host_ = NULL;
1850
1851   IDMap<IPC::Listener>::iterator iter(&listeners_);
1852   while (!iter.IsAtEnd()) {
1853     iter.GetCurrentValue()->OnMessageReceived(
1854         ViewHostMsg_RenderProcessGone(iter.GetCurrentKey(),
1855                                       static_cast<int>(status),
1856                                       exit_code));
1857     iter.Advance();
1858   }
1859
1860   mojo_application_host_.reset();
1861
1862   // It's possible that one of the calls out to the observers might have caused
1863   // this object to be no longer needed.
1864   if (delayed_cleanup_needed_)
1865     Cleanup();
1866
1867   // This object is not deleted at this point and might be reused later.
1868   // TODO(darin): clean this up
1869 }
1870
1871 int RenderProcessHostImpl::GetActiveViewCount() {
1872   int num_active_views = 0;
1873   scoped_ptr<RenderWidgetHostIterator> widgets(
1874       RenderWidgetHost::GetRenderWidgetHosts());
1875   while (RenderWidgetHost* widget = widgets->GetNextHost()) {
1876     // Count only RenderWidgetHosts in this process.
1877     if (widget->GetProcess()->GetID() == GetID())
1878       num_active_views++;
1879   }
1880   return num_active_views;
1881 }
1882
1883 // Frame subscription API for this class is for accelerated composited path
1884 // only. These calls are redirected to GpuMessageFilter.
1885 void RenderProcessHostImpl::BeginFrameSubscription(
1886     int route_id,
1887     scoped_ptr<RenderWidgetHostViewFrameSubscriber> subscriber) {
1888   if (!gpu_message_filter_)
1889     return;
1890   BrowserThread::PostTask(BrowserThread::IO, FROM_HERE, base::Bind(
1891       &GpuMessageFilter::BeginFrameSubscription,
1892       gpu_message_filter_,
1893       route_id, base::Passed(&subscriber)));
1894 }
1895
1896 void RenderProcessHostImpl::EndFrameSubscription(int route_id) {
1897   if (!gpu_message_filter_)
1898     return;
1899   BrowserThread::PostTask(BrowserThread::IO, FROM_HERE, base::Bind(
1900       &GpuMessageFilter::EndFrameSubscription,
1901       gpu_message_filter_,
1902       route_id));
1903 }
1904
1905 #if defined(ENABLE_WEBRTC)
1906 void RenderProcessHostImpl::WebRtcLogMessage(const std::string& message) {
1907   DCHECK_CURRENTLY_ON(BrowserThread::UI);
1908   if (!webrtc_log_message_callback_.is_null())
1909     webrtc_log_message_callback_.Run(message);
1910 }
1911 #endif
1912
1913 scoped_refptr<ScreenOrientationDispatcherHost>
1914 RenderProcessHostImpl::screen_orientation_dispatcher_host() const {
1915   return make_scoped_refptr(screen_orientation_dispatcher_host_);
1916 }
1917
1918 void RenderProcessHostImpl::OnShutdownRequest() {
1919   // Don't shut down if there are active RenderViews, or if there are pending
1920   // RenderViews being swapped back in.
1921   // In single process mode, we never shutdown the renderer.
1922   int num_active_views = GetActiveViewCount();
1923   if (pending_views_ || num_active_views > 0 || run_renderer_in_process())
1924     return;
1925
1926   // Notify any contents that might have swapped out renderers from this
1927   // process. They should not attempt to swap them back in.
1928   NotificationService::current()->Notify(
1929       NOTIFICATION_RENDERER_PROCESS_CLOSING,
1930       Source<RenderProcessHost>(this),
1931       NotificationService::NoDetails());
1932
1933   Send(new ChildProcessMsg_Shutdown());
1934 }
1935
1936 void RenderProcessHostImpl::SuddenTerminationChanged(bool enabled) {
1937   SetSuddenTerminationAllowed(enabled);
1938 }
1939
1940 void RenderProcessHostImpl::OnDumpHandlesDone() {
1941   Cleanup();
1942 }
1943
1944 void RenderProcessHostImpl::SetBackgrounded(bool backgrounded) {
1945   // Note: we always set the backgrounded_ value.  If the process is NULL
1946   // (and hence hasn't been created yet), we will set the process priority
1947   // later when we create the process.
1948   backgrounded_ = backgrounded;
1949   if (!child_process_launcher_.get() || child_process_launcher_->IsStarting())
1950     return;
1951
1952 #if defined(OS_WIN)
1953   // The cbstext.dll loads as a global GetMessage hook in the browser process
1954   // and intercepts/unintercepts the kernel32 API SetPriorityClass in a
1955   // background thread. If the UI thread invokes this API just when it is
1956   // intercepted the stack is messed up on return from the interceptor
1957   // which causes random crashes in the browser process. Our hack for now
1958   // is to not invoke the SetPriorityClass API if the dll is loaded.
1959   if (GetModuleHandle(L"cbstext.dll"))
1960     return;
1961 #endif  // OS_WIN
1962
1963   child_process_launcher_->SetProcessBackgrounded(backgrounded);
1964 }
1965
1966 void RenderProcessHostImpl::OnProcessLaunched() {
1967   // No point doing anything, since this object will be destructed soon.  We
1968   // especially don't want to send the RENDERER_PROCESS_CREATED notification,
1969   // since some clients might expect a RENDERER_PROCESS_TERMINATED afterwards to
1970   // properly cleanup.
1971   if (deleting_soon_)
1972     return;
1973
1974   if (child_process_launcher_) {
1975     if (!child_process_launcher_->GetHandle()) {
1976       OnChannelError();
1977       return;
1978     }
1979
1980     child_process_launcher_->SetProcessBackgrounded(backgrounded_);
1981   }
1982
1983   // NOTE: This needs to be before sending queued messages because
1984   // ExtensionService uses this notification to initialize the renderer process
1985   // with state that must be there before any JavaScript executes.
1986   //
1987   // The queued messages contain such things as "navigate". If this notification
1988   // was after, we can end up executing JavaScript before the initialization
1989   // happens.
1990   NotificationService::current()->Notify(
1991       NOTIFICATION_RENDERER_PROCESS_CREATED,
1992       Source<RenderProcessHost>(this),
1993       NotificationService::NoDetails());
1994
1995   // Allow Mojo to be setup before the renderer sees any Chrome IPC messages.
1996   // This way, Mojo can be safely used from the renderer in response to any
1997   // Chrome IPC message.
1998   MaybeActivateMojo();
1999
2000   while (!queued_messages_.empty()) {
2001     Send(queued_messages_.front());
2002     queued_messages_.pop();
2003   }
2004
2005 #if defined(ENABLE_WEBRTC)
2006   if (WebRTCInternals::GetInstance()->aec_dump_enabled())
2007     EnableAecDump(WebRTCInternals::GetInstance()->aec_dump_file_path());
2008 #endif
2009 }
2010
2011 scoped_refptr<AudioRendererHost>
2012 RenderProcessHostImpl::audio_renderer_host() const {
2013   return audio_renderer_host_;
2014 }
2015
2016 void RenderProcessHostImpl::OnUserMetricsRecordAction(
2017     const std::string& action) {
2018   RecordComputedAction(action);
2019 }
2020
2021 void RenderProcessHostImpl::OnSavedPageAsMHTML(int job_id, int64 data_size) {
2022   MHTMLGenerationManager::GetInstance()->MHTMLGenerated(job_id, data_size);
2023 }
2024
2025 void RenderProcessHostImpl::OnCompositorSurfaceBuffersSwappedNoHost(
2026       const ViewHostMsg_CompositorSurfaceBuffersSwapped_Params& params) {
2027   TRACE_EVENT0("renderer_host",
2028                "RenderWidgetHostImpl::OnCompositorSurfaceBuffersSwappedNoHost");
2029   if (!ui::LatencyInfo::Verify(params.latency_info,
2030                                "ViewHostMsg_CompositorSurfaceBuffersSwapped"))
2031     return;
2032   AcceleratedSurfaceMsg_BufferPresented_Params ack_params;
2033   ack_params.sync_point = 0;
2034   RenderWidgetHostImpl::AcknowledgeBufferPresent(params.route_id,
2035                                                  params.gpu_process_host_id,
2036                                                  ack_params);
2037 }
2038
2039 void RenderProcessHostImpl::OnGpuSwitching() {
2040   // We are updating all widgets including swapped out ones.
2041   scoped_ptr<RenderWidgetHostIterator> widgets(
2042       RenderWidgetHostImpl::GetAllRenderWidgetHosts());
2043   while (RenderWidgetHost* widget = widgets->GetNextHost()) {
2044     if (!widget->IsRenderView())
2045       continue;
2046
2047     // Skip widgets in other processes.
2048     if (widget->GetProcess()->GetID() != GetID())
2049       continue;
2050
2051     RenderViewHost* rvh = RenderViewHost::From(widget);
2052     rvh->UpdateWebkitPreferences(rvh->GetWebkitPreferences());
2053   }
2054 }
2055
2056 #if defined(ENABLE_WEBRTC)
2057 void RenderProcessHostImpl::SendAecDumpFileToRenderer(
2058     IPC::PlatformFileForTransit file_for_transit) {
2059   if (file_for_transit == IPC::InvalidPlatformFileForTransit())
2060     return;
2061   Send(new MediaStreamMsg_EnableAecDump(file_for_transit));
2062 }
2063
2064 void RenderProcessHostImpl::SendDisableAecDumpToRenderer() {
2065   Send(new MediaStreamMsg_DisableAecDump());
2066 }
2067 #endif
2068
2069 void RenderProcessHostImpl::IncrementWorkerRefCount() {
2070   DCHECK_CURRENTLY_ON(BrowserThread::UI);
2071   ++worker_ref_count_;
2072 }
2073
2074 void RenderProcessHostImpl::DecrementWorkerRefCount() {
2075   DCHECK_CURRENTLY_ON(BrowserThread::UI);
2076   DCHECK_GT(worker_ref_count_, 0);
2077   --worker_ref_count_;
2078   if (worker_ref_count_ == 0)
2079     Cleanup();
2080 }
2081
2082 void RenderProcessHostImpl::ConnectTo(
2083     const base::StringPiece& service_name,
2084     mojo::ScopedMessagePipeHandle handle) {
2085   mojo_activation_required_ = true;
2086   MaybeActivateMojo();
2087
2088   mojo::AllocationScope scope;
2089   mojo_application_host_->shell_client()->AcceptConnection(service_name,
2090                                                            handle.Pass());
2091 }
2092
2093 }  // namespace content