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/debug/trace_event.h"
15 #include "base/lazy_instance.h"
16 #include "base/logging.h"
17 #include "base/memory/discardable_memory.h"
18 #include "base/memory/discardable_memory_emulated.h"
19 #include "base/memory/discardable_memory_shmem_allocator.h"
20 #include "base/memory/shared_memory.h"
21 #include "base/metrics/field_trial.h"
22 #include "base/metrics/histogram.h"
23 #include "base/metrics/stats_table.h"
24 #include "base/path_service.h"
25 #include "base/single_thread_task_runner.h"
26 #include "base/strings/string16.h"
27 #include "base/strings/string_number_conversions.h"
28 #include "base/strings/string_tokenizer.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/values.h"
33 #include "cc/base/switches.h"
34 #include "cc/blink/web_external_bitmap_impl.h"
35 #include "cc/blink/web_layer_impl.h"
36 #include "cc/resources/tile_task_worker_pool.h"
37 #include "content/child/appcache/appcache_dispatcher.h"
38 #include "content/child/appcache/appcache_frontend_impl.h"
39 #include "content/child/child_discardable_shared_memory_manager.h"
40 #include "content/child/child_gpu_memory_buffer_manager.h"
41 #include "content/child/child_histogram_message_filter.h"
42 #include "content/child/child_resource_message_filter.h"
43 #include "content/child/child_shared_bitmap_manager.h"
44 #include "content/child/content_child_helpers.h"
45 #include "content/child/db_message_filter.h"
46 #include "content/child/indexed_db/indexed_db_dispatcher.h"
47 #include "content/child/indexed_db/indexed_db_message_filter.h"
48 #include "content/child/npapi/npobject_util.h"
49 #include "content/child/plugin_messages.h"
50 #include "content/child/resource_dispatcher.h"
51 #include "content/child/resource_scheduling_filter.h"
52 #include "content/child/runtime_features.h"
53 #include "content/child/thread_safe_sender.h"
54 #include "content/child/web_database_observer_impl.h"
55 #include "content/child/worker_task_runner.h"
56 #include "content/common/child_process_messages.h"
57 #include "content/common/content_constants_internal.h"
58 #include "content/common/database_messages.h"
59 #include "content/common/dom_storage/dom_storage_messages.h"
60 #include "content/common/frame_messages.h"
61 #include "content/common/gpu/client/context_provider_command_buffer.h"
62 #include "content/common/gpu/client/gpu_channel_host.h"
63 #include "content/common/gpu/gpu_messages.h"
64 #include "content/common/gpu/gpu_process_launch_causes.h"
65 #include "content/common/render_frame_setup.mojom.h"
66 #include "content/common/resource_messages.h"
67 #include "content/common/view_messages.h"
68 #include "content/common/worker_messages.h"
69 #include "content/public/common/content_constants.h"
70 #include "content/public/common/content_paths.h"
71 #include "content/public/common/content_switches.h"
72 #include "content/public/common/renderer_preferences.h"
73 #include "content/public/common/url_constants.h"
74 #include "content/public/renderer/content_renderer_client.h"
75 #include "content/public/renderer/render_process_observer.h"
76 #include "content/public/renderer/render_view_visitor.h"
77 #include "content/renderer/browser_plugin/browser_plugin_manager.h"
78 #include "content/renderer/devtools/devtools_agent_filter.h"
79 #include "content/renderer/devtools/v8_sampling_profiler.h"
80 #include "content/renderer/dom_storage/dom_storage_dispatcher.h"
81 #include "content/renderer/dom_storage/webstoragearea_impl.h"
82 #include "content/renderer/dom_storage/webstoragenamespace_impl.h"
83 #include "content/renderer/gpu/compositor_external_begin_frame_source.h"
84 #include "content/renderer/gpu/compositor_forwarding_message_filter.h"
85 #include "content/renderer/gpu/compositor_output_surface.h"
86 #include "content/renderer/input/input_event_filter.h"
87 #include "content/renderer/input/input_handler_manager.h"
88 #include "content/renderer/input/main_thread_input_event_filter.h"
89 #include "content/renderer/media/aec_dump_message_filter.h"
90 #include "content/renderer/media/audio_input_message_filter.h"
91 #include "content/renderer/media/audio_message_filter.h"
92 #include "content/renderer/media/audio_renderer_mixer_manager.h"
93 #include "content/renderer/media/media_stream_center.h"
94 #include "content/renderer/media/midi_message_filter.h"
95 #include "content/renderer/media/render_media_client.h"
96 #include "content/renderer/media/renderer_gpu_video_accelerator_factories.h"
97 #include "content/renderer/media/video_capture_impl_manager.h"
98 #include "content/renderer/media/video_capture_message_filter.h"
99 #include "content/renderer/net_info_helper.h"
100 #include "content/renderer/p2p/socket_dispatcher.h"
101 #include "content/renderer/render_frame_proxy.h"
102 #include "content/renderer/render_process_impl.h"
103 #include "content/renderer/render_view_impl.h"
104 #include "content/renderer/renderer_blink_platform_impl.h"
105 #include "content/renderer/scheduler/renderer_scheduler.h"
106 #include "content/renderer/service_worker/embedded_worker_context_message_filter.h"
107 #include "content/renderer/service_worker/embedded_worker_dispatcher.h"
108 #include "content/renderer/shared_worker/embedded_shared_worker_stub.h"
109 #include "gin/public/debug.h"
110 #include "gpu/GLES2/gl2extchromium.h"
111 #include "gpu/command_buffer/common/gles2_cmd_utils.h"
112 #include "ipc/ipc_channel_handle.h"
113 #include "ipc/ipc_platform_file.h"
114 #include "ipc/mojo/ipc_channel_mojo.h"
115 #include "media/base/audio_hardware_config.h"
116 #include "media/base/media.h"
117 #include "media/filters/gpu_video_accelerator_factories.h"
118 #include "mojo/common/common_type_converters.h"
119 #include "net/base/net_errors.h"
120 #include "net/base/net_util.h"
121 #include "skia/ext/event_tracer_impl.h"
122 #include "third_party/WebKit/public/platform/WebString.h"
123 #include "third_party/WebKit/public/platform/WebThread.h"
124 #include "third_party/WebKit/public/web/WebColorName.h"
125 #include "third_party/WebKit/public/web/WebDatabase.h"
126 #include "third_party/WebKit/public/web/WebDocument.h"
127 #include "third_party/WebKit/public/web/WebFrame.h"
128 #include "third_party/WebKit/public/web/WebImageCache.h"
129 #include "third_party/WebKit/public/web/WebKit.h"
130 #include "third_party/WebKit/public/web/WebNetworkStateNotifier.h"
131 #include "third_party/WebKit/public/web/WebPopupMenu.h"
132 #include "third_party/WebKit/public/web/WebRuntimeFeatures.h"
133 #include "third_party/WebKit/public/web/WebScriptController.h"
134 #include "third_party/WebKit/public/web/WebSecurityPolicy.h"
135 #include "third_party/WebKit/public/web/WebView.h"
136 #include "third_party/skia/include/core/SkGraphics.h"
137 #include "ui/base/layout.h"
138 #include "ui/base/ui_base_switches.h"
139 #include "v8/include/v8.h"
141 #if defined(OS_ANDROID)
142 #include <cpu-features.h>
143 #include "content/renderer/android/synchronous_compositor_factory.h"
144 #include "content/renderer/media/android/renderer_demuxer_android.h"
147 #if defined(OS_MACOSX)
148 #include "content/renderer/webscrollbarbehavior_impl_mac.h"
151 #if defined(OS_POSIX)
152 #include "ipc/ipc_channel_posix.h"
160 #include "content/child/npapi/np_channel_base.h"
163 #if defined(ENABLE_PLUGINS)
164 #include "content/renderer/npapi/plugin_channel_host.h"
167 #if defined(ENABLE_WEBRTC)
168 #include "content/renderer/media/peer_connection_tracker.h"
169 #include "content/renderer/media/rtc_peer_connection_handler.h"
170 #include "content/renderer/media/webrtc/peer_connection_dependency_factory.h"
171 #include "content/renderer/media/webrtc_identity_service.h"
174 #ifdef ENABLE_VTUNE_JIT_INTERFACE
175 #include "v8/src/third_party/vtune/v8-vtune.h"
178 using base::ThreadRestrictions
;
179 using blink::WebDocument
;
180 using blink::WebFrame
;
181 using blink::WebNetworkStateNotifier
;
182 using blink::WebRuntimeFeatures
;
183 using blink::WebScriptController
;
184 using blink::WebSecurityPolicy
;
185 using blink::WebString
;
186 using blink::WebView
;
192 const int64 kInitialIdleHandlerDelayMs
= 1000;
193 const int64 kLongIdleHandlerDelayMs
= 30*1000;
195 // Maximum allocation size allowed for image scaling filters that
196 // require pre-scaling. Skia will fallback to a filter that doesn't
197 // require pre-scaling if the default filter would require an
198 // allocation that exceeds this limit.
199 const size_t kImageCacheSingleAllocationByteLimit
= 64 * 1024 * 1024;
201 const size_t kEmulatedDiscardableMemoryBytesToKeepWhenWidgetsHidden
=
204 // Keep the global RenderThreadImpl in a TLS slot so it is impossible to access
205 // incorrectly from the wrong thread.
206 base::LazyInstance
<base::ThreadLocalPointer
<RenderThreadImpl
> >
207 lazy_tls
= LAZY_INSTANCE_INITIALIZER
;
209 class RenderViewZoomer
: public RenderViewVisitor
{
211 RenderViewZoomer(const std::string
& scheme
,
212 const std::string
& host
,
213 double zoom_level
) : scheme_(scheme
),
215 zoom_level_(zoom_level
) {
218 bool Visit(RenderView
* render_view
) override
{
219 WebView
* webview
= render_view
->GetWebView();
220 WebDocument document
= webview
->mainFrame()->document();
222 // Don't set zoom level for full-page plugin since they don't use the same
224 if (document
.isPluginDocument())
226 GURL
url(document
.url());
227 // Empty scheme works as wildcard that matches any scheme,
228 if ((net::GetHostOrSpecFromURL(url
) == host_
) &&
229 (scheme_
.empty() || scheme_
== url
.scheme()) &&
230 !static_cast<RenderViewImpl
*>(render_view
)
231 ->uses_temporary_zoom_level()) {
232 webview
->hidePopups();
233 webview
->setZoomLevel(zoom_level_
);
239 const std::string scheme_
;
240 const std::string host_
;
241 const double zoom_level_
;
243 DISALLOW_COPY_AND_ASSIGN(RenderViewZoomer
);
246 std::string
HostToCustomHistogramSuffix(const std::string
& host
) {
247 if (host
== "mail.google.com")
249 if (host
== "docs.google.com" || host
== "drive.google.com")
251 if (host
== "plus.google.com")
253 return std::string();
256 void* CreateHistogram(
257 const char *name
, int min
, int max
, size_t buckets
) {
260 std::string histogram_name
;
261 RenderThreadImpl
* render_thread_impl
= RenderThreadImpl::current();
262 if (render_thread_impl
) { // Can be null in tests.
263 histogram_name
= render_thread_impl
->
264 histogram_customizer()->ConvertToCustomHistogramName(name
);
266 histogram_name
= std::string(name
);
268 base::HistogramBase
* histogram
= base::Histogram::FactoryGet(
269 histogram_name
, min
, max
, buckets
,
270 base::Histogram::kUmaTargetedHistogramFlag
);
274 void AddHistogramSample(void* hist
, int sample
) {
275 base::Histogram
* histogram
= static_cast<base::Histogram
*>(hist
);
276 histogram
->Add(sample
);
279 scoped_ptr
<cc::SharedBitmap
> AllocateSharedBitmapFunction(
280 const gfx::Size
& size
) {
281 return ChildThread::current()->shared_bitmap_manager()->AllocateSharedBitmap(
285 void EnableBlinkPlatformLogChannels(const std::string
& channels
) {
286 if (channels
.empty())
288 base::StringTokenizer
t(channels
, ", ");
290 blink::enableLogChannel(t
.token().c_str());
293 void NotifyTimezoneChangeOnThisThread() {
294 v8::Isolate
* isolate
= v8::Isolate::GetCurrent();
297 v8::Date::DateTimeConfigurationChangeNotification(isolate
);
300 class RenderFrameSetupImpl
: public mojo::InterfaceImpl
<RenderFrameSetup
> {
302 RenderFrameSetupImpl()
303 : routing_id_highmark_(-1) {
306 void GetServiceProviderForFrame(
307 int32_t frame_routing_id
,
308 mojo::InterfaceRequest
<mojo::ServiceProvider
> request
) override
{
309 // TODO(morrita): This is for investigating http://crbug.com/415059 and
310 // should be removed once it is fixed.
311 CHECK_LT(routing_id_highmark_
, frame_routing_id
);
312 routing_id_highmark_
= frame_routing_id
;
314 RenderFrameImpl
* frame
= RenderFrameImpl::FromRoutingID(frame_routing_id
);
315 // We can receive a GetServiceProviderForFrame message for a frame not yet
316 // created due to a race between the message and a ViewMsg_New IPC that
317 // triggers creation of the RenderFrame we want.
319 RenderThreadImpl::current()->RegisterPendingRenderFrameConnect(
320 frame_routing_id
, request
.PassMessagePipe());
324 frame
->BindServiceRegistry(request
.PassMessagePipe());
328 int32_t routing_id_highmark_
;
331 void CreateRenderFrameSetup(mojo::InterfaceRequest
<RenderFrameSetup
> request
) {
332 mojo::BindToRequest(new RenderFrameSetupImpl(), &request
);
335 bool ShouldUseMojoChannel() {
336 return base::CommandLine::ForCurrentProcess()->HasSwitch(
337 switches::kEnableRendererMojoChannel
) ||
338 IPC::ChannelMojo::ShouldBeUsed();
341 blink::WebGraphicsContext3D::Attributes
GetOffscreenAttribs() {
342 blink::WebGraphicsContext3D::Attributes attributes
;
343 attributes
.shareResources
= true;
344 attributes
.depth
= false;
345 attributes
.stencil
= false;
346 attributes
.antialias
= false;
347 attributes
.noAutomaticFlushes
= true;
353 // For measuring memory usage after each task. Behind a command line flag.
354 class MemoryObserver
: public base::MessageLoop::TaskObserver
{
357 ~MemoryObserver() override
{}
359 void WillProcessTask(const base::PendingTask
& pending_task
) override
{}
361 void DidProcessTask(const base::PendingTask
& pending_task
) override
{
362 LOCAL_HISTOGRAM_MEMORY_KB("Memory.RendererUsed", GetMemoryUsageKB());
366 DISALLOW_COPY_AND_ASSIGN(MemoryObserver
);
369 RenderThreadImpl::HistogramCustomizer::HistogramCustomizer() {
370 custom_histograms_
.insert("V8.MemoryExternalFragmentationTotal");
371 custom_histograms_
.insert("V8.MemoryHeapSampleTotalCommitted");
372 custom_histograms_
.insert("V8.MemoryHeapSampleTotalUsed");
375 RenderThreadImpl::HistogramCustomizer::~HistogramCustomizer() {}
377 void RenderThreadImpl::HistogramCustomizer::RenderViewNavigatedToHost(
378 const std::string
& host
, size_t view_count
) {
379 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
380 switches::kDisableHistogramCustomizer
)) {
383 // Check if all RenderViews are displaying a page from the same host. If there
384 // is only one RenderView, the common host is this view's host. If there are
385 // many, check if this one shares the common host of the other
386 // RenderViews. It's ok to not detect some cases where the RenderViews share a
387 // common host. This information is only used for producing custom histograms.
390 else if (host
!= common_host_
)
391 SetCommonHost(std::string());
394 std::string
RenderThreadImpl::HistogramCustomizer::ConvertToCustomHistogramName(
395 const char* histogram_name
) const {
396 std::string
name(histogram_name
);
397 if (!common_host_histogram_suffix_
.empty() &&
398 custom_histograms_
.find(name
) != custom_histograms_
.end())
399 name
+= common_host_histogram_suffix_
;
403 void RenderThreadImpl::HistogramCustomizer::SetCommonHost(
404 const std::string
& host
) {
405 if (host
!= common_host_
) {
407 common_host_histogram_suffix_
= HostToCustomHistogramSuffix(host
);
408 blink::mainThreadIsolate()->SetCreateHistogramFunction(CreateHistogram
);
412 RenderThreadImpl
* RenderThreadImpl::current() {
413 return lazy_tls
.Pointer()->Get();
416 // When we run plugins in process, we actually run them on the render thread,
417 // which means that we need to make the render thread pump UI events.
418 RenderThreadImpl::RenderThreadImpl()
419 : ChildThread(Options(ShouldUseMojoChannel())) {
423 RenderThreadImpl::RenderThreadImpl(const std::string
& channel_name
)
424 : ChildThread(Options(channel_name
, ShouldUseMojoChannel())) {
428 RenderThreadImpl::RenderThreadImpl(
429 scoped_ptr
<base::MessageLoop
> main_message_loop
)
430 : ChildThread(Options(ShouldUseMojoChannel())),
431 main_message_loop_(main_message_loop
.Pass()) {
435 void RenderThreadImpl::Init() {
436 TRACE_EVENT_BEGIN_ETW("RenderThreadImpl::Init", 0, "");
438 base::debug::TraceLog::GetInstance()->SetThreadSortIndex(
439 base::PlatformThread::CurrentId(),
440 kTraceEventRendererMainThreadSortIndex
);
442 #if defined(OS_MACOSX) || defined(OS_ANDROID)
443 // On Mac and Android, the select popups are rendered by the browser.
444 blink::WebView::setUseExternalPopupMenus(true);
447 lazy_tls
.Pointer()->Set(this);
449 // Register this object as the main thread.
450 ChildProcess::current()->set_main_thread(this);
452 // In single process the single process is all there is.
453 suspend_webkit_shared_timer_
= true;
454 notify_webkit_of_modal_loop_
= true;
455 webkit_shared_timer_suspended_
= false;
457 hidden_widget_count_
= 0;
458 idle_notification_delay_in_ms_
= kInitialIdleHandlerDelayMs
;
459 idle_notifications_to_skip_
= 0;
460 layout_test_mode_
= false;
462 appcache_dispatcher_
.reset(
463 new AppCacheDispatcher(Get(), new AppCacheFrontendImpl()));
464 dom_storage_dispatcher_
.reset(new DomStorageDispatcher());
465 main_thread_indexed_db_dispatcher_
.reset(new IndexedDBDispatcher(
466 thread_safe_sender()));
467 renderer_scheduler_
= RendererScheduler::Create();
468 channel()->SetListenerTaskRunner(renderer_scheduler_
->DefaultTaskRunner());
469 embedded_worker_dispatcher_
.reset(new EmbeddedWorkerDispatcher());
471 media_stream_center_
= NULL
;
473 db_message_filter_
= new DBMessageFilter();
474 AddFilter(db_message_filter_
.get());
476 vc_manager_
.reset(new VideoCaptureImplManager());
477 AddFilter(vc_manager_
->video_capture_message_filter());
479 browser_plugin_manager_
.reset(new BrowserPluginManager());
480 AddObserver(browser_plugin_manager_
.get());
482 #if defined(ENABLE_WEBRTC)
483 peer_connection_tracker_
.reset(new PeerConnectionTracker());
484 AddObserver(peer_connection_tracker_
.get());
486 p2p_socket_dispatcher_
=
487 new P2PSocketDispatcher(GetIOMessageLoopProxy().get());
488 AddFilter(p2p_socket_dispatcher_
.get());
490 webrtc_identity_service_
.reset(new WebRTCIdentityService());
492 aec_dump_message_filter_
=
493 new AecDumpMessageFilter(GetIOMessageLoopProxy(),
494 message_loop()->message_loop_proxy());
495 AddFilter(aec_dump_message_filter_
.get());
497 peer_connection_factory_
.reset(new PeerConnectionDependencyFactory(
498 p2p_socket_dispatcher_
.get()));
499 #endif // defined(ENABLE_WEBRTC)
501 audio_input_message_filter_
=
502 new AudioInputMessageFilter(GetIOMessageLoopProxy());
503 AddFilter(audio_input_message_filter_
.get());
505 audio_message_filter_
= new AudioMessageFilter(GetIOMessageLoopProxy());
506 AddFilter(audio_message_filter_
.get());
508 midi_message_filter_
= new MidiMessageFilter(GetIOMessageLoopProxy());
509 AddFilter(midi_message_filter_
.get());
511 AddFilter((new IndexedDBMessageFilter(thread_safe_sender()))->GetFilter());
513 AddFilter((new EmbeddedWorkerContextMessageFilter())->GetFilter());
515 GetContentClient()->renderer()->RenderThreadStarted();
517 InitSkiaEventTracer();
519 const base::CommandLine
& command_line
=
520 *base::CommandLine::ForCurrentProcess();
522 is_impl_side_painting_enabled_
=
523 command_line
.HasSwitch(switches::kEnableImplSidePainting
);
524 cc_blink::WebLayerImpl::SetImplSidePaintingEnabled(
525 is_impl_side_painting_enabled_
);
527 is_zero_copy_enabled_
= command_line
.HasSwitch(switches::kEnableZeroCopy
);
529 #if defined(OS_MACOSX) || defined(OS_ANDROID)
530 // TODO(danakj): If changing these also update NumberOfRendererRasterThreads
531 // in compositor_util.cc. We should be using methods from compositor_util here
532 // instead of inspecting flags.
533 is_one_copy_enabled_
= command_line
.HasSwitch(switches::kEnableOneCopy
);
535 is_one_copy_enabled_
= !command_line
.HasSwitch(switches::kDisableOneCopy
);
538 use_image_texture_target_
= GL_TEXTURE_2D
;
539 if (command_line
.HasSwitch(switches::kUseImageTextureTarget
)) {
540 std::string target_string
=
541 command_line
.GetSwitchValueASCII(switches::kUseImageTextureTarget
);
542 const unsigned targets
[] = {
543 GL_TEXTURE_RECTANGLE_ARB
,
544 GL_TEXTURE_EXTERNAL_OES
546 for (auto target
: targets
) {
547 if (target_string
== gpu::gles2::GLES2Util::GetStringEnum(target
))
548 use_image_texture_target_
= target
;
552 if (command_line
.HasSwitch(switches::kDisableLCDText
)) {
553 is_lcd_text_enabled_
= false;
554 } else if (command_line
.HasSwitch(switches::kEnableLCDText
)) {
555 is_lcd_text_enabled_
= true;
557 #if defined(OS_ANDROID)
558 is_lcd_text_enabled_
= false;
560 is_lcd_text_enabled_
= true;
564 is_gpu_rasterization_enabled_
=
565 command_line
.HasSwitch(switches::kEnableGpuRasterization
);
566 is_gpu_rasterization_forced_
=
567 command_line
.HasSwitch(switches::kForceGpuRasterization
);
569 if (command_line
.HasSwitch(switches::kDisableDistanceFieldText
)) {
570 is_distance_field_text_enabled_
= false;
571 } else if (command_line
.HasSwitch(switches::kEnableDistanceFieldText
)) {
572 is_distance_field_text_enabled_
= true;
574 is_distance_field_text_enabled_
= false;
577 // Note that under Linux, the media library will normally already have
578 // been initialized by the Zygote before this instance became a Renderer.
579 base::FilePath media_path
;
580 PathService::Get(DIR_MEDIA_LIBS
, &media_path
);
581 if (!media_path
.empty())
582 media::InitializeMediaLibrary(media_path
);
584 memory_pressure_listener_
.reset(new base::MemoryPressureListener(
585 base::Bind(&RenderThreadImpl::OnMemoryPressure
, base::Unretained(this))));
587 std::vector
<base::DiscardableMemoryType
> supported_types
;
588 base::DiscardableMemory::GetSupportedTypes(&supported_types
);
589 DCHECK(!supported_types
.empty());
591 // The default preferred type is always the first one in list.
592 base::DiscardableMemoryType type
= supported_types
[0];
594 if (command_line
.HasSwitch(switches::kUseDiscardableMemory
)) {
595 std::string requested_type_name
= command_line
.GetSwitchValueASCII(
596 switches::kUseDiscardableMemory
);
597 base::DiscardableMemoryType requested_type
=
598 base::DiscardableMemory::GetNamedType(requested_type_name
);
599 if (std::find(supported_types
.begin(),
600 supported_types
.end(),
601 requested_type
) != supported_types
.end()) {
602 type
= requested_type
;
604 LOG(ERROR
) << "Requested discardable memory type is not supported.";
608 base::DiscardableMemory::SetPreferredType(type
);
610 if (is_impl_side_painting_enabled_
) {
611 int num_raster_threads
= 0;
612 std::string string_value
=
613 command_line
.GetSwitchValueASCII(switches::kNumRasterThreads
);
614 bool parsed_num_raster_threads
=
615 base::StringToInt(string_value
, &num_raster_threads
);
616 DCHECK(parsed_num_raster_threads
) << string_value
;
617 DCHECK_GT(num_raster_threads
, 0);
618 cc::TileTaskWorkerPool::SetNumWorkerThreads(num_raster_threads
);
620 #if defined(OS_ANDROID) || defined(OS_LINUX)
621 if (!command_line
.HasSwitch(
622 switches::kUseNormalPriorityForTileTaskWorkerThreads
)) {
623 cc::TileTaskWorkerPool::SetWorkerThreadPriority(
624 base::kThreadPriority_Background
);
629 base::DiscardableMemoryShmemAllocator::SetInstance(
630 ChildThread::discardable_shared_memory_manager());
632 service_registry()->AddService
<RenderFrameSetup
>(
633 base::Bind(CreateRenderFrameSetup
));
635 TRACE_EVENT_END_ETW("RenderThreadImpl::Init", 0, "");
638 RenderThreadImpl::~RenderThreadImpl() {
639 for (std::map
<int, mojo::MessagePipeHandle
>::iterator it
=
640 pending_render_frame_connects_
.begin();
641 it
!= pending_render_frame_connects_
.end();
643 mojo::CloseRaw(it
->second
);
647 void RenderThreadImpl::Shutdown() {
649 RenderProcessObserver
, observers_
, OnRenderProcessShutdown());
651 ChildThread::Shutdown();
653 if (memory_observer_
) {
654 message_loop()->RemoveTaskObserver(memory_observer_
.get());
655 memory_observer_
.reset();
658 // Wait for all databases to be closed.
659 if (blink_platform_impl_
) {
660 // WaitForAllDatabasesToClose might run a nested message loop. To avoid
661 // processing timer events while we're already in the process of shutting
662 // down blink, put a ScopePageLoadDeferrer on the stack.
663 WebView::willEnterModalLoop();
664 blink_platform_impl_
->web_database_observer_impl()
665 ->WaitForAllDatabasesToClose();
666 WebView::didExitModalLoop();
669 // Shutdown in reverse of the initialization order.
670 if (devtools_agent_message_filter_
.get()) {
671 RemoveFilter(devtools_agent_message_filter_
.get());
672 devtools_agent_message_filter_
= NULL
;
675 RemoveFilter(audio_input_message_filter_
.get());
676 audio_input_message_filter_
= NULL
;
678 #if defined(ENABLE_WEBRTC)
679 RTCPeerConnectionHandler::DestructAllHandlers();
680 // |peer_connection_factory_| cannot be deleted until after the main message
681 // loop has been destroyed. This is because there may be pending tasks that
682 // hold on to objects produced by the PC factory that depend on threads owned
683 // by the PC factory. Once those tasks have been freed, the factory can be
686 RemoveFilter(vc_manager_
->video_capture_message_filter());
689 RemoveFilter(db_message_filter_
.get());
690 db_message_filter_
= NULL
;
692 // Shutdown the file thread if it's running.
694 file_thread_
->Stop();
696 if (compositor_message_filter_
.get()) {
697 RemoveFilter(compositor_message_filter_
.get());
698 compositor_message_filter_
= NULL
;
701 media_thread_
.reset();
703 // AudioMessageFilter may be accessed on |media_thread_|, so shutdown after.
704 RemoveFilter(audio_message_filter_
.get());
705 audio_message_filter_
= NULL
;
707 compositor_thread_
.reset();
709 main_input_callback_
.Cancel();
710 input_handler_manager_
.reset();
711 if (input_event_filter_
.get()) {
712 RemoveFilter(input_event_filter_
.get());
713 input_event_filter_
= NULL
;
716 // RemoveEmbeddedWorkerRoute may be called while deleting
717 // EmbeddedWorkerDispatcher. So it must be deleted before deleting
719 embedded_worker_dispatcher_
.reset();
721 // Ramp down IDB before we ramp down WebKit (and V8), since IDB classes might
722 // hold pointers to V8 objects (e.g., via pending requests).
723 main_thread_indexed_db_dispatcher_
.reset();
725 main_thread_compositor_task_runner_
= NULL
;
727 if (gpu_channel_
.get())
728 gpu_channel_
->DestroyChannel();
732 // Clean up plugin channels before this thread goes away.
733 NPChannelBase::CleanupChannels();
736 // Shut down the message loop before shutting down Blink.
737 // This prevents a scenario where a pending task in the message loop accesses
738 // Blink objects after Blink shuts down.
739 // This must be at the very end of the shutdown sequence. You must not touch
740 // the message loop after this.
741 main_message_loop_
.reset();
742 if (blink_platform_impl_
)
745 lazy_tls
.Pointer()->Set(NULL
);
748 bool RenderThreadImpl::Send(IPC::Message
* msg
) {
749 // Certain synchronous messages cannot always be processed synchronously by
750 // the browser, e.g., putting up UI and waiting for the user. This could cause
751 // a complete hang of Chrome if a windowed plug-in is trying to communicate
752 // with the renderer thread since the browser's UI thread could be stuck
753 // (within a Windows API call) trying to synchronously communicate with the
754 // plug-in. The remedy is to pump messages on this thread while the browser
755 // is processing this request. This creates an opportunity for re-entrancy
756 // into WebKit, so we need to take care to disable callbacks, timers, and
757 // pending network loads that could trigger such callbacks.
758 bool pumping_events
= false;
759 if (msg
->is_sync()) {
760 if (msg
->is_caller_pumping_messages()) {
761 pumping_events
= true;
765 bool suspend_webkit_shared_timer
= true; // default value
766 std::swap(suspend_webkit_shared_timer
, suspend_webkit_shared_timer_
);
768 bool notify_webkit_of_modal_loop
= true; // default value
769 std::swap(notify_webkit_of_modal_loop
, notify_webkit_of_modal_loop_
);
771 #if defined(ENABLE_PLUGINS)
772 int render_view_id
= MSG_ROUTING_NONE
;
775 if (pumping_events
) {
776 if (suspend_webkit_shared_timer
)
777 blink_platform_impl_
->SuspendSharedTimer();
779 if (notify_webkit_of_modal_loop
)
780 WebView::willEnterModalLoop();
781 #if defined(ENABLE_PLUGINS)
782 RenderViewImpl
* render_view
=
783 RenderViewImpl::FromRoutingID(msg
->routing_id());
785 render_view_id
= msg
->routing_id();
786 PluginChannelHost::Broadcast(
787 new PluginMsg_SignalModalDialogEvent(render_view_id
));
792 bool rv
= ChildThread::Send(msg
);
794 if (pumping_events
) {
795 #if defined(ENABLE_PLUGINS)
796 if (render_view_id
!= MSG_ROUTING_NONE
) {
797 PluginChannelHost::Broadcast(
798 new PluginMsg_ResetModalDialogEvent(render_view_id
));
802 if (notify_webkit_of_modal_loop
)
803 WebView::didExitModalLoop();
805 if (suspend_webkit_shared_timer
)
806 blink_platform_impl_
->ResumeSharedTimer();
812 base::MessageLoop
* RenderThreadImpl::GetMessageLoop() {
813 return message_loop();
816 IPC::SyncChannel
* RenderThreadImpl::GetChannel() {
820 std::string
RenderThreadImpl::GetLocale() {
821 // The browser process should have passed the locale to the renderer via the
822 // --lang command line flag.
823 const base::CommandLine
& parsed_command_line
=
824 *base::CommandLine::ForCurrentProcess();
825 const std::string
& lang
=
826 parsed_command_line
.GetSwitchValueASCII(switches::kLang
);
827 DCHECK(!lang
.empty());
831 IPC::SyncMessageFilter
* RenderThreadImpl::GetSyncMessageFilter() {
832 return sync_message_filter();
835 scoped_refptr
<base::MessageLoopProxy
>
836 RenderThreadImpl::GetIOMessageLoopProxy() {
837 return ChildProcess::current()->io_message_loop_proxy();
840 void RenderThreadImpl::AddRoute(int32 routing_id
, IPC::Listener
* listener
) {
841 ChildThread::GetRouter()->AddRoute(routing_id
, listener
);
842 std::map
<int, mojo::MessagePipeHandle
>::iterator it
=
843 pending_render_frame_connects_
.find(routing_id
);
844 if (it
== pending_render_frame_connects_
.end())
847 RenderFrameImpl
* frame
= RenderFrameImpl::FromRoutingID(routing_id
);
851 mojo::ScopedMessagePipeHandle
handle(it
->second
);
852 pending_render_frame_connects_
.erase(it
);
853 frame
->BindServiceRegistry(handle
.Pass());
856 void RenderThreadImpl::RemoveRoute(int32 routing_id
) {
857 ChildThread::GetRouter()->RemoveRoute(routing_id
);
860 void RenderThreadImpl::AddEmbeddedWorkerRoute(int32 routing_id
,
861 IPC::Listener
* listener
) {
862 AddRoute(routing_id
, listener
);
863 if (devtools_agent_message_filter_
.get()) {
864 devtools_agent_message_filter_
->AddEmbeddedWorkerRouteOnMainThread(
869 void RenderThreadImpl::RemoveEmbeddedWorkerRoute(int32 routing_id
) {
870 RemoveRoute(routing_id
);
871 if (devtools_agent_message_filter_
.get()) {
872 devtools_agent_message_filter_
->RemoveEmbeddedWorkerRouteOnMainThread(
877 void RenderThreadImpl::RegisterPendingRenderFrameConnect(
879 mojo::ScopedMessagePipeHandle handle
) {
880 std::pair
<std::map
<int, mojo::MessagePipeHandle
>::iterator
, bool> result
=
881 pending_render_frame_connects_
.insert(
882 std::make_pair(routing_id
, handle
.release()));
883 CHECK(result
.second
) << "Inserting a duplicate item.";
886 int RenderThreadImpl::GenerateRoutingID() {
887 int routing_id
= MSG_ROUTING_NONE
;
888 Send(new ViewHostMsg_GenerateRoutingID(&routing_id
));
892 void RenderThreadImpl::AddFilter(IPC::MessageFilter
* filter
) {
893 channel()->AddFilter(filter
);
896 void RenderThreadImpl::RemoveFilter(IPC::MessageFilter
* filter
) {
897 channel()->RemoveFilter(filter
);
900 void RenderThreadImpl::AddObserver(RenderProcessObserver
* observer
) {
901 observers_
.AddObserver(observer
);
904 void RenderThreadImpl::RemoveObserver(RenderProcessObserver
* observer
) {
905 observers_
.RemoveObserver(observer
);
908 void RenderThreadImpl::SetResourceDispatcherDelegate(
909 ResourceDispatcherDelegate
* delegate
) {
910 resource_dispatcher()->set_delegate(delegate
);
913 void RenderThreadImpl::SetResourceDispatchTaskQueue(
914 const scoped_refptr
<base::SingleThreadTaskRunner
>& resource_task_queue
) {
915 // Add a filter that forces resource messages to be dispatched via a
916 // particular task runner.
917 resource_scheduling_filter_
=
918 new ResourceSchedulingFilter(resource_task_queue
, resource_dispatcher());
919 channel()->AddFilter(resource_scheduling_filter_
.get());
921 // The ChildResourceMessageFilter and the ResourceDispatcher need to use the
922 // same queue to ensure tasks are executed in the expected order.
923 child_resource_message_filter()->SetMainThreadTaskRunner(resource_task_queue
);
924 resource_dispatcher()->SetMainThreadTaskRunner(resource_task_queue
);
927 void RenderThreadImpl::EnsureWebKitInitialized() {
928 if (blink_platform_impl_
)
931 const base::CommandLine
& command_line
=
932 *base::CommandLine::ForCurrentProcess();
934 #ifdef ENABLE_VTUNE_JIT_INTERFACE
935 if (command_line
.HasSwitch(switches::kEnableVtune
))
936 gin::Debug::SetJitCodeEventHandler(vTune::GetVtuneCodeEventHandler());
939 blink_platform_impl_
.reset(
940 new RendererBlinkPlatformImpl(renderer_scheduler_
.get()));
941 blink::initialize(blink_platform_impl_
.get());
943 v8::Isolate
* isolate
= blink::mainThreadIsolate();
945 isolate
->SetCounterFunction(base::StatsTable::FindLocation
);
946 isolate
->SetCreateHistogramFunction(CreateHistogram
);
947 isolate
->SetAddHistogramSampleFunction(AddHistogramSample
);
949 main_thread_compositor_task_runner_
=
950 renderer_scheduler_
->CompositorTaskRunner();
952 main_input_callback_
.Reset(
953 base::Bind(base::IgnoreResult(&RenderThreadImpl::OnMessageReceived
),
954 base::Unretained(this)));
956 // TODO(alexclarke): Add a dedicated loading task queue
957 SetResourceDispatchTaskQueue(renderer_scheduler_
->DefaultTaskRunner());
959 bool enable
= !command_line
.HasSwitch(switches::kDisableThreadedCompositing
);
961 #if defined(OS_ANDROID)
962 if (SynchronousCompositorFactory
* factory
=
963 SynchronousCompositorFactory::GetInstance())
964 compositor_message_loop_proxy_
=
965 factory
->GetCompositorMessageLoop();
967 if (!compositor_message_loop_proxy_
.get()) {
968 compositor_thread_
.reset(new base::Thread("Compositor"));
969 compositor_thread_
->Start();
970 #if defined(OS_ANDROID)
971 compositor_thread_
->SetPriority(base::kThreadPriority_Display
);
973 compositor_message_loop_proxy_
=
974 compositor_thread_
->message_loop_proxy();
975 compositor_message_loop_proxy_
->PostTask(
977 base::Bind(base::IgnoreResult(&ThreadRestrictions::SetIOAllowed
),
981 InputHandlerManagerClient
* input_handler_manager_client
= NULL
;
982 #if defined(OS_ANDROID)
983 if (SynchronousCompositorFactory
* factory
=
984 SynchronousCompositorFactory::GetInstance()) {
985 input_handler_manager_client
= factory
->GetInputHandlerManagerClient();
988 if (!input_handler_manager_client
) {
989 scoped_refptr
<InputEventFilter
> compositor_input_event_filter(
990 new InputEventFilter(main_input_callback_
.callback(),
991 main_thread_compositor_task_runner_
,
992 compositor_message_loop_proxy_
));
993 input_handler_manager_client
= compositor_input_event_filter
.get();
994 input_event_filter_
= compositor_input_event_filter
;
996 input_handler_manager_
.reset(new InputHandlerManager(
997 compositor_message_loop_proxy_
, input_handler_manager_client
,
998 renderer_scheduler_
.get()));
1001 if (!input_event_filter_
.get()) {
1002 // Always provide an input event filter implementation to ensure consistent
1003 // input event scheduling and prioritization.
1004 // TODO(jdduke): Merge InputEventFilter, InputHandlerManager and
1005 // MainThreadInputEventFilter, crbug.com/436057.
1006 input_event_filter_
= new MainThreadInputEventFilter(
1007 main_input_callback_
.callback(), main_thread_compositor_task_runner_
);
1009 AddFilter(input_event_filter_
.get());
1011 scoped_refptr
<base::MessageLoopProxy
> compositor_impl_side_loop
;
1013 compositor_impl_side_loop
= compositor_message_loop_proxy_
;
1015 compositor_impl_side_loop
= base::MessageLoopProxy::current();
1017 compositor_message_filter_
= new CompositorForwardingMessageFilter(
1018 compositor_impl_side_loop
.get());
1019 AddFilter(compositor_message_filter_
.get());
1021 RenderThreadImpl::RegisterSchemes();
1023 EnableBlinkPlatformLogChannels(
1024 command_line
.GetSwitchValueASCII(switches::kBlinkPlatformLogChannels
));
1026 SetRuntimeFeaturesDefaultsAndUpdateFromArgs(command_line
);
1028 if (!media::IsMediaLibraryInitialized()) {
1029 WebRuntimeFeatures::enableWebAudio(false);
1032 RenderMediaClient::Initialize();
1034 FOR_EACH_OBSERVER(RenderProcessObserver
, observers_
, WebKitInitialized());
1036 devtools_agent_message_filter_
= new DevToolsAgentFilter();
1037 AddFilter(devtools_agent_message_filter_
.get());
1039 v8_sampling_profiler_
.reset(new V8SamplingProfiler());
1041 if (GetContentClient()->renderer()->RunIdleHandlerWhenWidgetsHidden())
1042 ScheduleIdleHandler(kLongIdleHandlerDelayMs
);
1044 cc_blink::SetSharedBitmapAllocationFunction(AllocateSharedBitmapFunction
);
1046 // Limit use of the scaled image cache to when deferred image decoding is
1048 if (!command_line
.HasSwitch(switches::kEnableDeferredImageDecoding
) &&
1049 !is_impl_side_painting_enabled_
)
1050 SkGraphics::SetResourceCacheTotalByteLimit(0u);
1052 SkGraphics::SetResourceCacheSingleAllocationByteLimit(
1053 kImageCacheSingleAllocationByteLimit
);
1055 if (command_line
.HasSwitch(switches::kMemoryMetrics
)) {
1056 memory_observer_
.reset(new MemoryObserver());
1057 message_loop()->AddTaskObserver(memory_observer_
.get());
1061 void RenderThreadImpl::RegisterSchemes() {
1062 // swappedout: pages should not be accessible, and should also
1063 // be treated as empty documents that can commit synchronously.
1064 WebString
swappedout_scheme(base::ASCIIToUTF16(kSwappedOutScheme
));
1065 WebSecurityPolicy::registerURLSchemeAsDisplayIsolated(swappedout_scheme
);
1066 WebSecurityPolicy::registerURLSchemeAsEmptyDocument(swappedout_scheme
);
1069 void RenderThreadImpl::NotifyTimezoneChange() {
1070 NotifyTimezoneChangeOnThisThread();
1071 RenderThread::Get()->PostTaskToAllWebWorkers(
1072 base::Bind(&NotifyTimezoneChangeOnThisThread
));
1075 void RenderThreadImpl::RecordAction(const base::UserMetricsAction
& action
) {
1076 Send(new ViewHostMsg_UserMetricsRecordAction(action
.str_
));
1079 void RenderThreadImpl::RecordComputedAction(const std::string
& action
) {
1080 Send(new ViewHostMsg_UserMetricsRecordAction(action
));
1083 scoped_ptr
<base::SharedMemory
>
1084 RenderThreadImpl::HostAllocateSharedMemoryBuffer(size_t size
) {
1085 return ChildThread::AllocateSharedMemory(size
, thread_safe_sender());
1088 cc::SharedBitmapManager
* RenderThreadImpl::GetSharedBitmapManager() {
1089 return shared_bitmap_manager();
1092 void RenderThreadImpl::RegisterExtension(v8::Extension
* extension
) {
1093 WebScriptController::registerExtension(extension
);
1096 void RenderThreadImpl::ScheduleIdleHandler(int64 initial_delay_ms
) {
1097 idle_notification_delay_in_ms_
= initial_delay_ms
;
1099 idle_timer_
.Start(FROM_HERE
,
1100 base::TimeDelta::FromMilliseconds(initial_delay_ms
),
1101 this, &RenderThreadImpl::IdleHandler
);
1104 void RenderThreadImpl::IdleHandler() {
1105 bool run_in_foreground_tab
= (widget_count_
> hidden_widget_count_
) &&
1106 GetContentClient()->renderer()->
1107 RunIdleHandlerWhenWidgetsHidden();
1108 if (run_in_foreground_tab
) {
1109 if (idle_notifications_to_skip_
> 0) {
1110 --idle_notifications_to_skip_
;
1112 base::allocator::ReleaseFreeMemory();
1113 base::DiscardableMemory::ReduceMemoryUsage();
1115 ScheduleIdleHandler(kLongIdleHandlerDelayMs
);
1119 base::allocator::ReleaseFreeMemory();
1120 base::DiscardableMemory::ReleaseFreeMemory();
1122 // Continue the idle timer if the webkit shared timer is not suspended or
1123 // something is left to do.
1124 bool continue_timer
= !webkit_shared_timer_suspended_
;
1126 if (blink::mainThreadIsolate() &&
1127 !blink::mainThreadIsolate()->IdleNotification(1000)) {
1128 continue_timer
= true;
1130 if (!base::DiscardableMemory::ReduceMemoryUsage()) {
1131 continue_timer
= true;
1134 // Schedule next invocation. When the tab is originally hidden, an invocation
1135 // is scheduled for kInitialIdleHandlerDelayMs in
1136 // RenderThreadImpl::WidgetHidden in order to race to a minimal heap.
1137 // After that, idle calls can be much less frequent, so run at a maximum of
1138 // once every kLongIdleHandlerDelayMs.
1139 // Dampen the delay using the algorithm (if delay is in seconds):
1140 // delay = delay + 1 / (delay + 2)
1141 // Using floor(delay) has a dampening effect such as:
1142 // 30s, 30, 30, 31, 31, 31, 31, 32, 32, ...
1143 // If the delay is in milliseconds, the above formula is equivalent to:
1144 // delay_ms / 1000 = delay_ms / 1000 + 1 / (delay_ms / 1000 + 2)
1145 // which is equivalent to
1146 // delay_ms = delay_ms + 1000*1000 / (delay_ms + 2000).
1147 if (continue_timer
) {
1148 ScheduleIdleHandler(
1149 std::max(kLongIdleHandlerDelayMs
,
1150 idle_notification_delay_in_ms_
+
1151 1000000 / (idle_notification_delay_in_ms_
+ 2000)));
1157 FOR_EACH_OBSERVER(RenderProcessObserver
, observers_
, IdleNotification());
1160 int64
RenderThreadImpl::GetIdleNotificationDelayInMs() const {
1161 return idle_notification_delay_in_ms_
;
1164 void RenderThreadImpl::SetIdleNotificationDelayInMs(
1165 int64 idle_notification_delay_in_ms
) {
1166 idle_notification_delay_in_ms_
= idle_notification_delay_in_ms
;
1169 void RenderThreadImpl::UpdateHistograms(int sequence_number
) {
1170 child_histogram_message_filter()->SendHistograms(sequence_number
);
1173 int RenderThreadImpl::PostTaskToAllWebWorkers(const base::Closure
& closure
) {
1174 return WorkerTaskRunner::Instance()->PostTaskToAllThreads(closure
);
1177 bool RenderThreadImpl::ResolveProxy(const GURL
& url
, std::string
* proxy_list
) {
1178 bool result
= false;
1179 Send(new ViewHostMsg_ResolveProxy(url
, &result
, proxy_list
));
1183 void RenderThreadImpl::PostponeIdleNotification() {
1184 idle_notifications_to_skip_
= 2;
1187 scoped_refptr
<media::GpuVideoAcceleratorFactories
>
1188 RenderThreadImpl::GetGpuFactories() {
1189 DCHECK(IsMainThread());
1191 scoped_refptr
<GpuChannelHost
> gpu_channel_host
= GetGpuChannel();
1192 const base::CommandLine
* cmd_line
= base::CommandLine::ForCurrentProcess();
1193 scoped_refptr
<media::GpuVideoAcceleratorFactories
> gpu_factories
;
1194 scoped_refptr
<base::SingleThreadTaskRunner
> media_task_runner
=
1195 GetMediaThreadTaskRunner();
1196 if (!cmd_line
->HasSwitch(switches::kDisableAcceleratedVideoDecode
)) {
1197 if (!gpu_va_context_provider_
.get() ||
1198 gpu_va_context_provider_
->DestroyedOnMainThread()) {
1199 if (!gpu_channel_host
.get()) {
1200 gpu_channel_host
= EstablishGpuChannelSync(
1201 CAUSE_FOR_GPU_LAUNCH_WEBGRAPHICSCONTEXT3DCOMMANDBUFFERIMPL_INITIALIZE
);
1203 blink::WebGraphicsContext3D::Attributes attributes
;
1204 bool lose_context_when_out_of_memory
= false;
1205 gpu_va_context_provider_
= ContextProviderCommandBuffer::Create(
1207 WebGraphicsContext3DCommandBufferImpl::CreateOffscreenContext(
1208 gpu_channel_host
.get(),
1210 lose_context_when_out_of_memory
,
1211 GURL("chrome://gpu/RenderThreadImpl::GetGpuVDAContext3D"),
1212 WebGraphicsContext3DCommandBufferImpl::SharedMemoryLimits(),
1214 "GPU-VideoAccelerator-Offscreen");
1217 if (gpu_va_context_provider_
.get()) {
1218 gpu_factories
= RendererGpuVideoAcceleratorFactories::Create(
1219 gpu_channel_host
.get(), media_task_runner
, gpu_va_context_provider_
);
1221 return gpu_factories
;
1224 scoped_ptr
<WebGraphicsContext3DCommandBufferImpl
>
1225 RenderThreadImpl::CreateOffscreenContext3d() {
1226 blink::WebGraphicsContext3D::Attributes
attributes(GetOffscreenAttribs());
1227 bool lose_context_when_out_of_memory
= true;
1229 scoped_refptr
<GpuChannelHost
> gpu_channel_host(EstablishGpuChannelSync(
1230 CAUSE_FOR_GPU_LAUNCH_WEBGRAPHICSCONTEXT3DCOMMANDBUFFERIMPL_INITIALIZE
));
1231 return make_scoped_ptr(
1232 WebGraphicsContext3DCommandBufferImpl::CreateOffscreenContext(
1233 gpu_channel_host
.get(),
1235 lose_context_when_out_of_memory
,
1236 GURL("chrome://gpu/RenderThreadImpl::CreateOffscreenContext3d"),
1237 WebGraphicsContext3DCommandBufferImpl::SharedMemoryLimits(),
1241 scoped_refptr
<webkit::gpu::ContextProviderWebContext
>
1242 RenderThreadImpl::SharedMainThreadContextProvider() {
1243 DCHECK(IsMainThread());
1244 if (!shared_main_thread_contexts_
.get() ||
1245 shared_main_thread_contexts_
->DestroyedOnMainThread()) {
1246 shared_main_thread_contexts_
= NULL
;
1247 #if defined(OS_ANDROID)
1248 if (SynchronousCompositorFactory
* factory
=
1249 SynchronousCompositorFactory::GetInstance()) {
1250 shared_main_thread_contexts_
= factory
->CreateOffscreenContextProvider(
1251 GetOffscreenAttribs(), "Offscreen-MainThread");
1254 if (!shared_main_thread_contexts_
.get()) {
1255 shared_main_thread_contexts_
= ContextProviderCommandBuffer::Create(
1256 CreateOffscreenContext3d(), "Offscreen-MainThread");
1258 if (shared_main_thread_contexts_
.get() &&
1259 !shared_main_thread_contexts_
->BindToCurrentThread())
1260 shared_main_thread_contexts_
= NULL
;
1262 return shared_main_thread_contexts_
;
1265 AudioRendererMixerManager
* RenderThreadImpl::GetAudioRendererMixerManager() {
1266 if (!audio_renderer_mixer_manager_
) {
1267 audio_renderer_mixer_manager_
.reset(new AudioRendererMixerManager(
1268 GetAudioHardwareConfig()));
1271 return audio_renderer_mixer_manager_
.get();
1274 media::AudioHardwareConfig
* RenderThreadImpl::GetAudioHardwareConfig() {
1275 if (!audio_hardware_config_
) {
1276 media::AudioParameters input_params
;
1277 media::AudioParameters output_params
;
1278 Send(new ViewHostMsg_GetAudioHardwareConfig(
1279 &input_params
, &output_params
));
1281 audio_hardware_config_
.reset(new media::AudioHardwareConfig(
1282 input_params
, output_params
));
1283 audio_message_filter_
->SetAudioHardwareConfig(audio_hardware_config_
.get());
1286 return audio_hardware_config_
.get();
1289 base::WaitableEvent
* RenderThreadImpl::GetShutdownEvent() {
1290 return ChildProcess::current()->GetShutDownEvent();
1294 void RenderThreadImpl::PreCacheFontCharacters(const LOGFONT
& log_font
,
1295 const base::string16
& str
) {
1296 Send(new ViewHostMsg_PreCacheFontCharacters(log_font
, str
));
1299 void RenderThreadImpl::PreCacheFont(const LOGFONT
& log_font
) {
1300 Send(new ChildProcessHostMsg_PreCacheFont(log_font
));
1303 void RenderThreadImpl::ReleaseCachedFonts() {
1304 Send(new ChildProcessHostMsg_ReleaseCachedFonts());
1309 ServiceRegistry
* RenderThreadImpl::GetServiceRegistry() {
1310 return service_registry();
1313 bool RenderThreadImpl::IsImplSidePaintingEnabled() {
1314 return is_impl_side_painting_enabled_
;
1317 bool RenderThreadImpl::IsGpuRasterizationForced() {
1318 return is_gpu_rasterization_forced_
;
1321 bool RenderThreadImpl::IsGpuRasterizationEnabled() {
1322 return is_gpu_rasterization_enabled_
;
1325 bool RenderThreadImpl::IsLcdTextEnabled() {
1326 return is_lcd_text_enabled_
;
1329 bool RenderThreadImpl::IsDistanceFieldTextEnabled() {
1330 return is_distance_field_text_enabled_
;
1333 bool RenderThreadImpl::IsZeroCopyEnabled() {
1334 return is_zero_copy_enabled_
;
1337 bool RenderThreadImpl::IsOneCopyEnabled() {
1338 return is_one_copy_enabled_
;
1341 uint32
RenderThreadImpl::GetImageTextureTarget() {
1342 return use_image_texture_target_
;
1344 scoped_refptr
<base::SingleThreadTaskRunner
>
1345 RenderThreadImpl::GetCompositorMainThreadTaskRunner() {
1346 return main_thread_compositor_task_runner_
;
1349 scoped_refptr
<base::SingleThreadTaskRunner
>
1350 RenderThreadImpl::GetCompositorImplThreadTaskRunner() {
1351 return compositor_message_loop_proxy_
;
1354 gpu::GpuMemoryBufferManager
* RenderThreadImpl::GetGpuMemoryBufferManager() {
1355 return gpu_memory_buffer_manager();
1358 RendererScheduler
* RenderThreadImpl::GetRendererScheduler() {
1359 return renderer_scheduler_
.get();
1362 cc::ContextProvider
* RenderThreadImpl::GetSharedMainThreadContextProvider() {
1363 return SharedMainThreadContextProvider().get();
1366 scoped_ptr
<cc::BeginFrameSource
>
1367 RenderThreadImpl::CreateExternalBeginFrameSource(int routing_id
) {
1368 #if defined(OS_ANDROID)
1369 if (SynchronousCompositorFactory
* factory
=
1370 SynchronousCompositorFactory::GetInstance()) {
1371 return factory
->CreateExternalBeginFrameSource(routing_id
);
1374 return make_scoped_ptr(new CompositorExternalBeginFrameSource(
1375 compositor_message_filter_
.get(), sync_message_filter(), routing_id
));
1378 bool RenderThreadImpl::IsMainThread() {
1382 base::MessageLoop
* RenderThreadImpl::GetMainLoop() {
1383 return message_loop();
1386 scoped_refptr
<base::MessageLoopProxy
> RenderThreadImpl::GetIOLoopProxy() {
1387 return io_message_loop_proxy_
;
1390 scoped_ptr
<base::SharedMemory
> RenderThreadImpl::AllocateSharedMemory(
1392 return scoped_ptr
<base::SharedMemory
>(
1393 HostAllocateSharedMemoryBuffer(size
));
1396 CreateCommandBufferResult
RenderThreadImpl::CreateViewCommandBuffer(
1398 const GPUCreateCommandBufferConfig
& init_params
,
1401 "RenderThreadImpl::CreateViewCommandBuffer",
1405 CreateCommandBufferResult result
= CREATE_COMMAND_BUFFER_FAILED
;
1406 IPC::Message
* message
= new GpuHostMsg_CreateViewCommandBuffer(
1412 // Allow calling this from the compositor thread.
1413 thread_safe_sender()->Send(message
);
1418 void RenderThreadImpl::DoNotSuspendWebKitSharedTimer() {
1419 suspend_webkit_shared_timer_
= false;
1422 void RenderThreadImpl::DoNotNotifyWebKitOfModalLoop() {
1423 notify_webkit_of_modal_loop_
= false;
1426 bool RenderThreadImpl::OnControlMessageReceived(const IPC::Message
& msg
) {
1427 ObserverListBase
<RenderProcessObserver
>::Iterator
it(observers_
);
1428 RenderProcessObserver
* observer
;
1429 while ((observer
= it
.GetNext()) != NULL
) {
1430 if (observer
->OnControlMessageReceived(msg
))
1434 // Some messages are handled by delegates.
1435 if (appcache_dispatcher_
->OnMessageReceived(msg
) ||
1436 dom_storage_dispatcher_
->OnMessageReceived(msg
) ||
1437 embedded_worker_dispatcher_
->OnMessageReceived(msg
)) {
1441 bool handled
= true;
1442 IPC_BEGIN_MESSAGE_MAP(RenderThreadImpl
, msg
)
1443 IPC_MESSAGE_HANDLER(FrameMsg_NewFrame
, OnCreateNewFrame
)
1444 IPC_MESSAGE_HANDLER(FrameMsg_NewFrameProxy
, OnCreateNewFrameProxy
)
1445 IPC_MESSAGE_HANDLER(ViewMsg_SetZoomLevelForCurrentURL
,
1446 OnSetZoomLevelForCurrentURL
)
1447 // TODO(port): removed from render_messages_internal.h;
1448 // is there a new non-windows message I should add here?
1449 IPC_MESSAGE_HANDLER(ViewMsg_New
, OnCreateNewView
)
1450 IPC_MESSAGE_HANDLER(ViewMsg_NetworkTypeChanged
, OnNetworkTypeChanged
)
1451 IPC_MESSAGE_HANDLER(ViewMsg_TempCrashWithData
, OnTempCrashWithData
)
1452 IPC_MESSAGE_HANDLER(WorkerProcessMsg_CreateWorker
, OnCreateNewSharedWorker
)
1453 IPC_MESSAGE_HANDLER(ViewMsg_TimezoneChange
, OnUpdateTimezone
)
1454 #if defined(OS_ANDROID)
1455 IPC_MESSAGE_HANDLER(ViewMsg_SetWebKitSharedTimersSuspended
,
1456 OnSetWebKitSharedTimersSuspended
)
1458 #if defined(OS_MACOSX)
1459 IPC_MESSAGE_HANDLER(ViewMsg_UpdateScrollbarTheme
, OnUpdateScrollbarTheme
)
1461 #if defined(ENABLE_PLUGINS)
1462 IPC_MESSAGE_HANDLER(ViewMsg_PurgePluginListCache
, OnPurgePluginListCache
)
1464 IPC_MESSAGE_UNHANDLED(handled
= false)
1465 IPC_END_MESSAGE_MAP()
1469 void RenderThreadImpl::OnCreateNewFrame(int routing_id
,
1470 int parent_routing_id
,
1471 int proxy_routing_id
) {
1472 RenderFrameImpl::CreateFrame(routing_id
, parent_routing_id
, proxy_routing_id
);
1475 void RenderThreadImpl::OnCreateNewFrameProxy(
1477 int parent_routing_id
,
1478 int render_view_routing_id
,
1479 const FrameReplicationState
& replicated_state
) {
1480 RenderFrameProxy::CreateFrameProxy(routing_id
, parent_routing_id
,
1481 render_view_routing_id
, replicated_state
);
1484 void RenderThreadImpl::OnSetZoomLevelForCurrentURL(const std::string
& scheme
,
1485 const std::string
& host
,
1486 double zoom_level
) {
1487 RenderViewZoomer
zoomer(scheme
, host
, zoom_level
);
1488 RenderView::ForEach(&zoomer
);
1491 void RenderThreadImpl::OnCreateNewView(const ViewMsg_New_Params
& params
) {
1492 EnsureWebKitInitialized();
1493 CompositorDependencies
* compositor_deps
= this;
1494 // When bringing in render_view, also bring in webkit's glue and jsbindings.
1495 RenderViewImpl::Create(params
, compositor_deps
, false);
1498 GpuChannelHost
* RenderThreadImpl::EstablishGpuChannelSync(
1499 CauseForGpuLaunch cause_for_gpu_launch
) {
1500 TRACE_EVENT0("gpu", "RenderThreadImpl::EstablishGpuChannelSync");
1502 if (gpu_channel_
.get()) {
1503 // Do nothing if we already have a GPU channel or are already
1504 // establishing one.
1505 if (!gpu_channel_
->IsLost())
1506 return gpu_channel_
.get();
1508 // Recreate the channel if it has been lost.
1509 gpu_channel_
= NULL
;
1512 // Ask the browser for the channel name.
1514 IPC::ChannelHandle channel_handle
;
1515 gpu::GPUInfo gpu_info
;
1516 if (!Send(new GpuHostMsg_EstablishGpuChannel(cause_for_gpu_launch
,
1520 #if defined(OS_POSIX)
1521 channel_handle
.socket
.fd
== -1 ||
1523 channel_handle
.name
.empty()) {
1524 // Otherwise cancel the connection.
1528 GetContentClient()->SetGpuInfo(gpu_info
);
1530 // Cache some variables that are needed on the compositor thread for our
1531 // implementation of GpuChannelHostFactory.
1532 io_message_loop_proxy_
= ChildProcess::current()->io_message_loop_proxy();
1535 GpuChannelHost::Create(this,
1538 ChildProcess::current()->GetShutDownEvent(),
1539 gpu_memory_buffer_manager());
1540 return gpu_channel_
.get();
1543 blink::WebMediaStreamCenter
* RenderThreadImpl::CreateMediaStreamCenter(
1544 blink::WebMediaStreamCenterClient
* client
) {
1545 #if defined(OS_ANDROID)
1546 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
1547 switches::kDisableWebRTC
))
1551 #if defined(ENABLE_WEBRTC)
1552 if (!media_stream_center_
) {
1553 media_stream_center_
= GetContentClient()->renderer()
1554 ->OverrideCreateWebMediaStreamCenter(client
);
1555 if (!media_stream_center_
) {
1556 scoped_ptr
<MediaStreamCenter
> media_stream_center(
1557 new MediaStreamCenter(client
, GetPeerConnectionDependencyFactory()));
1558 media_stream_center_
= media_stream_center
.release();
1562 return media_stream_center_
;
1565 #if defined(ENABLE_WEBRTC)
1566 PeerConnectionDependencyFactory
*
1567 RenderThreadImpl::GetPeerConnectionDependencyFactory() {
1568 return peer_connection_factory_
.get();
1572 GpuChannelHost
* RenderThreadImpl::GetGpuChannel() {
1573 if (!gpu_channel_
.get())
1576 if (gpu_channel_
->IsLost())
1579 return gpu_channel_
.get();
1582 #if defined(ENABLE_PLUGINS)
1583 void RenderThreadImpl::OnPurgePluginListCache(bool reload_pages
) {
1584 EnsureWebKitInitialized();
1585 // The call below will cause a GetPlugins call with refresh=true, but at this
1586 // point we already know that the browser has refreshed its list, so disable
1587 // refresh temporarily to prevent each renderer process causing the list to be
1589 blink_platform_impl_
->set_plugin_refresh_allowed(false);
1590 blink::resetPluginCache(reload_pages
);
1591 blink_platform_impl_
->set_plugin_refresh_allowed(true);
1593 FOR_EACH_OBSERVER(RenderProcessObserver
, observers_
, PluginListChanged());
1597 void RenderThreadImpl::OnNetworkTypeChanged(
1598 net::NetworkChangeNotifier::ConnectionType type
) {
1599 EnsureWebKitInitialized();
1600 bool online
= type
!= net::NetworkChangeNotifier::CONNECTION_NONE
;
1601 WebNetworkStateNotifier::setOnLine(online
);
1603 RenderProcessObserver
, observers_
, NetworkStateChanged(online
));
1604 WebNetworkStateNotifier::setWebConnectionType(
1605 NetConnectionTypeToWebConnectionType(type
));
1608 void RenderThreadImpl::OnTempCrashWithData(const GURL
& data
) {
1609 GetContentClient()->SetActiveURL(data
);
1613 void RenderThreadImpl::OnUpdateTimezone() {
1614 if (!blink_platform_impl_
)
1616 NotifyTimezoneChange();
1619 #if defined(OS_ANDROID)
1620 void RenderThreadImpl::OnSetWebKitSharedTimersSuspended(bool suspend
) {
1621 if (suspend_webkit_shared_timer_
) {
1622 EnsureWebKitInitialized();
1624 blink_platform_impl_
->SuspendSharedTimer();
1626 blink_platform_impl_
->ResumeSharedTimer();
1628 webkit_shared_timer_suspended_
= suspend
;
1633 #if defined(OS_MACOSX)
1634 void RenderThreadImpl::OnUpdateScrollbarTheme(
1635 float initial_button_delay
,
1636 float autoscroll_button_delay
,
1637 bool jump_on_track_click
,
1638 blink::ScrollerStyle preferred_scroller_style
,
1640 EnsureWebKitInitialized();
1641 static_cast<WebScrollbarBehaviorImpl
*>(
1642 blink_platform_impl_
->scrollbarBehavior())
1643 ->set_jump_on_track_click(jump_on_track_click
);
1644 blink::WebScrollbarTheme::updateScrollbars(initial_button_delay
,
1645 autoscroll_button_delay
,
1646 preferred_scroller_style
,
1651 void RenderThreadImpl::OnCreateNewSharedWorker(
1652 const WorkerProcessMsg_CreateWorker_Params
& params
) {
1653 // EmbeddedSharedWorkerStub will self-destruct.
1654 new EmbeddedSharedWorkerStub(params
.url
,
1656 params
.content_security_policy
,
1657 params
.security_policy_type
,
1658 params
.pause_on_start
,
1662 void RenderThreadImpl::OnMemoryPressure(
1663 base::MemoryPressureListener::MemoryPressureLevel memory_pressure_level
) {
1664 base::allocator::ReleaseFreeMemory();
1666 // Trigger full v8 garbage collection on critical memory notification. This
1667 // will potentially hang the renderer for a long time, however, when we
1668 // receive a memory pressure notification, we might be about to be killed.
1669 if (blink_platform_impl_
&& blink::mainThreadIsolate()) {
1670 blink::mainThreadIsolate()->LowMemoryNotification();
1673 if (memory_pressure_level
==
1674 base::MemoryPressureListener::MEMORY_PRESSURE_LEVEL_CRITICAL
) {
1675 if (blink_platform_impl_
) {
1676 // Clear the image cache. Do not call into blink if it is not initialized.
1677 blink::WebImageCache::clear();
1680 // Purge Skia font cache, by setting it to 0 and then again to the previous
1682 size_t font_cache_limit
= SkGraphics::SetFontCacheLimit(0);
1683 SkGraphics::SetFontCacheLimit(font_cache_limit
);
1687 scoped_refptr
<base::MessageLoopProxy
>
1688 RenderThreadImpl::GetFileThreadMessageLoopProxy() {
1689 DCHECK(message_loop() == base::MessageLoop::current());
1690 if (!file_thread_
) {
1691 file_thread_
.reset(new base::Thread("Renderer::FILE"));
1692 file_thread_
->Start();
1694 return file_thread_
->message_loop_proxy();
1697 scoped_refptr
<base::SingleThreadTaskRunner
>
1698 RenderThreadImpl::GetMediaThreadTaskRunner() {
1699 DCHECK(message_loop() == base::MessageLoop::current());
1700 if (!media_thread_
) {
1701 media_thread_
.reset(new base::Thread("Media"));
1702 media_thread_
->Start();
1704 #if defined(OS_ANDROID)
1705 renderer_demuxer_
= new RendererDemuxerAndroid();
1706 AddFilter(renderer_demuxer_
.get());
1709 return media_thread_
->message_loop_proxy();
1712 void RenderThreadImpl::SampleGamepads(blink::WebGamepads
* data
) {
1713 blink_platform_impl_
->sampleGamepads(*data
);
1716 void RenderThreadImpl::WidgetCreated() {
1720 void RenderThreadImpl::WidgetDestroyed() {
1724 void RenderThreadImpl::WidgetHidden() {
1725 DCHECK_LT(hidden_widget_count_
, widget_count_
);
1726 hidden_widget_count_
++;
1728 if (widget_count_
&& hidden_widget_count_
== widget_count_
) {
1729 // TODO(reveman): Remove this when we have a better mechanism to prevent
1730 // total discardable memory used by all renderers from growing too large.
1731 base::internal::DiscardableMemoryEmulated::
1732 ReduceMemoryUsageUntilWithinLimit(
1733 kEmulatedDiscardableMemoryBytesToKeepWhenWidgetsHidden
);
1735 if (GetContentClient()->renderer()->RunIdleHandlerWhenWidgetsHidden())
1736 ScheduleIdleHandler(kInitialIdleHandlerDelayMs
);
1740 void RenderThreadImpl::WidgetRestored() {
1741 DCHECK_GT(hidden_widget_count_
, 0);
1742 hidden_widget_count_
--;
1744 if (!GetContentClient()->renderer()->RunIdleHandlerWhenWidgetsHidden()) {
1748 ScheduleIdleHandler(kLongIdleHandlerDelayMs
);
1751 } // namespace content