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/raster_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_shared_bitmap_manager.h"
43 #include "content/child/content_child_helpers.h"
44 #include "content/child/db_message_filter.h"
45 #include "content/child/indexed_db/indexed_db_dispatcher.h"
46 #include "content/child/indexed_db/indexed_db_message_filter.h"
47 #include "content/child/npapi/npobject_util.h"
48 #include "content/child/plugin_messages.h"
49 #include "content/child/resource_dispatcher.h"
50 #include "content/child/runtime_features.h"
51 #include "content/child/thread_safe_sender.h"
52 #include "content/child/web_database_observer_impl.h"
53 #include "content/child/worker_task_runner.h"
54 #include "content/common/child_process_messages.h"
55 #include "content/common/content_constants_internal.h"
56 #include "content/common/database_messages.h"
57 #include "content/common/dom_storage/dom_storage_messages.h"
58 #include "content/common/frame_messages.h"
59 #include "content/common/gpu/client/context_provider_command_buffer.h"
60 #include "content/common/gpu/client/gpu_channel_host.h"
61 #include "content/common/gpu/gpu_messages.h"
62 #include "content/common/gpu/gpu_process_launch_causes.h"
63 #include "content/common/render_frame_setup.mojom.h"
64 #include "content/common/resource_messages.h"
65 #include "content/common/view_messages.h"
66 #include "content/common/worker_messages.h"
67 #include "content/public/common/content_constants.h"
68 #include "content/public/common/content_paths.h"
69 #include "content/public/common/content_switches.h"
70 #include "content/public/common/renderer_preferences.h"
71 #include "content/public/common/url_constants.h"
72 #include "content/public/renderer/content_renderer_client.h"
73 #include "content/public/renderer/render_process_observer.h"
74 #include "content/public/renderer/render_view_visitor.h"
75 #include "content/renderer/devtools/devtools_agent_filter.h"
76 #include "content/renderer/devtools/v8_sampling_profiler.h"
77 #include "content/renderer/dom_storage/dom_storage_dispatcher.h"
78 #include "content/renderer/dom_storage/webstoragearea_impl.h"
79 #include "content/renderer/dom_storage/webstoragenamespace_impl.h"
80 #include "content/renderer/gpu/compositor_external_begin_frame_source.h"
81 #include "content/renderer/gpu/compositor_forwarding_message_filter.h"
82 #include "content/renderer/gpu/compositor_output_surface.h"
83 #include "content/renderer/input/input_event_filter.h"
84 #include "content/renderer/input/input_handler_manager.h"
85 #include "content/renderer/input/main_thread_input_event_filter.h"
86 #include "content/renderer/media/aec_dump_message_filter.h"
87 #include "content/renderer/media/audio_input_message_filter.h"
88 #include "content/renderer/media/audio_message_filter.h"
89 #include "content/renderer/media/audio_renderer_mixer_manager.h"
90 #include "content/renderer/media/media_stream_center.h"
91 #include "content/renderer/media/midi_message_filter.h"
92 #include "content/renderer/media/render_media_client.h"
93 #include "content/renderer/media/renderer_gpu_video_accelerator_factories.h"
94 #include "content/renderer/media/video_capture_impl_manager.h"
95 #include "content/renderer/media/video_capture_message_filter.h"
96 #include "content/renderer/net_info_helper.h"
97 #include "content/renderer/p2p/socket_dispatcher.h"
98 #include "content/renderer/render_frame_proxy.h"
99 #include "content/renderer/render_process_impl.h"
100 #include "content/renderer/render_view_impl.h"
101 #include "content/renderer/renderer_blink_platform_impl.h"
102 #include "content/renderer/scheduler/renderer_scheduler.h"
103 #include "content/renderer/service_worker/embedded_worker_context_message_filter.h"
104 #include "content/renderer/service_worker/embedded_worker_dispatcher.h"
105 #include "content/renderer/shared_worker/embedded_shared_worker_stub.h"
106 #include "gin/public/debug.h"
107 #include "gpu/GLES2/gl2extchromium.h"
108 #include "gpu/command_buffer/common/gles2_cmd_utils.h"
109 #include "ipc/ipc_channel_handle.h"
110 #include "ipc/ipc_platform_file.h"
111 #include "ipc/mojo/ipc_channel_mojo.h"
112 #include "media/base/audio_hardware_config.h"
113 #include "media/base/media.h"
114 #include "media/filters/gpu_video_accelerator_factories.h"
115 #include "mojo/common/common_type_converters.h"
116 #include "net/base/net_errors.h"
117 #include "net/base/net_util.h"
118 #include "skia/ext/event_tracer_impl.h"
119 #include "third_party/WebKit/public/platform/WebString.h"
120 #include "third_party/WebKit/public/platform/WebThread.h"
121 #include "third_party/WebKit/public/web/WebColorName.h"
122 #include "third_party/WebKit/public/web/WebDatabase.h"
123 #include "third_party/WebKit/public/web/WebDocument.h"
124 #include "third_party/WebKit/public/web/WebFrame.h"
125 #include "third_party/WebKit/public/web/WebImageCache.h"
126 #include "third_party/WebKit/public/web/WebKit.h"
127 #include "third_party/WebKit/public/web/WebNetworkStateNotifier.h"
128 #include "third_party/WebKit/public/web/WebPopupMenu.h"
129 #include "third_party/WebKit/public/web/WebRuntimeFeatures.h"
130 #include "third_party/WebKit/public/web/WebScriptController.h"
131 #include "third_party/WebKit/public/web/WebSecurityPolicy.h"
132 #include "third_party/WebKit/public/web/WebView.h"
133 #include "third_party/skia/include/core/SkGraphics.h"
134 #include "ui/base/layout.h"
135 #include "ui/base/ui_base_switches.h"
136 #include "v8/include/v8.h"
138 #if defined(OS_ANDROID)
139 #include <cpu-features.h>
140 #include "content/renderer/android/synchronous_compositor_factory.h"
141 #include "content/renderer/media/android/renderer_demuxer_android.h"
144 #if defined(OS_MACOSX)
145 #include "content/renderer/webscrollbarbehavior_impl_mac.h"
148 #if defined(OS_POSIX)
149 #include "ipc/ipc_channel_posix.h"
157 #include "content/child/npapi/np_channel_base.h"
160 #if defined(ENABLE_PLUGINS)
161 #include "content/renderer/npapi/plugin_channel_host.h"
164 #if defined(ENABLE_WEBRTC)
165 #include "content/renderer/media/peer_connection_tracker.h"
166 #include "content/renderer/media/rtc_peer_connection_handler.h"
167 #include "content/renderer/media/webrtc/peer_connection_dependency_factory.h"
168 #include "content/renderer/media/webrtc_identity_service.h"
171 #ifdef ENABLE_VTUNE_JIT_INTERFACE
172 #include "v8/src/third_party/vtune/v8-vtune.h"
175 using base::ThreadRestrictions
;
176 using blink::WebDocument
;
177 using blink::WebFrame
;
178 using blink::WebNetworkStateNotifier
;
179 using blink::WebRuntimeFeatures
;
180 using blink::WebScriptController
;
181 using blink::WebSecurityPolicy
;
182 using blink::WebString
;
183 using blink::WebView
;
189 const int64 kInitialIdleHandlerDelayMs
= 1000;
190 const int64 kLongIdleHandlerDelayMs
= 30*1000;
192 // Maximum allocation size allowed for image scaling filters that
193 // require pre-scaling. Skia will fallback to a filter that doesn't
194 // require pre-scaling if the default filter would require an
195 // allocation that exceeds this limit.
196 const size_t kImageCacheSingleAllocationByteLimit
= 64 * 1024 * 1024;
198 const size_t kEmulatedDiscardableMemoryBytesToKeepWhenWidgetsHidden
=
201 // Keep the global RenderThreadImpl in a TLS slot so it is impossible to access
202 // incorrectly from the wrong thread.
203 base::LazyInstance
<base::ThreadLocalPointer
<RenderThreadImpl
> >
204 lazy_tls
= LAZY_INSTANCE_INITIALIZER
;
206 class RenderViewZoomer
: public RenderViewVisitor
{
208 RenderViewZoomer(const std::string
& scheme
,
209 const std::string
& host
,
210 double zoom_level
) : scheme_(scheme
),
212 zoom_level_(zoom_level
) {
215 bool Visit(RenderView
* render_view
) override
{
216 WebView
* webview
= render_view
->GetWebView();
217 WebDocument document
= webview
->mainFrame()->document();
219 // Don't set zoom level for full-page plugin since they don't use the same
221 if (document
.isPluginDocument())
223 GURL
url(document
.url());
224 // Empty scheme works as wildcard that matches any scheme,
225 if ((net::GetHostOrSpecFromURL(url
) == host_
) &&
226 (scheme_
.empty() || scheme_
== url
.scheme()) &&
227 !static_cast<RenderViewImpl
*>(render_view
)
228 ->uses_temporary_zoom_level()) {
229 webview
->hidePopups();
230 webview
->setZoomLevel(zoom_level_
);
236 const std::string scheme_
;
237 const std::string host_
;
238 const double zoom_level_
;
240 DISALLOW_COPY_AND_ASSIGN(RenderViewZoomer
);
243 std::string
HostToCustomHistogramSuffix(const std::string
& host
) {
244 if (host
== "mail.google.com")
246 if (host
== "docs.google.com" || host
== "drive.google.com")
248 if (host
== "plus.google.com")
250 return std::string();
253 void* CreateHistogram(
254 const char *name
, int min
, int max
, size_t buckets
) {
257 std::string histogram_name
;
258 RenderThreadImpl
* render_thread_impl
= RenderThreadImpl::current();
259 if (render_thread_impl
) { // Can be null in tests.
260 histogram_name
= render_thread_impl
->
261 histogram_customizer()->ConvertToCustomHistogramName(name
);
263 histogram_name
= std::string(name
);
265 base::HistogramBase
* histogram
= base::Histogram::FactoryGet(
266 histogram_name
, min
, max
, buckets
,
267 base::Histogram::kUmaTargetedHistogramFlag
);
271 void AddHistogramSample(void* hist
, int sample
) {
272 base::Histogram
* histogram
= static_cast<base::Histogram
*>(hist
);
273 histogram
->Add(sample
);
276 scoped_ptr
<base::SharedMemory
> AllocateSharedMemoryFunction(size_t size
) {
277 return RenderThreadImpl::Get()->HostAllocateSharedMemoryBuffer(size
);
280 void EnableBlinkPlatformLogChannels(const std::string
& channels
) {
281 if (channels
.empty())
283 base::StringTokenizer
t(channels
, ", ");
285 blink::enableLogChannel(t
.token().c_str());
288 void NotifyTimezoneChangeOnThisThread() {
289 v8::Isolate
* isolate
= v8::Isolate::GetCurrent();
292 v8::Date::DateTimeConfigurationChangeNotification(isolate
);
295 class RenderFrameSetupImpl
: public mojo::InterfaceImpl
<RenderFrameSetup
> {
297 RenderFrameSetupImpl()
298 : routing_id_highmark_(-1) {
301 void GetServiceProviderForFrame(
302 int32_t frame_routing_id
,
303 mojo::InterfaceRequest
<mojo::ServiceProvider
> request
) override
{
304 // TODO(morrita): This is for investigating http://crbug.com/415059 and
305 // should be removed once it is fixed.
306 CHECK_LT(routing_id_highmark_
, frame_routing_id
);
307 routing_id_highmark_
= frame_routing_id
;
309 RenderFrameImpl
* frame
= RenderFrameImpl::FromRoutingID(frame_routing_id
);
310 // We can receive a GetServiceProviderForFrame message for a frame not yet
311 // created due to a race between the message and a ViewMsg_New IPC that
312 // triggers creation of the RenderFrame we want.
314 RenderThreadImpl::current()->RegisterPendingRenderFrameConnect(
315 frame_routing_id
, request
.PassMessagePipe());
319 frame
->BindServiceRegistry(request
.PassMessagePipe());
323 int32_t routing_id_highmark_
;
326 void CreateRenderFrameSetup(mojo::InterfaceRequest
<RenderFrameSetup
> request
) {
327 mojo::BindToRequest(new RenderFrameSetupImpl(), &request
);
330 bool ShouldUseMojoChannel() {
331 return CommandLine::ForCurrentProcess()->HasSwitch(
332 switches::kEnableRendererMojoChannel
) ||
333 IPC::ChannelMojo::ShouldBeUsed();
336 blink::WebGraphicsContext3D::Attributes
GetOffscreenAttribs() {
337 blink::WebGraphicsContext3D::Attributes attributes
;
338 attributes
.shareResources
= true;
339 attributes
.depth
= false;
340 attributes
.stencil
= false;
341 attributes
.antialias
= false;
342 attributes
.noAutomaticFlushes
= true;
348 // For measuring memory usage after each task. Behind a command line flag.
349 class MemoryObserver
: public base::MessageLoop::TaskObserver
{
352 ~MemoryObserver() override
{}
354 void WillProcessTask(const base::PendingTask
& pending_task
) override
{}
356 void DidProcessTask(const base::PendingTask
& pending_task
) override
{
357 LOCAL_HISTOGRAM_MEMORY_KB("Memory.RendererUsed", GetMemoryUsageKB());
361 DISALLOW_COPY_AND_ASSIGN(MemoryObserver
);
364 RenderThreadImpl::HistogramCustomizer::HistogramCustomizer() {
365 custom_histograms_
.insert("V8.MemoryExternalFragmentationTotal");
366 custom_histograms_
.insert("V8.MemoryHeapSampleTotalCommitted");
367 custom_histograms_
.insert("V8.MemoryHeapSampleTotalUsed");
370 RenderThreadImpl::HistogramCustomizer::~HistogramCustomizer() {}
372 void RenderThreadImpl::HistogramCustomizer::RenderViewNavigatedToHost(
373 const std::string
& host
, size_t view_count
) {
374 if (CommandLine::ForCurrentProcess()->HasSwitch(
375 switches::kDisableHistogramCustomizer
)) {
378 // Check if all RenderViews are displaying a page from the same host. If there
379 // is only one RenderView, the common host is this view's host. If there are
380 // many, check if this one shares the common host of the other
381 // RenderViews. It's ok to not detect some cases where the RenderViews share a
382 // common host. This information is only used for producing custom histograms.
385 else if (host
!= common_host_
)
386 SetCommonHost(std::string());
389 std::string
RenderThreadImpl::HistogramCustomizer::ConvertToCustomHistogramName(
390 const char* histogram_name
) const {
391 std::string
name(histogram_name
);
392 if (!common_host_histogram_suffix_
.empty() &&
393 custom_histograms_
.find(name
) != custom_histograms_
.end())
394 name
+= common_host_histogram_suffix_
;
398 void RenderThreadImpl::HistogramCustomizer::SetCommonHost(
399 const std::string
& host
) {
400 if (host
!= common_host_
) {
402 common_host_histogram_suffix_
= HostToCustomHistogramSuffix(host
);
403 blink::mainThreadIsolate()->SetCreateHistogramFunction(CreateHistogram
);
407 RenderThreadImpl
* RenderThreadImpl::current() {
408 return lazy_tls
.Pointer()->Get();
411 // When we run plugins in process, we actually run them on the render thread,
412 // which means that we need to make the render thread pump UI events.
413 RenderThreadImpl::RenderThreadImpl()
414 : ChildThread(Options(ShouldUseMojoChannel())) {
418 RenderThreadImpl::RenderThreadImpl(const std::string
& channel_name
)
419 : ChildThread(Options(channel_name
, ShouldUseMojoChannel())) {
423 RenderThreadImpl::RenderThreadImpl(
424 scoped_ptr
<base::MessageLoop
> main_message_loop
)
425 : ChildThread(Options(ShouldUseMojoChannel())),
426 main_message_loop_(main_message_loop
.Pass()) {
430 void RenderThreadImpl::Init() {
431 TRACE_EVENT_BEGIN_ETW("RenderThreadImpl::Init", 0, "");
433 base::debug::TraceLog::GetInstance()->SetThreadSortIndex(
434 base::PlatformThread::CurrentId(),
435 kTraceEventRendererMainThreadSortIndex
);
437 #if defined(OS_MACOSX) || defined(OS_ANDROID)
438 // On Mac and Android, the select popups are rendered by the browser.
439 blink::WebView::setUseExternalPopupMenus(true);
442 lazy_tls
.Pointer()->Set(this);
444 // Register this object as the main thread.
445 ChildProcess::current()->set_main_thread(this);
447 // In single process the single process is all there is.
448 suspend_webkit_shared_timer_
= true;
449 notify_webkit_of_modal_loop_
= true;
450 webkit_shared_timer_suspended_
= false;
452 hidden_widget_count_
= 0;
453 idle_notification_delay_in_ms_
= kInitialIdleHandlerDelayMs
;
454 idle_notifications_to_skip_
= 0;
455 layout_test_mode_
= false;
457 appcache_dispatcher_
.reset(
458 new AppCacheDispatcher(Get(), new AppCacheFrontendImpl()));
459 dom_storage_dispatcher_
.reset(new DomStorageDispatcher());
460 main_thread_indexed_db_dispatcher_
.reset(new IndexedDBDispatcher(
461 thread_safe_sender()));
462 renderer_scheduler_
= RendererScheduler::Create();
463 embedded_worker_dispatcher_
.reset(new EmbeddedWorkerDispatcher());
465 media_stream_center_
= NULL
;
467 db_message_filter_
= new DBMessageFilter();
468 AddFilter(db_message_filter_
.get());
470 vc_manager_
.reset(new VideoCaptureImplManager());
471 AddFilter(vc_manager_
->video_capture_message_filter());
473 #if defined(ENABLE_WEBRTC)
474 peer_connection_tracker_
.reset(new PeerConnectionTracker());
475 AddObserver(peer_connection_tracker_
.get());
477 p2p_socket_dispatcher_
=
478 new P2PSocketDispatcher(GetIOMessageLoopProxy().get());
479 AddFilter(p2p_socket_dispatcher_
.get());
481 webrtc_identity_service_
.reset(new WebRTCIdentityService());
483 aec_dump_message_filter_
=
484 new AecDumpMessageFilter(GetIOMessageLoopProxy(),
485 message_loop()->message_loop_proxy());
486 AddFilter(aec_dump_message_filter_
.get());
488 peer_connection_factory_
.reset(new PeerConnectionDependencyFactory(
489 p2p_socket_dispatcher_
.get()));
490 #endif // defined(ENABLE_WEBRTC)
492 audio_input_message_filter_
=
493 new AudioInputMessageFilter(GetIOMessageLoopProxy());
494 AddFilter(audio_input_message_filter_
.get());
496 audio_message_filter_
= new AudioMessageFilter(GetIOMessageLoopProxy());
497 AddFilter(audio_message_filter_
.get());
499 midi_message_filter_
= new MidiMessageFilter(GetIOMessageLoopProxy());
500 AddFilter(midi_message_filter_
.get());
502 AddFilter((new IndexedDBMessageFilter(thread_safe_sender()))->GetFilter());
504 AddFilter((new EmbeddedWorkerContextMessageFilter())->GetFilter());
506 GetContentClient()->renderer()->RenderThreadStarted();
508 InitSkiaEventTracer();
510 const CommandLine
& command_line
= *CommandLine::ForCurrentProcess();
512 is_impl_side_painting_enabled_
=
513 command_line
.HasSwitch(switches::kEnableImplSidePainting
);
514 cc_blink::WebLayerImpl::SetImplSidePaintingEnabled(
515 is_impl_side_painting_enabled_
);
517 is_zero_copy_enabled_
= command_line
.HasSwitch(switches::kEnableZeroCopy
);
519 #if defined(OS_MACOSX) || defined(OS_ANDROID)
520 // TODO(danakj): If changing these also update NumberOfRendererRasterThreads
521 // in compositor_util.cc. We should be using methods from compositor_util here
522 // instead of inspecting flags.
523 is_one_copy_enabled_
= command_line
.HasSwitch(switches::kEnableOneCopy
);
525 is_one_copy_enabled_
= !command_line
.HasSwitch(switches::kDisableOneCopy
);
528 use_image_texture_target_
= GL_TEXTURE_2D
;
529 if (command_line
.HasSwitch(switches::kUseImageTextureTarget
)) {
530 std::string target_string
=
531 command_line
.GetSwitchValueASCII(switches::kUseImageTextureTarget
);
532 const unsigned targets
[] = {
533 GL_TEXTURE_RECTANGLE_ARB
,
534 GL_TEXTURE_EXTERNAL_OES
536 for (auto target
: targets
) {
537 if (target_string
== gpu::gles2::GLES2Util::GetStringEnum(target
))
538 use_image_texture_target_
= target
;
542 if (command_line
.HasSwitch(switches::kDisableLCDText
)) {
543 is_lcd_text_enabled_
= false;
544 } else if (command_line
.HasSwitch(switches::kEnableLCDText
)) {
545 is_lcd_text_enabled_
= true;
547 #if defined(OS_ANDROID)
548 is_lcd_text_enabled_
= false;
550 is_lcd_text_enabled_
= true;
554 is_gpu_rasterization_enabled_
=
555 command_line
.HasSwitch(switches::kEnableGpuRasterization
);
556 is_gpu_rasterization_forced_
=
557 command_line
.HasSwitch(switches::kForceGpuRasterization
);
559 if (command_line
.HasSwitch(switches::kDisableDistanceFieldText
)) {
560 is_distance_field_text_enabled_
= false;
561 } else if (command_line
.HasSwitch(switches::kEnableDistanceFieldText
)) {
562 is_distance_field_text_enabled_
= true;
564 is_distance_field_text_enabled_
= false;
567 // Note that under Linux, the media library will normally already have
568 // been initialized by the Zygote before this instance became a Renderer.
569 base::FilePath media_path
;
570 PathService::Get(DIR_MEDIA_LIBS
, &media_path
);
571 if (!media_path
.empty())
572 media::InitializeMediaLibrary(media_path
);
574 memory_pressure_listener_
.reset(new base::MemoryPressureListener(
575 base::Bind(&RenderThreadImpl::OnMemoryPressure
, base::Unretained(this))));
577 std::vector
<base::DiscardableMemoryType
> supported_types
;
578 base::DiscardableMemory::GetSupportedTypes(&supported_types
);
579 DCHECK(!supported_types
.empty());
581 // The default preferred type is always the first one in list.
582 base::DiscardableMemoryType type
= supported_types
[0];
584 if (command_line
.HasSwitch(switches::kUseDiscardableMemory
)) {
585 std::string requested_type_name
= command_line
.GetSwitchValueASCII(
586 switches::kUseDiscardableMemory
);
587 base::DiscardableMemoryType requested_type
=
588 base::DiscardableMemory::GetNamedType(requested_type_name
);
589 if (std::find(supported_types
.begin(),
590 supported_types
.end(),
591 requested_type
) != supported_types
.end()) {
592 type
= requested_type
;
594 LOG(ERROR
) << "Requested discardable memory type is not supported.";
598 base::DiscardableMemory::SetPreferredType(type
);
600 if (is_impl_side_painting_enabled_
) {
601 int num_raster_threads
= 0;
602 std::string string_value
=
603 command_line
.GetSwitchValueASCII(switches::kNumRasterThreads
);
604 bool parsed_num_raster_threads
=
605 base::StringToInt(string_value
, &num_raster_threads
);
606 DCHECK(parsed_num_raster_threads
) << string_value
;
607 DCHECK_GT(num_raster_threads
, 0);
608 cc::RasterWorkerPool::SetNumRasterThreads(num_raster_threads
);
611 base::DiscardableMemoryShmemAllocator::SetInstance(
612 ChildThread::discardable_shared_memory_manager());
614 service_registry()->AddService
<RenderFrameSetup
>(
615 base::Bind(CreateRenderFrameSetup
));
617 TRACE_EVENT_END_ETW("RenderThreadImpl::Init", 0, "");
620 RenderThreadImpl::~RenderThreadImpl() {
621 for (std::map
<int, mojo::MessagePipeHandle
>::iterator it
=
622 pending_render_frame_connects_
.begin();
623 it
!= pending_render_frame_connects_
.end();
625 mojo::CloseRaw(it
->second
);
629 void RenderThreadImpl::Shutdown() {
631 RenderProcessObserver
, observers_
, OnRenderProcessShutdown());
633 ChildThread::Shutdown();
635 if (memory_observer_
) {
636 message_loop()->RemoveTaskObserver(memory_observer_
.get());
637 memory_observer_
.reset();
640 // Wait for all databases to be closed.
641 if (blink_platform_impl_
) {
642 // WaitForAllDatabasesToClose might run a nested message loop. To avoid
643 // processing timer events while we're already in the process of shutting
644 // down blink, put a ScopePageLoadDeferrer on the stack.
645 WebView::willEnterModalLoop();
646 blink_platform_impl_
->web_database_observer_impl()
647 ->WaitForAllDatabasesToClose();
648 WebView::didExitModalLoop();
651 // Shutdown in reverse of the initialization order.
652 if (devtools_agent_message_filter_
.get()) {
653 RemoveFilter(devtools_agent_message_filter_
.get());
654 devtools_agent_message_filter_
= NULL
;
657 RemoveFilter(audio_input_message_filter_
.get());
658 audio_input_message_filter_
= NULL
;
660 #if defined(ENABLE_WEBRTC)
661 RTCPeerConnectionHandler::DestructAllHandlers();
662 // |peer_connection_factory_| cannot be deleted until after the main message
663 // loop has been destroyed. This is because there may be pending tasks that
664 // hold on to objects produced by the PC factory that depend on threads owned
665 // by the PC factory. Once those tasks have been freed, the factory can be
668 RemoveFilter(vc_manager_
->video_capture_message_filter());
671 RemoveFilter(db_message_filter_
.get());
672 db_message_filter_
= NULL
;
674 // Shutdown the file thread if it's running.
676 file_thread_
->Stop();
678 if (compositor_message_filter_
.get()) {
679 RemoveFilter(compositor_message_filter_
.get());
680 compositor_message_filter_
= NULL
;
683 media_thread_
.reset();
685 // AudioMessageFilter may be accessed on |media_thread_|, so shutdown after.
686 RemoveFilter(audio_message_filter_
.get());
687 audio_message_filter_
= NULL
;
689 compositor_thread_
.reset();
691 main_input_callback_
.Cancel();
692 input_handler_manager_
.reset();
693 if (input_event_filter_
.get()) {
694 RemoveFilter(input_event_filter_
.get());
695 input_event_filter_
= NULL
;
698 // RemoveEmbeddedWorkerRoute may be called while deleting
699 // EmbeddedWorkerDispatcher. So it must be deleted before deleting
701 embedded_worker_dispatcher_
.reset();
703 // Ramp down IDB before we ramp down WebKit (and V8), since IDB classes might
704 // hold pointers to V8 objects (e.g., via pending requests).
705 main_thread_indexed_db_dispatcher_
.reset();
707 main_thread_compositor_task_runner_
= NULL
;
709 if (gpu_channel_
.get())
710 gpu_channel_
->DestroyChannel();
714 // Clean up plugin channels before this thread goes away.
715 NPChannelBase::CleanupChannels();
718 // Shut down the message loop before shutting down Blink.
719 // This prevents a scenario where a pending task in the message loop accesses
720 // Blink objects after Blink shuts down.
721 // This must be at the very end of the shutdown sequence. You must not touch
722 // the message loop after this.
723 main_message_loop_
.reset();
724 if (blink_platform_impl_
)
727 lazy_tls
.Pointer()->Set(NULL
);
730 bool RenderThreadImpl::Send(IPC::Message
* msg
) {
731 // Certain synchronous messages cannot always be processed synchronously by
732 // the browser, e.g., putting up UI and waiting for the user. This could cause
733 // a complete hang of Chrome if a windowed plug-in is trying to communicate
734 // with the renderer thread since the browser's UI thread could be stuck
735 // (within a Windows API call) trying to synchronously communicate with the
736 // plug-in. The remedy is to pump messages on this thread while the browser
737 // is processing this request. This creates an opportunity for re-entrancy
738 // into WebKit, so we need to take care to disable callbacks, timers, and
739 // pending network loads that could trigger such callbacks.
740 bool pumping_events
= false;
741 if (msg
->is_sync()) {
742 if (msg
->is_caller_pumping_messages()) {
743 pumping_events
= true;
747 bool suspend_webkit_shared_timer
= true; // default value
748 std::swap(suspend_webkit_shared_timer
, suspend_webkit_shared_timer_
);
750 bool notify_webkit_of_modal_loop
= true; // default value
751 std::swap(notify_webkit_of_modal_loop
, notify_webkit_of_modal_loop_
);
753 #if defined(ENABLE_PLUGINS)
754 int render_view_id
= MSG_ROUTING_NONE
;
757 if (pumping_events
) {
758 if (suspend_webkit_shared_timer
)
759 blink_platform_impl_
->SuspendSharedTimer();
761 if (notify_webkit_of_modal_loop
)
762 WebView::willEnterModalLoop();
763 #if defined(ENABLE_PLUGINS)
764 RenderViewImpl
* render_view
=
765 RenderViewImpl::FromRoutingID(msg
->routing_id());
767 render_view_id
= msg
->routing_id();
768 PluginChannelHost::Broadcast(
769 new PluginMsg_SignalModalDialogEvent(render_view_id
));
774 bool rv
= ChildThread::Send(msg
);
776 if (pumping_events
) {
777 #if defined(ENABLE_PLUGINS)
778 if (render_view_id
!= MSG_ROUTING_NONE
) {
779 PluginChannelHost::Broadcast(
780 new PluginMsg_ResetModalDialogEvent(render_view_id
));
784 if (notify_webkit_of_modal_loop
)
785 WebView::didExitModalLoop();
787 if (suspend_webkit_shared_timer
)
788 blink_platform_impl_
->ResumeSharedTimer();
794 base::MessageLoop
* RenderThreadImpl::GetMessageLoop() {
795 return message_loop();
798 IPC::SyncChannel
* RenderThreadImpl::GetChannel() {
802 std::string
RenderThreadImpl::GetLocale() {
803 // The browser process should have passed the locale to the renderer via the
804 // --lang command line flag.
805 const CommandLine
& parsed_command_line
= *CommandLine::ForCurrentProcess();
806 const std::string
& lang
=
807 parsed_command_line
.GetSwitchValueASCII(switches::kLang
);
808 DCHECK(!lang
.empty());
812 IPC::SyncMessageFilter
* RenderThreadImpl::GetSyncMessageFilter() {
813 return sync_message_filter();
816 scoped_refptr
<base::MessageLoopProxy
>
817 RenderThreadImpl::GetIOMessageLoopProxy() {
818 return ChildProcess::current()->io_message_loop_proxy();
821 void RenderThreadImpl::AddRoute(int32 routing_id
, IPC::Listener
* listener
) {
822 ChildThread::GetRouter()->AddRoute(routing_id
, listener
);
823 std::map
<int, mojo::MessagePipeHandle
>::iterator it
=
824 pending_render_frame_connects_
.find(routing_id
);
825 if (it
== pending_render_frame_connects_
.end())
828 RenderFrameImpl
* frame
= RenderFrameImpl::FromRoutingID(routing_id
);
832 mojo::ScopedMessagePipeHandle
handle(it
->second
);
833 pending_render_frame_connects_
.erase(it
);
834 frame
->BindServiceRegistry(handle
.Pass());
837 void RenderThreadImpl::RemoveRoute(int32 routing_id
) {
838 ChildThread::GetRouter()->RemoveRoute(routing_id
);
841 void RenderThreadImpl::AddEmbeddedWorkerRoute(int32 routing_id
,
842 IPC::Listener
* listener
) {
843 AddRoute(routing_id
, listener
);
844 if (devtools_agent_message_filter_
.get()) {
845 devtools_agent_message_filter_
->AddEmbeddedWorkerRouteOnMainThread(
850 void RenderThreadImpl::RemoveEmbeddedWorkerRoute(int32 routing_id
) {
851 RemoveRoute(routing_id
);
852 if (devtools_agent_message_filter_
.get()) {
853 devtools_agent_message_filter_
->RemoveEmbeddedWorkerRouteOnMainThread(
858 void RenderThreadImpl::RegisterPendingRenderFrameConnect(
860 mojo::ScopedMessagePipeHandle handle
) {
861 std::pair
<std::map
<int, mojo::MessagePipeHandle
>::iterator
, bool> result
=
862 pending_render_frame_connects_
.insert(
863 std::make_pair(routing_id
, handle
.release()));
864 CHECK(result
.second
) << "Inserting a duplicate item.";
867 int RenderThreadImpl::GenerateRoutingID() {
868 int routing_id
= MSG_ROUTING_NONE
;
869 Send(new ViewHostMsg_GenerateRoutingID(&routing_id
));
873 void RenderThreadImpl::AddFilter(IPC::MessageFilter
* filter
) {
874 channel()->AddFilter(filter
);
877 void RenderThreadImpl::RemoveFilter(IPC::MessageFilter
* filter
) {
878 channel()->RemoveFilter(filter
);
881 void RenderThreadImpl::AddObserver(RenderProcessObserver
* observer
) {
882 observers_
.AddObserver(observer
);
885 void RenderThreadImpl::RemoveObserver(RenderProcessObserver
* observer
) {
886 observers_
.RemoveObserver(observer
);
889 void RenderThreadImpl::SetResourceDispatcherDelegate(
890 ResourceDispatcherDelegate
* delegate
) {
891 resource_dispatcher()->set_delegate(delegate
);
894 void RenderThreadImpl::EnsureWebKitInitialized() {
895 if (blink_platform_impl_
)
898 const CommandLine
& command_line
= *CommandLine::ForCurrentProcess();
900 #ifdef ENABLE_VTUNE_JIT_INTERFACE
901 if (command_line
.HasSwitch(switches::kEnableVtune
))
902 gin::Debug::SetJitCodeEventHandler(vTune::GetVtuneCodeEventHandler());
905 blink_platform_impl_
.reset(
906 new RendererBlinkPlatformImpl(renderer_scheduler_
.get()));
907 blink::initialize(blink_platform_impl_
.get());
909 v8::Isolate
* isolate
= blink::mainThreadIsolate();
911 isolate
->SetCounterFunction(base::StatsTable::FindLocation
);
912 isolate
->SetCreateHistogramFunction(CreateHistogram
);
913 isolate
->SetAddHistogramSampleFunction(AddHistogramSample
);
915 main_thread_compositor_task_runner_
=
916 renderer_scheduler()->CompositorTaskRunner();
918 main_input_callback_
.Reset(
919 base::Bind(base::IgnoreResult(&RenderThreadImpl::OnMessageReceived
),
920 base::Unretained(this)));
922 bool enable
= !command_line
.HasSwitch(switches::kDisableThreadedCompositing
);
924 #if defined(OS_ANDROID)
925 if (SynchronousCompositorFactory
* factory
=
926 SynchronousCompositorFactory::GetInstance())
927 compositor_message_loop_proxy_
=
928 factory
->GetCompositorMessageLoop();
930 if (!compositor_message_loop_proxy_
.get()) {
931 compositor_thread_
.reset(new base::Thread("Compositor"));
932 compositor_thread_
->Start();
933 #if defined(OS_ANDROID)
934 compositor_thread_
->SetPriority(base::kThreadPriority_Display
);
936 compositor_message_loop_proxy_
=
937 compositor_thread_
->message_loop_proxy();
938 compositor_message_loop_proxy_
->PostTask(
940 base::Bind(base::IgnoreResult(&ThreadRestrictions::SetIOAllowed
),
944 InputHandlerManagerClient
* input_handler_manager_client
= NULL
;
945 #if defined(OS_ANDROID)
946 if (SynchronousCompositorFactory
* factory
=
947 SynchronousCompositorFactory::GetInstance()) {
948 input_handler_manager_client
= factory
->GetInputHandlerManagerClient();
951 if (!input_handler_manager_client
) {
952 scoped_refptr
<InputEventFilter
> compositor_input_event_filter(
953 new InputEventFilter(main_input_callback_
.callback(),
954 main_thread_compositor_task_runner_
,
955 compositor_message_loop_proxy_
));
956 input_handler_manager_client
= compositor_input_event_filter
.get();
957 input_event_filter_
= compositor_input_event_filter
;
959 input_handler_manager_
.reset(new InputHandlerManager(
960 compositor_message_loop_proxy_
, input_handler_manager_client
,
961 renderer_scheduler()));
964 if (!input_event_filter_
.get()) {
965 // Always provide an input event filter implementation to ensure consistent
966 // input event scheduling and prioritization.
967 // TODO(jdduke): Merge InputEventFilter, InputHandlerManager and
968 // MainThreadInputEventFilter, crbug.com/436057.
969 input_event_filter_
= new MainThreadInputEventFilter(
970 main_input_callback_
.callback(), main_thread_compositor_task_runner_
);
972 AddFilter(input_event_filter_
.get());
974 scoped_refptr
<base::MessageLoopProxy
> compositor_impl_side_loop
;
976 compositor_impl_side_loop
= compositor_message_loop_proxy_
;
978 compositor_impl_side_loop
= base::MessageLoopProxy::current();
980 compositor_message_filter_
= new CompositorForwardingMessageFilter(
981 compositor_impl_side_loop
.get());
982 AddFilter(compositor_message_filter_
.get());
984 RenderThreadImpl::RegisterSchemes();
986 EnableBlinkPlatformLogChannels(
987 command_line
.GetSwitchValueASCII(switches::kBlinkPlatformLogChannels
));
989 SetRuntimeFeaturesDefaultsAndUpdateFromArgs(command_line
);
991 if (!media::IsMediaLibraryInitialized()) {
992 WebRuntimeFeatures::enableWebAudio(false);
995 RenderMediaClient::Initialize();
997 FOR_EACH_OBSERVER(RenderProcessObserver
, observers_
, WebKitInitialized());
999 devtools_agent_message_filter_
= new DevToolsAgentFilter();
1000 AddFilter(devtools_agent_message_filter_
.get());
1002 v8_sampling_profiler_
.reset(new V8SamplingProfiler());
1004 if (GetContentClient()->renderer()->RunIdleHandlerWhenWidgetsHidden())
1005 ScheduleIdleHandler(kLongIdleHandlerDelayMs
);
1007 cc_blink::SetSharedMemoryAllocationFunction(AllocateSharedMemoryFunction
);
1009 // Limit use of the scaled image cache to when deferred image decoding is
1011 if (!command_line
.HasSwitch(switches::kEnableDeferredImageDecoding
) &&
1012 !is_impl_side_painting_enabled_
)
1013 SkGraphics::SetResourceCacheTotalByteLimit(0u);
1015 SkGraphics::SetResourceCacheSingleAllocationByteLimit(
1016 kImageCacheSingleAllocationByteLimit
);
1018 if (command_line
.HasSwitch(switches::kMemoryMetrics
)) {
1019 memory_observer_
.reset(new MemoryObserver());
1020 message_loop()->AddTaskObserver(memory_observer_
.get());
1024 void RenderThreadImpl::RegisterSchemes() {
1025 // swappedout: pages should not be accessible, and should also
1026 // be treated as empty documents that can commit synchronously.
1027 WebString
swappedout_scheme(base::ASCIIToUTF16(kSwappedOutScheme
));
1028 WebSecurityPolicy::registerURLSchemeAsDisplayIsolated(swappedout_scheme
);
1029 WebSecurityPolicy::registerURLSchemeAsEmptyDocument(swappedout_scheme
);
1032 void RenderThreadImpl::NotifyTimezoneChange() {
1033 NotifyTimezoneChangeOnThisThread();
1034 RenderThread::Get()->PostTaskToAllWebWorkers(
1035 base::Bind(&NotifyTimezoneChangeOnThisThread
));
1038 void RenderThreadImpl::RecordAction(const base::UserMetricsAction
& action
) {
1039 Send(new ViewHostMsg_UserMetricsRecordAction(action
.str_
));
1042 void RenderThreadImpl::RecordComputedAction(const std::string
& action
) {
1043 Send(new ViewHostMsg_UserMetricsRecordAction(action
));
1046 scoped_ptr
<base::SharedMemory
>
1047 RenderThreadImpl::HostAllocateSharedMemoryBuffer(size_t size
) {
1048 return ChildThread::AllocateSharedMemory(size
, thread_safe_sender());
1051 cc::SharedBitmapManager
* RenderThreadImpl::GetSharedBitmapManager() {
1052 return shared_bitmap_manager();
1055 void RenderThreadImpl::RegisterExtension(v8::Extension
* extension
) {
1056 WebScriptController::registerExtension(extension
);
1059 void RenderThreadImpl::ScheduleIdleHandler(int64 initial_delay_ms
) {
1060 idle_notification_delay_in_ms_
= initial_delay_ms
;
1062 idle_timer_
.Start(FROM_HERE
,
1063 base::TimeDelta::FromMilliseconds(initial_delay_ms
),
1064 this, &RenderThreadImpl::IdleHandler
);
1067 void RenderThreadImpl::IdleHandler() {
1068 bool run_in_foreground_tab
= (widget_count_
> hidden_widget_count_
) &&
1069 GetContentClient()->renderer()->
1070 RunIdleHandlerWhenWidgetsHidden();
1071 if (run_in_foreground_tab
) {
1072 if (idle_notifications_to_skip_
> 0) {
1073 --idle_notifications_to_skip_
;
1075 base::allocator::ReleaseFreeMemory();
1076 base::DiscardableMemory::ReduceMemoryUsage();
1078 ScheduleIdleHandler(kLongIdleHandlerDelayMs
);
1082 base::allocator::ReleaseFreeMemory();
1083 base::DiscardableMemory::ReleaseFreeMemory();
1085 // Continue the idle timer if the webkit shared timer is not suspended or
1086 // something is left to do.
1087 bool continue_timer
= !webkit_shared_timer_suspended_
;
1089 if (blink::mainThreadIsolate() &&
1090 !blink::mainThreadIsolate()->IdleNotification(1000)) {
1091 continue_timer
= true;
1093 if (!base::DiscardableMemory::ReduceMemoryUsage()) {
1094 continue_timer
= true;
1097 // Schedule next invocation. When the tab is originally hidden, an invocation
1098 // is scheduled for kInitialIdleHandlerDelayMs in
1099 // RenderThreadImpl::WidgetHidden in order to race to a minimal heap.
1100 // After that, idle calls can be much less frequent, so run at a maximum of
1101 // once every kLongIdleHandlerDelayMs.
1102 // Dampen the delay using the algorithm (if delay is in seconds):
1103 // delay = delay + 1 / (delay + 2)
1104 // Using floor(delay) has a dampening effect such as:
1105 // 30s, 30, 30, 31, 31, 31, 31, 32, 32, ...
1106 // If the delay is in milliseconds, the above formula is equivalent to:
1107 // delay_ms / 1000 = delay_ms / 1000 + 1 / (delay_ms / 1000 + 2)
1108 // which is equivalent to
1109 // delay_ms = delay_ms + 1000*1000 / (delay_ms + 2000).
1110 if (continue_timer
) {
1111 ScheduleIdleHandler(
1112 std::max(kLongIdleHandlerDelayMs
,
1113 idle_notification_delay_in_ms_
+
1114 1000000 / (idle_notification_delay_in_ms_
+ 2000)));
1120 FOR_EACH_OBSERVER(RenderProcessObserver
, observers_
, IdleNotification());
1123 int64
RenderThreadImpl::GetIdleNotificationDelayInMs() const {
1124 return idle_notification_delay_in_ms_
;
1127 void RenderThreadImpl::SetIdleNotificationDelayInMs(
1128 int64 idle_notification_delay_in_ms
) {
1129 idle_notification_delay_in_ms_
= idle_notification_delay_in_ms
;
1132 void RenderThreadImpl::UpdateHistograms(int sequence_number
) {
1133 child_histogram_message_filter()->SendHistograms(sequence_number
);
1136 int RenderThreadImpl::PostTaskToAllWebWorkers(const base::Closure
& closure
) {
1137 return WorkerTaskRunner::Instance()->PostTaskToAllThreads(closure
);
1140 bool RenderThreadImpl::ResolveProxy(const GURL
& url
, std::string
* proxy_list
) {
1141 bool result
= false;
1142 Send(new ViewHostMsg_ResolveProxy(url
, &result
, proxy_list
));
1146 void RenderThreadImpl::PostponeIdleNotification() {
1147 idle_notifications_to_skip_
= 2;
1150 scoped_refptr
<media::GpuVideoAcceleratorFactories
>
1151 RenderThreadImpl::GetGpuFactories() {
1152 DCHECK(IsMainThread());
1154 scoped_refptr
<GpuChannelHost
> gpu_channel_host
= GetGpuChannel();
1155 const CommandLine
* cmd_line
= CommandLine::ForCurrentProcess();
1156 scoped_refptr
<media::GpuVideoAcceleratorFactories
> gpu_factories
;
1157 scoped_refptr
<base::SingleThreadTaskRunner
> media_task_runner
=
1158 GetMediaThreadTaskRunner();
1159 if (!cmd_line
->HasSwitch(switches::kDisableAcceleratedVideoDecode
)) {
1160 if (!gpu_va_context_provider_
.get() ||
1161 gpu_va_context_provider_
->DestroyedOnMainThread()) {
1162 if (!gpu_channel_host
.get()) {
1163 gpu_channel_host
= EstablishGpuChannelSync(
1164 CAUSE_FOR_GPU_LAUNCH_WEBGRAPHICSCONTEXT3DCOMMANDBUFFERIMPL_INITIALIZE
);
1166 blink::WebGraphicsContext3D::Attributes attributes
;
1167 bool lose_context_when_out_of_memory
= false;
1168 gpu_va_context_provider_
= ContextProviderCommandBuffer::Create(
1170 WebGraphicsContext3DCommandBufferImpl::CreateOffscreenContext(
1171 gpu_channel_host
.get(),
1173 lose_context_when_out_of_memory
,
1174 GURL("chrome://gpu/RenderThreadImpl::GetGpuVDAContext3D"),
1175 WebGraphicsContext3DCommandBufferImpl::SharedMemoryLimits(),
1177 "GPU-VideoAccelerator-Offscreen");
1180 if (gpu_va_context_provider_
.get()) {
1181 gpu_factories
= RendererGpuVideoAcceleratorFactories::Create(
1182 gpu_channel_host
.get(), media_task_runner
, gpu_va_context_provider_
);
1184 return gpu_factories
;
1187 scoped_ptr
<WebGraphicsContext3DCommandBufferImpl
>
1188 RenderThreadImpl::CreateOffscreenContext3d() {
1189 blink::WebGraphicsContext3D::Attributes
attributes(GetOffscreenAttribs());
1190 bool lose_context_when_out_of_memory
= true;
1192 scoped_refptr
<GpuChannelHost
> gpu_channel_host(EstablishGpuChannelSync(
1193 CAUSE_FOR_GPU_LAUNCH_WEBGRAPHICSCONTEXT3DCOMMANDBUFFERIMPL_INITIALIZE
));
1194 return make_scoped_ptr(
1195 WebGraphicsContext3DCommandBufferImpl::CreateOffscreenContext(
1196 gpu_channel_host
.get(),
1198 lose_context_when_out_of_memory
,
1199 GURL("chrome://gpu/RenderThreadImpl::CreateOffscreenContext3d"),
1200 WebGraphicsContext3DCommandBufferImpl::SharedMemoryLimits(),
1204 scoped_refptr
<webkit::gpu::ContextProviderWebContext
>
1205 RenderThreadImpl::SharedMainThreadContextProvider() {
1206 DCHECK(IsMainThread());
1207 if (!shared_main_thread_contexts_
.get() ||
1208 shared_main_thread_contexts_
->DestroyedOnMainThread()) {
1209 shared_main_thread_contexts_
= NULL
;
1210 #if defined(OS_ANDROID)
1211 if (SynchronousCompositorFactory
* factory
=
1212 SynchronousCompositorFactory::GetInstance()) {
1213 shared_main_thread_contexts_
= factory
->CreateOffscreenContextProvider(
1214 GetOffscreenAttribs(), "Offscreen-MainThread");
1217 if (!shared_main_thread_contexts_
.get()) {
1218 shared_main_thread_contexts_
= ContextProviderCommandBuffer::Create(
1219 CreateOffscreenContext3d(), "Offscreen-MainThread");
1221 if (shared_main_thread_contexts_
.get() &&
1222 !shared_main_thread_contexts_
->BindToCurrentThread())
1223 shared_main_thread_contexts_
= NULL
;
1225 return shared_main_thread_contexts_
;
1228 AudioRendererMixerManager
* RenderThreadImpl::GetAudioRendererMixerManager() {
1229 if (!audio_renderer_mixer_manager_
) {
1230 audio_renderer_mixer_manager_
.reset(new AudioRendererMixerManager(
1231 GetAudioHardwareConfig()));
1234 return audio_renderer_mixer_manager_
.get();
1237 media::AudioHardwareConfig
* RenderThreadImpl::GetAudioHardwareConfig() {
1238 if (!audio_hardware_config_
) {
1239 media::AudioParameters input_params
;
1240 media::AudioParameters output_params
;
1241 Send(new ViewHostMsg_GetAudioHardwareConfig(
1242 &input_params
, &output_params
));
1244 audio_hardware_config_
.reset(new media::AudioHardwareConfig(
1245 input_params
, output_params
));
1246 audio_message_filter_
->SetAudioHardwareConfig(audio_hardware_config_
.get());
1249 return audio_hardware_config_
.get();
1252 base::WaitableEvent
* RenderThreadImpl::GetShutdownEvent() {
1253 return ChildProcess::current()->GetShutDownEvent();
1257 void RenderThreadImpl::PreCacheFontCharacters(const LOGFONT
& log_font
,
1258 const base::string16
& str
) {
1259 Send(new ViewHostMsg_PreCacheFontCharacters(log_font
, str
));
1262 void RenderThreadImpl::PreCacheFont(const LOGFONT
& log_font
) {
1263 Send(new ChildProcessHostMsg_PreCacheFont(log_font
));
1266 void RenderThreadImpl::ReleaseCachedFonts() {
1267 Send(new ChildProcessHostMsg_ReleaseCachedFonts());
1272 ServiceRegistry
* RenderThreadImpl::GetServiceRegistry() {
1273 return service_registry();
1276 bool RenderThreadImpl::IsMainThread() {
1280 base::MessageLoop
* RenderThreadImpl::GetMainLoop() {
1281 return message_loop();
1284 scoped_refptr
<base::MessageLoopProxy
> RenderThreadImpl::GetIOLoopProxy() {
1285 return io_message_loop_proxy_
;
1288 scoped_ptr
<base::SharedMemory
> RenderThreadImpl::AllocateSharedMemory(
1290 return scoped_ptr
<base::SharedMemory
>(
1291 HostAllocateSharedMemoryBuffer(size
));
1294 CreateCommandBufferResult
RenderThreadImpl::CreateViewCommandBuffer(
1296 const GPUCreateCommandBufferConfig
& init_params
,
1299 "RenderThreadImpl::CreateViewCommandBuffer",
1303 CreateCommandBufferResult result
= CREATE_COMMAND_BUFFER_FAILED
;
1304 IPC::Message
* message
= new GpuHostMsg_CreateViewCommandBuffer(
1310 // Allow calling this from the compositor thread.
1311 thread_safe_sender()->Send(message
);
1316 void RenderThreadImpl::DoNotSuspendWebKitSharedTimer() {
1317 suspend_webkit_shared_timer_
= false;
1320 void RenderThreadImpl::DoNotNotifyWebKitOfModalLoop() {
1321 notify_webkit_of_modal_loop_
= false;
1324 bool RenderThreadImpl::OnControlMessageReceived(const IPC::Message
& msg
) {
1325 ObserverListBase
<RenderProcessObserver
>::Iterator
it(observers_
);
1326 RenderProcessObserver
* observer
;
1327 while ((observer
= it
.GetNext()) != NULL
) {
1328 if (observer
->OnControlMessageReceived(msg
))
1332 // Some messages are handled by delegates.
1333 if (appcache_dispatcher_
->OnMessageReceived(msg
) ||
1334 dom_storage_dispatcher_
->OnMessageReceived(msg
) ||
1335 embedded_worker_dispatcher_
->OnMessageReceived(msg
)) {
1339 bool handled
= true;
1340 IPC_BEGIN_MESSAGE_MAP(RenderThreadImpl
, msg
)
1341 IPC_MESSAGE_HANDLER(FrameMsg_NewFrame
, OnCreateNewFrame
)
1342 IPC_MESSAGE_HANDLER(FrameMsg_NewFrameProxy
, OnCreateNewFrameProxy
)
1343 IPC_MESSAGE_HANDLER(ViewMsg_SetZoomLevelForCurrentURL
,
1344 OnSetZoomLevelForCurrentURL
)
1345 // TODO(port): removed from render_messages_internal.h;
1346 // is there a new non-windows message I should add here?
1347 IPC_MESSAGE_HANDLER(ViewMsg_New
, OnCreateNewView
)
1348 IPC_MESSAGE_HANDLER(ViewMsg_NetworkTypeChanged
, OnNetworkTypeChanged
)
1349 IPC_MESSAGE_HANDLER(ViewMsg_TempCrashWithData
, OnTempCrashWithData
)
1350 IPC_MESSAGE_HANDLER(WorkerProcessMsg_CreateWorker
, OnCreateNewSharedWorker
)
1351 IPC_MESSAGE_HANDLER(ViewMsg_TimezoneChange
, OnUpdateTimezone
)
1352 #if defined(OS_ANDROID)
1353 IPC_MESSAGE_HANDLER(ViewMsg_SetWebKitSharedTimersSuspended
,
1354 OnSetWebKitSharedTimersSuspended
)
1356 #if defined(OS_MACOSX)
1357 IPC_MESSAGE_HANDLER(ViewMsg_UpdateScrollbarTheme
, OnUpdateScrollbarTheme
)
1359 #if defined(ENABLE_PLUGINS)
1360 IPC_MESSAGE_HANDLER(ViewMsg_PurgePluginListCache
, OnPurgePluginListCache
)
1362 IPC_MESSAGE_UNHANDLED(handled
= false)
1363 IPC_END_MESSAGE_MAP()
1367 void RenderThreadImpl::OnCreateNewFrame(int routing_id
,
1368 int parent_routing_id
,
1369 int proxy_routing_id
) {
1370 RenderFrameImpl::CreateFrame(routing_id
, parent_routing_id
, proxy_routing_id
);
1373 void RenderThreadImpl::OnCreateNewFrameProxy(
1375 int parent_routing_id
,
1376 int render_view_routing_id
,
1377 const FrameReplicationState
& replicated_state
) {
1378 RenderFrameProxy::CreateFrameProxy(routing_id
, parent_routing_id
,
1379 render_view_routing_id
, replicated_state
);
1382 void RenderThreadImpl::OnSetZoomLevelForCurrentURL(const std::string
& scheme
,
1383 const std::string
& host
,
1384 double zoom_level
) {
1385 RenderViewZoomer
zoomer(scheme
, host
, zoom_level
);
1386 RenderView::ForEach(&zoomer
);
1389 void RenderThreadImpl::OnCreateNewView(const ViewMsg_New_Params
& params
) {
1390 EnsureWebKitInitialized();
1391 // When bringing in render_view, also bring in webkit's glue and jsbindings.
1392 RenderViewImpl::Create(params
, false);
1395 GpuChannelHost
* RenderThreadImpl::EstablishGpuChannelSync(
1396 CauseForGpuLaunch cause_for_gpu_launch
) {
1397 TRACE_EVENT0("gpu", "RenderThreadImpl::EstablishGpuChannelSync");
1399 if (gpu_channel_
.get()) {
1400 // Do nothing if we already have a GPU channel or are already
1401 // establishing one.
1402 if (!gpu_channel_
->IsLost())
1403 return gpu_channel_
.get();
1405 // Recreate the channel if it has been lost.
1406 gpu_channel_
= NULL
;
1409 // Ask the browser for the channel name.
1411 IPC::ChannelHandle channel_handle
;
1412 gpu::GPUInfo gpu_info
;
1413 if (!Send(new GpuHostMsg_EstablishGpuChannel(cause_for_gpu_launch
,
1417 #if defined(OS_POSIX)
1418 channel_handle
.socket
.fd
== -1 ||
1420 channel_handle
.name
.empty()) {
1421 // Otherwise cancel the connection.
1425 GetContentClient()->SetGpuInfo(gpu_info
);
1427 // Cache some variables that are needed on the compositor thread for our
1428 // implementation of GpuChannelHostFactory.
1429 io_message_loop_proxy_
= ChildProcess::current()->io_message_loop_proxy();
1432 GpuChannelHost::Create(this,
1435 ChildProcess::current()->GetShutDownEvent(),
1436 gpu_memory_buffer_manager());
1437 return gpu_channel_
.get();
1440 blink::WebMediaStreamCenter
* RenderThreadImpl::CreateMediaStreamCenter(
1441 blink::WebMediaStreamCenterClient
* client
) {
1442 #if defined(OS_ANDROID)
1443 if (CommandLine::ForCurrentProcess()->HasSwitch(
1444 switches::kDisableWebRTC
))
1448 #if defined(ENABLE_WEBRTC)
1449 if (!media_stream_center_
) {
1450 media_stream_center_
= GetContentClient()->renderer()
1451 ->OverrideCreateWebMediaStreamCenter(client
);
1452 if (!media_stream_center_
) {
1453 scoped_ptr
<MediaStreamCenter
> media_stream_center(
1454 new MediaStreamCenter(client
, GetPeerConnectionDependencyFactory()));
1455 media_stream_center_
= media_stream_center
.release();
1459 return media_stream_center_
;
1462 #if defined(ENABLE_WEBRTC)
1463 PeerConnectionDependencyFactory
*
1464 RenderThreadImpl::GetPeerConnectionDependencyFactory() {
1465 return peer_connection_factory_
.get();
1469 GpuChannelHost
* RenderThreadImpl::GetGpuChannel() {
1470 if (!gpu_channel_
.get())
1473 if (gpu_channel_
->IsLost())
1476 return gpu_channel_
.get();
1479 #if defined(ENABLE_PLUGINS)
1480 void RenderThreadImpl::OnPurgePluginListCache(bool reload_pages
) {
1481 EnsureWebKitInitialized();
1482 // The call below will cause a GetPlugins call with refresh=true, but at this
1483 // point we already know that the browser has refreshed its list, so disable
1484 // refresh temporarily to prevent each renderer process causing the list to be
1486 blink_platform_impl_
->set_plugin_refresh_allowed(false);
1487 blink::resetPluginCache(reload_pages
);
1488 blink_platform_impl_
->set_plugin_refresh_allowed(true);
1490 FOR_EACH_OBSERVER(RenderProcessObserver
, observers_
, PluginListChanged());
1494 void RenderThreadImpl::OnNetworkTypeChanged(
1495 net::NetworkChangeNotifier::ConnectionType type
) {
1496 EnsureWebKitInitialized();
1497 bool online
= type
!= net::NetworkChangeNotifier::CONNECTION_NONE
;
1498 WebNetworkStateNotifier::setOnLine(online
);
1500 RenderProcessObserver
, observers_
, NetworkStateChanged(online
));
1501 WebNetworkStateNotifier::setWebConnectionType(
1502 NetConnectionTypeToWebConnectionType(type
));
1505 void RenderThreadImpl::OnTempCrashWithData(const GURL
& data
) {
1506 GetContentClient()->SetActiveURL(data
);
1510 void RenderThreadImpl::OnUpdateTimezone() {
1511 if (!blink_platform_impl_
)
1513 NotifyTimezoneChange();
1516 #if defined(OS_ANDROID)
1517 void RenderThreadImpl::OnSetWebKitSharedTimersSuspended(bool suspend
) {
1518 if (suspend_webkit_shared_timer_
) {
1519 EnsureWebKitInitialized();
1521 blink_platform_impl_
->SuspendSharedTimer();
1523 blink_platform_impl_
->ResumeSharedTimer();
1525 webkit_shared_timer_suspended_
= suspend
;
1530 #if defined(OS_MACOSX)
1531 void RenderThreadImpl::OnUpdateScrollbarTheme(
1532 float initial_button_delay
,
1533 float autoscroll_button_delay
,
1534 bool jump_on_track_click
,
1535 blink::ScrollerStyle preferred_scroller_style
,
1537 EnsureWebKitInitialized();
1538 static_cast<WebScrollbarBehaviorImpl
*>(
1539 blink_platform_impl_
->scrollbarBehavior())
1540 ->set_jump_on_track_click(jump_on_track_click
);
1541 blink::WebScrollbarTheme::updateScrollbars(initial_button_delay
,
1542 autoscroll_button_delay
,
1543 preferred_scroller_style
,
1548 void RenderThreadImpl::OnCreateNewSharedWorker(
1549 const WorkerProcessMsg_CreateWorker_Params
& params
) {
1550 // EmbeddedSharedWorkerStub will self-destruct.
1551 new EmbeddedSharedWorkerStub(params
.url
,
1553 params
.content_security_policy
,
1554 params
.security_policy_type
,
1555 params
.pause_on_start
,
1559 void RenderThreadImpl::OnMemoryPressure(
1560 base::MemoryPressureListener::MemoryPressureLevel memory_pressure_level
) {
1561 base::allocator::ReleaseFreeMemory();
1563 // Trigger full v8 garbage collection on critical memory notification. This
1564 // will potentially hang the renderer for a long time, however, when we
1565 // receive a memory pressure notification, we might be about to be killed.
1566 if (blink_platform_impl_
&& blink::mainThreadIsolate()) {
1567 blink::mainThreadIsolate()->LowMemoryNotification();
1570 if (memory_pressure_level
==
1571 base::MemoryPressureListener::MEMORY_PRESSURE_LEVEL_CRITICAL
) {
1572 if (blink_platform_impl_
) {
1573 // Clear the image cache. Do not call into blink if it is not initialized.
1574 blink::WebImageCache::clear();
1577 // Purge Skia font cache, by setting it to 0 and then again to the previous
1579 size_t font_cache_limit
= SkGraphics::SetFontCacheLimit(0);
1580 SkGraphics::SetFontCacheLimit(font_cache_limit
);
1584 scoped_refptr
<base::MessageLoopProxy
>
1585 RenderThreadImpl::GetFileThreadMessageLoopProxy() {
1586 DCHECK(message_loop() == base::MessageLoop::current());
1587 if (!file_thread_
) {
1588 file_thread_
.reset(new base::Thread("Renderer::FILE"));
1589 file_thread_
->Start();
1591 return file_thread_
->message_loop_proxy();
1594 scoped_refptr
<base::SingleThreadTaskRunner
>
1595 RenderThreadImpl::GetMediaThreadTaskRunner() {
1596 DCHECK(message_loop() == base::MessageLoop::current());
1597 if (!media_thread_
) {
1598 media_thread_
.reset(new base::Thread("Media"));
1599 media_thread_
->Start();
1601 #if defined(OS_ANDROID)
1602 renderer_demuxer_
= new RendererDemuxerAndroid();
1603 AddFilter(renderer_demuxer_
.get());
1606 return media_thread_
->message_loop_proxy();
1609 void RenderThreadImpl::SampleGamepads(blink::WebGamepads
* data
) {
1610 blink_platform_impl_
->sampleGamepads(*data
);
1613 void RenderThreadImpl::WidgetCreated() {
1617 void RenderThreadImpl::WidgetDestroyed() {
1621 void RenderThreadImpl::WidgetHidden() {
1622 DCHECK_LT(hidden_widget_count_
, widget_count_
);
1623 hidden_widget_count_
++;
1625 if (widget_count_
&& hidden_widget_count_
== widget_count_
) {
1626 // TODO(reveman): Remove this when we have a better mechanism to prevent
1627 // total discardable memory used by all renderers from growing too large.
1628 base::internal::DiscardableMemoryEmulated::
1629 ReduceMemoryUsageUntilWithinLimit(
1630 kEmulatedDiscardableMemoryBytesToKeepWhenWidgetsHidden
);
1632 if (GetContentClient()->renderer()->RunIdleHandlerWhenWidgetsHidden())
1633 ScheduleIdleHandler(kInitialIdleHandlerDelayMs
);
1637 void RenderThreadImpl::WidgetRestored() {
1638 DCHECK_GT(hidden_widget_count_
, 0);
1639 hidden_widget_count_
--;
1641 if (!GetContentClient()->renderer()->RunIdleHandlerWhenWidgetsHidden()) {
1645 ScheduleIdleHandler(kLongIdleHandlerDelayMs
);
1648 } // namespace content