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.
5 #include "content/renderer/render_thread_impl.h"
12 #include "base/allocator/allocator_extension.h"
13 #include "base/command_line.h"
14 #include "base/lazy_instance.h"
15 #include "base/logging.h"
16 #include "base/memory/discardable_memory.h"
17 #include "base/memory/discardable_memory_emulated.h"
18 #include "base/memory/discardable_memory_shmem_allocator.h"
19 #include "base/memory/shared_memory.h"
20 #include "base/metrics/field_trial.h"
21 #include "base/metrics/histogram.h"
22 #include "base/metrics/stats_table.h"
23 #include "base/path_service.h"
24 #include "base/single_thread_task_runner.h"
25 #include "base/strings/string16.h"
26 #include "base/strings/string_number_conversions.h"
27 #include "base/strings/string_tokenizer.h"
28 #include "base/strings/sys_string_conversions.h"
29 #include "base/strings/utf_string_conversions.h"
30 #include "base/threading/thread_local.h"
31 #include "base/threading/thread_restrictions.h"
32 #include "base/trace_event/trace_event.h"
33 #include "base/values.h"
34 #include "cc/base/switches.h"
35 #include "cc/blink/web_external_bitmap_impl.h"
36 #include "cc/blink/web_layer_impl.h"
37 #include "cc/resources/tile_task_worker_pool.h"
38 #include "content/child/appcache/appcache_dispatcher.h"
39 #include "content/child/appcache/appcache_frontend_impl.h"
40 #include "content/child/child_discardable_shared_memory_manager.h"
41 #include "content/child/child_gpu_memory_buffer_manager.h"
42 #include "content/child/child_histogram_message_filter.h"
43 #include "content/child/child_resource_message_filter.h"
44 #include "content/child/child_shared_bitmap_manager.h"
45 #include "content/child/content_child_helpers.h"
46 #include "content/child/db_message_filter.h"
47 #include "content/child/indexed_db/indexed_db_dispatcher.h"
48 #include "content/child/indexed_db/indexed_db_message_filter.h"
49 #include "content/child/npapi/npobject_util.h"
50 #include "content/child/plugin_messages.h"
51 #include "content/child/resource_dispatcher.h"
52 #include "content/child/resource_scheduling_filter.h"
53 #include "content/child/runtime_features.h"
54 #include "content/child/thread_safe_sender.h"
55 #include "content/child/web_database_observer_impl.h"
56 #include "content/child/worker_task_runner.h"
57 #include "content/common/child_process_messages.h"
58 #include "content/common/content_constants_internal.h"
59 #include "content/common/database_messages.h"
60 #include "content/common/dom_storage/dom_storage_messages.h"
61 #include "content/common/frame_messages.h"
62 #include "content/common/gpu/client/context_provider_command_buffer.h"
63 #include "content/common/gpu/client/gpu_channel_host.h"
64 #include "content/common/gpu/gpu_messages.h"
65 #include "content/common/gpu/gpu_process_launch_causes.h"
66 #include "content/common/render_frame_setup.mojom.h"
67 #include "content/common/resource_messages.h"
68 #include "content/common/view_messages.h"
69 #include "content/common/worker_messages.h"
70 #include "content/public/common/content_constants.h"
71 #include "content/public/common/content_paths.h"
72 #include "content/public/common/content_switches.h"
73 #include "content/public/common/mojo_channel_switches.h"
74 #include "content/public/common/renderer_preferences.h"
75 #include "content/public/common/url_constants.h"
76 #include "content/public/renderer/content_renderer_client.h"
77 #include "content/public/renderer/render_process_observer.h"
78 #include "content/public/renderer/render_view_visitor.h"
79 #include "content/renderer/browser_plugin/browser_plugin_manager.h"
80 #include "content/renderer/devtools/devtools_agent_filter.h"
81 #include "content/renderer/devtools/v8_sampling_profiler.h"
82 #include "content/renderer/dom_storage/dom_storage_dispatcher.h"
83 #include "content/renderer/dom_storage/webstoragearea_impl.h"
84 #include "content/renderer/dom_storage/webstoragenamespace_impl.h"
85 #include "content/renderer/gpu/compositor_external_begin_frame_source.h"
86 #include "content/renderer/gpu/compositor_forwarding_message_filter.h"
87 #include "content/renderer/gpu/compositor_output_surface.h"
88 #include "content/renderer/input/input_event_filter.h"
89 #include "content/renderer/input/input_handler_manager.h"
90 #include "content/renderer/input/main_thread_input_event_filter.h"
91 #include "content/renderer/media/aec_dump_message_filter.h"
92 #include "content/renderer/media/audio_input_message_filter.h"
93 #include "content/renderer/media/audio_message_filter.h"
94 #include "content/renderer/media/audio_renderer_mixer_manager.h"
95 #include "content/renderer/media/media_stream_center.h"
96 #include "content/renderer/media/midi_message_filter.h"
97 #include "content/renderer/media/render_media_client.h"
98 #include "content/renderer/media/renderer_gpu_video_accelerator_factories.h"
99 #include "content/renderer/media/video_capture_impl_manager.h"
100 #include "content/renderer/media/video_capture_message_filter.h"
101 #include "content/renderer/net_info_helper.h"
102 #include "content/renderer/p2p/socket_dispatcher.h"
103 #include "content/renderer/render_frame_proxy.h"
104 #include "content/renderer/render_process_impl.h"
105 #include "content/renderer/render_view_impl.h"
106 #include "content/renderer/renderer_blink_platform_impl.h"
107 #include "content/renderer/scheduler/renderer_scheduler.h"
108 #include "content/renderer/service_worker/embedded_worker_context_message_filter.h"
109 #include "content/renderer/service_worker/embedded_worker_dispatcher.h"
110 #include "content/renderer/shared_worker/embedded_shared_worker_stub.h"
111 #include "gin/public/debug.h"
112 #include "gpu/GLES2/gl2extchromium.h"
113 #include "gpu/command_buffer/common/gles2_cmd_utils.h"
114 #include "ipc/ipc_channel_handle.h"
115 #include "ipc/ipc_platform_file.h"
116 #include "ipc/mojo/ipc_channel_mojo.h"
117 #include "media/base/audio_hardware_config.h"
118 #include "media/base/media.h"
119 #include "media/filters/gpu_video_accelerator_factories.h"
120 #include "mojo/common/common_type_converters.h"
121 #include "net/base/net_errors.h"
122 #include "net/base/net_util.h"
123 #include "skia/ext/event_tracer_impl.h"
124 #include "third_party/WebKit/public/platform/WebString.h"
125 #include "third_party/WebKit/public/platform/WebThread.h"
126 #include "third_party/WebKit/public/web/WebCache.h"
127 #include "third_party/WebKit/public/web/WebColorName.h"
128 #include "third_party/WebKit/public/web/WebDatabase.h"
129 #include "third_party/WebKit/public/web/WebDocument.h"
130 #include "third_party/WebKit/public/web/WebFrame.h"
131 #include "third_party/WebKit/public/web/WebImageCache.h"
132 #include "third_party/WebKit/public/web/WebKit.h"
133 #include "third_party/WebKit/public/web/WebNetworkStateNotifier.h"
134 #include "third_party/WebKit/public/web/WebPopupMenu.h"
135 #include "third_party/WebKit/public/web/WebRuntimeFeatures.h"
136 #include "third_party/WebKit/public/web/WebScriptController.h"
137 #include "third_party/WebKit/public/web/WebSecurityPolicy.h"
138 #include "third_party/WebKit/public/web/WebView.h"
139 #include "third_party/skia/include/core/SkGraphics.h"
140 #include "ui/base/layout.h"
141 #include "ui/base/ui_base_switches.h"
142 #include "v8/include/v8.h"
144 #if defined(OS_ANDROID)
145 #include <cpu-features.h>
146 #include "content/renderer/android/synchronous_compositor_factory.h"
147 #include "content/renderer/media/android/renderer_demuxer_android.h"
150 #if defined(OS_MACOSX)
151 #include "base/mac/mac_util.h"
152 #include "content/renderer/webscrollbarbehavior_impl_mac.h"
155 #if defined(OS_POSIX)
156 #include "ipc/ipc_channel_posix.h"
164 #include "content/child/npapi/np_channel_base.h"
167 #if defined(ENABLE_PLUGINS)
168 #include "content/renderer/npapi/plugin_channel_host.h"
171 #if defined(ENABLE_WEBRTC)
172 #include "content/renderer/media/peer_connection_tracker.h"
173 #include "content/renderer/media/rtc_peer_connection_handler.h"
174 #include "content/renderer/media/webrtc/peer_connection_dependency_factory.h"
175 #include "content/renderer/media/webrtc_identity_service.h"
178 #ifdef ENABLE_VTUNE_JIT_INTERFACE
179 #include "v8/src/third_party/vtune/v8-vtune.h"
182 using base::ThreadRestrictions
;
183 using blink::WebDocument
;
184 using blink::WebFrame
;
185 using blink::WebNetworkStateNotifier
;
186 using blink::WebRuntimeFeatures
;
187 using blink::WebScriptController
;
188 using blink::WebSecurityPolicy
;
189 using blink::WebString
;
190 using blink::WebView
;
196 const int64 kInitialIdleHandlerDelayMs
= 1000;
197 const int64 kLongIdleHandlerDelayMs
= 30*1000;
199 // Maximum allocation size allowed for image scaling filters that
200 // require pre-scaling. Skia will fallback to a filter that doesn't
201 // require pre-scaling if the default filter would require an
202 // allocation that exceeds this limit.
203 const size_t kImageCacheSingleAllocationByteLimit
= 64 * 1024 * 1024;
205 const size_t kEmulatedDiscardableMemoryBytesToKeepWhenWidgetsHidden
=
208 // Keep the global RenderThreadImpl in a TLS slot so it is impossible to access
209 // incorrectly from the wrong thread.
210 base::LazyInstance
<base::ThreadLocalPointer
<RenderThreadImpl
> >
211 lazy_tls
= LAZY_INSTANCE_INITIALIZER
;
213 class RenderViewZoomer
: public RenderViewVisitor
{
215 RenderViewZoomer(const std::string
& scheme
,
216 const std::string
& host
,
217 double zoom_level
) : scheme_(scheme
),
219 zoom_level_(zoom_level
) {
222 bool Visit(RenderView
* render_view
) override
{
223 WebView
* webview
= render_view
->GetWebView();
224 WebDocument document
= webview
->mainFrame()->document();
226 // Don't set zoom level for full-page plugin since they don't use the same
228 if (document
.isPluginDocument())
230 GURL
url(document
.url());
231 // Empty scheme works as wildcard that matches any scheme,
232 if ((net::GetHostOrSpecFromURL(url
) == host_
) &&
233 (scheme_
.empty() || scheme_
== url
.scheme()) &&
234 !static_cast<RenderViewImpl
*>(render_view
)
235 ->uses_temporary_zoom_level()) {
236 webview
->hidePopups();
237 webview
->setZoomLevel(zoom_level_
);
243 const std::string scheme_
;
244 const std::string host_
;
245 const double zoom_level_
;
247 DISALLOW_COPY_AND_ASSIGN(RenderViewZoomer
);
250 std::string
HostToCustomHistogramSuffix(const std::string
& host
) {
251 if (host
== "mail.google.com")
253 if (host
== "docs.google.com" || host
== "drive.google.com")
255 if (host
== "plus.google.com")
257 return std::string();
260 void* CreateHistogram(
261 const char *name
, int min
, int max
, size_t buckets
) {
264 std::string histogram_name
;
265 RenderThreadImpl
* render_thread_impl
= RenderThreadImpl::current();
266 if (render_thread_impl
) { // Can be null in tests.
267 histogram_name
= render_thread_impl
->
268 histogram_customizer()->ConvertToCustomHistogramName(name
);
270 histogram_name
= std::string(name
);
272 base::HistogramBase
* histogram
= base::Histogram::FactoryGet(
273 histogram_name
, min
, max
, buckets
,
274 base::Histogram::kUmaTargetedHistogramFlag
);
278 void AddHistogramSample(void* hist
, int sample
) {
279 base::Histogram
* histogram
= static_cast<base::Histogram
*>(hist
);
280 histogram
->Add(sample
);
283 scoped_ptr
<cc::SharedBitmap
> AllocateSharedBitmapFunction(
284 const gfx::Size
& size
) {
285 return ChildThreadImpl::current()->shared_bitmap_manager()->
286 AllocateSharedBitmap(size
);
289 void EnableBlinkPlatformLogChannels(const std::string
& channels
) {
290 if (channels
.empty())
292 base::StringTokenizer
t(channels
, ", ");
294 blink::enableLogChannel(t
.token().c_str());
297 void NotifyTimezoneChangeOnThisThread() {
298 v8::Isolate
* isolate
= v8::Isolate::GetCurrent();
301 v8::Date::DateTimeConfigurationChangeNotification(isolate
);
304 void LowMemoryNotificationOnThisThread() {
305 v8::Isolate
* isolate
= v8::Isolate::GetCurrent();
308 isolate
->LowMemoryNotification();
311 class RenderFrameSetupImpl
: public mojo::InterfaceImpl
<RenderFrameSetup
> {
313 RenderFrameSetupImpl()
314 : routing_id_highmark_(-1) {
317 void ExchangeServiceProviders(
318 int32_t frame_routing_id
,
319 mojo::InterfaceRequest
<mojo::ServiceProvider
> services
,
320 mojo::ServiceProviderPtr exposed_services
)
322 // TODO(morrita): This is for investigating http://crbug.com/415059 and
323 // should be removed once it is fixed.
324 CHECK_LT(routing_id_highmark_
, frame_routing_id
);
325 routing_id_highmark_
= frame_routing_id
;
327 RenderFrameImpl
* frame
= RenderFrameImpl::FromRoutingID(frame_routing_id
);
328 // We can receive a GetServiceProviderForFrame message for a frame not yet
329 // created due to a race between the message and a ViewMsg_New IPC that
330 // triggers creation of the RenderFrame we want.
332 RenderThreadImpl::current()->RegisterPendingRenderFrameConnect(
333 frame_routing_id
, services
.Pass(), exposed_services
.Pass());
337 frame
->BindServiceRegistry(services
.Pass(), exposed_services
.Pass());
341 int32_t routing_id_highmark_
;
344 void CreateRenderFrameSetup(mojo::InterfaceRequest
<RenderFrameSetup
> request
) {
345 mojo::BindToRequest(new RenderFrameSetupImpl(), &request
);
348 blink::WebGraphicsContext3D::Attributes
GetOffscreenAttribs() {
349 blink::WebGraphicsContext3D::Attributes attributes
;
350 attributes
.shareResources
= true;
351 attributes
.depth
= false;
352 attributes
.stencil
= false;
353 attributes
.antialias
= false;
354 attributes
.noAutomaticFlushes
= true;
360 // For measuring memory usage after each task. Behind a command line flag.
361 class MemoryObserver
: public base::MessageLoop::TaskObserver
{
364 ~MemoryObserver() override
{}
366 void WillProcessTask(const base::PendingTask
& pending_task
) override
{}
368 void DidProcessTask(const base::PendingTask
& pending_task
) override
{
369 LOCAL_HISTOGRAM_MEMORY_KB("Memory.RendererUsed", GetMemoryUsageKB());
373 DISALLOW_COPY_AND_ASSIGN(MemoryObserver
);
376 RenderThreadImpl::HistogramCustomizer::HistogramCustomizer() {
377 custom_histograms_
.insert("V8.MemoryExternalFragmentationTotal");
378 custom_histograms_
.insert("V8.MemoryHeapSampleTotalCommitted");
379 custom_histograms_
.insert("V8.MemoryHeapSampleTotalUsed");
382 RenderThreadImpl::HistogramCustomizer::~HistogramCustomizer() {}
384 void RenderThreadImpl::HistogramCustomizer::RenderViewNavigatedToHost(
385 const std::string
& host
, size_t view_count
) {
386 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
387 switches::kDisableHistogramCustomizer
)) {
390 // Check if all RenderViews are displaying a page from the same host. If there
391 // is only one RenderView, the common host is this view's host. If there are
392 // many, check if this one shares the common host of the other
393 // RenderViews. It's ok to not detect some cases where the RenderViews share a
394 // common host. This information is only used for producing custom histograms.
397 else if (host
!= common_host_
)
398 SetCommonHost(std::string());
401 std::string
RenderThreadImpl::HistogramCustomizer::ConvertToCustomHistogramName(
402 const char* histogram_name
) const {
403 std::string
name(histogram_name
);
404 if (!common_host_histogram_suffix_
.empty() &&
405 custom_histograms_
.find(name
) != custom_histograms_
.end())
406 name
+= common_host_histogram_suffix_
;
410 void RenderThreadImpl::HistogramCustomizer::SetCommonHost(
411 const std::string
& host
) {
412 if (host
!= common_host_
) {
414 common_host_histogram_suffix_
= HostToCustomHistogramSuffix(host
);
415 blink::mainThreadIsolate()->SetCreateHistogramFunction(CreateHistogram
);
419 RenderThreadImpl
* RenderThreadImpl::current() {
420 return lazy_tls
.Pointer()->Get();
423 // When we run plugins in process, we actually run them on the render thread,
424 // which means that we need to make the render thread pump UI events.
425 RenderThreadImpl::RenderThreadImpl()
426 : ChildThreadImpl(Options(ShouldUseMojoChannel())) {
430 RenderThreadImpl::RenderThreadImpl(const std::string
& channel_name
)
431 : ChildThreadImpl(Options(channel_name
, ShouldUseMojoChannel())) {
435 RenderThreadImpl::RenderThreadImpl(
436 scoped_ptr
<base::MessageLoop
> main_message_loop
)
437 : ChildThreadImpl(Options(ShouldUseMojoChannel())),
438 main_message_loop_(main_message_loop
.Pass()) {
442 void RenderThreadImpl::Init() {
443 TRACE_EVENT_BEGIN_ETW("RenderThreadImpl::Init", 0, "");
445 base::debug::TraceLog::GetInstance()->SetThreadSortIndex(
446 base::PlatformThread::CurrentId(),
447 kTraceEventRendererMainThreadSortIndex
);
449 #if defined(OS_MACOSX) || defined(OS_ANDROID)
450 // On Mac and Android, the select popups are rendered by the browser.
451 blink::WebView::setUseExternalPopupMenus(true);
454 lazy_tls
.Pointer()->Set(this);
456 // Register this object as the main thread.
457 ChildProcess::current()->set_main_thread(this);
459 // In single process the single process is all there is.
460 suspend_webkit_shared_timer_
= true;
461 notify_webkit_of_modal_loop_
= true;
462 webkit_shared_timer_suspended_
= false;
464 hidden_widget_count_
= 0;
465 idle_notification_delay_in_ms_
= kInitialIdleHandlerDelayMs
;
466 idle_notifications_to_skip_
= 0;
467 layout_test_mode_
= false;
469 appcache_dispatcher_
.reset(
470 new AppCacheDispatcher(Get(), new AppCacheFrontendImpl()));
471 dom_storage_dispatcher_
.reset(new DomStorageDispatcher());
472 main_thread_indexed_db_dispatcher_
.reset(new IndexedDBDispatcher(
473 thread_safe_sender()));
474 renderer_scheduler_
= RendererScheduler::Create();
475 channel()->SetListenerTaskRunner(renderer_scheduler_
->DefaultTaskRunner());
476 embedded_worker_dispatcher_
.reset(new EmbeddedWorkerDispatcher());
478 media_stream_center_
= NULL
;
480 db_message_filter_
= new DBMessageFilter();
481 AddFilter(db_message_filter_
.get());
483 vc_manager_
.reset(new VideoCaptureImplManager());
484 AddFilter(vc_manager_
->video_capture_message_filter());
486 browser_plugin_manager_
.reset(new BrowserPluginManager());
487 AddObserver(browser_plugin_manager_
.get());
489 #if defined(ENABLE_WEBRTC)
490 peer_connection_tracker_
.reset(new PeerConnectionTracker());
491 AddObserver(peer_connection_tracker_
.get());
493 p2p_socket_dispatcher_
=
494 new P2PSocketDispatcher(GetIOMessageLoopProxy().get());
495 AddFilter(p2p_socket_dispatcher_
.get());
497 webrtc_identity_service_
.reset(new WebRTCIdentityService());
499 aec_dump_message_filter_
=
500 new AecDumpMessageFilter(GetIOMessageLoopProxy(),
501 message_loop()->message_loop_proxy());
502 AddFilter(aec_dump_message_filter_
.get());
504 peer_connection_factory_
.reset(new PeerConnectionDependencyFactory(
505 p2p_socket_dispatcher_
.get()));
506 #endif // defined(ENABLE_WEBRTC)
508 audio_input_message_filter_
=
509 new AudioInputMessageFilter(GetIOMessageLoopProxy());
510 AddFilter(audio_input_message_filter_
.get());
512 audio_message_filter_
= new AudioMessageFilter(GetIOMessageLoopProxy());
513 AddFilter(audio_message_filter_
.get());
515 midi_message_filter_
= new MidiMessageFilter(GetIOMessageLoopProxy());
516 AddFilter(midi_message_filter_
.get());
518 AddFilter((new IndexedDBMessageFilter(thread_safe_sender()))->GetFilter());
520 AddFilter((new EmbeddedWorkerContextMessageFilter())->GetFilter());
522 GetContentClient()->renderer()->RenderThreadStarted();
524 InitSkiaEventTracer();
526 const base::CommandLine
& command_line
=
527 *base::CommandLine::ForCurrentProcess();
529 is_impl_side_painting_enabled_
=
530 !command_line
.HasSwitch(switches::kDisableImplSidePainting
);
531 cc_blink::WebLayerImpl::SetImplSidePaintingEnabled(
532 is_impl_side_painting_enabled_
);
534 is_zero_copy_enabled_
= command_line
.HasSwitch(switches::kEnableZeroCopy
);
535 is_one_copy_enabled_
= !command_line
.HasSwitch(switches::kDisableOneCopy
);
537 #if defined(OS_MACOSX) && !defined(OS_IOS)
538 is_elastic_overscroll_enabled_
=
539 !base::CommandLine::ForCurrentProcess()->HasSwitch(
540 switches::kDisableThreadedEventHandlingMac
) &&
541 base::mac::IsOSLionOrLater();
542 if (is_elastic_overscroll_enabled_
) {
543 base::ScopedCFTypeRef
<CFStringRef
> key(
544 base::SysUTF8ToCFStringRef("NSScrollViewRubberbanding"));
545 Boolean key_exists
= false;
546 Boolean value
= CFPreferencesGetAppBooleanValue(
547 key
, kCFPreferencesCurrentApplication
, &key_exists
);
548 if (key_exists
&& !value
)
549 is_elastic_overscroll_enabled_
= false;
552 is_elastic_overscroll_enabled_
= false;
555 use_image_texture_target_
= GL_TEXTURE_2D
;
556 if (command_line
.HasSwitch(switches::kUseImageTextureTarget
)) {
557 std::string target_string
=
558 command_line
.GetSwitchValueASCII(switches::kUseImageTextureTarget
);
559 const unsigned targets
[] = {
560 GL_TEXTURE_RECTANGLE_ARB
,
561 GL_TEXTURE_EXTERNAL_OES
563 for (auto target
: targets
) {
564 if (target_string
== gpu::gles2::GLES2Util::GetStringEnum(target
))
565 use_image_texture_target_
= target
;
569 if (command_line
.HasSwitch(switches::kDisableLCDText
)) {
570 is_lcd_text_enabled_
= false;
571 } else if (command_line
.HasSwitch(switches::kEnableLCDText
)) {
572 is_lcd_text_enabled_
= true;
574 #if defined(OS_ANDROID)
575 is_lcd_text_enabled_
= false;
577 is_lcd_text_enabled_
= true;
581 is_gpu_rasterization_enabled_
=
582 command_line
.HasSwitch(switches::kEnableGpuRasterization
);
583 is_gpu_rasterization_forced_
=
584 command_line
.HasSwitch(switches::kForceGpuRasterization
);
586 if (command_line
.HasSwitch(switches::kGpuRasterizationMSAASampleCount
)) {
587 std::string string_value
= command_line
.GetSwitchValueASCII(
588 switches::kGpuRasterizationMSAASampleCount
);
589 bool parsed_msaa_sample_count
=
590 base::StringToInt(string_value
, &gpu_rasterization_msaa_sample_count_
);
591 DCHECK(parsed_msaa_sample_count
) << string_value
;
592 DCHECK_GE(gpu_rasterization_msaa_sample_count_
, 0);
594 gpu_rasterization_msaa_sample_count_
= 0;
596 is_threaded_gpu_rasterization_enabled_
=
597 command_line
.HasSwitch(switches::kEnableThreadedGpuRasterization
);
599 if (command_line
.HasSwitch(switches::kDisableDistanceFieldText
)) {
600 is_distance_field_text_enabled_
= false;
601 } else if (command_line
.HasSwitch(switches::kEnableDistanceFieldText
)) {
602 is_distance_field_text_enabled_
= true;
604 is_distance_field_text_enabled_
= false;
607 // Note that under Linux, the media library will normally already have
608 // been initialized by the Zygote before this instance became a Renderer.
609 base::FilePath media_path
;
610 PathService::Get(DIR_MEDIA_LIBS
, &media_path
);
611 if (!media_path
.empty())
612 media::InitializeMediaLibrary(media_path
);
614 memory_pressure_listener_
.reset(new base::MemoryPressureListener(
615 base::Bind(&RenderThreadImpl::OnMemoryPressure
, base::Unretained(this))));
617 std::vector
<base::DiscardableMemoryType
> supported_types
;
618 base::DiscardableMemory::GetSupportedTypes(&supported_types
);
619 DCHECK(!supported_types
.empty());
621 // The default preferred type is always the first one in list.
622 base::DiscardableMemoryType type
= supported_types
[0];
624 if (command_line
.HasSwitch(switches::kUseDiscardableMemory
)) {
625 std::string requested_type_name
= command_line
.GetSwitchValueASCII(
626 switches::kUseDiscardableMemory
);
627 base::DiscardableMemoryType requested_type
=
628 base::DiscardableMemory::GetNamedType(requested_type_name
);
629 if (std::find(supported_types
.begin(),
630 supported_types
.end(),
631 requested_type
) != supported_types
.end()) {
632 type
= requested_type
;
634 LOG(ERROR
) << "Requested discardable memory type is not supported.";
638 base::DiscardableMemory::SetPreferredType(type
);
640 if (is_impl_side_painting_enabled_
) {
641 int num_raster_threads
= 0;
642 std::string string_value
=
643 command_line
.GetSwitchValueASCII(switches::kNumRasterThreads
);
644 bool parsed_num_raster_threads
=
645 base::StringToInt(string_value
, &num_raster_threads
);
646 DCHECK(parsed_num_raster_threads
) << string_value
;
647 DCHECK_GT(num_raster_threads
, 0);
648 cc::TileTaskWorkerPool::SetNumWorkerThreads(num_raster_threads
);
650 #if defined(OS_ANDROID) || defined(OS_LINUX)
651 if (!command_line
.HasSwitch(
652 switches::kUseNormalPriorityForTileTaskWorkerThreads
)) {
653 cc::TileTaskWorkerPool::SetWorkerThreadPriority(
654 base::kThreadPriority_Background
);
659 base::DiscardableMemoryShmemAllocator::SetInstance(
660 ChildThreadImpl::discardable_shared_memory_manager());
662 service_registry()->AddService
<RenderFrameSetup
>(
663 base::Bind(CreateRenderFrameSetup
));
665 TRACE_EVENT_END_ETW("RenderThreadImpl::Init", 0, "");
668 RenderThreadImpl::~RenderThreadImpl() {
671 void RenderThreadImpl::Shutdown() {
673 RenderProcessObserver
, observers_
, OnRenderProcessShutdown());
675 ChildThreadImpl::Shutdown();
677 if (memory_observer_
) {
678 message_loop()->RemoveTaskObserver(memory_observer_
.get());
679 memory_observer_
.reset();
682 // Wait for all databases to be closed.
683 if (blink_platform_impl_
) {
684 // WaitForAllDatabasesToClose might run a nested message loop. To avoid
685 // processing timer events while we're already in the process of shutting
686 // down blink, put a ScopePageLoadDeferrer on the stack.
687 WebView::willEnterModalLoop();
688 blink_platform_impl_
->web_database_observer_impl()
689 ->WaitForAllDatabasesToClose();
690 WebView::didExitModalLoop();
693 // Shutdown in reverse of the initialization order.
694 if (devtools_agent_message_filter_
.get()) {
695 RemoveFilter(devtools_agent_message_filter_
.get());
696 devtools_agent_message_filter_
= NULL
;
699 RemoveFilter(audio_input_message_filter_
.get());
700 audio_input_message_filter_
= NULL
;
702 #if defined(ENABLE_WEBRTC)
703 RTCPeerConnectionHandler::DestructAllHandlers();
704 // |peer_connection_factory_| cannot be deleted until after the main message
705 // loop has been destroyed. This is because there may be pending tasks that
706 // hold on to objects produced by the PC factory that depend on threads owned
707 // by the PC factory. Once those tasks have been freed, the factory can be
710 RemoveFilter(vc_manager_
->video_capture_message_filter());
713 RemoveFilter(db_message_filter_
.get());
714 db_message_filter_
= NULL
;
716 // Shutdown the file thread if it's running.
718 file_thread_
->Stop();
720 if (compositor_message_filter_
.get()) {
721 RemoveFilter(compositor_message_filter_
.get());
722 compositor_message_filter_
= NULL
;
725 media_thread_
.reset();
727 // AudioMessageFilter may be accessed on |media_thread_|, so shutdown after.
728 RemoveFilter(audio_message_filter_
.get());
729 audio_message_filter_
= NULL
;
731 compositor_thread_
.reset();
733 main_input_callback_
.Cancel();
734 input_handler_manager_
.reset();
735 if (input_event_filter_
.get()) {
736 RemoveFilter(input_event_filter_
.get());
737 input_event_filter_
= NULL
;
740 // RemoveEmbeddedWorkerRoute may be called while deleting
741 // EmbeddedWorkerDispatcher. So it must be deleted before deleting
743 embedded_worker_dispatcher_
.reset();
745 // Ramp down IDB before we ramp down WebKit (and V8), since IDB classes might
746 // hold pointers to V8 objects (e.g., via pending requests).
747 main_thread_indexed_db_dispatcher_
.reset();
749 main_thread_compositor_task_runner_
= NULL
;
751 if (gpu_channel_
.get())
752 gpu_channel_
->DestroyChannel();
756 // Clean up plugin channels before this thread goes away.
757 NPChannelBase::CleanupChannels();
760 // Shut down the message loop before shutting down Blink.
761 // This prevents a scenario where a pending task in the message loop accesses
762 // Blink objects after Blink shuts down.
763 // This must be at the very end of the shutdown sequence. You must not touch
764 // the message loop after this.
765 main_message_loop_
.reset();
766 if (blink_platform_impl_
)
769 lazy_tls
.Pointer()->Set(NULL
);
772 bool RenderThreadImpl::Send(IPC::Message
* msg
) {
773 // Certain synchronous messages cannot always be processed synchronously by
774 // the browser, e.g., putting up UI and waiting for the user. This could cause
775 // a complete hang of Chrome if a windowed plug-in is trying to communicate
776 // with the renderer thread since the browser's UI thread could be stuck
777 // (within a Windows API call) trying to synchronously communicate with the
778 // plug-in. The remedy is to pump messages on this thread while the browser
779 // is processing this request. This creates an opportunity for re-entrancy
780 // into WebKit, so we need to take care to disable callbacks, timers, and
781 // pending network loads that could trigger such callbacks.
782 bool pumping_events
= false;
783 if (msg
->is_sync()) {
784 if (msg
->is_caller_pumping_messages()) {
785 pumping_events
= true;
789 bool suspend_webkit_shared_timer
= true; // default value
790 std::swap(suspend_webkit_shared_timer
, suspend_webkit_shared_timer_
);
792 bool notify_webkit_of_modal_loop
= true; // default value
793 std::swap(notify_webkit_of_modal_loop
, notify_webkit_of_modal_loop_
);
795 #if defined(ENABLE_PLUGINS)
796 int render_view_id
= MSG_ROUTING_NONE
;
799 if (pumping_events
) {
800 if (suspend_webkit_shared_timer
)
801 blink_platform_impl_
->SuspendSharedTimer();
803 if (notify_webkit_of_modal_loop
)
804 WebView::willEnterModalLoop();
805 #if defined(ENABLE_PLUGINS)
806 RenderViewImpl
* render_view
=
807 RenderViewImpl::FromRoutingID(msg
->routing_id());
809 render_view_id
= msg
->routing_id();
810 PluginChannelHost::Broadcast(
811 new PluginMsg_SignalModalDialogEvent(render_view_id
));
816 bool rv
= ChildThreadImpl::Send(msg
);
818 if (pumping_events
) {
819 #if defined(ENABLE_PLUGINS)
820 if (render_view_id
!= MSG_ROUTING_NONE
) {
821 PluginChannelHost::Broadcast(
822 new PluginMsg_ResetModalDialogEvent(render_view_id
));
826 if (notify_webkit_of_modal_loop
)
827 WebView::didExitModalLoop();
829 if (suspend_webkit_shared_timer
)
830 blink_platform_impl_
->ResumeSharedTimer();
836 scoped_refptr
<base::SingleThreadTaskRunner
> RenderThreadImpl::GetTaskRunner() {
837 return GetRendererScheduler()->DefaultTaskRunner();
840 IPC::SyncChannel
* RenderThreadImpl::GetChannel() {
844 std::string
RenderThreadImpl::GetLocale() {
845 // The browser process should have passed the locale to the renderer via the
846 // --lang command line flag.
847 const base::CommandLine
& parsed_command_line
=
848 *base::CommandLine::ForCurrentProcess();
849 const std::string
& lang
=
850 parsed_command_line
.GetSwitchValueASCII(switches::kLang
);
851 DCHECK(!lang
.empty());
855 IPC::SyncMessageFilter
* RenderThreadImpl::GetSyncMessageFilter() {
856 return sync_message_filter();
859 scoped_refptr
<base::MessageLoopProxy
>
860 RenderThreadImpl::GetIOMessageLoopProxy() {
861 return ChildProcess::current()->io_message_loop_proxy();
864 void RenderThreadImpl::AddRoute(int32 routing_id
, IPC::Listener
* listener
) {
865 ChildThreadImpl::GetRouter()->AddRoute(routing_id
, listener
);
866 PendingRenderFrameConnectMap::iterator it
=
867 pending_render_frame_connects_
.find(routing_id
);
868 if (it
== pending_render_frame_connects_
.end())
871 RenderFrameImpl
* frame
= RenderFrameImpl::FromRoutingID(routing_id
);
875 scoped_refptr
<PendingRenderFrameConnect
> connection(it
->second
);
876 mojo::InterfaceRequest
<mojo::ServiceProvider
> services(
877 connection
->services
.Pass());
878 mojo::ServiceProviderPtr
exposed_services(
879 connection
->exposed_services
.Pass());
880 pending_render_frame_connects_
.erase(it
);
882 frame
->BindServiceRegistry(services
.Pass(), exposed_services
.Pass());
885 void RenderThreadImpl::RemoveRoute(int32 routing_id
) {
886 ChildThreadImpl::GetRouter()->RemoveRoute(routing_id
);
889 void RenderThreadImpl::AddEmbeddedWorkerRoute(int32 routing_id
,
890 IPC::Listener
* listener
) {
891 AddRoute(routing_id
, listener
);
892 if (devtools_agent_message_filter_
.get()) {
893 devtools_agent_message_filter_
->AddEmbeddedWorkerRouteOnMainThread(
898 void RenderThreadImpl::RemoveEmbeddedWorkerRoute(int32 routing_id
) {
899 RemoveRoute(routing_id
);
900 if (devtools_agent_message_filter_
.get()) {
901 devtools_agent_message_filter_
->RemoveEmbeddedWorkerRouteOnMainThread(
906 void RenderThreadImpl::RegisterPendingRenderFrameConnect(
908 mojo::InterfaceRequest
<mojo::ServiceProvider
> services
,
909 mojo::ServiceProviderPtr exposed_services
) {
910 std::pair
<PendingRenderFrameConnectMap::iterator
, bool> result
=
911 pending_render_frame_connects_
.insert(std::make_pair(
913 make_scoped_refptr(new PendingRenderFrameConnect(
915 exposed_services
.Pass()))));
916 CHECK(result
.second
) << "Inserting a duplicate item.";
919 int RenderThreadImpl::GenerateRoutingID() {
920 int routing_id
= MSG_ROUTING_NONE
;
921 Send(new ViewHostMsg_GenerateRoutingID(&routing_id
));
925 void RenderThreadImpl::AddFilter(IPC::MessageFilter
* filter
) {
926 channel()->AddFilter(filter
);
929 void RenderThreadImpl::RemoveFilter(IPC::MessageFilter
* filter
) {
930 channel()->RemoveFilter(filter
);
933 void RenderThreadImpl::AddObserver(RenderProcessObserver
* observer
) {
934 observers_
.AddObserver(observer
);
937 void RenderThreadImpl::RemoveObserver(RenderProcessObserver
* observer
) {
938 observers_
.RemoveObserver(observer
);
941 void RenderThreadImpl::SetResourceDispatcherDelegate(
942 ResourceDispatcherDelegate
* delegate
) {
943 resource_dispatcher()->set_delegate(delegate
);
946 void RenderThreadImpl::SetResourceDispatchTaskQueue(
947 const scoped_refptr
<base::SingleThreadTaskRunner
>& resource_task_queue
) {
948 // Add a filter that forces resource messages to be dispatched via a
949 // particular task runner.
950 resource_scheduling_filter_
=
951 new ResourceSchedulingFilter(resource_task_queue
, resource_dispatcher());
952 channel()->AddFilter(resource_scheduling_filter_
.get());
954 // The ChildResourceMessageFilter and the ResourceDispatcher need to use the
955 // same queue to ensure tasks are executed in the expected order.
956 child_resource_message_filter()->SetMainThreadTaskRunner(resource_task_queue
);
957 resource_dispatcher()->SetMainThreadTaskRunner(resource_task_queue
);
960 void RenderThreadImpl::EnsureWebKitInitialized() {
961 if (blink_platform_impl_
)
964 const base::CommandLine
& command_line
=
965 *base::CommandLine::ForCurrentProcess();
967 #ifdef ENABLE_VTUNE_JIT_INTERFACE
968 if (command_line
.HasSwitch(switches::kEnableVtune
))
969 gin::Debug::SetJitCodeEventHandler(vTune::GetVtuneCodeEventHandler());
972 SetRuntimeFeaturesDefaultsAndUpdateFromArgs(command_line
);
974 blink_platform_impl_
.reset(
975 new RendererBlinkPlatformImpl(renderer_scheduler_
.get()));
976 blink::initialize(blink_platform_impl_
.get());
978 v8::Isolate
* isolate
= blink::mainThreadIsolate();
980 isolate
->SetCounterFunction(base::StatsTable::FindLocation
);
981 isolate
->SetCreateHistogramFunction(CreateHistogram
);
982 isolate
->SetAddHistogramSampleFunction(AddHistogramSample
);
984 main_thread_compositor_task_runner_
=
985 renderer_scheduler_
->CompositorTaskRunner();
987 main_input_callback_
.Reset(
988 base::Bind(base::IgnoreResult(&RenderThreadImpl::OnMessageReceived
),
989 base::Unretained(this)));
991 SetResourceDispatchTaskQueue(renderer_scheduler_
->LoadingTaskRunner());
993 bool enable
= !command_line
.HasSwitch(switches::kDisableThreadedCompositing
);
995 #if defined(OS_ANDROID)
996 if (SynchronousCompositorFactory
* factory
=
997 SynchronousCompositorFactory::GetInstance())
998 compositor_message_loop_proxy_
=
999 factory
->GetCompositorMessageLoop();
1001 if (!compositor_message_loop_proxy_
.get()) {
1002 compositor_thread_
.reset(new base::Thread("Compositor"));
1003 compositor_thread_
->Start();
1004 #if defined(OS_ANDROID)
1005 compositor_thread_
->SetPriority(base::kThreadPriority_Display
);
1007 compositor_message_loop_proxy_
=
1008 compositor_thread_
->message_loop_proxy();
1009 compositor_message_loop_proxy_
->PostTask(
1011 base::Bind(base::IgnoreResult(&ThreadRestrictions::SetIOAllowed
),
1015 InputHandlerManagerClient
* input_handler_manager_client
= NULL
;
1016 #if defined(OS_ANDROID)
1017 if (SynchronousCompositorFactory
* factory
=
1018 SynchronousCompositorFactory::GetInstance()) {
1019 input_handler_manager_client
= factory
->GetInputHandlerManagerClient();
1022 if (!input_handler_manager_client
) {
1023 scoped_refptr
<InputEventFilter
> compositor_input_event_filter(
1024 new InputEventFilter(main_input_callback_
.callback(),
1025 main_thread_compositor_task_runner_
,
1026 compositor_message_loop_proxy_
));
1027 input_handler_manager_client
= compositor_input_event_filter
.get();
1028 input_event_filter_
= compositor_input_event_filter
;
1030 input_handler_manager_
.reset(new InputHandlerManager(
1031 compositor_message_loop_proxy_
, input_handler_manager_client
,
1032 renderer_scheduler_
.get()));
1035 if (!input_event_filter_
.get()) {
1036 // Always provide an input event filter implementation to ensure consistent
1037 // input event scheduling and prioritization.
1038 // TODO(jdduke): Merge InputEventFilter, InputHandlerManager and
1039 // MainThreadInputEventFilter, crbug.com/436057.
1040 input_event_filter_
= new MainThreadInputEventFilter(
1041 main_input_callback_
.callback(), main_thread_compositor_task_runner_
);
1043 AddFilter(input_event_filter_
.get());
1045 scoped_refptr
<base::MessageLoopProxy
> compositor_impl_side_loop
;
1047 compositor_impl_side_loop
= compositor_message_loop_proxy_
;
1049 compositor_impl_side_loop
= base::MessageLoopProxy::current();
1051 compositor_message_filter_
= new CompositorForwardingMessageFilter(
1052 compositor_impl_side_loop
.get());
1053 AddFilter(compositor_message_filter_
.get());
1055 RenderThreadImpl::RegisterSchemes();
1057 EnableBlinkPlatformLogChannels(
1058 command_line
.GetSwitchValueASCII(switches::kBlinkPlatformLogChannels
));
1060 if (!media::IsMediaLibraryInitialized()) {
1061 WebRuntimeFeatures::enableWebAudio(false);
1064 RenderMediaClient::Initialize();
1066 FOR_EACH_OBSERVER(RenderProcessObserver
, observers_
, WebKitInitialized());
1068 devtools_agent_message_filter_
= new DevToolsAgentFilter();
1069 AddFilter(devtools_agent_message_filter_
.get());
1071 v8_sampling_profiler_
.reset(new V8SamplingProfiler());
1073 if (GetContentClient()->renderer()->RunIdleHandlerWhenWidgetsHidden())
1074 ScheduleIdleHandler(kLongIdleHandlerDelayMs
);
1076 cc_blink::SetSharedBitmapAllocationFunction(AllocateSharedBitmapFunction
);
1078 // Limit use of the scaled image cache to when deferred image decoding is
1080 if (!command_line
.HasSwitch(switches::kEnableDeferredImageDecoding
) &&
1081 !is_impl_side_painting_enabled_
)
1082 SkGraphics::SetResourceCacheTotalByteLimit(0u);
1084 SkGraphics::SetResourceCacheSingleAllocationByteLimit(
1085 kImageCacheSingleAllocationByteLimit
);
1087 if (command_line
.HasSwitch(switches::kMemoryMetrics
)) {
1088 memory_observer_
.reset(new MemoryObserver());
1089 message_loop()->AddTaskObserver(memory_observer_
.get());
1093 void RenderThreadImpl::RegisterSchemes() {
1094 // swappedout: pages should not be accessible, and should also
1095 // be treated as empty documents that can commit synchronously.
1096 WebString
swappedout_scheme(base::ASCIIToUTF16(kSwappedOutScheme
));
1097 WebSecurityPolicy::registerURLSchemeAsDisplayIsolated(swappedout_scheme
);
1098 WebSecurityPolicy::registerURLSchemeAsEmptyDocument(swappedout_scheme
);
1101 void RenderThreadImpl::NotifyTimezoneChange() {
1102 NotifyTimezoneChangeOnThisThread();
1103 RenderThread::Get()->PostTaskToAllWebWorkers(
1104 base::Bind(&NotifyTimezoneChangeOnThisThread
));
1107 void RenderThreadImpl::RecordAction(const base::UserMetricsAction
& action
) {
1108 Send(new ViewHostMsg_UserMetricsRecordAction(action
.str_
));
1111 void RenderThreadImpl::RecordComputedAction(const std::string
& action
) {
1112 Send(new ViewHostMsg_UserMetricsRecordAction(action
));
1115 scoped_ptr
<base::SharedMemory
>
1116 RenderThreadImpl::HostAllocateSharedMemoryBuffer(size_t size
) {
1117 return ChildThreadImpl::AllocateSharedMemory(size
, thread_safe_sender());
1120 cc::SharedBitmapManager
* RenderThreadImpl::GetSharedBitmapManager() {
1121 return shared_bitmap_manager();
1124 void RenderThreadImpl::RegisterExtension(v8::Extension
* extension
) {
1125 WebScriptController::registerExtension(extension
);
1128 void RenderThreadImpl::ScheduleIdleHandler(int64 initial_delay_ms
) {
1129 idle_notification_delay_in_ms_
= initial_delay_ms
;
1131 idle_timer_
.Start(FROM_HERE
,
1132 base::TimeDelta::FromMilliseconds(initial_delay_ms
),
1133 this, &RenderThreadImpl::IdleHandler
);
1136 void RenderThreadImpl::IdleHandler() {
1137 bool run_in_foreground_tab
= (widget_count_
> hidden_widget_count_
) &&
1138 GetContentClient()->renderer()->
1139 RunIdleHandlerWhenWidgetsHidden();
1140 if (run_in_foreground_tab
) {
1141 if (idle_notifications_to_skip_
> 0) {
1142 --idle_notifications_to_skip_
;
1144 base::allocator::ReleaseFreeMemory();
1145 base::DiscardableMemory::ReduceMemoryUsage();
1147 ScheduleIdleHandler(kLongIdleHandlerDelayMs
);
1151 base::allocator::ReleaseFreeMemory();
1152 base::DiscardableMemory::ReleaseFreeMemory();
1154 // Continue the idle timer if the webkit shared timer is not suspended or
1155 // something is left to do.
1156 bool continue_timer
= !webkit_shared_timer_suspended_
;
1158 if (blink::mainThreadIsolate() &&
1159 !blink::mainThreadIsolate()->IdleNotification(1000)) {
1160 continue_timer
= true;
1162 if (!base::DiscardableMemory::ReduceMemoryUsage()) {
1163 continue_timer
= true;
1166 // Schedule next invocation. When the tab is originally hidden, an invocation
1167 // is scheduled for kInitialIdleHandlerDelayMs in
1168 // RenderThreadImpl::WidgetHidden in order to race to a minimal heap.
1169 // After that, idle calls can be much less frequent, so run at a maximum of
1170 // once every kLongIdleHandlerDelayMs.
1171 // Dampen the delay using the algorithm (if delay is in seconds):
1172 // delay = delay + 1 / (delay + 2)
1173 // Using floor(delay) has a dampening effect such as:
1174 // 30s, 30, 30, 31, 31, 31, 31, 32, 32, ...
1175 // If the delay is in milliseconds, the above formula is equivalent to:
1176 // delay_ms / 1000 = delay_ms / 1000 + 1 / (delay_ms / 1000 + 2)
1177 // which is equivalent to
1178 // delay_ms = delay_ms + 1000*1000 / (delay_ms + 2000).
1179 if (continue_timer
) {
1180 ScheduleIdleHandler(
1181 std::max(kLongIdleHandlerDelayMs
,
1182 idle_notification_delay_in_ms_
+
1183 1000000 / (idle_notification_delay_in_ms_
+ 2000)));
1189 FOR_EACH_OBSERVER(RenderProcessObserver
, observers_
, IdleNotification());
1192 int64
RenderThreadImpl::GetIdleNotificationDelayInMs() const {
1193 return idle_notification_delay_in_ms_
;
1196 void RenderThreadImpl::SetIdleNotificationDelayInMs(
1197 int64 idle_notification_delay_in_ms
) {
1198 idle_notification_delay_in_ms_
= idle_notification_delay_in_ms
;
1201 void RenderThreadImpl::UpdateHistograms(int sequence_number
) {
1202 child_histogram_message_filter()->SendHistograms(sequence_number
);
1205 int RenderThreadImpl::PostTaskToAllWebWorkers(const base::Closure
& closure
) {
1206 return WorkerTaskRunner::Instance()->PostTaskToAllThreads(closure
);
1209 bool RenderThreadImpl::ResolveProxy(const GURL
& url
, std::string
* proxy_list
) {
1210 bool result
= false;
1211 Send(new ViewHostMsg_ResolveProxy(url
, &result
, proxy_list
));
1215 void RenderThreadImpl::PostponeIdleNotification() {
1216 idle_notifications_to_skip_
= 2;
1219 scoped_refptr
<media::GpuVideoAcceleratorFactories
>
1220 RenderThreadImpl::GetGpuFactories() {
1221 DCHECK(IsMainThread());
1223 scoped_refptr
<GpuChannelHost
> gpu_channel_host
= GetGpuChannel();
1224 const base::CommandLine
* cmd_line
= base::CommandLine::ForCurrentProcess();
1225 scoped_refptr
<media::GpuVideoAcceleratorFactories
> gpu_factories
;
1226 scoped_refptr
<base::SingleThreadTaskRunner
> media_task_runner
=
1227 GetMediaThreadTaskRunner();
1228 if (!cmd_line
->HasSwitch(switches::kDisableAcceleratedVideoDecode
)) {
1229 if (!gpu_va_context_provider_
.get() ||
1230 gpu_va_context_provider_
->DestroyedOnMainThread()) {
1231 if (!gpu_channel_host
.get()) {
1232 gpu_channel_host
= EstablishGpuChannelSync(
1233 CAUSE_FOR_GPU_LAUNCH_WEBGRAPHICSCONTEXT3DCOMMANDBUFFERIMPL_INITIALIZE
);
1235 blink::WebGraphicsContext3D::Attributes attributes
;
1236 bool lose_context_when_out_of_memory
= false;
1237 gpu_va_context_provider_
= ContextProviderCommandBuffer::Create(
1239 WebGraphicsContext3DCommandBufferImpl::CreateOffscreenContext(
1240 gpu_channel_host
.get(),
1242 lose_context_when_out_of_memory
,
1243 GURL("chrome://gpu/RenderThreadImpl::GetGpuVDAContext3D"),
1244 WebGraphicsContext3DCommandBufferImpl::SharedMemoryLimits(),
1246 "GPU-VideoAccelerator-Offscreen");
1249 if (gpu_va_context_provider_
.get()) {
1250 gpu_factories
= RendererGpuVideoAcceleratorFactories::Create(
1251 gpu_channel_host
.get(), media_task_runner
, gpu_va_context_provider_
);
1253 return gpu_factories
;
1256 scoped_ptr
<WebGraphicsContext3DCommandBufferImpl
>
1257 RenderThreadImpl::CreateOffscreenContext3d() {
1258 blink::WebGraphicsContext3D::Attributes
attributes(GetOffscreenAttribs());
1259 bool lose_context_when_out_of_memory
= true;
1261 scoped_refptr
<GpuChannelHost
> gpu_channel_host(EstablishGpuChannelSync(
1262 CAUSE_FOR_GPU_LAUNCH_WEBGRAPHICSCONTEXT3DCOMMANDBUFFERIMPL_INITIALIZE
));
1263 return make_scoped_ptr(
1264 WebGraphicsContext3DCommandBufferImpl::CreateOffscreenContext(
1265 gpu_channel_host
.get(),
1267 lose_context_when_out_of_memory
,
1268 GURL("chrome://gpu/RenderThreadImpl::CreateOffscreenContext3d"),
1269 WebGraphicsContext3DCommandBufferImpl::SharedMemoryLimits(),
1273 scoped_refptr
<cc_blink::ContextProviderWebContext
>
1274 RenderThreadImpl::SharedMainThreadContextProvider() {
1275 DCHECK(IsMainThread());
1276 if (!shared_main_thread_contexts_
.get() ||
1277 shared_main_thread_contexts_
->DestroyedOnMainThread()) {
1278 shared_main_thread_contexts_
= NULL
;
1279 #if defined(OS_ANDROID)
1280 if (SynchronousCompositorFactory
* factory
=
1281 SynchronousCompositorFactory::GetInstance()) {
1282 shared_main_thread_contexts_
= factory
->CreateOffscreenContextProvider(
1283 GetOffscreenAttribs(), "Offscreen-MainThread");
1286 if (!shared_main_thread_contexts_
.get()) {
1287 shared_main_thread_contexts_
= ContextProviderCommandBuffer::Create(
1288 CreateOffscreenContext3d(), "Offscreen-MainThread");
1290 if (shared_main_thread_contexts_
.get() &&
1291 !shared_main_thread_contexts_
->BindToCurrentThread())
1292 shared_main_thread_contexts_
= NULL
;
1294 return shared_main_thread_contexts_
;
1297 AudioRendererMixerManager
* RenderThreadImpl::GetAudioRendererMixerManager() {
1298 if (!audio_renderer_mixer_manager_
) {
1299 audio_renderer_mixer_manager_
.reset(new AudioRendererMixerManager(
1300 GetAudioHardwareConfig()));
1303 return audio_renderer_mixer_manager_
.get();
1306 media::AudioHardwareConfig
* RenderThreadImpl::GetAudioHardwareConfig() {
1307 if (!audio_hardware_config_
) {
1308 media::AudioParameters input_params
;
1309 media::AudioParameters output_params
;
1310 Send(new ViewHostMsg_GetAudioHardwareConfig(
1311 &input_params
, &output_params
));
1313 audio_hardware_config_
.reset(new media::AudioHardwareConfig(
1314 input_params
, output_params
));
1315 audio_message_filter_
->SetAudioHardwareConfig(audio_hardware_config_
.get());
1318 return audio_hardware_config_
.get();
1321 base::WaitableEvent
* RenderThreadImpl::GetShutdownEvent() {
1322 return ChildProcess::current()->GetShutDownEvent();
1326 void RenderThreadImpl::PreCacheFontCharacters(const LOGFONT
& log_font
,
1327 const base::string16
& str
) {
1328 Send(new ViewHostMsg_PreCacheFontCharacters(log_font
, str
));
1333 ServiceRegistry
* RenderThreadImpl::GetServiceRegistry() {
1334 return service_registry();
1337 bool RenderThreadImpl::IsImplSidePaintingEnabled() {
1338 return is_impl_side_painting_enabled_
;
1341 bool RenderThreadImpl::IsGpuRasterizationForced() {
1342 return is_gpu_rasterization_forced_
;
1345 bool RenderThreadImpl::IsGpuRasterizationEnabled() {
1346 return is_gpu_rasterization_enabled_
;
1349 bool RenderThreadImpl::IsThreadedGpuRasterizationEnabled() {
1350 return is_threaded_gpu_rasterization_enabled_
;
1353 int RenderThreadImpl::GetGpuRasterizationMSAASampleCount() {
1354 return gpu_rasterization_msaa_sample_count_
;
1357 bool RenderThreadImpl::IsLcdTextEnabled() {
1358 return is_lcd_text_enabled_
;
1361 bool RenderThreadImpl::IsDistanceFieldTextEnabled() {
1362 return is_distance_field_text_enabled_
;
1365 bool RenderThreadImpl::IsZeroCopyEnabled() {
1366 return is_zero_copy_enabled_
;
1369 bool RenderThreadImpl::IsOneCopyEnabled() {
1370 return is_one_copy_enabled_
;
1373 bool RenderThreadImpl::IsElasticOverscrollEnabled() {
1374 return is_elastic_overscroll_enabled_
;
1377 bool RenderThreadImpl::UseSingleThreadScheduler() {
1378 base::CommandLine
* cmd
= base::CommandLine::ForCurrentProcess();
1379 return !cmd
->HasSwitch(switches::kDisableSingleThreadProxyScheduler
);
1382 uint32
RenderThreadImpl::GetImageTextureTarget() {
1383 return use_image_texture_target_
;
1386 scoped_refptr
<base::SingleThreadTaskRunner
>
1387 RenderThreadImpl::GetCompositorMainThreadTaskRunner() {
1388 return main_thread_compositor_task_runner_
;
1391 scoped_refptr
<base::SingleThreadTaskRunner
>
1392 RenderThreadImpl::GetCompositorImplThreadTaskRunner() {
1393 return compositor_message_loop_proxy_
;
1396 gpu::GpuMemoryBufferManager
* RenderThreadImpl::GetGpuMemoryBufferManager() {
1397 return gpu_memory_buffer_manager();
1400 RendererScheduler
* RenderThreadImpl::GetRendererScheduler() {
1401 return renderer_scheduler_
.get();
1404 cc::ContextProvider
* RenderThreadImpl::GetSharedMainThreadContextProvider() {
1405 return SharedMainThreadContextProvider().get();
1408 scoped_ptr
<cc::BeginFrameSource
>
1409 RenderThreadImpl::CreateExternalBeginFrameSource(int routing_id
) {
1410 #if defined(OS_ANDROID)
1411 if (SynchronousCompositorFactory
* factory
=
1412 SynchronousCompositorFactory::GetInstance()) {
1413 return factory
->CreateExternalBeginFrameSource(routing_id
);
1416 return make_scoped_ptr(new CompositorExternalBeginFrameSource(
1417 compositor_message_filter_
.get(), sync_message_filter(), routing_id
));
1420 bool RenderThreadImpl::IsMainThread() {
1424 base::MessageLoop
* RenderThreadImpl::GetMainLoop() {
1425 return message_loop();
1428 scoped_refptr
<base::MessageLoopProxy
> RenderThreadImpl::GetIOLoopProxy() {
1429 return io_message_loop_proxy_
;
1432 scoped_ptr
<base::SharedMemory
> RenderThreadImpl::AllocateSharedMemory(
1434 return scoped_ptr
<base::SharedMemory
>(
1435 HostAllocateSharedMemoryBuffer(size
));
1438 CreateCommandBufferResult
RenderThreadImpl::CreateViewCommandBuffer(
1440 const GPUCreateCommandBufferConfig
& init_params
,
1443 "RenderThreadImpl::CreateViewCommandBuffer",
1447 CreateCommandBufferResult result
= CREATE_COMMAND_BUFFER_FAILED
;
1448 IPC::Message
* message
= new GpuHostMsg_CreateViewCommandBuffer(
1454 // Allow calling this from the compositor thread.
1455 thread_safe_sender()->Send(message
);
1460 void RenderThreadImpl::DoNotSuspendWebKitSharedTimer() {
1461 suspend_webkit_shared_timer_
= false;
1464 void RenderThreadImpl::DoNotNotifyWebKitOfModalLoop() {
1465 notify_webkit_of_modal_loop_
= false;
1468 bool RenderThreadImpl::OnControlMessageReceived(const IPC::Message
& msg
) {
1469 ObserverListBase
<RenderProcessObserver
>::Iterator
it(observers_
);
1470 RenderProcessObserver
* observer
;
1471 while ((observer
= it
.GetNext()) != NULL
) {
1472 if (observer
->OnControlMessageReceived(msg
))
1476 // Some messages are handled by delegates.
1477 if (appcache_dispatcher_
->OnMessageReceived(msg
) ||
1478 dom_storage_dispatcher_
->OnMessageReceived(msg
) ||
1479 embedded_worker_dispatcher_
->OnMessageReceived(msg
)) {
1483 bool handled
= true;
1484 IPC_BEGIN_MESSAGE_MAP(RenderThreadImpl
, msg
)
1485 IPC_MESSAGE_HANDLER(FrameMsg_NewFrame
, OnCreateNewFrame
)
1486 IPC_MESSAGE_HANDLER(FrameMsg_NewFrameProxy
, OnCreateNewFrameProxy
)
1487 IPC_MESSAGE_HANDLER(ViewMsg_SetZoomLevelForCurrentURL
,
1488 OnSetZoomLevelForCurrentURL
)
1489 // TODO(port): removed from render_messages_internal.h;
1490 // is there a new non-windows message I should add here?
1491 IPC_MESSAGE_HANDLER(ViewMsg_New
, OnCreateNewView
)
1492 IPC_MESSAGE_HANDLER(ViewMsg_NetworkTypeChanged
, OnNetworkTypeChanged
)
1493 IPC_MESSAGE_HANDLER(ViewMsg_TempCrashWithData
, OnTempCrashWithData
)
1494 IPC_MESSAGE_HANDLER(WorkerProcessMsg_CreateWorker
, OnCreateNewSharedWorker
)
1495 IPC_MESSAGE_HANDLER(ViewMsg_TimezoneChange
, OnUpdateTimezone
)
1496 #if defined(OS_ANDROID)
1497 IPC_MESSAGE_HANDLER(ViewMsg_SetWebKitSharedTimersSuspended
,
1498 OnSetWebKitSharedTimersSuspended
)
1500 #if defined(OS_MACOSX)
1501 IPC_MESSAGE_HANDLER(ViewMsg_UpdateScrollbarTheme
, OnUpdateScrollbarTheme
)
1503 #if defined(ENABLE_PLUGINS)
1504 IPC_MESSAGE_HANDLER(ViewMsg_PurgePluginListCache
, OnPurgePluginListCache
)
1506 IPC_MESSAGE_UNHANDLED(handled
= false)
1507 IPC_END_MESSAGE_MAP()
1511 void RenderThreadImpl::OnCreateNewFrame(
1513 int parent_routing_id
,
1514 int proxy_routing_id
,
1515 const FrameReplicationState
& replicated_state
,
1516 FrameMsg_NewFrame_WidgetParams params
) {
1517 CompositorDependencies
* compositor_deps
= this;
1518 RenderFrameImpl::CreateFrame(routing_id
, parent_routing_id
, proxy_routing_id
,
1519 replicated_state
, compositor_deps
, params
);
1522 void RenderThreadImpl::OnCreateNewFrameProxy(
1524 int parent_routing_id
,
1525 int render_view_routing_id
,
1526 const FrameReplicationState
& replicated_state
) {
1527 RenderFrameProxy::CreateFrameProxy(routing_id
, parent_routing_id
,
1528 render_view_routing_id
, replicated_state
);
1531 void RenderThreadImpl::OnSetZoomLevelForCurrentURL(const std::string
& scheme
,
1532 const std::string
& host
,
1533 double zoom_level
) {
1534 RenderViewZoomer
zoomer(scheme
, host
, zoom_level
);
1535 RenderView::ForEach(&zoomer
);
1538 void RenderThreadImpl::OnCreateNewView(const ViewMsg_New_Params
& params
) {
1539 EnsureWebKitInitialized();
1540 CompositorDependencies
* compositor_deps
= this;
1541 // When bringing in render_view, also bring in webkit's glue and jsbindings.
1542 RenderViewImpl::Create(params
, compositor_deps
, false);
1545 GpuChannelHost
* RenderThreadImpl::EstablishGpuChannelSync(
1546 CauseForGpuLaunch cause_for_gpu_launch
) {
1547 TRACE_EVENT0("gpu", "RenderThreadImpl::EstablishGpuChannelSync");
1549 if (gpu_channel_
.get()) {
1550 // Do nothing if we already have a GPU channel or are already
1551 // establishing one.
1552 if (!gpu_channel_
->IsLost())
1553 return gpu_channel_
.get();
1555 // Recreate the channel if it has been lost.
1556 gpu_channel_
= NULL
;
1559 // Ask the browser for the channel name.
1561 IPC::ChannelHandle channel_handle
;
1562 gpu::GPUInfo gpu_info
;
1563 if (!Send(new GpuHostMsg_EstablishGpuChannel(cause_for_gpu_launch
,
1567 #if defined(OS_POSIX)
1568 channel_handle
.socket
.fd
== -1 ||
1570 channel_handle
.name
.empty()) {
1571 // Otherwise cancel the connection.
1575 GetContentClient()->SetGpuInfo(gpu_info
);
1577 // Cache some variables that are needed on the compositor thread for our
1578 // implementation of GpuChannelHostFactory.
1579 io_message_loop_proxy_
= ChildProcess::current()->io_message_loop_proxy();
1582 GpuChannelHost::Create(this,
1585 ChildProcess::current()->GetShutDownEvent(),
1586 gpu_memory_buffer_manager());
1587 return gpu_channel_
.get();
1590 blink::WebMediaStreamCenter
* RenderThreadImpl::CreateMediaStreamCenter(
1591 blink::WebMediaStreamCenterClient
* client
) {
1592 #if defined(OS_ANDROID)
1593 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
1594 switches::kDisableWebRTC
))
1598 #if defined(ENABLE_WEBRTC)
1599 if (!media_stream_center_
) {
1600 media_stream_center_
= GetContentClient()->renderer()
1601 ->OverrideCreateWebMediaStreamCenter(client
);
1602 if (!media_stream_center_
) {
1603 scoped_ptr
<MediaStreamCenter
> media_stream_center(
1604 new MediaStreamCenter(client
, GetPeerConnectionDependencyFactory()));
1605 media_stream_center_
= media_stream_center
.release();
1609 return media_stream_center_
;
1612 #if defined(ENABLE_WEBRTC)
1613 PeerConnectionDependencyFactory
*
1614 RenderThreadImpl::GetPeerConnectionDependencyFactory() {
1615 return peer_connection_factory_
.get();
1619 GpuChannelHost
* RenderThreadImpl::GetGpuChannel() {
1620 if (!gpu_channel_
.get())
1623 if (gpu_channel_
->IsLost())
1626 return gpu_channel_
.get();
1629 #if defined(ENABLE_PLUGINS)
1630 void RenderThreadImpl::OnPurgePluginListCache(bool reload_pages
) {
1631 EnsureWebKitInitialized();
1632 // The call below will cause a GetPlugins call with refresh=true, but at this
1633 // point we already know that the browser has refreshed its list, so disable
1634 // refresh temporarily to prevent each renderer process causing the list to be
1636 blink_platform_impl_
->set_plugin_refresh_allowed(false);
1637 blink::resetPluginCache(reload_pages
);
1638 blink_platform_impl_
->set_plugin_refresh_allowed(true);
1640 FOR_EACH_OBSERVER(RenderProcessObserver
, observers_
, PluginListChanged());
1644 void RenderThreadImpl::OnNetworkTypeChanged(
1645 net::NetworkChangeNotifier::ConnectionType type
) {
1646 EnsureWebKitInitialized();
1647 bool online
= type
!= net::NetworkChangeNotifier::CONNECTION_NONE
;
1648 WebNetworkStateNotifier::setOnLine(online
);
1650 RenderProcessObserver
, observers_
, NetworkStateChanged(online
));
1651 WebNetworkStateNotifier::setWebConnectionType(
1652 NetConnectionTypeToWebConnectionType(type
));
1655 void RenderThreadImpl::OnTempCrashWithData(const GURL
& data
) {
1656 GetContentClient()->SetActiveURL(data
);
1660 void RenderThreadImpl::OnUpdateTimezone() {
1661 if (!blink_platform_impl_
)
1663 NotifyTimezoneChange();
1666 #if defined(OS_ANDROID)
1667 void RenderThreadImpl::OnSetWebKitSharedTimersSuspended(bool suspend
) {
1668 if (suspend_webkit_shared_timer_
) {
1669 EnsureWebKitInitialized();
1671 blink_platform_impl_
->SuspendSharedTimer();
1673 blink_platform_impl_
->ResumeSharedTimer();
1675 webkit_shared_timer_suspended_
= suspend
;
1680 #if defined(OS_MACOSX)
1681 void RenderThreadImpl::OnUpdateScrollbarTheme(
1682 float initial_button_delay
,
1683 float autoscroll_button_delay
,
1684 bool jump_on_track_click
,
1685 blink::ScrollerStyle preferred_scroller_style
,
1687 EnsureWebKitInitialized();
1688 static_cast<WebScrollbarBehaviorImpl
*>(
1689 blink_platform_impl_
->scrollbarBehavior())
1690 ->set_jump_on_track_click(jump_on_track_click
);
1691 blink::WebScrollbarTheme::updateScrollbars(initial_button_delay
,
1692 autoscroll_button_delay
,
1693 preferred_scroller_style
,
1698 void RenderThreadImpl::OnCreateNewSharedWorker(
1699 const WorkerProcessMsg_CreateWorker_Params
& params
) {
1700 // EmbeddedSharedWorkerStub will self-destruct.
1701 new EmbeddedSharedWorkerStub(params
.url
,
1703 params
.content_security_policy
,
1704 params
.security_policy_type
,
1705 params
.pause_on_start
,
1709 void RenderThreadImpl::OnMemoryPressure(
1710 base::MemoryPressureListener::MemoryPressureLevel memory_pressure_level
) {
1711 base::allocator::ReleaseFreeMemory();
1713 // Trigger full v8 garbage collection on critical memory notification. This
1714 // will potentially hang the renderer for a long time, however, when we
1715 // receive a memory pressure notification, we might be about to be killed.
1716 if (blink_platform_impl_
&& blink::mainThreadIsolate()) {
1717 blink::mainThreadIsolate()->LowMemoryNotification();
1718 RenderThread::Get()->PostTaskToAllWebWorkers(
1719 base::Bind(&LowMemoryNotificationOnThisThread
));
1722 if (memory_pressure_level
==
1723 base::MemoryPressureListener::MEMORY_PRESSURE_LEVEL_CRITICAL
) {
1724 if (blink_platform_impl_
) {
1725 // Clear the image cache. Do not call into blink if it is not initialized.
1726 blink::WebImageCache::clear();
1729 // Purge Skia font cache, by setting it to 0 and then again to the previous
1731 size_t font_cache_limit
= SkGraphics::SetFontCacheLimit(0);
1732 SkGraphics::SetFontCacheLimit(font_cache_limit
);
1735 blink::WebCache::pruneAll();
1738 scoped_refptr
<base::MessageLoopProxy
>
1739 RenderThreadImpl::GetFileThreadMessageLoopProxy() {
1740 DCHECK(message_loop() == base::MessageLoop::current());
1741 if (!file_thread_
) {
1742 file_thread_
.reset(new base::Thread("Renderer::FILE"));
1743 file_thread_
->Start();
1745 return file_thread_
->message_loop_proxy();
1748 scoped_refptr
<base::SingleThreadTaskRunner
>
1749 RenderThreadImpl::GetMediaThreadTaskRunner() {
1750 DCHECK(message_loop() == base::MessageLoop::current());
1751 if (!media_thread_
) {
1752 media_thread_
.reset(new base::Thread("Media"));
1753 media_thread_
->Start();
1755 #if defined(OS_ANDROID)
1756 renderer_demuxer_
= new RendererDemuxerAndroid();
1757 AddFilter(renderer_demuxer_
.get());
1760 return media_thread_
->message_loop_proxy();
1763 void RenderThreadImpl::SampleGamepads(blink::WebGamepads
* data
) {
1764 blink_platform_impl_
->sampleGamepads(*data
);
1767 void RenderThreadImpl::WidgetCreated() {
1771 void RenderThreadImpl::WidgetDestroyed() {
1775 void RenderThreadImpl::WidgetHidden() {
1776 DCHECK_LT(hidden_widget_count_
, widget_count_
);
1777 hidden_widget_count_
++;
1779 if (widget_count_
&& hidden_widget_count_
== widget_count_
) {
1780 // TODO(reveman): Remove this when we have a better mechanism to prevent
1781 // total discardable memory used by all renderers from growing too large.
1782 base::internal::DiscardableMemoryEmulated::
1783 ReduceMemoryUsageUntilWithinLimit(
1784 kEmulatedDiscardableMemoryBytesToKeepWhenWidgetsHidden
);
1786 if (GetContentClient()->renderer()->RunIdleHandlerWhenWidgetsHidden())
1787 ScheduleIdleHandler(kInitialIdleHandlerDelayMs
);
1791 void RenderThreadImpl::WidgetRestored() {
1792 DCHECK_GT(hidden_widget_count_
, 0);
1793 hidden_widget_count_
--;
1795 if (!GetContentClient()->renderer()->RunIdleHandlerWhenWidgetsHidden()) {
1799 ScheduleIdleHandler(kLongIdleHandlerDelayMs
);
1802 RenderThreadImpl::PendingRenderFrameConnect::PendingRenderFrameConnect(
1803 mojo::InterfaceRequest
<mojo::ServiceProvider
> services
,
1804 mojo::ServiceProviderPtr exposed_services
)
1805 : services(services
.Pass()),
1806 exposed_services(exposed_services
.Pass()) {
1809 RenderThreadImpl::PendingRenderFrameConnect::~PendingRenderFrameConnect() {
1812 } // namespace content