blob: 408fe12d6ba9d655cfbd606a9a0bd9bd4c664dfa [file] [log] [blame]
[email protected]d3d6325d2012-01-03 21:17:361// Copyright (c) 2012 The Chromium Authors. All rights reserved.
license.botbf09a502008-08-24 00:55:552// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
initial.commit09911bf2008-07-26 23:55:294
[email protected]f1a29a02011-10-06 23:08:445#include "content/renderer/render_thread_impl.h"
initial.commit09911bf2008-07-26 23:55:296
[email protected]da00a2882009-03-09 17:51:197#include <algorithm>
[email protected]61a9b2d82010-02-26 00:31:088#include <limits>
[email protected]75e126b932009-09-28 19:38:499#include <map>
dcheng07945f632015-12-26 07:59:3210#include <utility>
[email protected]da00a2882009-03-09 17:51:1911#include <vector>
12
[email protected]237a14852012-04-28 02:56:3813#include "base/allocator/allocator_extension.h"
harakenbbfdd9f02017-01-12 07:14:0414#include "base/at_exit.h"
[email protected]06533c0b2009-03-05 21:39:1115#include "base/command_line.h"
creis9f7248b2016-01-27 20:27:3916#include "base/debug/crash_logging.h"
[email protected]94f9a0f682009-06-15 18:30:3017#include "base/lazy_instance.h"
[email protected]bee16aab2009-08-26 15:55:0318#include "base/logging.h"
avi1023d012015-12-25 02:39:1419#include "base/macros.h"
reveman1af05cb32015-03-17 23:18:1620#include "base/memory/discardable_memory_allocator.h"
hajimehoshi7bb39582016-10-12 04:30:5721#include "base/memory/memory_coordinator_client_registry.h"
dchengcedca5612016-04-09 01:40:1522#include "base/memory/ptr_util.h"
[email protected]8bac37b2013-07-18 19:13:5623#include "base/memory/shared_memory.h"
[email protected]835d7c82010-10-14 04:38:3824#include "base/metrics/field_trial.h"
asvitkine8d51e9d2016-09-02 23:55:4325#include "base/metrics/histogram_macros.h"
[email protected]433df472012-03-07 20:33:3926#include "base/path_service.h"
tasakb46626a2016-10-18 05:54:4427#include "base/process/process_metrics.h"
fdoray2df4a9e2016-07-18 23:47:1628#include "base/run_loop.h"
[email protected]21aa99682013-06-11 07:17:0129#include "base/strings/string16.h"
[email protected]1e1d1e12014-01-17 16:14:2930#include "base/strings/string_number_conversions.h"
hablichd6a4f122015-10-28 11:34:4931#include "base/strings/string_split.h"
ccameron6728bae32015-01-09 20:18:0632#include "base/strings/sys_string_conversions.h"
[email protected]74ebfb12013-06-07 20:48:0033#include "base/strings/utf_string_conversions.h"
fdoray50a38342016-11-21 20:46:0434#include "base/threading/sequenced_worker_pool.h"
reveman34b7a1522015-03-23 20:27:4735#include "base/threading/simple_thread.h"
[email protected]1357c322010-12-30 22:18:5636#include "base/threading/thread_local.h"
[email protected]d293572a2013-05-23 18:50:4537#include "base/threading/thread_restrictions.h"
gab30f26df2016-05-11 19:37:5538#include "base/threading/thread_task_runner_handle.h"
ccameron9c48d1d42016-09-22 01:46:0139#include "base/trace_event/memory_dump_manager.h"
primiano9e38d552015-01-28 04:18:0140#include "base/trace_event/trace_event.h"
[email protected]7a4de7a62010-08-17 18:38:2441#include "base/values.h"
avi1023d012015-12-25 02:39:1442#include "build/build_config.h"
jbroman0d302162015-09-05 05:46:2343#include "cc/base/histograms.h"
[email protected]d72493152014-01-08 17:37:4544#include "cc/base/switches.h"
[email protected]38564622014-08-19 02:47:1845#include "cc/blink/web_layer_impl.h"
ericrk9151705c2016-07-26 19:53:1646#include "cc/output/buffer_to_texture_target_map.h"
danakj1120f4c2016-09-15 02:05:3247#include "cc/output/compositor_frame_sink.h"
jbroman6ccbc7d472016-07-27 04:45:4148#include "cc/output/copy_output_request.h"
danakj83066a32016-06-21 02:34:4949#include "cc/output/vulkan_in_process_context_provider.h"
danakj920156852015-05-18 20:22:2950#include "cc/raster/task_graph_runner.h"
vollick1050cc62015-12-03 07:04:5451#include "cc/trees/layer_tree_host_common.h"
loysoa6edaaff2015-05-25 03:26:4452#include "cc/trees/layer_tree_settings.h"
penghuangd81c1a62016-11-02 20:06:0653#include "components/discardable_memory/client/client_discardable_shared_memory_manager.h"
[email protected]a8cb3b73b2013-08-12 05:50:5054#include "content/child/appcache/appcache_dispatcher.h"
55#include "content/child/appcache/appcache_frontend_impl.h"
dmurph1fb98482016-03-30 21:14:2656#include "content/child/blob_storage/blob_message_filter.h"
[email protected]10208ea2013-06-06 20:08:0357#include "content/child/child_histogram_message_filter.h"
alexclarke0bc36e8d32014-12-17 17:29:2058#include "content/child/child_resource_message_filter.h"
jbauman2f5c1942014-12-06 03:28:2459#include "content/child/child_shared_bitmap_manager.h"
[email protected]fdeac262014-07-10 12:52:5160#include "content/child/content_child_helpers.h"
[email protected]89c36f82013-07-17 06:23:2761#include "content/child/db_message_filter.h"
[email protected]c7199a6e2013-06-04 12:56:0162#include "content/child/indexed_db/indexed_db_dispatcher.h"
bashia6264042016-09-15 04:49:5163#include "content/child/memory/child_memory_coordinator_impl.h"
[email protected]10208ea2013-06-06 20:08:0364#include "content/child/resource_dispatcher.h"
alexclarke0bc36e8d32014-12-17 17:29:2065#include "content/child/resource_scheduling_filter.h"
[email protected]643255da2013-06-12 20:55:1366#include "content/child/runtime_features.h"
[email protected]57cf97882013-06-26 20:39:0167#include "content/child/thread_safe_sender.h"
[email protected]c7199a6e2013-06-04 12:56:0168#include "content/child/web_database_observer_impl.h"
kinukoef647412015-12-23 06:10:4369#include "content/child/worker_thread_registry.h"
[email protected]bdae9812011-10-15 00:33:0370#include "content/common/child_process_messages.h"
[email protected]89c36f82013-07-17 06:23:2771#include "content/common/content_constants_internal.h"
[email protected]5f2aa722013-08-07 16:59:4172#include "content/common/dom_storage/dom_storage_messages.h"
thakis18e426412017-03-15 12:06:3773#include "content/common/features.h"
chiniforooshan614d70a2017-03-17 01:19:3374#include "content/common/field_trial_recorder.mojom.h"
[email protected]82307f6b2014-08-07 03:30:1275#include "content/common/frame_messages.h"
raymesbba82b32016-07-19 00:41:3876#include "content/common/frame_owner_properties.h"
avia7c3f51c2015-09-16 00:30:3177#include "content/common/render_process_messages.h"
[email protected]94dc971d2011-03-05 19:08:3278#include "content/common/resource_messages.h"
alexmos68734212016-08-27 00:06:3179#include "content/common/site_isolation_policy.h"
[email protected]778574e2011-03-21 22:03:5080#include "content/common/view_messages.h"
[email protected]0ec90d522014-03-12 16:28:1981#include "content/common/worker_messages.h"
[email protected]a458504b2012-07-23 19:57:0682#include "content/public/common/content_constants.h"
bashia6264042016-09-15 04:49:5183#include "content/public/common/content_features.h"
[email protected]433df472012-03-07 20:33:3984#include "content/public/common/content_paths.h"
[email protected]c08950d22011-10-13 22:20:2985#include "content/public/common/content_switches.h"
[email protected]daf82f82011-10-31 22:35:3186#include "content/public/common/renderer_preferences.h"
[email protected]58436a12012-03-21 17:10:2687#include "content/public/common/url_constants.h"
[email protected]d344114c2011-10-01 01:24:3488#include "content/public/renderer/content_renderer_client.h"
tyoshino832a58a2016-04-18 08:14:0889#include "content/public/renderer/render_thread_observer.h"
[email protected]64ffa0442011-10-03 22:08:3690#include "content/public/renderer/render_view_visitor.h"
fsamuel6c1dfeb2014-12-18 19:21:3391#include "content/renderer/browser_plugin/browser_plugin_manager.h"
jsbell279efb42015-03-31 17:02:4692#include "content/renderer/cache_storage/cache_storage_dispatcher.h"
93#include "content/renderer/cache_storage/cache_storage_message_filter.h"
prashant.nfad657e2016-06-01 07:52:1794#include "content/renderer/categorized_worker_pool.h"
[email protected]70019152012-12-19 11:44:1995#include "content/renderer/devtools/devtools_agent_filter.h"
[email protected]1910fe82012-05-10 00:04:1096#include "content/renderer/dom_storage/dom_storage_dispatcher.h"
97#include "content/renderer/dom_storage/webstoragearea_impl.h"
98#include "content/renderer/dom_storage/webstoragenamespace_impl.h"
simonhonga7e3ac42014-11-11 20:50:2299#include "content/renderer/gpu/compositor_external_begin_frame_source.h"
100#include "content/renderer/gpu/compositor_forwarding_message_filter.h"
danakj83066a32016-06-21 02:34:49101#include "content/renderer/gpu/frame_swap_message_queue.h"
danakj1120f4c2016-09-15 02:05:32102#include "content/renderer/gpu/renderer_compositor_frame_sink.h"
[email protected]7a72d452013-12-13 10:01:13103#include "content/renderer/input/input_event_filter.h"
104#include "content/renderer/input/input_handler_manager.h"
jdduke691dd572014-12-02 20:47:52105#include "content/renderer/input/main_thread_input_event_filter.h"
[email protected]f7eb0a392011-07-12 10:19:51106#include "content/renderer/media/audio_input_message_filter.h"
107#include "content/renderer/media/audio_message_filter.h"
[email protected]3958e972012-07-17 00:25:41108#include "content/renderer/media/audio_renderer_mixer_manager.h"
[email protected]d8cd8372012-03-09 10:49:51109#include "content/renderer/media/media_stream_center.h"
[email protected]a9875152013-06-22 04:03:03110#include "content/renderer/media/midi_message_filter.h"
xhwang194acae2014-11-12 22:46:33111#include "content/renderer/media/render_media_client.h"
[email protected]2329bfc72014-02-28 02:03:21112#include "content/renderer/media/renderer_gpu_video_accelerator_factories.h"
[email protected]80b161a2011-06-27 17:42:11113#include "content/renderer/media/video_capture_impl_manager.h"
[email protected]d7ff5fb2014-05-29 19:50:25114#include "content/renderer/net_info_helper.h"
[email protected]4761cf12012-09-12 10:37:55115#include "content/renderer/p2p/socket_dispatcher.h"
[email protected]82307f6b2014-08-07 03:30:12116#include "content/renderer/render_frame_proxy.h"
[email protected]8704f89b2011-04-15 00:30:05117#include "content/renderer/render_process_impl.h"
[email protected]310ebd6302011-10-10 19:06:28118#include "content/renderer/render_view_impl.h"
tfarina556a7232014-10-05 01:02:09119#include "content/renderer/renderer_blink_platform_impl.h"
jdduke94ae1f32015-02-05 06:27:13120#include "content/renderer/scheduler/resource_dispatch_throttler.h"
[email protected]7670d4332013-11-29 04:35:00121#include "content/renderer/service_worker/embedded_worker_dispatcher.h"
shimazu5de409e42016-09-29 08:45:28122#include "content/renderer/service_worker/embedded_worker_instance_client_impl.h"
mek27c9d742015-07-16 18:30:18123#include "content/renderer/service_worker/service_worker_context_client.h"
kinuko5af4ffe2015-06-09 03:38:46124#include "content/renderer/service_worker/service_worker_context_message_filter.h"
[email protected]0ec90d522014-03-12 16:28:19125#include "content/renderer/shared_worker/embedded_shared_worker_stub.h"
chunyang.daibe874c52014-11-14 06:45:05126#include "gin/public/debug.h"
dongseong.hwang72183b02014-12-08 10:41:55127#include "gpu/GLES2/gl2extchromium.h"
danakj6f4e1e22016-04-20 03:27:34128#include "gpu/command_buffer/client/shared_memory_limits.h"
danakj870925d42016-05-03 20:07:38129#include "gpu/ipc/client/command_buffer_proxy_impl.h"
penghuang346a46f92016-03-31 21:37:52130#include "gpu/ipc/client/gpu_channel_host.h"
[email protected]46f36a492010-07-28 19:36:41131#include "ipc/ipc_channel_handle.h"
amistryd4aa70d2016-06-23 07:52:37132#include "ipc/ipc_channel_mojo.h"
[email protected]cb6037d2009-11-16 22:55:17133#include "ipc/ipc_platform_file.h"
[email protected]433df472012-03-07 20:33:39134#include "media/base/media.h"
chcunningham9a285ed2017-03-08 21:48:56135#include "media/base/media_switches.h"
Brett Wilson0748bf412016-11-22 17:55:46136#include "media/media_features.h"
servolk8b3b39b2015-03-03 19:08:18137#include "media/renderers/gpu_video_accelerator_factories.h"
rockot85dce0862015-11-13 01:33:59138#include "mojo/public/cpp/bindings/strong_binding.h"
[email protected]620161e2011-03-07 18:05:26139#include "net/base/net_errors.h"
eroman9ab64842015-07-21 05:07:52140#include "net/base/port_util.h"
hablichd6a4f122015-10-28 11:34:49141#include "net/base/registry_controlled_domains/registry_controlled_domain.h"
tfarina7a4a7fd2016-01-20 14:23:44142#include "net/base/url_util.h"
brettw4b461082016-11-19 18:55:16143#include "ppapi/features/features.h"
penghuangd6843e42016-12-17 13:57:20144#include "services/service_manager/public/cpp/connector.h"
rockot734fb662016-10-15 16:41:30145#include "services/service_manager/public/cpp/interface_provider.h"
146#include "services/service_manager/public/cpp/interface_registry.h"
sadrul85cc5d82016-12-20 03:37:41147#include "services/ui/public/cpp/gpu/context_provider_command_buffer.h"
penghuangd6843e42016-12-17 13:57:20148#include "services/ui/public/interfaces/constants.mojom.h"
[email protected]b48c53ad2014-02-05 21:59:18149#include "skia/ext/event_tracer_impl.h"
ssid59c969162015-07-28 13:02:58150#include "skia/ext/skia_memory_dump_provider.h"
kinukoed1ed1d2017-02-08 09:13:43151#include "third_party/WebKit/public/platform/WebCache.h"
reed6e5a72222015-08-06 20:37:16152#include "third_party/WebKit/public/platform/WebImageGenerator.h"
bashi5f4c78922016-08-18 23:06:08153#include "third_party/WebKit/public/platform/WebMemoryCoordinator.h"
kinukofbfee762017-03-08 04:01:06154#include "third_party/WebKit/public/platform/WebNetworkStateNotifier.h"
[email protected]89c36f82013-07-17 06:23:27155#include "third_party/WebKit/public/platform/WebString.h"
skyostil457b0a12014-09-09 10:12:07156#include "third_party/WebKit/public/platform/WebThread.h"
skyostil529caa292016-08-10 17:44:51157#include "third_party/WebKit/public/platform/scheduler/child/compositor_worker_scheduler.h"
158#include "third_party/WebKit/public/platform/scheduler/child/webthread_impl_for_worker_scheduler.h"
159#include "third_party/WebKit/public/platform/scheduler/renderer/renderer_scheduler.h"
[email protected]2255a9332013-06-17 05:12:31160#include "third_party/WebKit/public/web/WebDatabase.h"
161#include "third_party/WebKit/public/web/WebDocument.h"
162#include "third_party/WebKit/public/web/WebFrame.h"
163#include "third_party/WebKit/public/web/WebKit.h"
[email protected]2255a9332013-06-17 05:12:31164#include "third_party/WebKit/public/web/WebRuntimeFeatures.h"
165#include "third_party/WebKit/public/web/WebScriptController.h"
166#include "third_party/WebKit/public/web/WebSecurityPolicy.h"
[email protected]2255a9332013-06-17 05:12:31167#include "third_party/WebKit/public/web/WebView.h"
[email protected]ddbb53342014-01-06 10:59:47168#include "third_party/skia/include/core/SkGraphics.h"
[email protected]c49201a2012-05-24 11:04:57169#include "ui/base/layout.h"
[email protected]18ad6772011-09-20 21:51:32170#include "ui/base/ui_base_switches.h"
ennee292bdc2016-09-15 19:57:15171#include "ui/gl/gl_switches.h"
[email protected]2c62b562009-01-27 19:04:50172
[email protected]33b02992014-03-01 01:06:29173#if defined(OS_ANDROID)
174#include <cpu-features.h>
boliubee541f42015-11-05 00:52:53175#include "content/renderer/android/synchronous_compositor_filter.h"
danakj1120f4c2016-09-15 02:05:32176#include "content/renderer/android/synchronous_compositor_frame_sink.h"
boliue81d16132016-04-26 00:54:41177#include "content/renderer/media/android/stream_texture_factory.h"
dalecurtis88af3932016-02-20 00:12:20178#include "media/base/android/media_codec_util.h"
[email protected]33b02992014-03-01 01:06:29179#endif
180
181#if defined(OS_MACOSX)
ccamerona7644752014-12-30 01:16:31182#include "base/mac/mac_util.h"
rsesek1efb3c32015-09-29 15:39:50183#include "content/renderer/theme_helper_mac.h"
[email protected]33b02992014-03-01 01:06:29184#include "content/renderer/webscrollbarbehavior_impl_mac.h"
185#endif
186
[email protected]da00a2882009-03-09 17:51:19187#if defined(OS_WIN)
188#include <windows.h>
189#include <objbase.h>
190#endif
191
Brett Wilson0748bf412016-11-22 17:55:46192#if BUILDFLAG(ENABLE_WEBRTC)
liushouqun517b1292016-09-14 05:58:59193#include "content/renderer/media/aec_dump_message_filter.h"
[email protected]22fe91d2014-08-12 17:07:12194#include "content/renderer/media/peer_connection_tracker.h"
195#include "content/renderer/media/rtc_peer_connection_handler.h"
196#include "content/renderer/media/webrtc/peer_connection_dependency_factory.h"
[email protected]22fe91d2014-08-12 17:07:12197#endif
198
chunyang.daibe874c52014-11-14 06:45:05199#ifdef ENABLE_VTUNE_JIT_INTERFACE
200#include "v8/src/third_party/vtune/v8-vtune.h"
201#endif
202
bend32292b2016-10-07 00:21:58203#include "content/public/common/service_manager_connection.h"
fsamuel2545ecc2015-12-05 00:44:46204#include "content/renderer/mus/render_widget_window_tree_client_factory.h"
sadrul602ce1362017-01-26 06:41:10205#include "content/renderer/mus/renderer_window_tree_client.h"
sadrul04cfa892016-12-09 17:53:49206#include "services/ui/public/cpp/gpu/gpu.h"
fsamuel6c6da0232015-11-26 05:13:46207
ochangdd89a1e2016-06-08 16:39:01208#if defined(ENABLE_IPC_FUZZER)
209#include "content/common/external_ipc_dumper.h"
210#endif
211
tasakb46626a2016-10-18 05:54:44212#if defined(OS_MACOSX)
213#include <malloc/malloc.h>
214#else
215#include <malloc.h>
216#endif
217
[email protected]d293572a2013-05-23 18:50:45218using base::ThreadRestrictions;
[email protected]180ef242013-11-07 06:50:46219using blink::WebDocument;
220using blink::WebFrame;
221using blink::WebNetworkStateNotifier;
222using blink::WebRuntimeFeatures;
223using blink::WebScriptController;
224using blink::WebSecurityPolicy;
225using blink::WebString;
226using blink::WebView;
skyostil529caa292016-08-10 17:44:51227using blink::scheduler::WebThreadImplForWorkerScheduler;
[email protected]e9ff79c2012-10-19 21:31:26228
229namespace content {
initial.commit09911bf2008-07-26 23:55:29230
[email protected]42f1d7822009-07-23 18:17:55231namespace {
[email protected]da9ccfb2012-01-28 00:34:40232
avi1023d012015-12-25 02:39:14233const int64_t kInitialIdleHandlerDelayMs = 1000;
234const int64_t kLongIdleHandlerDelayMs = 30 * 1000;
[email protected]bee16aab2009-08-26 15:55:03235
jdduke94ae1f32015-02-05 06:27:13236#if defined(OS_ANDROID)
237// On Android, resource messages can each take ~1.5ms to dispatch on the browser
238// IO thread. Limiting the message rate to 3/frame at 60hz ensures that the
239// induced work takes but a fraction (~1/4) of the overall frame budget.
240const int kMaxResourceRequestsPerFlushWhenThrottled = 3;
241#else
242const int kMaxResourceRequestsPerFlushWhenThrottled = 8;
243#endif
244const double kThrottledResourceRequestFlushPeriodS = 1. / 60.;
245
[email protected]dd2c1022014-07-22 23:13:57246// Maximum allocation size allowed for image scaling filters that
247// require pre-scaling. Skia will fallback to a filter that doesn't
248// require pre-scaling if the default filter would require an
249// allocation that exceeds this limit.
250const size_t kImageCacheSingleAllocationByteLimit = 64 * 1024 * 1024;
251
danakj83066a32016-06-21 02:34:49252// Unique identifier for each output surface created.
danakj1120f4c2016-09-15 02:05:32253uint32_t g_next_compositor_frame_sink_id = 1;
danakj83066a32016-06-21 02:34:49254
rockot5c478a72016-09-28 23:14:18255// An implementation of mojom::RenderMessageFilter which can be mocked out
256// for tests which may indirectly send messages over this interface.
257mojom::RenderMessageFilter* g_render_message_filter_for_testing;
258
[email protected]f1a29a02011-10-06 23:08:44259// Keep the global RenderThreadImpl in a TLS slot so it is impossible to access
[email protected]f3ede412010-06-21 22:52:16260// incorrectly from the wrong thread.
scottmg5e65e3a2017-03-08 08:48:46261base::LazyInstance<base::ThreadLocalPointer<RenderThreadImpl>>::DestructorAtExit
[email protected]6de0fd1d2011-11-15 13:31:49262 lazy_tls = LAZY_INSTANCE_INITIALIZER;
[email protected]1edc16b82009-04-07 17:45:54263
hong.zhengb28b5332016-05-11 02:33:39264// v8::MemoryPressureLevel should correspond to base::MemoryPressureListener.
265static_assert(static_cast<v8::MemoryPressureLevel>(
266 base::MemoryPressureListener::MEMORY_PRESSURE_LEVEL_NONE) ==
267 v8::MemoryPressureLevel::kNone, "none level not align");
268static_assert(static_cast<v8::MemoryPressureLevel>(
269 base::MemoryPressureListener::MEMORY_PRESSURE_LEVEL_MODERATE) ==
270 v8::MemoryPressureLevel::kModerate, "moderate level not align");
271static_assert(static_cast<v8::MemoryPressureLevel>(
272 base::MemoryPressureListener::MEMORY_PRESSURE_LEVEL_CRITICAL) ==
273 v8::MemoryPressureLevel::kCritical, "critical level not align");
274
hong.zheng2e296f822016-06-29 02:47:44275// WebMemoryPressureLevel should correspond to base::MemoryPressureListener.
276static_assert(static_cast<blink::WebMemoryPressureLevel>(
277 base::MemoryPressureListener::MEMORY_PRESSURE_LEVEL_NONE) ==
278 blink::WebMemoryPressureLevelNone,
279 "blink::WebMemoryPressureLevelNone not align");
280static_assert(static_cast<blink::WebMemoryPressureLevel>(
281 base::MemoryPressureListener::MEMORY_PRESSURE_LEVEL_MODERATE) ==
282 blink::WebMemoryPressureLevelModerate,
283 "blink::WebMemoryPressureLevelModerate not align");
284static_assert(static_cast<blink::WebMemoryPressureLevel>(
285 base::MemoryPressureListener::MEMORY_PRESSURE_LEVEL_CRITICAL) ==
286 blink::WebMemoryPressureLevelCritical,
287 "blink::WebMemoryPressureLevelCritical not align");
288
sadrulff12c002016-01-14 20:52:20289class WebThreadForCompositor : public WebThreadImplForWorkerScheduler {
290 public:
291 explicit WebThreadForCompositor(base::Thread::Options options)
292 : WebThreadImplForWorkerScheduler("Compositor", options) {
293 Init();
294 }
295 ~WebThreadForCompositor() override {}
296
297 private:
298 // WebThreadImplForWorkerScheduler:
skyostil529caa292016-08-10 17:44:51299 std::unique_ptr<blink::scheduler::WorkerScheduler> CreateWorkerScheduler()
300 override {
ricea29649b92016-08-31 09:30:21301 return base::MakeUnique<blink::scheduler::CompositorWorkerScheduler>(
302 thread());
sadrulff12c002016-01-14 20:52:20303 }
304
305 DISALLOW_COPY_AND_ASSIGN(WebThreadForCompositor);
306};
307
[email protected]b2d98762012-09-03 17:04:06308void* CreateHistogram(
[email protected]d1b8fccc2011-08-03 01:20:13309 const char *name, int min, int max, size_t buckets) {
310 if (min <= 0)
311 min = 1;
[email protected]b2d98762012-09-03 17:04:06312 std::string histogram_name;
313 RenderThreadImpl* render_thread_impl = RenderThreadImpl::current();
314 if (render_thread_impl) { // Can be null in tests.
315 histogram_name = render_thread_impl->
316 histogram_customizer()->ConvertToCustomHistogramName(name);
317 } else {
318 histogram_name = std::string(name);
319 }
[email protected]de415552013-01-23 04:12:17320 base::HistogramBase* histogram = base::Histogram::FactoryGet(
[email protected]b2d98762012-09-03 17:04:06321 histogram_name, min, max, buckets,
322 base::Histogram::kUmaTargetedHistogramFlag);
[email protected]d1b8fccc2011-08-03 01:20:13323 return histogram;
324}
325
[email protected]b2d98762012-09-03 17:04:06326void AddHistogramSample(void* hist, int sample) {
[email protected]d1b8fccc2011-08-03 01:20:13327 base::Histogram* histogram = static_cast<base::Histogram*>(hist);
328 histogram->Add(sample);
329}
330
ben76f52b242016-06-18 05:42:48331class FrameFactoryImpl : public mojom::FrameFactory {
rockotf8fdd9b2015-12-16 22:22:35332 public:
rockot8e66a08d2016-09-13 00:48:21333 FrameFactoryImpl() : routing_id_highmark_(-1) {}
rockotf8fdd9b2015-12-16 22:22:35334
ben76f52b242016-06-18 05:42:48335 private:
336 // mojom::FrameFactory:
337 void CreateFrame(int32_t frame_routing_id,
338 mojom::FrameRequest frame_request,
339 mojom::FrameHostPtr frame_host) override {
rockotf8fdd9b2015-12-16 22:22:35340 // TODO(morrita): This is for investigating http://crbug.com/415059 and
341 // should be removed once it is fixed.
342 CHECK_LT(routing_id_highmark_, frame_routing_id);
343 routing_id_highmark_ = frame_routing_id;
344
345 RenderFrameImpl* frame = RenderFrameImpl::FromRoutingID(frame_routing_id);
346 // We can receive a GetServiceProviderForFrame message for a frame not yet
rockot067ca55f2016-09-30 22:00:15347 // created due to a race between the message and a
348 // mojom::Renderer::CreateView IPC that triggers creation of the RenderFrame
349 // we want.
rockotf8fdd9b2015-12-16 22:22:35350 if (!frame) {
ben76f52b242016-06-18 05:42:48351 RenderThreadImpl::current()->RegisterPendingFrameCreate(
352 frame_routing_id, std::move(frame_request), std::move(frame_host));
rockotf8fdd9b2015-12-16 22:22:35353 return;
354 }
355
dominickn6c1f1cf2016-12-20 06:13:33356 frame->BindFrame(std::move(frame_request), std::move(frame_host));
rockotf8fdd9b2015-12-16 22:22:35357 }
358
359 private:
360 int32_t routing_id_highmark_;
rockotf8fdd9b2015-12-16 22:22:35361};
362
ben76f52b242016-06-18 05:42:48363void CreateFrameFactory(mojom::FrameFactoryRequest request) {
rockot8e66a08d2016-09-13 00:48:21364 mojo::MakeStrongBinding(base::MakeUnique<FrameFactoryImpl>(),
365 std::move(request));
rockotf8fdd9b2015-12-16 22:22:35366}
367
sadrul85cc5d82016-12-20 03:37:41368scoped_refptr<ui::ContextProviderCommandBuffer> CreateOffscreenContext(
danakjc3983552016-05-03 00:04:35369 scoped_refptr<gpu::GpuChannelHost> gpu_channel_host,
danakj0dd9e1e2016-05-11 22:15:09370 const gpu::SharedMemoryLimits& limits,
danakj9a04adc2016-05-16 22:45:07371 bool support_locking,
sadrul85cc5d82016-12-20 03:37:41372 ui::command_buffer_metrics::ContextType type,
sunnypsd8ce1c22016-05-10 18:02:40373 int32_t stream_id,
374 gpu::GpuStreamPriority stream_priority) {
danakje8ec797e2016-04-19 04:08:43375 DCHECK(gpu_channel_host);
376 // This is used to create a few different offscreen contexts:
377 // - The shared main thread context (offscreen) used by blink for canvas.
378 // - The worker context (offscreen) used for GPU raster and video decoding.
379 // This is for an offscreen context, so the default framebuffer doesn't need
380 // alpha, depth, stencil, antialiasing.
381 gpu::gles2::ContextCreationAttribHelper attributes;
382 attributes.alpha_size = -1;
383 attributes.depth_size = 0;
384 attributes.stencil_size = 0;
385 attributes.samples = 0;
386 attributes.sample_buffers = 0;
387 attributes.bind_generates_resource = false;
388 attributes.lose_context_when_out_of_memory = true;
sunnypsd8ce1c22016-05-10 18:02:40389 const bool automatic_flushes = false;
sadrul85cc5d82016-12-20 03:37:41390 return make_scoped_refptr(new ui::ContextProviderCommandBuffer(
sunnypsd8ce1c22016-05-10 18:02:40391 std::move(gpu_channel_host), stream_id, stream_priority,
392 gpu::kNullSurfaceHandle,
zmo09ea813b2017-01-20 23:38:36393 GURL("chrome://gpu/RenderThreadImpl::CreateOffscreenContext/" +
394 ui::command_buffer_metrics::ContextTypeToString(type)),
pimand488e8b42016-06-30 19:06:59395 automatic_flushes, support_locking, limits, attributes, nullptr, type));
danakje8ec797e2016-04-19 04:08:43396}
397
penghuange1d86512016-07-08 18:15:00398bool IsRunningInMash() {
399 const base::CommandLine* cmdline = base::CommandLine::ForCurrentProcess();
400 return cmdline->HasSwitch(switches::kIsRunningInMash);
401}
402
[email protected]b2d98762012-09-03 17:04:06403} // namespace
404
[email protected]fdeac262014-07-10 12:52:51405// For measuring memory usage after each task. Behind a command line flag.
406class MemoryObserver : public base::MessageLoop::TaskObserver {
407 public:
408 MemoryObserver() {}
dcheng6d18e402014-10-21 12:32:52409 ~MemoryObserver() override {}
[email protected]fdeac262014-07-10 12:52:51410
dcheng6d18e402014-10-21 12:32:52411 void WillProcessTask(const base::PendingTask& pending_task) override {}
[email protected]fdeac262014-07-10 12:52:51412
dcheng6d18e402014-10-21 12:32:52413 void DidProcessTask(const base::PendingTask& pending_task) override {
asvitkinec0fb8022014-08-26 04:39:35414 LOCAL_HISTOGRAM_MEMORY_KB("Memory.RendererUsed", GetMemoryUsageKB());
[email protected]fdeac262014-07-10 12:52:51415 }
416
417 private:
418 DISALLOW_COPY_AND_ASSIGN(MemoryObserver);
419};
420
[email protected]b2d98762012-09-03 17:04:06421RenderThreadImpl::HistogramCustomizer::HistogramCustomizer() {
422 custom_histograms_.insert("V8.MemoryExternalFragmentationTotal");
423 custom_histograms_.insert("V8.MemoryHeapSampleTotalCommitted");
424 custom_histograms_.insert("V8.MemoryHeapSampleTotalUsed");
hablich4598ddc2015-11-07 18:37:28425 custom_histograms_.insert("V8.MemoryHeapUsed");
426 custom_histograms_.insert("V8.MemoryHeapCommitted");
[email protected]b2d98762012-09-03 17:04:06427}
428
429RenderThreadImpl::HistogramCustomizer::~HistogramCustomizer() {}
430
431void RenderThreadImpl::HistogramCustomizer::RenderViewNavigatedToHost(
432 const std::string& host, size_t view_count) {
avi83883c82014-12-23 00:08:49433 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
434 switches::kDisableHistogramCustomizer)) {
[email protected]9baee832012-12-10 11:07:15435 return;
436 }
[email protected]b2d98762012-09-03 17:04:06437 // Check if all RenderViews are displaying a page from the same host. If there
438 // is only one RenderView, the common host is this view's host. If there are
439 // many, check if this one shares the common host of the other
440 // RenderViews. It's ok to not detect some cases where the RenderViews share a
441 // common host. This information is only used for producing custom histograms.
442 if (view_count == 1)
443 SetCommonHost(host);
444 else if (host != common_host_)
445 SetCommonHost(std::string());
446}
447
448std::string RenderThreadImpl::HistogramCustomizer::ConvertToCustomHistogramName(
449 const char* histogram_name) const {
450 std::string name(histogram_name);
451 if (!common_host_histogram_suffix_.empty() &&
452 custom_histograms_.find(name) != custom_histograms_.end())
453 name += common_host_histogram_suffix_;
454 return name;
455}
456
457void RenderThreadImpl::HistogramCustomizer::SetCommonHost(
458 const std::string& host) {
459 if (host != common_host_) {
460 common_host_ = host;
461 common_host_histogram_suffix_ = HostToCustomHistogramSuffix(host);
[email protected]4b5340282014-07-08 11:37:34462 blink::mainThreadIsolate()->SetCreateHistogramFunction(CreateHistogram);
[email protected]b2d98762012-09-03 17:04:06463 }
464}
465
hablichd6a4f122015-10-28 11:34:49466std::string RenderThreadImpl::HistogramCustomizer::HostToCustomHistogramSuffix(
467 const std::string& host) {
468 if (host == "mail.google.com")
469 return ".gmail";
470 if (host == "docs.google.com" || host == "drive.google.com")
471 return ".docs";
472 if (host == "plus.google.com")
473 return ".plus";
474 if (host == "inbox.google.com")
475 return ".inbox";
hpayerdd4def052016-02-06 19:06:10476 if (host == "calendar.google.com")
477 return ".calendar";
hablichd6a4f122015-10-28 11:34:49478 if (host == "www.youtube.com")
479 return ".youtube";
480 if (IsAlexaTop10NonGoogleSite(host))
481 return ".top10";
482
483 return std::string();
484}
485
486bool RenderThreadImpl::HistogramCustomizer::IsAlexaTop10NonGoogleSite(
487 const std::string& host) {
488 // The Top10 sites have different TLD and/or subdomains depending on the
489 // localization.
490 if (host == "sina.com.cn")
491 return true;
492
493 std::string sanitized_host =
494 net::registry_controlled_domains::GetDomainAndRegistry(
495 host, net::registry_controlled_domains::INCLUDE_PRIVATE_REGISTRIES);
496
497 if (sanitized_host == "facebook.com")
498 return true;
499 if (sanitized_host == "baidu.com")
500 return true;
501 if (sanitized_host == "qq.com")
502 return true;
503 if (sanitized_host == "twitter.com")
504 return true;
505 if (sanitized_host == "taobao.com")
506 return true;
507 if (sanitized_host == "live.com")
508 return true;
509
510 if (!sanitized_host.empty()) {
511 std::vector<base::StringPiece> host_tokens = base::SplitStringPiece(
512 sanitized_host, ".", base::TRIM_WHITESPACE, base::SPLIT_WANT_NONEMPTY);
513
514 if (host_tokens.size() >= 2) {
515 if ((host_tokens[0] == "yahoo") || (host_tokens[0] == "amazon") ||
516 (host_tokens[0] == "wikipedia")) {
517 return true;
518 }
519 }
520 }
521 return false;
522}
523
leon.han2c0f9f12015-07-11 02:01:19524// static
525RenderThreadImpl* RenderThreadImpl::Create(
526 const InProcessChildThreadParams& params) {
skyostil529caa292016-08-10 17:44:51527 std::unique_ptr<blink::scheduler::RendererScheduler> renderer_scheduler =
528 blink::scheduler::RendererScheduler::Create();
jam75c44222016-03-23 05:34:24529 scoped_refptr<base::SingleThreadTaskRunner> test_task_counter;
530 return new RenderThreadImpl(
531 params, std::move(renderer_scheduler), test_task_counter);
leon.han2c0f9f12015-07-11 02:01:19532}
533
534// static
535RenderThreadImpl* RenderThreadImpl::Create(
dchengcedca5612016-04-09 01:40:15536 std::unique_ptr<base::MessageLoop> main_message_loop,
skyostil529caa292016-08-10 17:44:51537 std::unique_ptr<blink::scheduler::RendererScheduler> renderer_scheduler) {
dcheng07945f632015-12-26 07:59:32538 return new RenderThreadImpl(std::move(main_message_loop),
539 std::move(renderer_scheduler));
leon.han2c0f9f12015-07-11 02:01:19540}
541
rockot5c478a72016-09-28 23:14:18542// static
[email protected]f1a29a02011-10-06 23:08:44543RenderThreadImpl* RenderThreadImpl::current() {
[email protected]526476902011-10-06 20:34:06544 return lazy_tls.Pointer()->Get();
545}
546
rockot5c478a72016-09-28 23:14:18547// static
548mojom::RenderMessageFilter* RenderThreadImpl::current_render_message_filter() {
549 if (g_render_message_filter_for_testing)
550 return g_render_message_filter_for_testing;
551 DCHECK(current());
552 return current()->render_message_filter();
553}
554
555// static
jcivelli315d17f2016-11-29 16:15:05556const scoped_refptr<mojom::ThreadSafeRenderMessageFilterAssociatedPtr>&
557RenderThreadImpl::current_thread_safe_render_message_filter() {
558 DCHECK(current());
559 return current()->thread_safe_render_message_filter();
560}
561
562// static
rockot5c478a72016-09-28 23:14:18563void RenderThreadImpl::SetRenderMessageFilterForTesting(
564 mojom::RenderMessageFilter* render_message_filter) {
565 g_render_message_filter_for_testing = render_message_filter;
566}
567
staraz067f58242016-11-07 21:06:41568// In single-process mode used for debugging, we don't pass a renderer client
569// ID via command line because RenderThreadImpl lives in the same process as
570// the browser
leon.han2c0f9f12015-07-11 02:01:19571RenderThreadImpl::RenderThreadImpl(
572 const InProcessChildThreadParams& params,
skyostil529caa292016-08-10 17:44:51573 std::unique_ptr<blink::scheduler::RendererScheduler> scheduler,
rockot97a86832016-12-10 04:53:06574 const scoped_refptr<base::SingleThreadTaskRunner>& resource_task_queue)
morritac6238ab2015-03-18 01:48:29575 : ChildThreadImpl(Options::Builder()
prashant.nfad657e2016-06-01 07:52:17576 .InBrowserProcess(params)
bend32292b2016-10-07 00:21:58577 .AutoStartServiceManagerConnection(false)
ben5be0b9132016-08-03 00:17:18578 .ConnectToBrowser(true)
prashant.nfad657e2016-06-01 07:52:17579 .Build()),
dcheng07945f632015-12-26 07:59:32580 renderer_scheduler_(std::move(scheduler)),
rockot067ca55f2016-09-30 22:00:15581 categorized_worker_pool_(new CategorizedWorkerPool()),
staraz067f58242016-11-07 21:06:41582 renderer_binding_(this),
chiniforooshan614d70a2017-03-17 01:19:33583 client_id_(1),
584 field_trial_syncer_(this) {
jam75c44222016-03-23 05:34:24585 Init(resource_task_queue);
morritac6238ab2015-03-18 01:48:29586}
587
[email protected]42f1d7822009-07-23 18:17:55588// When we run plugins in process, we actually run them on the render thread,
589// which means that we need to make the render thread pump UI events.
haraken53f081d2014-11-11 01:03:40590RenderThreadImpl::RenderThreadImpl(
dchengcedca5612016-04-09 01:40:15591 std::unique_ptr<base::MessageLoop> main_message_loop,
skyostil529caa292016-08-10 17:44:51592 std::unique_ptr<blink::scheduler::RendererScheduler> scheduler)
rockotcef38272016-07-15 22:47:47593 : ChildThreadImpl(Options::Builder()
bend32292b2016-10-07 00:21:58594 .AutoStartServiceManagerConnection(false)
ben5be0b9132016-08-03 00:17:18595 .ConnectToBrowser(true)
rockotcef38272016-07-15 22:47:47596 .Build()),
dcheng07945f632015-12-26 07:59:32597 renderer_scheduler_(std::move(scheduler)),
598 main_message_loop_(std::move(main_message_loop)),
rockot067ca55f2016-09-30 22:00:15599 categorized_worker_pool_(new CategorizedWorkerPool()),
wjmaclean1d970622017-01-21 22:28:24600 is_scroll_animator_enabled_(false),
fsamuel4c5c87142017-03-14 03:14:26601 is_surface_synchronization_enabled_(false),
chiniforooshan614d70a2017-03-17 01:19:33602 renderer_binding_(this),
603 field_trial_syncer_(this) {
jam75c44222016-03-23 05:34:24604 scoped_refptr<base::SingleThreadTaskRunner> test_task_counter;
staraz067f58242016-11-07 21:06:41605 DCHECK(base::CommandLine::ForCurrentProcess()->HasSwitch(
606 switches::kRendererClientId));
607 base::StringToInt(base::CommandLine::ForCurrentProcess()->GetSwitchValueASCII(
608 switches::kRendererClientId),
609 &client_id_);
jam75c44222016-03-23 05:34:24610 Init(test_task_counter);
haraken53f081d2014-11-11 01:03:40611}
612
jam75c44222016-03-23 05:34:24613void RenderThreadImpl::Init(
rockot97a86832016-12-10 04:53:06614 const scoped_refptr<base::SingleThreadTaskRunner>& resource_task_queue) {
fdorayf6d86242015-10-08 16:49:53615 TRACE_EVENT0("startup", "RenderThreadImpl::Init");
[email protected]a872ea1f2010-08-11 04:45:33616
ssidb2e3ece2015-02-09 16:02:20617 base::trace_event::TraceLog::GetInstance()->SetThreadSortIndex(
[email protected]91a2aea2013-07-08 23:14:39618 base::PlatformThread::CurrentId(),
619 kTraceEventRendererMainThreadSortIndex);
620
thakis18e426412017-03-15 12:06:37621#if BUILDFLAG(USE_EXTERNAL_POPUP_MENU)
sievers9dff72052015-11-16 18:35:57622 // On Mac and Android Java UI, the select popups are rendered by the browser.
[email protected]180ef242013-11-07 06:50:46623 blink::WebView::setUseExternalPopupMenus(true);
[email protected]53c607c2011-03-21 23:19:04624#endif
625
[email protected]94f9a0f682009-06-15 18:30:30626 lazy_tls.Pointer()->Set(this);
[email protected]b3e83de2012-02-07 03:33:28627
[email protected]06c694d2012-02-01 22:26:16628 // Register this object as the main thread.
629 ChildProcess::current()->set_main_thread(this);
630
sadrul62c31132016-08-11 04:13:17631 if (IsRunningInMash()) {
sadrul04cfa892016-12-09 17:53:49632 gpu_ = ui::Gpu::Create(GetServiceManagerConnection()->GetConnector(),
penghuangd6843e42016-12-17 13:57:20633 GetIOTaskRunner());
sadrul53546592016-12-17 01:44:21634 } else {
penghuangd6843e42016-12-17 13:57:20635 gpu_ = ui::Gpu::Create(GetRemoteInterfaces(), GetIOTaskRunner());
sadrul62c31132016-08-11 04:13:17636 }
penghuange1d86512016-07-08 18:15:00637
rockota628d0b2017-02-09 08:40:15638 channel()->GetThreadSafeRemoteAssociatedInterface(
639 &thread_safe_render_message_filter_);
jcivelli0f21bd52016-12-07 21:21:33640 shared_bitmap_manager_.reset(
641 new ChildSharedBitmapManager(thread_safe_render_message_filter_));
642
jam75c44222016-03-23 05:34:24643 InitializeWebKit(resource_task_queue);
644
[email protected]31f87132010-04-21 23:36:21645 // In single process the single process is all there is.
[email protected]26e82322014-01-20 14:18:22646 webkit_shared_timer_suspended_ = false;
[email protected]bee16aab2009-08-26 15:55:03647 widget_count_ = 0;
648 hidden_widget_count_ = 0;
[email protected]6593ae12011-11-14 12:09:44649 idle_notification_delay_in_ms_ = kInitialIdleHandlerDelayMs;
[email protected]1784b2f2011-11-24 10:53:48650 idle_notifications_to_skip_ = 0;
[email protected]8d86fce2009-02-26 23:37:55651
[email protected]d5b2fdf2013-06-05 09:36:55652 appcache_dispatcher_.reset(
[email protected]a8cb3b73b2013-08-12 05:50:50653 new AppCacheDispatcher(Get(), new AppCacheFrontendImpl()));
[email protected]1910fe82012-05-10 00:04:10654 dom_storage_dispatcher_.reset(new DomStorageDispatcher());
reillyg39fb4662016-11-22 20:27:17655 main_thread_indexed_db_dispatcher_.reset(new IndexedDBDispatcher());
jsbellabadb9b2015-03-23 21:03:44656 main_thread_cache_storage_dispatcher_.reset(
jsbell279efb42015-03-31 17:02:46657 new CacheStorageDispatcher(thread_safe_sender()));
[email protected]7670d4332013-11-29 04:35:00658 embedded_worker_dispatcher_.reset(new EmbeddedWorkerDispatcher());
[email protected]dd9241932010-02-24 19:23:13659
jdduke94ae1f32015-02-05 06:27:13660 // Note: This may reorder messages from the ResourceDispatcher with respect to
661 // other subsystems.
662 resource_dispatch_throttler_.reset(new ResourceDispatchThrottler(
663 static_cast<RenderThread*>(this), renderer_scheduler_.get(),
664 base::TimeDelta::FromSecondsD(kThrottledResourceRequestFlushPeriodS),
665 kMaxResourceRequestsPerFlushWhenThrottled));
666 resource_dispatcher()->set_message_sender(resource_dispatch_throttler_.get());
667
penghuange1d86512016-07-08 18:15:00668 media_stream_center_ = nullptr;
[email protected]d8cd8372012-03-09 10:49:51669
thestig529ad8a2016-07-08 20:30:12670 blob_message_filter_ = new BlobMessageFilter(GetFileThreadTaskRunner());
dmurph1fb98482016-03-30 21:14:26671 AddFilter(blob_message_filter_.get());
[email protected]017022b2009-07-27 23:06:34672 db_message_filter_ = new DBMessageFilter();
673 AddFilter(db_message_filter_.get());
[email protected]dd9241932010-02-24 19:23:13674
[email protected]45048072014-01-14 13:51:29675 vc_manager_.reset(new VideoCaptureImplManager());
[email protected]c9c43a02013-12-17 08:59:54676
fsamuel6c1dfeb2014-12-18 19:21:33677 browser_plugin_manager_.reset(new BrowserPluginManager());
678 AddObserver(browser_plugin_manager_.get());
679
Brett Wilson0748bf412016-11-22 17:55:46680#if BUILDFLAG(ENABLE_WEBRTC)
[email protected]af089972013-01-10 04:04:40681 peer_connection_tracker_.reset(new PeerConnectionTracker());
682 AddObserver(peer_connection_tracker_.get());
683
thestig529ad8a2016-07-08 20:30:12684 p2p_socket_dispatcher_ = new P2PSocketDispatcher(GetIOTaskRunner().get());
[email protected]fc72bb12013-06-02 21:13:46685 AddFilter(p2p_socket_dispatcher_.get());
[email protected]921480f62013-07-20 03:42:57686
ivocadd54f0d2015-12-18 23:17:05687 peer_connection_factory_.reset(
688 new PeerConnectionDependencyFactory(p2p_socket_dispatcher_.get()));
689
skyostil2d3b5bd2015-05-27 15:40:59690 aec_dump_message_filter_ = new AecDumpMessageFilter(
thestig529ad8a2016-07-08 20:30:12691 GetIOTaskRunner(), message_loop()->task_runner());
ivocadd54f0d2015-12-18 23:17:05692
[email protected]da9f30a2014-06-18 19:39:04693 AddFilter(aec_dump_message_filter_.get());
694
Brett Wilson0748bf412016-11-22 17:55:46695#endif // BUILDFLAG(ENABLE_WEBRTC)
[email protected]e25f4d72011-06-08 20:58:46696
thestig529ad8a2016-07-08 20:30:12697 audio_input_message_filter_ = new AudioInputMessageFilter(GetIOTaskRunner());
[email protected]f7eb0a392011-07-12 10:19:51698 AddFilter(audio_input_message_filter_.get());
699
thestig529ad8a2016-07-08 20:30:12700 audio_message_filter_ = new AudioMessageFilter(GetIOTaskRunner());
[email protected]f7eb0a392011-07-12 10:19:51701 AddFilter(audio_message_filter_.get());
702
thestig529ad8a2016-07-08 20:30:12703 midi_message_filter_ = new MidiMessageFilter(GetIOTaskRunner());
[email protected]a9875152013-06-22 04:03:03704 AddFilter(midi_message_filter_.get());
705
jsbellabadb9b2015-03-23 21:03:44706 AddFilter((new CacheStorageMessageFilter(thread_safe_sender()))->GetFilter());
707
kinuko5af4ffe2015-06-09 03:38:46708 AddFilter((new ServiceWorkerContextMessageFilter())->GetFilter());
[email protected]ddbb53342014-01-06 10:59:47709
sadrul943e3b32016-08-04 18:22:59710#if defined(USE_AURA)
fsamuel098eade2017-03-21 18:06:14711 if (IsRunningInMash()) {
bend32292b2016-10-07 00:21:58712 CreateRenderWidgetWindowTreeClientFactory(GetServiceManagerConnection());
rockotcef38272016-07-15 22:47:47713 }
714#endif
715
716 // Must be called before RenderThreadStarted() below.
bend32292b2016-10-07 00:21:58717 StartServiceManagerConnection();
rockotcef38272016-07-15 22:47:47718
[email protected]e9ff79c2012-10-19 21:31:26719 GetContentClient()->renderer()->RenderThreadStarted();
[email protected]6779aa12011-03-29 17:32:24720
chiniforooshan614d70a2017-03-17 01:19:33721 field_trial_syncer_.InitFieldTrialObserving(
722 *base::CommandLine::ForCurrentProcess(), switches::kSingleProcess);
723
rockot067ca55f2016-09-30 22:00:15724 GetAssociatedInterfaceRegistry()->AddInterface(
725 base::Bind(&RenderThreadImpl::OnRendererInterfaceRequest,
726 base::Unretained(this)));
727
[email protected]b48c53ad2014-02-05 21:59:18728 InitSkiaEventTracer();
ssid59c969162015-07-28 13:02:58729 base::trace_event::MemoryDumpManager::GetInstance()->RegisterDumpProvider(
primiano186d6bfe2015-10-30 13:21:40730 skia::SkiaMemoryDumpProvider::GetInstance(), "Skia", nullptr);
[email protected]b48c53ad2014-02-05 21:59:18731
avi83883c82014-12-23 00:08:49732 const base::CommandLine& command_line =
733 *base::CommandLine::ForCurrentProcess();
[email protected]e54ab492012-06-12 19:40:01734
ochangdd89a1e2016-06-08 16:39:01735#if defined(ENABLE_IPC_FUZZER)
736 if (command_line.HasSwitch(switches::kIpcDumpDirectory)) {
737 base::FilePath dump_directory =
738 command_line.GetSwitchValuePath(switches::kIpcDumpDirectory);
739 IPC::ChannelProxy::OutgoingMessageFilter* filter =
740 LoadExternalIPCDumper(dump_directory);
741 GetChannel()->set_outgoing_message_filter(filter);
742 }
743#endif
744
jbroman0d302162015-09-05 05:46:23745 cc::SetClientNameForMetrics("Renderer");
loysoa6edaaff2015-05-25 03:26:44746
loyso65c93c602015-08-11 05:15:57747 is_threaded_animation_enabled_ =
748 !command_line.HasSwitch(cc::switches::kDisableThreadedAnimation);
749
fsamuel4c5c87142017-03-14 03:14:26750 is_surface_synchronization_enabled_ =
751 command_line.HasSwitch(cc::switches::kEnableSurfaceSynchronization);
752
reveman91a0a872014-11-04 03:40:32753 is_zero_copy_enabled_ = command_line.HasSwitch(switches::kEnableZeroCopy);
ericrk1d17f752015-10-20 03:03:07754 is_partial_raster_enabled_ =
dongseong.hwang23db47f2016-03-08 07:50:02755 !command_line.HasSwitch(switches::kDisablePartialRaster);
ccameronc7fcd132015-11-03 20:14:31756 is_gpu_memory_buffer_compositor_resources_enabled_ = command_line.HasSwitch(
757 switches::kEnableGpuMemoryBufferCompositorResources);
[email protected]a23530d2014-03-11 06:04:14758
jame1f453c2016-03-21 15:51:34759#if defined(OS_MACOSX)
thakis114a1ef2016-04-26 16:02:59760 base::ScopedCFTypeRef<CFStringRef> key(
761 base::SysUTF8ToCFStringRef("NSScrollViewRubberbanding"));
762 Boolean key_exists = false;
763 Boolean value = CFPreferencesGetAppBooleanValue(
764 key, kCFPreferencesCurrentApplication, &key_exists);
765 is_elastic_overscroll_enabled_ = !key_exists || value;
ccamerona7644752014-12-30 01:16:31766#else
767 is_elastic_overscroll_enabled_ = false;
768#endif
769
danakje6eb185c2015-02-27 23:52:05770 std::string image_texture_target_string =
dcastagna7f2f7192015-06-16 18:44:35771 command_line.GetSwitchValueASCII(switches::kContentImageTextureTarget);
ericrk9151705c2016-07-26 19:53:16772 buffer_to_texture_target_map_ =
773 cc::StringToBufferToTextureTargetMap(image_texture_target_string);
reveman44b807f12014-11-26 02:44:50774
[email protected]a23530d2014-03-11 06:04:14775 if (command_line.HasSwitch(switches::kDisableLCDText)) {
776 is_lcd_text_enabled_ = false;
777 } else if (command_line.HasSwitch(switches::kEnableLCDText)) {
778 is_lcd_text_enabled_ = true;
779 } else {
780#if defined(OS_ANDROID)
781 is_lcd_text_enabled_ = false;
782#else
783 is_lcd_text_enabled_ = true;
784#endif
785 }
786
[email protected]b8d82c22014-03-31 20:12:46787 is_gpu_rasterization_forced_ =
788 command_line.HasSwitch(switches::kForceGpuRasterization);
sunnypsd8ce1c22016-05-10 18:02:40789 is_async_worker_context_enabled_ =
790 command_line.HasSwitch(switches::kEnableGpuAsyncWorkerContext);
[email protected]a23530d2014-03-11 06:04:14791
senorblancob60ba952015-01-27 19:12:36792 if (command_line.HasSwitch(switches::kGpuRasterizationMSAASampleCount)) {
793 std::string string_value = command_line.GetSwitchValueASCII(
794 switches::kGpuRasterizationMSAASampleCount);
795 bool parsed_msaa_sample_count =
796 base::StringToInt(string_value, &gpu_rasterization_msaa_sample_count_);
797 DCHECK(parsed_msaa_sample_count) << string_value;
798 DCHECK_GE(gpu_rasterization_msaa_sample_count_, 0);
799 } else {
senorblanco2a5b0e12015-08-14 21:55:37800 gpu_rasterization_msaa_sample_count_ = -1;
senorblancob60ba952015-01-27 19:12:36801 }
802
[email protected]b242b142014-05-07 14:48:49803 if (command_line.HasSwitch(switches::kDisableDistanceFieldText)) {
804 is_distance_field_text_enabled_ = false;
805 } else if (command_line.HasSwitch(switches::kEnableDistanceFieldText)) {
806 is_distance_field_text_enabled_ = true;
807 } else {
808 is_distance_field_text_enabled_ = false;
809 }
810
[email protected]433df472012-03-07 20:33:39811 // Note that under Linux, the media library will normally already have
812 // been initialized by the Zygote before this instance became a Renderer.
chcunninghamfd11b3c2015-06-09 02:09:42813 media::InitializeMediaLibrary();
[email protected]433df472012-03-07 20:33:39814
dalecurtis88af3932016-02-20 00:12:20815#if defined(OS_ANDROID)
816 if (!command_line.HasSwitch(switches::kDisableAcceleratedVideoDecode) &&
817 media::MediaCodecUtil::IsMediaCodecAvailable()) {
818 media::EnablePlatformDecoderSupport();
819 }
820#endif
821
hubbee6c6eb342017-03-15 20:34:11822 if (base::CommandLine::ForCurrentProcess()->HasSwitch(switches::kEnableHDR) ||
chcunningham9a285ed2017-03-08 21:48:56823 base::CommandLine::ForCurrentProcess()->HasSwitch(
824 switches::kEnableNewVp9CodecString)) {
825 media::EnableNewVp9CodecStringSupport();
826 }
827
[email protected]5071cb22013-07-10 02:19:06828 memory_pressure_listener_.reset(new base::MemoryPressureListener(
hong.zhengb28b5332016-05-11 02:33:39829 base::Bind(&RenderThreadImpl::OnMemoryPressure, base::Unretained(this)),
830 base::Bind(&RenderThreadImpl::OnSyncMemoryPressure,
831 base::Unretained(this))));
[email protected]5071cb22013-07-10 02:19:06832
bashia6264042016-09-15 04:49:51833 if (base::FeatureList::IsEnabled(features::kMemoryCoordinator)) {
bashi58dd2fa2016-10-17 00:01:07834 // Disable MemoryPressureListener when memory coordinator is enabled.
835 base::MemoryPressureListener::SetNotificationsSuppressed(true);
836
bashi77f19b32016-07-19 11:19:43837 // TODO(bashi): Revisit how to manage the lifetime of
838 // ChildMemoryCoordinatorImpl.
839 // https://codereview.chromium.org/2094583002/#msg52
bashia6264042016-09-15 04:49:51840 mojom::MemoryCoordinatorHandlePtr parent_coordinator;
blundelle0a9f1582016-12-20 11:23:32841 GetRemoteInterfaces()->GetInterface(mojo::MakeRequest(&parent_coordinator));
bashia6264042016-09-15 04:49:51842 memory_coordinator_ = CreateChildMemoryCoordinator(
bashic4b4afcb2016-08-23 06:37:52843 std::move(parent_coordinator), this);
bashi77f19b32016-07-19 11:19:43844 }
845
danakj16275d4c2015-06-11 19:23:51846 int num_raster_threads = 0;
847 std::string string_value =
848 command_line.GetSwitchValueASCII(switches::kNumRasterThreads);
849 bool parsed_num_raster_threads =
850 base::StringToInt(string_value, &num_raster_threads);
851 DCHECK(parsed_num_raster_threads) << string_value;
852 DCHECK_GT(num_raster_threads, 0);
vmiura78b69282015-02-14 00:01:17853
vmpstr6c0b5112016-04-25 22:12:14854 // TODO(vmpstr): If the flag sticks, we should clean it up and always have
855 // image decode tasks.
vmpstr9dd810a2016-01-19 21:16:10856 are_image_decode_tasks_enabled_ = true;
halliwell4b3deee2014-12-19 19:57:49857
prashant.nfad657e2016-06-01 07:52:17858 categorized_worker_pool_->Start(num_raster_threads);
[email protected]1e1d1e12014-01-17 16:14:29859
penghuang342762b2016-12-02 21:04:58860 discardable_memory::mojom::DiscardableSharedMemoryManagerPtr manager_ptr;
penghuangd6843e42016-12-17 13:57:20861 if (IsRunningInMash()) {
862#if defined(USE_AURA)
benbd3c2482017-01-07 05:48:21863 GetServiceManagerConnection()->GetConnector()->BindInterface(
penghuangd6843e42016-12-17 13:57:20864 ui::mojom::kServiceName, &manager_ptr);
865#else
866 NOTREACHED();
867#endif
868 } else {
869 ChildThread::Get()->GetRemoteInterfaces()->GetInterface(
blundelle0a9f1582016-12-20 11:23:32870 mojo::MakeRequest(&manager_ptr));
penghuangd6843e42016-12-17 13:57:20871 }
872
penghuang342762b2016-12-02 21:04:58873 discardable_shared_memory_manager_ = base::MakeUnique<
874 discardable_memory::ClientDiscardableSharedMemoryManager>(
875 std::move(manager_ptr), GetIOTaskRunner());
876
boliu9760e212015-06-23 22:49:06877 // TODO(boliu): In single process, browser main loop should set up the
878 // discardable memory manager, and should skip this if kSingleProcess.
879 // See crbug.com/503724.
880 base::DiscardableMemoryAllocator::SetInstance(
penghuang342762b2016-12-02 21:04:58881 discardable_shared_memory_manager_.get());
revemancb5a66af2014-10-25 00:34:39882
bend1dd50f52016-06-26 22:10:48883 GetContentClient()->renderer()->ExposeInterfacesToBrowser(
884 GetInterfaceRegistry());
rockot229fb28e2016-06-16 04:46:16885
shimazu5de409e42016-09-29 08:45:28886 GetInterfaceRegistry()->AddInterface(base::Bind(&CreateFrameFactory));
shimazu5de409e42016-09-29 08:45:28887 GetInterfaceRegistry()->AddInterface(
888 base::Bind(&EmbeddedWorkerInstanceClientImpl::Create,
889 base::Unretained(embedded_worker_dispatcher_.get())));
fsamuel6c6da0232015-11-26 05:13:46890
bend1dd50f52016-06-26 22:10:48891 GetRemoteInterfaces()->GetInterface(
blundelle0a9f1582016-12-20 11:23:32892 mojo::MakeRequest(&storage_partition_service_));
hajimehoshi69093272016-05-13 08:30:58893
reveman7b97c322016-09-20 02:10:58894#if defined(OS_LINUX)
895 ChildProcess::current()->SetIOThreadPriority(base::ThreadPriority::DISPLAY);
896 ChildThreadImpl::current()->SetThreadPriority(
battre40937c02017-02-07 17:40:55897 categorized_worker_pool_->background_worker_thread_id(),
reveman7b97c322016-09-20 02:10:58898 base::ThreadPriority::BACKGROUND);
899#endif
900
tasakb46626a2016-10-18 05:54:44901 record_purge_suspend_metric_closure_.Reset(base::Bind(
902 &RenderThreadImpl::RecordPurgeAndSuspendMetrics, base::Unretained(this)));
tasak72f64042017-01-19 14:02:53903 record_purge_suspend_growth_metric_closure_.Reset(
904 base::Bind(&RenderThreadImpl::RecordPurgeAndSuspendMemoryGrowthMetrics,
905 base::Unretained(this)));
tasakb95dbb50c2017-02-08 18:07:50906 needs_to_record_first_active_paint_ = false;
hajimehoshi7bb39582016-10-12 04:30:57907
908 base::MemoryCoordinatorClientRegistry::GetInstance()->Register(this);
fdoray50a38342016-11-21 20:46:04909
910 // If this renderer doesn't run inside the browser process, enable
911 // SequencedWorkerPool. Otherwise, it should already have been enabled.
912 // TODO(fdoray): Remove this once the SequencedWorkerPool to TaskScheduler
913 // redirection experiment concludes https://crbug.com/622400.
914 if (!command_line.HasSwitch(switches::kSingleProcess))
915 base::SequencedWorkerPool::EnableForProcess();
initial.commit09911bf2008-07-26 23:55:29916}
917
[email protected]f1a29a02011-10-06 23:08:44918RenderThreadImpl::~RenderThreadImpl() {
[email protected]ce79d8512013-04-22 22:44:41919}
920
921void RenderThreadImpl::Shutdown() {
harakenbbfdd9f02017-01-12 07:14:04922 // In a multi-process mode, we immediately exit the renderer.
923 // Historically we had a graceful shutdown sequence here but it was
924 // 1) a waste of performance and 2) a source of lots of complicated
925 // crashes caused by shutdown ordering. Immediate exit eliminates
926 // those problems.
cbrunia3f655b2017-03-20 11:36:41927
928 // Give the V8 isolate a chance to dump internal stats useful for performance
929 // evaluation and debugging.
930 blink::mainThreadIsolate()->DumpAndResetStats();
931
harakenbbfdd9f02017-01-12 07:14:04932 // In a single-process mode, we cannot call _exit(0) in Shutdown() because
933 // it will exit the process before the browser side is ready to exit.
934 if (!base::CommandLine::ForCurrentProcess()->HasSwitch(
935 switches::kSingleProcess))
haraken940efb92017-02-08 05:58:15936 base::Process::TerminateCurrentProcessImmediately(0);
harakenbbfdd9f02017-01-12 07:14:04937}
[email protected]1223d6ef2011-03-28 16:47:50938
harakenbbfdd9f02017-01-12 07:14:04939bool RenderThreadImpl::ShouldBeDestroyed() {
940 DCHECK(base::CommandLine::ForCurrentProcess()->HasSwitch(
941 switches::kSingleProcess));
942 // In a single-process mode, it is unsafe to destruct this renderer thread
943 // because we haven't run the shutdown sequence. Hence we leak the render
944 // thread.
945 //
946 // In this case, we also need to disable at-exit callbacks because some of
947 // the at-exit callbacks are expected to run after the renderer thread
948 // has been destructed.
949 base::AtExitManager::DisableAllAtExitManagers();
950 return false;
initial.commit09911bf2008-07-26 23:55:29951}
952
[email protected]f1a29a02011-10-06 23:08:44953bool RenderThreadImpl::Send(IPC::Message* msg) {
changwan6ed4d432016-05-19 22:03:54954 // There are cases where we want to pump asynchronous messages while waiting
955 // synchronously for the replies to the message to be sent here. However, this
956 // may create an opportunity for re-entrancy into WebKit and other subsystems,
957 // so we need to take care to disable callbacks, timers, and pending network
958 // loads that could trigger such callbacks.
[email protected]38b592902011-04-16 02:08:42959 bool pumping_events = false;
[email protected]80fc08c52010-03-09 07:43:50960 if (msg->is_sync()) {
961 if (msg->is_caller_pumping_messages()) {
962 pumping_events = true;
[email protected]80fc08c52010-03-09 07:43:50963 }
[email protected]c1f50aa2010-02-18 03:46:57964 }
965
[email protected]c1f50aa2010-02-18 03:46:57966 if (pumping_events) {
jdduked73ae5412015-05-11 20:07:16967 renderer_scheduler_->SuspendTimerQueue();
changwan6ed4d432016-05-19 22:03:54968 WebView::willEnterModalLoop();
[email protected]c1f50aa2010-02-18 03:46:57969 }
970
jam8a021512a2015-02-03 18:16:08971 bool rv = ChildThreadImpl::Send(msg);
[email protected]c1f50aa2010-02-18 03:46:57972
973 if (pumping_events) {
changwan6ed4d432016-05-19 22:03:54974 WebView::didExitModalLoop();
jdduked73ae5412015-05-11 20:07:16975 renderer_scheduler_->ResumeTimerQueue();
[email protected]c1f50aa2010-02-18 03:46:57976 }
977
978 return rv;
979}
980
[email protected]f1a29a02011-10-06 23:08:44981IPC::SyncChannel* RenderThreadImpl::GetChannel() {
[email protected]526476902011-10-06 20:34:06982 return channel();
983}
984
[email protected]f1a29a02011-10-06 23:08:44985std::string RenderThreadImpl::GetLocale() {
[email protected]526476902011-10-06 20:34:06986 // The browser process should have passed the locale to the renderer via the
[email protected]dfd53652012-10-25 00:20:02987 // --lang command line flag.
avi83883c82014-12-23 00:08:49988 const base::CommandLine& parsed_command_line =
989 *base::CommandLine::ForCurrentProcess();
[email protected]526476902011-10-06 20:34:06990 const std::string& lang =
991 parsed_command_line.GetSwitchValueASCII(switches::kLang);
[email protected]dfd53652012-10-25 00:20:02992 DCHECK(!lang.empty());
[email protected]526476902011-10-06 20:34:06993 return lang;
994}
995
[email protected]07bb6332012-01-21 01:07:57996IPC::SyncMessageFilter* RenderThreadImpl::GetSyncMessageFilter() {
997 return sync_message_filter();
998}
999
skyostil12262cf2015-05-21 14:49:311000scoped_refptr<base::SingleThreadTaskRunner>
thestig529ad8a2016-07-08 20:30:121001RenderThreadImpl::GetIOTaskRunner() {
skyostil12262cf2015-05-21 14:49:311002 return ChildProcess::current()->io_task_runner();
[email protected]96191d52012-05-17 01:37:111003}
1004
avi1023d012015-12-25 02:39:141005void RenderThreadImpl::AddRoute(int32_t routing_id, IPC::Listener* listener) {
jam8a021512a2015-02-03 18:16:081006 ChildThreadImpl::GetRouter()->AddRoute(routing_id, listener);
ben76f52b242016-06-18 05:42:481007 auto it = pending_frame_creates_.find(routing_id);
1008 if (it == pending_frame_creates_.end())
rockotf8fdd9b2015-12-16 22:22:351009 return;
1010
1011 RenderFrameImpl* frame = RenderFrameImpl::FromRoutingID(routing_id);
1012 if (!frame)
1013 return;
1014
ben76f52b242016-06-18 05:42:481015 scoped_refptr<PendingFrameCreate> create(it->second);
dominickn6c1f1cf2016-12-20 06:13:331016 frame->BindFrame(it->second->TakeFrameRequest(), it->second->TakeFrameHost());
ben76f52b242016-06-18 05:42:481017 pending_frame_creates_.erase(it);
[email protected]c1f50aa2010-02-18 03:46:571018}
1019
avi1023d012015-12-25 02:39:141020void RenderThreadImpl::RemoveRoute(int32_t routing_id) {
jam8a021512a2015-02-03 18:16:081021 ChildThreadImpl::GetRouter()->RemoveRoute(routing_id);
[email protected]c1f50aa2010-02-18 03:46:571022}
[email protected]0ec90d522014-03-12 16:28:191023
avi1023d012015-12-25 02:39:141024void RenderThreadImpl::AddEmbeddedWorkerRoute(int32_t routing_id,
[email protected]a620b132014-04-30 22:39:171025 IPC::Listener* listener) {
[email protected]48e52e42014-03-20 06:58:071026 AddRoute(routing_id, listener);
1027 if (devtools_agent_message_filter_.get()) {
[email protected]a620b132014-04-30 22:39:171028 devtools_agent_message_filter_->AddEmbeddedWorkerRouteOnMainThread(
[email protected]48e52e42014-03-20 06:58:071029 routing_id);
1030 }
1031}
1032
avi1023d012015-12-25 02:39:141033void RenderThreadImpl::RemoveEmbeddedWorkerRoute(int32_t routing_id) {
[email protected]48e52e42014-03-20 06:58:071034 RemoveRoute(routing_id);
1035 if (devtools_agent_message_filter_.get()) {
[email protected]a620b132014-04-30 22:39:171036 devtools_agent_message_filter_->RemoveEmbeddedWorkerRouteOnMainThread(
[email protected]48e52e42014-03-20 06:58:071037 routing_id);
1038 }
1039}
1040
ben76f52b242016-06-18 05:42:481041void RenderThreadImpl::RegisterPendingFrameCreate(
rockotf8fdd9b2015-12-16 22:22:351042 int routing_id,
ben76f52b242016-06-18 05:42:481043 mojom::FrameRequest frame_request,
1044 mojom::FrameHostPtr frame_host) {
1045 std::pair<PendingFrameCreateMap::iterator, bool> result =
1046 pending_frame_creates_.insert(std::make_pair(
rockotf8fdd9b2015-12-16 22:22:351047 routing_id,
ben76f52b242016-06-18 05:42:481048 make_scoped_refptr(new PendingFrameCreate(
1049 routing_id, std::move(frame_request), std::move(frame_host)))));
rockotf8fdd9b2015-12-16 22:22:351050 CHECK(result.second) << "Inserting a duplicate item.";
1051}
1052
leon.han06e55662016-03-26 17:19:421053mojom::StoragePartitionService* RenderThreadImpl::GetStoragePartitionService() {
jamc912ca32016-02-24 20:17:311054 return storage_partition_service_.get();
1055}
1056
[email protected]77fc9b92011-10-15 16:20:371057int RenderThreadImpl::GenerateRoutingID() {
rockote261d2112016-09-21 22:22:231058 int32_t routing_id = MSG_ROUTING_NONE;
1059 render_message_filter()->GenerateRoutingID(&routing_id);
[email protected]77fc9b92011-10-15 16:20:371060 return routing_id;
1061}
1062
[email protected]74122042014-04-25 00:07:301063void RenderThreadImpl::AddFilter(IPC::MessageFilter* filter) {
[email protected]42f1d7822009-07-23 18:17:551064 channel()->AddFilter(filter);
1065}
1066
[email protected]74122042014-04-25 00:07:301067void RenderThreadImpl::RemoveFilter(IPC::MessageFilter* filter) {
[email protected]42f1d7822009-07-23 18:17:551068 channel()->RemoveFilter(filter);
1069}
1070
tyoshino832a58a2016-04-18 08:14:081071void RenderThreadImpl::AddObserver(RenderThreadObserver* observer) {
[email protected]526476902011-10-06 20:34:061072 observers_.AddObserver(observer);
nigeltao7cd8d5582016-12-12 06:05:281073 observer->RegisterMojoInterfaces(&associated_interfaces_);
[email protected]526476902011-10-06 20:34:061074}
1075
tyoshino832a58a2016-04-18 08:14:081076void RenderThreadImpl::RemoveObserver(RenderThreadObserver* observer) {
nigeltao7cd8d5582016-12-12 06:05:281077 observer->UnregisterMojoInterfaces(&associated_interfaces_);
[email protected]526476902011-10-06 20:34:061078 observers_.RemoveObserver(observer);
1079}
1080
[email protected]359dfa32011-10-12 01:10:151081void RenderThreadImpl::SetResourceDispatcherDelegate(
[email protected]e9ff79c2012-10-19 21:31:261082 ResourceDispatcherDelegate* delegate) {
[email protected]359dfa32011-10-12 01:10:151083 resource_dispatcher()->set_delegate(delegate);
1084}
1085
vollick1050cc62015-12-03 07:04:541086void RenderThreadImpl::InitializeCompositorThread() {
boliu66024c62016-04-20 04:00:411087 base::Thread::Options options;
vollick1050cc62015-12-03 07:04:541088#if defined(OS_ANDROID)
boliu66024c62016-04-20 04:00:411089 options.priority = base::ThreadPriority::DISPLAY;
vollick1050cc62015-12-03 07:04:541090#endif
boliu66024c62016-04-20 04:00:411091 compositor_thread_.reset(new WebThreadForCompositor(options));
1092 blink_platform_impl_->SetCompositorThread(compositor_thread_.get());
1093 compositor_task_runner_ = compositor_thread_->GetTaskRunner();
1094 compositor_task_runner_->PostTask(
1095 FROM_HERE,
1096 base::Bind(base::IgnoreResult(&ThreadRestrictions::SetIOAllowed), false));
reveman7b97c322016-09-20 02:10:581097#if defined(OS_LINUX)
1098 ChildThreadImpl::current()->SetThreadPriority(compositor_thread_->threadId(),
1099 base::ThreadPriority::DISPLAY);
1100#endif
vollick1050cc62015-12-03 07:04:541101
boliude5b75b2016-03-11 07:02:141102 SynchronousInputHandlerProxyClient* synchronous_input_handler_proxy_client =
1103 nullptr;
vollick1050cc62015-12-03 07:04:541104#if defined(OS_ANDROID)
boliu66024c62016-04-20 04:00:411105 if (GetContentClient()->UsingSynchronousCompositing()) {
vollick1050cc62015-12-03 07:04:541106 sync_compositor_message_filter_ =
1107 new SynchronousCompositorFilter(compositor_task_runner_);
1108 AddFilter(sync_compositor_message_filter_.get());
boliude5b75b2016-03-11 07:02:141109 synchronous_input_handler_proxy_client =
1110 sync_compositor_message_filter_.get();
vollick1050cc62015-12-03 07:04:541111 }
1112#endif
boliub2768db2016-06-03 23:35:161113 scoped_refptr<InputEventFilter> compositor_input_event_filter(
1114 new InputEventFilter(main_input_callback_.callback(),
1115 main_thread_compositor_task_runner_,
1116 compositor_task_runner_));
1117 InputHandlerManagerClient* input_handler_manager_client =
1118 compositor_input_event_filter.get();
1119 input_event_filter_ = compositor_input_event_filter;
vollick1050cc62015-12-03 07:04:541120 input_handler_manager_.reset(new InputHandlerManager(
1121 compositor_task_runner_, input_handler_manager_client,
boliude5b75b2016-03-11 07:02:141122 synchronous_input_handler_proxy_client, renderer_scheduler_.get()));
vollick1050cc62015-12-03 07:04:541123}
1124
jam75c44222016-03-23 05:34:241125void RenderThreadImpl::InitializeWebKit(
rockot97a86832016-12-10 04:53:061126 const scoped_refptr<base::SingleThreadTaskRunner>& resource_task_queue) {
jam75c44222016-03-23 05:34:241127 DCHECK(!blink_platform_impl_);
[email protected]d1b8fccc2011-08-03 01:20:131128
avi83883c82014-12-23 00:08:491129 const base::CommandLine& command_line =
1130 *base::CommandLine::ForCurrentProcess();
chunyang.daibe874c52014-11-14 06:45:051131
1132#ifdef ENABLE_VTUNE_JIT_INTERFACE
1133 if (command_line.HasSwitch(switches::kEnableVtune))
1134 gin::Debug::SetJitCodeEventHandler(vTune::GetVtuneCodeEventHandler());
1135#endif
1136
rmcilroy4073ae12015-01-08 13:08:101137 SetRuntimeFeaturesDefaultsAndUpdateFromArgs(command_line);
hlopko852ffcf2016-09-16 16:50:591138 GetContentClient()
1139 ->renderer()
1140 ->SetRuntimeFeaturesDefaultsBeforeBlinkInitialization();
rmcilroy4073ae12015-01-08 13:08:101141
sammcbebeb602016-04-06 06:42:551142 blink_platform_impl_.reset(new RendererBlinkPlatformImpl(
bashidbaff8bb2017-02-16 05:16:151143 renderer_scheduler_.get(), GetRemoteInterfaces()->GetWeakPtr()));
tfarina556a7232014-10-05 01:02:091144 blink::initialize(blink_platform_impl_.get());
[email protected]d1b8fccc2011-08-03 01:20:131145
[email protected]4b5340282014-07-08 11:37:341146 v8::Isolate* isolate = blink::mainThreadIsolate();
[email protected]4b5340282014-07-08 11:37:341147 isolate->SetCreateHistogramFunction(CreateHistogram);
1148 isolate->SetAddHistogramSampleFunction(AddHistogramSample);
skyostila37c2a72016-06-29 17:30:071149 renderer_scheduler_->SetRAILModeObserver(this);
[email protected]4b5340282014-07-08 11:37:341150
rmcilroy321f924d2014-11-06 00:56:001151 main_thread_compositor_task_runner_ =
danakj6e3bf8012014-12-16 18:27:531152 renderer_scheduler_->CompositorTaskRunner();
skyostilc30aa402014-10-10 13:49:091153
jdduke691dd572014-12-02 20:47:521154 main_input_callback_.Reset(
1155 base::Bind(base::IgnoreResult(&RenderThreadImpl::OnMessageReceived),
1156 base::Unretained(this)));
1157
jam75c44222016-03-23 05:34:241158 scoped_refptr<base::SingleThreadTaskRunner> resource_task_queue2;
1159 if (resource_task_queue) {
1160 resource_task_queue2 = resource_task_queue;
1161 } else {
1162 resource_task_queue2 = renderer_scheduler_->LoadingTaskRunner();
1163 }
1164 // Add a filter that forces resource messages to be dispatched via a
1165 // particular task runner.
1166 scoped_refptr<ResourceSchedulingFilter> filter(
1167 new ResourceSchedulingFilter(
1168 resource_task_queue2, resource_dispatcher()));
1169 channel()->AddFilter(filter.get());
1170 resource_dispatcher()->SetResourceSchedulingFilter(filter);
1171
1172 // The ChildResourceMessageFilter and the ResourceDispatcher need to use the
1173 // same queue to ensure tasks are executed in the expected order.
1174 child_resource_message_filter()->SetMainThreadTaskRunner(
1175 resource_task_queue2);
1176 resource_dispatcher()->SetMainThreadTaskRunner(resource_task_queue2);
1177
khushalsagard7178e42017-01-20 01:31:491178 if (!command_line.HasSwitch(switches::kDisableThreadedCompositing))
vollick1050cc62015-12-03 07:04:541179 InitializeCompositorThread();
[email protected]a9fb30aa2011-10-06 06:58:461180
jdduke691dd572014-12-02 20:47:521181 if (!input_event_filter_.get()) {
1182 // Always provide an input event filter implementation to ensure consistent
1183 // input event scheduling and prioritization.
1184 // TODO(jdduke): Merge InputEventFilter, InputHandlerManager and
1185 // MainThreadInputEventFilter, crbug.com/436057.
1186 input_event_filter_ = new MainThreadInputEventFilter(
1187 main_input_callback_.callback(), main_thread_compositor_task_runner_);
1188 }
1189 AddFilter(input_event_filter_.get());
1190
skyostil2d3b5bd2015-05-27 15:40:591191 scoped_refptr<base::SingleThreadTaskRunner> compositor_impl_side_task_runner;
vollick1050cc62015-12-03 07:04:541192 if (compositor_task_runner_)
skyostil2d3b5bd2015-05-27 15:40:591193 compositor_impl_side_task_runner = compositor_task_runner_;
[email protected]7f1f63f2013-03-07 06:07:291194 else
skyostil2d3b5bd2015-05-27 15:40:591195 compositor_impl_side_task_runner = base::ThreadTaskRunnerHandle::Get();
[email protected]1842fe22012-08-13 23:24:351196
simonhonga7e3ac42014-11-11 20:50:221197 compositor_message_filter_ = new CompositorForwardingMessageFilter(
skyostil2d3b5bd2015-05-27 15:40:591198 compositor_impl_side_task_runner.get());
simonhonga7e3ac42014-11-11 20:50:221199 AddFilter(compositor_message_filter_.get());
[email protected]1842fe22012-08-13 23:24:351200
[email protected]58436a12012-03-21 17:10:261201 RenderThreadImpl::RegisterSchemes();
1202
xhwang194acae2014-11-12 22:46:331203 RenderMediaClient::Initialize();
1204
[email protected]b146d6d2012-09-11 10:20:051205 devtools_agent_message_filter_ = new DevToolsAgentFilter();
1206 AddFilter(devtools_agent_message_filter_.get());
1207
ulan4a385192015-11-11 10:59:181208 if (GetContentClient()->renderer()->RunIdleHandlerWhenWidgetsHidden()) {
[email protected]1784b2f2011-11-24 10:53:481209 ScheduleIdleHandler(kLongIdleHandlerDelayMs);
ulan4a385192015-11-11 10:59:181210 } else {
1211 // If we do not track widget visibility, then assume conservatively that
1212 // the isolate is in background. This reduces memory usage.
1213 isolate->IsolateInBackgroundNotification();
1214 }
[email protected]2541d1a2013-07-10 07:33:271215
jdduke73220f02015-09-04 17:03:511216 renderer_scheduler_->SetTimerQueueSuspensionWhenBackgroundedEnabled(
1217 GetContentClient()
1218 ->renderer()
1219 ->AllowTimerSuspensionWhenProcessBackgrounded());
1220
reedccf98c52014-10-03 16:40:381221 SkGraphics::SetResourceCacheSingleAllocationByteLimit(
[email protected]dd2c1022014-07-22 23:13:571222 kImageCacheSingleAllocationByteLimit);
1223
reed6e5a72222015-08-06 20:37:161224 // Hook up blink's codecs so skia can call them
reed08cd16372017-02-21 22:11:411225 SkGraphics::SetImageGeneratorFromEncodedDataFactory(
reed6e5a72222015-08-06 20:37:161226 blink::WebImageGenerator::create);
1227
[email protected]fdeac262014-07-10 12:52:511228 if (command_line.HasSwitch(switches::kMemoryMetrics)) {
1229 memory_observer_.reset(new MemoryObserver());
1230 message_loop()->AddTaskObserver(memory_observer_.get());
1231 }
paritosh.in7e30c902015-04-15 17:04:071232
1233 if (command_line.HasSwitch(switches::kExplicitlyAllowedPorts)) {
1234 std::string allowed_ports =
1235 command_line.GetSwitchValueASCII(switches::kExplicitlyAllowedPorts);
1236 net::SetExplicitlyAllowedPorts(allowed_ports);
1237 }
[email protected]d1b8fccc2011-08-03 01:20:131238}
1239
[email protected]58436a12012-03-21 17:10:261240void RenderThreadImpl::RegisterSchemes() {
mkwst8e94fb32015-05-20 05:05:141241 // chrome:
kinukoa0d5ac62016-11-04 08:49:591242 WebString chrome_scheme(WebString::fromASCII(kChromeUIScheme));
mkwst8e94fb32015-05-20 05:05:141243 WebSecurityPolicy::registerURLSchemeAsDisplayIsolated(chrome_scheme);
1244 WebSecurityPolicy::registerURLSchemeAsNotAllowingJavascriptURLs(
1245 chrome_scheme);
mkwst8e94fb32015-05-20 05:05:141246
1247 // chrome-devtools:
kinukoa0d5ac62016-11-04 08:49:591248 WebString devtools_scheme(WebString::fromASCII(kChromeDevToolsScheme));
mkwst8e94fb32015-05-20 05:05:141249 WebSecurityPolicy::registerURLSchemeAsDisplayIsolated(devtools_scheme);
meacerce6b66032016-06-02 20:56:051250
1251 // view-source:
kinukoa0d5ac62016-11-04 08:49:591252 WebString view_source_scheme(WebString::fromASCII(kViewSourceScheme));
meacerce6b66032016-06-02 20:56:051253 WebSecurityPolicy::registerURLSchemeAsDisplayIsolated(view_source_scheme);
[email protected]58436a12012-03-21 17:10:261254}
1255
[email protected]e6e30ac2014-01-13 21:24:391256void RenderThreadImpl::RecordAction(const base::UserMetricsAction& action) {
[email protected]97880c82013-12-04 07:09:211257 Send(new ViewHostMsg_UserMetricsRecordAction(action.str_));
1258}
1259
1260void RenderThreadImpl::RecordComputedAction(const std::string& action) {
[email protected]526476902011-10-06 20:34:061261 Send(new ViewHostMsg_UserMetricsRecordAction(action));
1262}
1263
dchengcedca5612016-04-09 01:40:151264std::unique_ptr<base::SharedMemory>
1265RenderThreadImpl::HostAllocateSharedMemoryBuffer(size_t size) {
sadrulee3ff1f2016-12-09 04:22:011266 return ChildThreadImpl::AllocateSharedMemory(size);
[email protected]00614a82011-10-07 22:39:311267}
1268
jbauman2f5c1942014-12-06 03:28:241269cc::SharedBitmapManager* RenderThreadImpl::GetSharedBitmapManager() {
1270 return shared_bitmap_manager();
1271}
1272
[email protected]f1a29a02011-10-06 23:08:441273void RenderThreadImpl::RegisterExtension(v8::Extension* extension) {
[email protected]526476902011-10-06 20:34:061274 WebScriptController::registerExtension(extension);
[email protected]526476902011-10-06 20:34:061275}
1276
avi1023d012015-12-25 02:39:141277void RenderThreadImpl::ScheduleIdleHandler(int64_t initial_delay_ms) {
[email protected]6593ae12011-11-14 12:09:441278 idle_notification_delay_in_ms_ = initial_delay_ms;
[email protected]526476902011-10-06 20:34:061279 idle_timer_.Stop();
1280 idle_timer_.Start(FROM_HERE,
[email protected]6593ae12011-11-14 12:09:441281 base::TimeDelta::FromMilliseconds(initial_delay_ms),
[email protected]f1a29a02011-10-06 23:08:441282 this, &RenderThreadImpl::IdleHandler);
[email protected]526476902011-10-06 20:34:061283}
1284
[email protected]f1a29a02011-10-06 23:08:441285void RenderThreadImpl::IdleHandler() {
[email protected]1784b2f2011-11-24 10:53:481286 bool run_in_foreground_tab = (widget_count_ > hidden_widget_count_) &&
[email protected]e9ff79c2012-10-19 21:31:261287 GetContentClient()->renderer()->
[email protected]1784b2f2011-11-24 10:53:481288 RunIdleHandlerWhenWidgetsHidden();
1289 if (run_in_foreground_tab) {
jochen5a32aaf2014-09-26 20:37:431290 if (idle_notifications_to_skip_ > 0) {
1291 --idle_notifications_to_skip_;
1292 } else {
ssid0603ca9f2015-06-09 16:48:081293 ReleaseFreeMemory();
jochen5a32aaf2014-09-26 20:37:431294 }
1295 ScheduleIdleHandler(kLongIdleHandlerDelayMs);
[email protected]1784b2f2011-11-24 10:53:481296 return;
1297 }
[email protected]237a14852012-04-28 02:56:381298
ssid0603ca9f2015-06-09 16:48:081299 ReleaseFreeMemory();
[email protected]526476902011-10-06 20:34:061300
[email protected]26e82322014-01-20 14:18:221301 // Continue the idle timer if the webkit shared timer is not suspended or
1302 // something is left to do.
1303 bool continue_timer = !webkit_shared_timer_suspended_;
1304
sullivancd45a3e2014-09-19 14:39:181305 // Schedule next invocation. When the tab is originally hidden, an invocation
1306 // is scheduled for kInitialIdleHandlerDelayMs in
1307 // RenderThreadImpl::WidgetHidden in order to race to a minimal heap.
1308 // After that, idle calls can be much less frequent, so run at a maximum of
1309 // once every kLongIdleHandlerDelayMs.
[email protected]6593ae12011-11-14 12:09:441310 // Dampen the delay using the algorithm (if delay is in seconds):
[email protected]526476902011-10-06 20:34:061311 // delay = delay + 1 / (delay + 2)
1312 // Using floor(delay) has a dampening effect such as:
sullivancd45a3e2014-09-19 14:39:181313 // 30s, 30, 30, 31, 31, 31, 31, 32, 32, ...
[email protected]6593ae12011-11-14 12:09:441314 // If the delay is in milliseconds, the above formula is equivalent to:
1315 // delay_ms / 1000 = delay_ms / 1000 + 1 / (delay_ms / 1000 + 2)
1316 // which is equivalent to
1317 // delay_ms = delay_ms + 1000*1000 / (delay_ms + 2000).
[email protected]26e82322014-01-20 14:18:221318 if (continue_timer) {
sullivancd45a3e2014-09-19 14:39:181319 ScheduleIdleHandler(
1320 std::max(kLongIdleHandlerDelayMs,
1321 idle_notification_delay_in_ms_ +
1322 1000000 / (idle_notification_delay_in_ms_ + 2000)));
[email protected]26e82322014-01-20 14:18:221323
1324 } else {
1325 idle_timer_.Stop();
1326 }
[email protected]526476902011-10-06 20:34:061327
ericwilligers88e69742016-10-17 19:29:551328 for (auto& observer : observers_)
1329 observer.IdleNotification();
[email protected]526476902011-10-06 20:34:061330}
1331
avi1023d012015-12-25 02:39:141332int64_t RenderThreadImpl::GetIdleNotificationDelayInMs() const {
[email protected]6593ae12011-11-14 12:09:441333 return idle_notification_delay_in_ms_;
[email protected]526476902011-10-06 20:34:061334}
1335
[email protected]6593ae12011-11-14 12:09:441336void RenderThreadImpl::SetIdleNotificationDelayInMs(
avi1023d012015-12-25 02:39:141337 int64_t idle_notification_delay_in_ms) {
[email protected]6593ae12011-11-14 12:09:441338 idle_notification_delay_in_ms_ = idle_notification_delay_in_ms;
[email protected]4a7d6392011-09-19 20:55:081339}
1340
[email protected]5b18406362013-06-18 18:46:431341int RenderThreadImpl::PostTaskToAllWebWorkers(const base::Closure& closure) {
kinukoef647412015-12-23 06:10:431342 return WorkerThreadRegistry::Instance()->PostTaskToAllThreads(closure);
[email protected]a9bd323d2013-06-17 20:27:561343}
1344
[email protected]b02f5902012-12-19 07:33:001345bool RenderThreadImpl::ResolveProxy(const GURL& url, std::string* proxy_list) {
1346 bool result = false;
1347 Send(new ViewHostMsg_ResolveProxy(url, &result, proxy_list));
1348 return result;
1349}
1350
[email protected]1784b2f2011-11-24 10:53:481351void RenderThreadImpl::PostponeIdleNotification() {
1352 idle_notifications_to_skip_ = 2;
1353}
1354
dcastagna7f45dada2015-10-19 20:17:351355media::GpuVideoAcceleratorFactories* RenderThreadImpl::GetGpuFactories() {
[email protected]3bb8bb32013-07-11 13:13:031356 DCHECK(IsMainThread());
1357
dcastagna09bd6b32016-02-01 21:54:281358 if (!gpu_factories_.empty()) {
sadrul85cc5d82016-12-20 03:37:411359 scoped_refptr<ui::ContextProviderCommandBuffer> shared_context_provider =
dcastagna09bd6b32016-02-01 21:54:281360 gpu_factories_.back()->ContextProviderMainThread();
1361 if (shared_context_provider) {
1362 cc::ContextProvider::ScopedContextLock lock(
1363 shared_context_provider.get());
1364 if (lock.ContextGL()->GetGraphicsResetStatusKHR() == GL_NO_ERROR) {
leon.han21e0e482017-02-23 04:13:321365 return gpu_factories_.back().get();
dcastagna09bd6b32016-02-01 21:54:281366 } else {
1367 scoped_refptr<base::SingleThreadTaskRunner> media_task_runner =
1368 GetMediaThreadTaskRunner();
1369 media_task_runner->PostTask(
1370 FROM_HERE,
1371 base::Bind(
1372 base::IgnoreResult(
1373 &RendererGpuVideoAcceleratorFactories::CheckContextLost),
leon.han21e0e482017-02-23 04:13:321374 base::Unretained(gpu_factories_.back().get())));
dcastagna09bd6b32016-02-01 21:54:281375 }
1376 }
1377 }
dcastagna7f45dada2015-10-19 20:17:351378
tobiasjsca238b3b2015-06-24 22:53:541379 const base::CommandLine* cmd_line = base::CommandLine::ForCurrentProcess();
1380
danakj0b4b94e32016-05-10 22:33:011381 scoped_refptr<gpu::GpuChannelHost> gpu_channel_host =
sadrul6d310fa2016-08-04 02:12:161382 EstablishGpuChannelSync();
danakj0b4b94e32016-05-10 22:33:011383 if (!gpu_channel_host)
1384 return nullptr;
danakj0dd9e1e2016-05-11 22:15:091385 // This context is only used to create textures and mailbox them, so
1386 // use lower limits than the default.
1387 gpu::SharedMemoryLimits limits = gpu::SharedMemoryLimits::ForMailboxContext();
danakj9a04adc2016-05-16 22:45:071388 bool support_locking = true;
sadrul85cc5d82016-12-20 03:37:411389 scoped_refptr<ui::ContextProviderCommandBuffer> media_context_provider =
danakj9a04adc2016-05-16 22:45:071390 CreateOffscreenContext(gpu_channel_host, limits, support_locking,
ericrka20c1002017-03-13 21:08:131391 ui::command_buffer_metrics::MEDIA_CONTEXT,
danakj0dd9e1e2016-05-11 22:15:091392 gpu::GPU_STREAM_DEFAULT,
1393 gpu::GpuStreamPriority::NORMAL);
danakj0b4b94e32016-05-10 22:33:011394 if (!media_context_provider->BindToCurrentThread())
1395 return nullptr;
danakj0b4b94e32016-05-10 22:33:011396
acolwellb4034942014-08-28 15:42:431397 scoped_refptr<base::SingleThreadTaskRunner> media_task_runner =
1398 GetMediaThreadTaskRunner();
danakj0b4b94e32016-05-10 22:33:011399 const bool enable_video_accelerator =
1400 !cmd_line->HasSwitch(switches::kDisableAcceleratedVideoDecode);
1401 const bool enable_gpu_memory_buffer_video_frames =
dcastagna43c3a86a2016-02-02 21:16:381402#if defined(OS_MACOSX) || defined(OS_LINUX)
dcastagnaa82ed96a2016-05-12 02:52:471403 !cmd_line->HasSwitch(switches::kDisableGpuMemoryBufferVideoFrames) &&
1404 !cmd_line->HasSwitch(switches::kDisableGpuCompositing) &&
1405 !gpu_channel_host->gpu_info().software_rendering;
dcastagnab65e6072015-09-05 07:18:421406#else
danakj0b4b94e32016-05-10 22:33:011407 cmd_line->HasSwitch(switches::kEnableGpuMemoryBufferVideoFrames);
dcastagnab65e6072015-09-05 07:18:421408#endif
dcastagna5077d6d2016-01-27 00:07:051409
danakj0b4b94e32016-05-10 22:33:011410 gpu_factories_.push_back(RendererGpuVideoAcceleratorFactories::Create(
1411 std::move(gpu_channel_host), base::ThreadTaskRunnerHandle::Get(),
1412 media_task_runner, std::move(media_context_provider),
ericrk9151705c2016-07-26 19:53:161413 enable_gpu_memory_buffer_video_frames, buffer_to_texture_target_map_,
danakj0b4b94e32016-05-10 22:33:011414 enable_video_accelerator));
leon.han21e0e482017-02-23 04:13:321415 return gpu_factories_.back().get();
[email protected]3bb8bb32013-07-11 13:13:031416}
1417
sadrul85cc5d82016-12-20 03:37:411418scoped_refptr<ui::ContextProviderCommandBuffer>
[email protected]f10dc472013-09-27 03:31:591419RenderThreadImpl::SharedMainThreadContextProvider() {
[email protected]e06e1122013-03-15 17:12:381420 DCHECK(IsMainThread());
danakje8ec797e2016-04-19 04:08:431421 if (shared_main_thread_contexts_ &&
1422 shared_main_thread_contexts_->ContextGL()->GetGraphicsResetStatusKHR() ==
1423 GL_NO_ERROR)
1424 return shared_main_thread_contexts_;
1425
sadrul6d310fa2016-08-04 02:12:161426 scoped_refptr<gpu::GpuChannelHost> gpu_channel_host(
1427 EstablishGpuChannelSync());
danakje8ec797e2016-04-19 04:08:431428 if (!gpu_channel_host) {
1429 shared_main_thread_contexts_ = nullptr;
1430 return nullptr;
[email protected]c29b7ff2013-03-06 03:51:041431 }
danakje8ec797e2016-04-19 04:08:431432
danakj9a04adc2016-05-16 22:45:071433 bool support_locking = false;
danakjc3983552016-05-03 00:04:351434 shared_main_thread_contexts_ = CreateOffscreenContext(
danakj9a04adc2016-05-16 22:45:071435 std::move(gpu_channel_host), gpu::SharedMemoryLimits(), support_locking,
sadrul85cc5d82016-12-20 03:37:411436 ui::command_buffer_metrics::RENDERER_MAINTHREAD_CONTEXT,
sunnypsd8ce1c22016-05-10 18:02:401437 gpu::GPU_STREAM_DEFAULT, gpu::GpuStreamPriority::NORMAL);
danakje8ec797e2016-04-19 04:08:431438 if (!shared_main_thread_contexts_->BindToCurrentThread())
1439 shared_main_thread_contexts_ = nullptr;
[email protected]f10dc472013-09-27 03:31:591440 return shared_main_thread_contexts_;
[email protected]c29b7ff2013-03-06 03:51:041441}
1442
siva.gunturi5d4feb052015-11-15 16:15:311443#if defined(OS_ANDROID)
boliuf8753bf62016-02-11 20:09:421444
siva.gunturi5d4feb052015-11-15 16:15:311445scoped_refptr<StreamTextureFactory> RenderThreadImpl::GetStreamTexureFactory() {
1446 DCHECK(IsMainThread());
boliu30f1b262016-04-19 00:12:331447 if (!stream_texture_factory_.get() ||
1448 stream_texture_factory_->ContextGL()->GetGraphicsResetStatusKHR() !=
1449 GL_NO_ERROR) {
sadrul85cc5d82016-12-20 03:37:411450 scoped_refptr<ui::ContextProviderCommandBuffer> shared_context_provider =
piman9fc22f32016-05-02 22:21:221451 SharedMainThreadContextProvider();
1452 if (!shared_context_provider) {
penghuange1d86512016-07-08 18:15:001453 stream_texture_factory_ = nullptr;
1454 return nullptr;
siva.gunturi5d4feb052015-11-15 16:15:311455 }
piman9fc22f32016-05-02 22:21:221456 DCHECK(shared_context_provider->GetCommandBufferProxy());
1457 DCHECK(shared_context_provider->GetCommandBufferProxy()->channel());
1458 stream_texture_factory_ =
1459 StreamTextureFactory::Create(std::move(shared_context_provider));
siva.gunturi5d4feb052015-11-15 16:15:311460 }
1461 return stream_texture_factory_;
1462}
boliuf8753bf62016-02-11 20:09:421463
1464bool RenderThreadImpl::EnableStreamTextureCopy() {
boliu30f1b262016-04-19 00:12:331465 return sync_compositor_message_filter_.get();
boliuf8753bf62016-02-11 20:09:421466}
1467
siva.gunturi5d4feb052015-11-15 16:15:311468#endif
1469
[email protected]e9ff79c2012-10-19 21:31:261470AudioRendererMixerManager* RenderThreadImpl::GetAudioRendererMixerManager() {
[email protected]59383c782013-04-17 16:43:271471 if (!audio_renderer_mixer_manager_) {
olka7a4679392016-05-27 15:32:581472 audio_renderer_mixer_manager_ = AudioRendererMixerManager::Create();
[email protected]3958e972012-07-17 00:25:411473 }
1474
1475 return audio_renderer_mixer_manager_.get();
1476}
1477
[email protected]73429ca2014-03-06 06:07:471478base::WaitableEvent* RenderThreadImpl::GetShutdownEvent() {
1479 return ChildProcess::current()->GetShutDownEvent();
1480}
1481
staraz067f58242016-11-07 21:06:411482int32_t RenderThreadImpl::GetClientId() {
1483 return client_id_;
1484}
1485
altiminc8885e82017-01-18 13:11:141486scoped_refptr<base::SingleThreadTaskRunner>
1487RenderThreadImpl::GetTimerTaskRunner() {
1488 return renderer_scheduler_->TimerTaskRunner();
1489}
1490
1491scoped_refptr<base::SingleThreadTaskRunner>
1492RenderThreadImpl::GetLoadingTaskRunner() {
1493 return renderer_scheduler_->LoadingTaskRunner();
1494}
1495
chiniforooshan614d70a2017-03-17 01:19:331496void RenderThreadImpl::SetFieldTrialGroup(const std::string& trial_name,
1497 const std::string& group_name) {
1498 field_trial_syncer_.OnSetFieldTrialGroup(trial_name, group_name);
1499}
1500
rockot067ca55f2016-09-30 22:00:151501void RenderThreadImpl::OnAssociatedInterfaceRequest(
1502 const std::string& name,
1503 mojo::ScopedInterfaceEndpointHandle handle) {
rockot70bbb59492017-01-25 00:56:511504 if (associated_interfaces_.CanBindRequest(name))
1505 associated_interfaces_.BindRequest(name, std::move(handle));
1506 else
1507 ChildThreadImpl::OnAssociatedInterfaceRequest(name, std::move(handle));
rockot067ca55f2016-09-30 22:00:151508}
1509
danakj6e3bf8012014-12-16 18:27:531510bool RenderThreadImpl::IsGpuRasterizationForced() {
1511 return is_gpu_rasterization_forced_;
1512}
1513
sunnypsd8ce1c22016-05-10 18:02:401514bool RenderThreadImpl::IsAsyncWorkerContextEnabled() {
1515 return is_async_worker_context_enabled_;
1516}
1517
senorblancob60ba952015-01-27 19:12:361518int RenderThreadImpl::GetGpuRasterizationMSAASampleCount() {
1519 return gpu_rasterization_msaa_sample_count_;
1520}
1521
danakj6e3bf8012014-12-16 18:27:531522bool RenderThreadImpl::IsLcdTextEnabled() {
1523 return is_lcd_text_enabled_;
1524}
1525
1526bool RenderThreadImpl::IsDistanceFieldTextEnabled() {
1527 return is_distance_field_text_enabled_;
1528}
1529
1530bool RenderThreadImpl::IsZeroCopyEnabled() {
1531 return is_zero_copy_enabled_;
1532}
1533
ericrk1d17f752015-10-20 03:03:071534bool RenderThreadImpl::IsPartialRasterEnabled() {
1535 return is_partial_raster_enabled_;
jbroman5f7f71932015-08-18 16:24:461536}
1537
ccameronc7fcd132015-11-03 20:14:311538bool RenderThreadImpl::IsGpuMemoryBufferCompositorResourcesEnabled() {
1539 return is_gpu_memory_buffer_compositor_resources_enabled_;
1540}
1541
ccamerona7644752014-12-30 01:16:311542bool RenderThreadImpl::IsElasticOverscrollEnabled() {
1543 return is_elastic_overscroll_enabled_;
1544}
1545
ericrk9151705c2016-07-26 19:53:161546const cc::BufferToTextureTargetMap&
1547RenderThreadImpl::GetBufferToTextureTargetMap() {
1548 return buffer_to_texture_target_map_;
danakj6e3bf8012014-12-16 18:27:531549}
vmiura9084b342015-02-03 22:19:571550
danakj6e3bf8012014-12-16 18:27:531551scoped_refptr<base::SingleThreadTaskRunner>
1552RenderThreadImpl::GetCompositorMainThreadTaskRunner() {
1553 return main_thread_compositor_task_runner_;
1554}
1555
1556scoped_refptr<base::SingleThreadTaskRunner>
1557RenderThreadImpl::GetCompositorImplThreadTaskRunner() {
skyostil2d3b5bd2015-05-27 15:40:591558 return compositor_task_runner_;
danakj6e3bf8012014-12-16 18:27:531559}
1560
1561gpu::GpuMemoryBufferManager* RenderThreadImpl::GetGpuMemoryBufferManager() {
sadrul53546592016-12-17 01:44:211562 return gpu_->gpu_memory_buffer_manager();
danakj6e3bf8012014-12-16 18:27:531563}
1564
skyostil529caa292016-08-10 17:44:511565blink::scheduler::RendererScheduler* RenderThreadImpl::GetRendererScheduler() {
danakj6e3bf8012014-12-16 18:27:531566 return renderer_scheduler_.get();
1567}
1568
dchengcedca5612016-04-09 01:40:151569std::unique_ptr<cc::BeginFrameSource>
danakj6e3bf8012014-12-16 18:27:531570RenderThreadImpl::CreateExternalBeginFrameSource(int routing_id) {
ennee292bdc2016-09-15 19:57:151571 const base::CommandLine* cmd = base::CommandLine::ForCurrentProcess();
1572 if (cmd->HasSwitch(switches::kDisableGpuVsync)) {
1573 std::string display_vsync_string =
1574 cmd->GetSwitchValueASCII(switches::kDisableGpuVsync);
1575 if (display_vsync_string != "gpu") {
1576 // In disable gpu vsync mode, also let the renderer tick as fast as it
1577 // can. The top level begin frame source will also be running as a back
1578 // to back begin frame source, but using a synthetic begin frame source
1579 // here reduces latency when in this mode (at least for frames
1580 // starting--it potentially increases it for input on the other hand.)
1581 base::SingleThreadTaskRunner* compositor_impl_side_task_runner =
1582 compositor_task_runner_ ? compositor_task_runner_.get()
1583 : base::ThreadTaskRunnerHandle::Get().get();
1584 return base::MakeUnique<cc::BackToBackBeginFrameSource>(
1585 base::MakeUnique<cc::DelayBasedTimeSource>(
1586 compositor_impl_side_task_runner));
1587 }
1588 }
1589
ricea29649b92016-08-31 09:30:211590 return base::MakeUnique<CompositorExternalBeginFrameSource>(
1591 compositor_message_filter_.get(), sync_message_filter(), routing_id);
danakj6e3bf8012014-12-16 18:27:531592}
1593
reveman34b7a1522015-03-23 20:27:471594cc::TaskGraphRunner* RenderThreadImpl::GetTaskGraphRunner() {
prashant.nfad657e2016-06-01 07:52:171595 return categorized_worker_pool_->GetTaskGraphRunner();
reveman34b7a1522015-03-23 20:27:471596}
1597
vmpstrdfd22862015-09-25 17:42:411598bool RenderThreadImpl::AreImageDecodeTasksEnabled() {
1599 return are_image_decode_tasks_enabled_;
reveman34b7a1522015-03-23 20:27:471600}
1601
loyso65c93c602015-08-11 05:15:571602bool RenderThreadImpl::IsThreadedAnimationEnabled() {
1603 return is_threaded_animation_enabled_;
1604}
1605
wjmaclean1d970622017-01-21 22:28:241606bool RenderThreadImpl::IsScrollAnimatorEnabled() {
1607 return is_scroll_animator_enabled_;
1608}
1609
fsamuel4c5c87142017-03-14 03:14:261610bool RenderThreadImpl::IsSurfaceSynchronizationEnabled() {
1611 return is_surface_synchronization_enabled_;
1612}
1613
skyostila37c2a72016-06-29 17:30:071614void RenderThreadImpl::OnRAILModeChanged(v8::RAILMode rail_mode) {
1615 blink::mainThreadIsolate()->SetRAILMode(rail_mode);
1616 blink::setRAILModeOnWorkerThreadIsolates(rail_mode);
1617}
1618
[email protected]b3e83de2012-02-07 03:33:281619bool RenderThreadImpl::IsMainThread() {
1620 return !!current();
1621}
1622
torne88b66452016-05-03 13:22:141623void RenderThreadImpl::OnChannelError() {
1624 // In single-process mode, the renderer can't be restarted after shutdown.
1625 // So, if we get a channel error, crash the whole process right now to get a
1626 // more informative stack, since we will otherwise just crash later when we
1627 // try to restart it.
1628 CHECK(!base::CommandLine::ForCurrentProcess()->HasSwitch(
1629 switches::kSingleProcess));
1630 ChildThreadImpl::OnChannelError();
1631}
1632
[email protected]f1a29a02011-10-06 23:08:441633bool RenderThreadImpl::OnControlMessageReceived(const IPC::Message& msg) {
dchenga2d442c22016-10-13 15:39:211634 for (auto& observer : observers_) {
1635 if (observer.OnControlMessageReceived(msg))
[email protected]1223d6ef2011-03-28 16:47:501636 return true;
1637 }
1638
[email protected]70c19a932010-05-14 12:59:111639 // Some messages are handled by delegates.
[email protected]1910fe82012-05-10 00:04:101640 if (appcache_dispatcher_->OnMessageReceived(msg) ||
[email protected]7670d4332013-11-29 04:35:001641 dom_storage_dispatcher_->OnMessageReceived(msg) ||
1642 embedded_worker_dispatcher_->OnMessageReceived(msg)) {
[email protected]a95986a82010-12-24 06:19:281643 return true;
[email protected]1910fe82012-05-10 00:04:101644 }
[email protected]1edc16b82009-04-07 17:45:541645
[email protected]a95986a82010-12-24 06:19:281646 bool handled = true;
[email protected]f1a29a02011-10-06 23:08:441647 IPC_BEGIN_MESSAGE_MAP(RenderThreadImpl, msg)
[email protected]0ec90d522014-03-12 16:28:191648 IPC_MESSAGE_HANDLER(WorkerProcessMsg_CreateWorker, OnCreateNewSharedWorker)
[email protected]a95986a82010-12-24 06:19:281649 IPC_MESSAGE_UNHANDLED(handled = false)
[email protected]8930d472009-02-21 08:05:281650 IPC_END_MESSAGE_MAP()
[email protected]a95986a82010-12-24 06:19:281651 return handled;
initial.commit09911bf2008-07-26 23:55:291652}
1653
jdduke73220f02015-09-04 17:03:511654void RenderThreadImpl::OnProcessBackgrounded(bool backgrounded) {
1655 ChildThreadImpl::OnProcessBackgrounded(backgrounded);
1656
hajimehoshi69093272016-05-13 08:30:581657 if (backgrounded) {
jdduke73220f02015-09-04 17:03:511658 renderer_scheduler_->OnRendererBackgrounded();
tasakb95dbb50c2017-02-08 18:07:501659 needs_to_record_first_active_paint_ = false;
hajimehoshi69093272016-05-13 08:30:581660 } else {
jdduke73220f02015-09-04 17:03:511661 renderer_scheduler_->OnRendererForegrounded();
tasak6ff44032016-11-07 06:45:251662
tasakb46626a2016-10-18 05:54:441663 record_purge_suspend_metric_closure_.Cancel();
tasak07465a72016-10-21 06:38:521664 record_purge_suspend_metric_closure_.Reset(
1665 base::Bind(&RenderThreadImpl::RecordPurgeAndSuspendMetrics,
1666 base::Unretained(this)));
tasak72f64042017-01-19 14:02:531667 record_purge_suspend_growth_metric_closure_.Cancel();
1668 record_purge_suspend_growth_metric_closure_.Reset(
1669 base::Bind(&RenderThreadImpl::RecordPurgeAndSuspendMemoryGrowthMetrics,
1670 base::Unretained(this)));
hajimehoshi69093272016-05-13 08:30:581671 }
1672}
1673
1674void RenderThreadImpl::OnProcessPurgeAndSuspend() {
1675 ChildThreadImpl::OnProcessPurgeAndSuspend();
tasak6ff44032016-11-07 06:45:251676 if (!RendererIsHidden())
hajimehoshi69093272016-05-13 08:30:581677 return;
tasakff1e62422016-12-22 04:53:551678
tasak6ff44032016-11-07 06:45:251679 if (base::FeatureList::IsEnabled(features::kPurgeAndSuspend)) {
wezc80d2d2b02017-02-16 03:28:191680 base::MemoryCoordinatorClientRegistry::GetInstance()->PurgeMemory();
tasak6ff44032016-11-07 06:45:251681 }
tasakb46626a2016-10-18 05:54:441682 // Since purging is not a synchronous task (e.g. v8 GC, oilpan GC, ...),
1683 // we need to wait until the task is finished. So wait 15 seconds and
1684 // update purge+suspend UMA histogram.
1685 // TODO(tasak): use MemoryCoordinator's callback to report purge+suspend
1686 // UMA when MemoryCoordinator is available.
1687 GetRendererScheduler()->DefaultTaskRunner()->PostDelayedTask(
1688 FROM_HERE, record_purge_suspend_metric_closure_.callback(),
1689 base::TimeDelta::FromSeconds(15));
tasakb95dbb50c2017-02-08 18:07:501690 needs_to_record_first_active_paint_ = true;
tasakb46626a2016-10-18 05:54:441691}
1692
1693// TODO(tasak): Replace the following GetMallocUsage() with memory-infra
1694// when it is possible to run memory-infra without tracing.
1695#if defined(OS_WIN)
1696namespace {
1697
1698static size_t GetMallocUsage() {
siggi7fb93a52016-12-12 22:22:151699 // Iterate through whichever heap the CRT is using.
1700 HANDLE crt_heap = reinterpret_cast<HANDLE>(_get_heap_handle());
1701 if (crt_heap == NULL)
tasakb46626a2016-10-18 05:54:441702 return 0;
siggi7fb93a52016-12-12 22:22:151703 if (!::HeapLock(crt_heap))
tasak7415a3db2016-12-12 04:17:141704 return 0 ;
tasakb46626a2016-10-18 05:54:441705 size_t malloc_usage = 0;
tasak7415a3db2016-12-12 04:17:141706 PROCESS_HEAP_ENTRY heap_entry;
1707 heap_entry.lpData = NULL;
siggi7fb93a52016-12-12 22:22:151708 while (::HeapWalk(crt_heap, &heap_entry) != 0) {
tasak7415a3db2016-12-12 04:17:141709 if ((heap_entry.wFlags & PROCESS_HEAP_ENTRY_BUSY) != 0)
1710 malloc_usage += heap_entry.cbData;
tasakb46626a2016-10-18 05:54:441711 }
siggi7fb93a52016-12-12 22:22:151712 ::HeapUnlock(crt_heap);
tasakb46626a2016-10-18 05:54:441713 return malloc_usage;
1714}
1715
1716} // namespace
1717#elif defined(OS_MACOSX) || defined(OS_IOS)
1718namespace {
1719
1720static size_t GetMallocUsage() {
1721 malloc_statistics_t stats = {0};
1722 malloc_zone_statistics(nullptr, &stats);
1723 return stats.size_in_use;
1724}
1725
1726} // namespace
1727#endif
1728
keishi51ed0d52017-01-12 10:04:461729void RenderThreadImpl::GetRendererMemoryMetrics(
1730 RendererMemoryMetrics* memory_metrics) const {
1731 DCHECK(memory_metrics);
1732
1733 blink::WebMemoryStatistics blink_stats = blink::WebMemoryStatistics::Get();
1734 memory_metrics->partition_alloc_kb =
1735 blink_stats.partitionAllocTotalAllocatedBytes / 1024;
1736 memory_metrics->blink_gc_kb = blink_stats.blinkGCTotalAllocatedBytes / 1024;
1737#if defined(OS_LINUX) || defined(OS_ANDROID)
1738 struct mallinfo minfo = mallinfo();
1739#if defined(USE_TCMALLOC)
1740 size_t malloc_usage = minfo.uordblks;
1741#else
1742 size_t malloc_usage = minfo.hblkhd + minfo.arena;
1743#endif
1744#else
1745 size_t malloc_usage = GetMallocUsage();
1746#endif
1747 memory_metrics->malloc_mb = malloc_usage / 1024 / 1024;
1748
1749 discardable_memory::ClientDiscardableSharedMemoryManager::Statistics
1750 discardable_stats = discardable_shared_memory_manager_->GetStatistics();
1751 size_t discardable_usage =
1752 discardable_stats.total_size - discardable_stats.freelist_size;
1753 memory_metrics->discardable_kb = discardable_usage / 1024;
1754
1755 size_t v8_usage = 0;
1756 if (v8::Isolate* isolate = blink::mainThreadIsolate()) {
1757 v8::HeapStatistics v8_heap_statistics;
1758 isolate->GetHeapStatistics(&v8_heap_statistics);
1759 v8_usage = v8_heap_statistics.total_heap_size();
1760 }
1761 // TODO(tasak): Currently only memory usage of mainThreadIsolate() is
1762 // reported. We should collect memory usages of all isolates using
1763 // memory-infra.
1764 memory_metrics->v8_main_thread_isolate_mb = v8_usage / 1024 / 1024;
1765 size_t total_allocated = blink_stats.partitionAllocTotalAllocatedBytes +
1766 blink_stats.blinkGCTotalAllocatedBytes +
1767 malloc_usage + v8_usage + discardable_usage;
1768 memory_metrics->total_allocated_mb = total_allocated / 1024 / 1024;
1769 memory_metrics->non_discardable_total_allocated_mb =
1770 (total_allocated - discardable_usage) / 1024 / 1024;
1771 memory_metrics->total_allocated_per_render_view_mb =
1772 total_allocated / RenderView::GetRenderViewCount() / 1024 / 1024;
1773}
1774
tasakb46626a2016-10-18 05:54:441775// TODO(tasak): Once it is possible to use memory-infra without tracing,
1776// we should collect the metrics using memory-infra.
1777// TODO(tasak): We should also report a difference between the memory usages
1778// before and after purging by using memory-infra.
tasak72f64042017-01-19 14:02:531779void RenderThreadImpl::RecordPurgeAndSuspendMetrics() {
tasakb46626a2016-10-18 05:54:441780 // If this renderer is resumed, we should not update UMA.
tasak7e65dad2016-12-16 10:18:251781 if (!RendererIsHidden())
tasakb46626a2016-10-18 05:54:441782 return;
1783
1784 // TODO(tasak): Compare memory metrics between purge-enabled renderers and
1785 // purge-disabled renderers (A/B testing).
keishi51ed0d52017-01-12 10:04:461786 RendererMemoryMetrics memory_metrics;
1787 GetRendererMemoryMetrics(&memory_metrics);
tasakb46626a2016-10-18 05:54:441788 UMA_HISTOGRAM_MEMORY_KB("PurgeAndSuspend.Memory.PartitionAllocKB",
keishi51ed0d52017-01-12 10:04:461789 memory_metrics.partition_alloc_kb);
tasakb46626a2016-10-18 05:54:441790 UMA_HISTOGRAM_MEMORY_KB("PurgeAndSuspend.Memory.BlinkGCKB",
keishi51ed0d52017-01-12 10:04:461791 memory_metrics.blink_gc_kb);
tasakb46626a2016-10-18 05:54:441792 UMA_HISTOGRAM_MEMORY_MB("PurgeAndSuspend.Memory.MallocMB",
keishi51ed0d52017-01-12 10:04:461793 memory_metrics.malloc_mb);
tasakb46626a2016-10-18 05:54:441794 UMA_HISTOGRAM_MEMORY_KB("PurgeAndSuspend.Memory.DiscardableKB",
keishi51ed0d52017-01-12 10:04:461795 memory_metrics.discardable_kb);
tasakb46626a2016-10-18 05:54:441796 UMA_HISTOGRAM_MEMORY_MB("PurgeAndSuspend.Memory.V8MainThreadIsolateMB",
keishi51ed0d52017-01-12 10:04:461797 memory_metrics.v8_main_thread_isolate_mb);
tasakb46626a2016-10-18 05:54:441798 UMA_HISTOGRAM_MEMORY_MB("PurgeAndSuspend.Memory.TotalAllocatedMB",
keishi51ed0d52017-01-12 10:04:461799 memory_metrics.total_allocated_mb);
tasak72f64042017-01-19 14:02:531800 purge_and_suspend_memory_metrics_ = memory_metrics;
1801
1802 // record how many memory usage increases after purged.
1803 GetRendererScheduler()->DefaultTaskRunner()->PostDelayedTask(
1804 FROM_HERE, record_purge_suspend_growth_metric_closure_.callback(),
1805 base::TimeDelta::FromMinutes(5));
1806 GetRendererScheduler()->DefaultTaskRunner()->PostDelayedTask(
1807 FROM_HERE, record_purge_suspend_growth_metric_closure_.callback(),
1808 base::TimeDelta::FromMinutes(10));
1809 GetRendererScheduler()->DefaultTaskRunner()->PostDelayedTask(
1810 FROM_HERE, record_purge_suspend_growth_metric_closure_.callback(),
1811 base::TimeDelta::FromMinutes(15));
1812}
1813
1814#define GET_MEMORY_GROWTH(current, previous, allocator) \
1815 (current.allocator > previous.allocator \
1816 ? current.allocator - previous.allocator \
1817 : 0)
1818
1819void RenderThreadImpl::RecordPurgeAndSuspendMemoryGrowthMetrics() const {
1820 // If this renderer is resumed, we should not update UMA.
1821 if (!RendererIsHidden())
1822 return;
1823
1824 RendererMemoryMetrics memory_metrics;
1825 GetRendererMemoryMetrics(&memory_metrics);
1826 UMA_HISTOGRAM_MEMORY_KB(
1827 "PurgeAndSuspend.Experimental.MemoryGrowth.PartitionAllocKB",
1828 GET_MEMORY_GROWTH(memory_metrics, purge_and_suspend_memory_metrics_,
1829 partition_alloc_kb));
1830 UMA_HISTOGRAM_MEMORY_KB(
1831 "PurgeAndSuspend.Experimental.MemoryGrowth.BlinkGCKB",
1832 GET_MEMORY_GROWTH(memory_metrics, purge_and_suspend_memory_metrics_,
1833 blink_gc_kb));
tasak9b2c7fe2017-01-31 19:40:341834 UMA_HISTOGRAM_MEMORY_KB(
tasak72f64042017-01-19 14:02:531835 "PurgeAndSuspend.Experimental.MemoryGrowth.MallocKB",
1836 GET_MEMORY_GROWTH(memory_metrics, purge_and_suspend_memory_metrics_,
1837 malloc_mb) * 1024);
1838 UMA_HISTOGRAM_MEMORY_KB(
1839 "PurgeAndSuspend.Experimental.MemoryGrowth.DiscardableKB",
1840 GET_MEMORY_GROWTH(memory_metrics, purge_and_suspend_memory_metrics_,
1841 discardable_kb));
tasak9b2c7fe2017-01-31 19:40:341842 UMA_HISTOGRAM_MEMORY_KB(
tasak72f64042017-01-19 14:02:531843 "PurgeAndSuspend.Experimental.MemoryGrowth.V8MainThreadIsolateKB",
1844 GET_MEMORY_GROWTH(memory_metrics, purge_and_suspend_memory_metrics_,
1845 v8_main_thread_isolate_mb) * 1024);
tasak9b2c7fe2017-01-31 19:40:341846 UMA_HISTOGRAM_MEMORY_KB(
tasak72f64042017-01-19 14:02:531847 "PurgeAndSuspend.Experimental.MemoryGrowth.TotalAllocatedKB",
1848 GET_MEMORY_GROWTH(memory_metrics, purge_and_suspend_memory_metrics_,
1849 total_allocated_mb) * 1024);
jdduke73220f02015-09-04 17:03:511850}
1851
sadrul6d310fa2016-08-04 02:12:161852scoped_refptr<gpu::GpuChannelHost> RenderThreadImpl::EstablishGpuChannelSync() {
[email protected]d13f35d2012-05-18 02:28:151853 TRACE_EVENT0("gpu", "RenderThreadImpl::EstablishGpuChannelSync");
1854
piman9fc22f32016-05-02 22:21:221855 if (gpu_channel_) {
[email protected]1082b1d2010-03-30 00:31:221856 // Do nothing if we already have a GPU channel or are already
1857 // establishing one.
[email protected]7951bfe2013-06-13 01:43:341858 if (!gpu_channel_->IsLost())
piman9fc22f32016-05-02 22:21:221859 return gpu_channel_;
[email protected]6217d392010-03-25 22:08:351860
1861 // Recreate the channel if it has been lost.
piman765e5282015-05-08 03:43:011862 gpu_channel_->DestroyChannel();
penghuange1d86512016-07-08 18:15:001863 gpu_channel_ = nullptr;
[email protected]6217d392010-03-25 22:08:351864 }
1865
sadrul53546592016-12-17 01:44:211866 gpu_channel_ = gpu_->EstablishGpuChannelSync();
1867 if (gpu_channel_)
1868 GetContentClient()->SetGpuInfo(gpu_channel_->gpu_info());
piman9fc22f32016-05-02 22:21:221869 return gpu_channel_;
[email protected]3bf4d532010-03-27 00:23:341870}
1871
fsamuelcf3002e2017-03-20 23:13:471872void RenderThreadImpl::RequestNewCompositorFrameSink(
danakj83066a32016-06-21 02:34:491873 bool use_software,
1874 int routing_id,
1875 scoped_refptr<FrameSwapMessageQueue> frame_swap_message_queue,
fsamuelcf3002e2017-03-20 23:13:471876 const GURL& url,
1877 const CompositorFrameSinkCallback& callback) {
danakj83066a32016-06-21 02:34:491878 const base::CommandLine& command_line =
1879 *base::CommandLine::ForCurrentProcess();
1880 if (command_line.HasSwitch(switches::kDisableGpuCompositing))
1881 use_software = true;
1882
sadrul943e3b32016-08-04 18:22:591883#if defined(USE_AURA)
fsamuel098eade2017-03-21 18:06:141884 if (!use_software && IsRunningInMash()) {
sadrulbe22c4f2017-03-14 06:59:251885 scoped_refptr<gpu::GpuChannelHost> channel = EstablishGpuChannelSync();
1886 // If the channel could not be established correctly, then return null. This
1887 // would cause the compositor to wait and try again at a later time.
fsamuelcf3002e2017-03-20 23:13:471888 if (!channel) {
1889 callback.Run(nullptr);
1890 return;
1891 }
fsamuel95c974eb2017-03-22 10:00:251892 RendererWindowTreeClient::Get(routing_id)
1893 ->RequestCompositorFrameSink(
1894 gpu_->CreateContextProvider(std::move(channel)),
1895 GetGpuMemoryBufferManager(), callback);
fsamuelcf3002e2017-03-20 23:13:471896 return;
danakj83066a32016-06-21 02:34:491897 }
1898#endif
1899
danakj1120f4c2016-09-15 02:05:321900 uint32_t compositor_frame_sink_id = g_next_compositor_frame_sink_id++;
danakj83066a32016-06-21 02:34:491901
1902 if (command_line.HasSwitch(switches::kEnableVulkan)) {
1903 scoped_refptr<cc::VulkanContextProvider> vulkan_context_provider =
1904 cc::VulkanInProcessContextProvider::Create();
1905 if (vulkan_context_provider) {
1906 DCHECK(!layout_test_mode());
fsamuelcf3002e2017-03-20 23:13:471907 callback.Run(base::MakeUnique<RendererCompositorFrameSink>(
danakj1120f4c2016-09-15 02:05:321908 routing_id, compositor_frame_sink_id,
enne077ba4862016-09-12 20:59:531909 CreateExternalBeginFrameSource(routing_id),
1910 std::move(vulkan_context_provider),
fsamuelcf3002e2017-03-20 23:13:471911 std::move(frame_swap_message_queue)));
1912 return;
danakj83066a32016-06-21 02:34:491913 }
1914 }
1915
1916 // Create a gpu process channel and verify we want to use GPU compositing
1917 // before creating any context providers.
1918 scoped_refptr<gpu::GpuChannelHost> gpu_channel_host;
1919 if (!use_software) {
sadrul6d310fa2016-08-04 02:12:161920 gpu_channel_host = EstablishGpuChannelSync();
danakj83066a32016-06-21 02:34:491921 if (!gpu_channel_host) {
1922 // Cause the compositor to wait and try again.
fsamuelcf3002e2017-03-20 23:13:471923 callback.Run(nullptr);
1924 return;
danakj83066a32016-06-21 02:34:491925 }
1926 // We may get a valid channel, but with a software renderer. In that case,
1927 // disable GPU compositing.
1928 if (gpu_channel_host->gpu_info().software_rendering)
1929 use_software = true;
1930 }
1931
1932 if (use_software) {
1933 DCHECK(!layout_test_mode());
fsamuelcf3002e2017-03-20 23:13:471934 callback.Run(base::MakeUnique<RendererCompositorFrameSink>(
danakj1120f4c2016-09-15 02:05:321935 routing_id, compositor_frame_sink_id,
pimanc44437a22016-10-29 00:09:221936 CreateExternalBeginFrameSource(routing_id), nullptr, nullptr, nullptr,
fsamuelcf3002e2017-03-20 23:13:471937 shared_bitmap_manager(), std::move(frame_swap_message_queue)));
1938 return;
danakj83066a32016-06-21 02:34:491939 }
1940
sadrul85cc5d82016-12-20 03:37:411941 scoped_refptr<ui::ContextProviderCommandBuffer> worker_context_provider =
danakj83066a32016-06-21 02:34:491942 SharedCompositorWorkerContextProvider();
1943 if (!worker_context_provider) {
1944 // Cause the compositor to wait and try again.
fsamuelcf3002e2017-03-20 23:13:471945 callback.Run(nullptr);
1946 return;
danakj83066a32016-06-21 02:34:491947 }
1948
1949 // The renderer compositor context doesn't do a lot of stuff, so we don't
1950 // expect it to need a lot of space for commands or transfer. Raster and
1951 // uploads happen on the worker context instead.
1952 gpu::SharedMemoryLimits limits = gpu::SharedMemoryLimits::ForMailboxContext();
1953
1954 // This is for an offscreen context for the compositor. So the default
1955 // framebuffer doesn't need alpha, depth, stencil, antialiasing.
1956 gpu::gles2::ContextCreationAttribHelper attributes;
1957 attributes.alpha_size = -1;
1958 attributes.depth_size = 0;
1959 attributes.stencil_size = 0;
1960 attributes.samples = 0;
1961 attributes.sample_buffers = 0;
1962 attributes.bind_generates_resource = false;
1963 attributes.lose_context_when_out_of_memory = true;
1964
1965 constexpr bool automatic_flushes = false;
1966 constexpr bool support_locking = false;
1967
1968 // The compositor context shares resources with the worker context unless
1969 // the worker is async.
sadrul85cc5d82016-12-20 03:37:411970 ui::ContextProviderCommandBuffer* share_context =
1971 worker_context_provider.get();
danakj83066a32016-06-21 02:34:491972 if (IsAsyncWorkerContextEnabled())
1973 share_context = nullptr;
1974
sadrul85cc5d82016-12-20 03:37:411975 scoped_refptr<ui::ContextProviderCommandBuffer> context_provider(
1976 new ui::ContextProviderCommandBuffer(
danakja40dd4482016-06-28 01:14:101977 gpu_channel_host, gpu::GPU_STREAM_DEFAULT,
danakj83066a32016-06-21 02:34:491978 gpu::GpuStreamPriority::NORMAL, gpu::kNullSurfaceHandle, url,
pimand488e8b42016-06-30 19:06:591979 automatic_flushes, support_locking, limits, attributes, share_context,
sadrul85cc5d82016-12-20 03:37:411980 ui::command_buffer_metrics::RENDER_COMPOSITOR_CONTEXT));
danakj83066a32016-06-21 02:34:491981
danakj83066a32016-06-21 02:34:491982 if (layout_test_deps_) {
fsamuelcf3002e2017-03-20 23:13:471983 callback.Run(layout_test_deps_->CreateCompositorFrameSink(
jbroman6ccbc7d472016-07-27 04:45:411984 routing_id, std::move(gpu_channel_host), std::move(context_provider),
fsamuelcf3002e2017-03-20 23:13:471985 std::move(worker_context_provider), GetGpuMemoryBufferManager(), this));
1986 return;
danakj83066a32016-06-21 02:34:491987 }
1988
1989#if defined(OS_ANDROID)
1990 if (sync_compositor_message_filter_) {
fsamuelcf3002e2017-03-20 23:13:471991 callback.Run(base::MakeUnique<SynchronousCompositorFrameSink>(
danakja40dd4482016-06-28 01:14:101992 std::move(context_provider), std::move(worker_context_provider),
danakje9cf5812017-02-16 22:22:551993 GetGpuMemoryBufferManager(), shared_bitmap_manager(), routing_id,
1994 compositor_frame_sink_id, CreateExternalBeginFrameSource(routing_id),
enne077ba4862016-09-12 20:59:531995 sync_compositor_message_filter_.get(),
fsamuelcf3002e2017-03-20 23:13:471996 std::move(frame_swap_message_queue)));
1997 return;
danakj83066a32016-06-21 02:34:491998 }
1999#endif
fsamuelcf3002e2017-03-20 23:13:472000 callback.Run(base::WrapUnique(new RendererCompositorFrameSink(
danakj1120f4c2016-09-15 02:05:322001 routing_id, compositor_frame_sink_id,
2002 CreateExternalBeginFrameSource(routing_id), std::move(context_provider),
fsamuelcf3002e2017-03-20 23:13:472003 std::move(worker_context_provider), GetGpuMemoryBufferManager(), nullptr,
2004 std::move(frame_swap_message_queue))));
danakj83066a32016-06-21 02:34:492005}
2006
rockot067ca55f2016-09-30 22:00:152007AssociatedInterfaceRegistry*
2008RenderThreadImpl::GetAssociatedInterfaceRegistry() {
2009 return &associated_interfaces_;
2010}
2011
jbroman6ccbc7d472016-07-27 04:45:412012std::unique_ptr<cc::SwapPromise>
2013RenderThreadImpl::RequestCopyOfOutputForLayoutTest(
2014 int32_t routing_id,
2015 std::unique_ptr<cc::CopyOutputRequest> request) {
2016 DCHECK(layout_test_deps_);
2017 return layout_test_deps_->RequestCopyOfOutput(routing_id, std::move(request));
2018}
2019
[email protected]180ef242013-11-07 06:50:462020blink::WebMediaStreamCenter* RenderThreadImpl::CreateMediaStreamCenter(
2021 blink::WebMediaStreamCenterClient* client) {
Brett Wilson0748bf412016-11-22 17:55:462022#if BUILDFLAG(ENABLE_WEBRTC)
[email protected]68e5fee2013-02-18 10:04:222023 if (!media_stream_center_) {
2024 media_stream_center_ = GetContentClient()->renderer()
2025 ->OverrideCreateWebMediaStreamCenter(client);
2026 if (!media_stream_center_) {
dchengcedca5612016-04-09 01:40:152027 std::unique_ptr<MediaStreamCenter> media_stream_center(
[email protected]0107d8a2014-05-16 10:20:342028 new MediaStreamCenter(client, GetPeerConnectionDependencyFactory()));
[email protected]c1298742013-07-17 04:06:322029 media_stream_center_ = media_stream_center.release();
[email protected]68e5fee2013-02-18 10:04:222030 }
2031 }
[email protected]d8cd8372012-03-09 10:49:512032#endif
2033 return media_stream_center_;
2034}
2035
Brett Wilson0748bf412016-11-22 17:55:462036#if BUILDFLAG(ENABLE_WEBRTC)
[email protected]0107d8a2014-05-16 10:20:342037PeerConnectionDependencyFactory*
2038RenderThreadImpl::GetPeerConnectionDependencyFactory() {
[email protected]83e0a482014-05-22 18:07:182039 return peer_connection_factory_.get();
[email protected]6ee10bd2012-09-13 09:01:532040}
[email protected]22fe91d2014-08-12 17:07:122041#endif
[email protected]6ee10bd2012-09-13 09:01:532042
rockot1587e332016-07-27 17:44:142043mojom::RenderFrameMessageFilter*
2044RenderThreadImpl::render_frame_message_filter() {
2045 if (!render_frame_message_filter_)
2046 GetChannel()->GetRemoteAssociatedInterface(&render_frame_message_filter_);
2047 return render_frame_message_filter_.get();
2048}
2049
rockote261d2112016-09-21 22:22:232050mojom::RenderMessageFilter* RenderThreadImpl::render_message_filter() {
2051 if (!render_message_filter_)
2052 GetChannel()->GetRemoteAssociatedInterface(&render_message_filter_);
2053 return render_message_filter_.get();
2054}
2055
jcivelli315d17f2016-11-29 16:15:052056const scoped_refptr<mojom::ThreadSafeRenderMessageFilterAssociatedPtr>&
2057RenderThreadImpl::thread_safe_render_message_filter() {
2058 return thread_safe_render_message_filter_;
2059}
2060
penghuang346a46f92016-03-31 21:37:522061gpu::GpuChannelHost* RenderThreadImpl::GetGpuChannel() {
piman9fc22f32016-05-02 22:21:222062 if (!gpu_channel_)
danakj3873e852016-05-05 00:46:072063 return nullptr;
[email protected]7951bfe2013-06-13 01:43:342064 if (gpu_channel_->IsLost())
danakj3873e852016-05-05 00:46:072065 return nullptr;
[email protected]6217d392010-03-25 22:08:352066 return gpu_channel_.get();
2067}
2068
chiniforooshan614d70a2017-03-17 01:19:332069void RenderThreadImpl::OnFieldTrialGroupFinalized(
2070 const std::string& trial_name,
2071 const std::string& group_name) {
2072 mojom::FieldTrialRecorderPtr field_trial_recorder;
2073 GetRemoteInterfaces()->GetInterface(&field_trial_recorder);
2074 field_trial_recorder->FieldTrialActivated(trial_name);
2075}
2076
rockot067ca55f2016-09-30 22:00:152077void RenderThreadImpl::CreateView(mojom::CreateViewParamsPtr params) {
2078 CompositorDependencies* compositor_deps = this;
wjmaclean1d970622017-01-21 22:28:242079 is_scroll_animator_enabled_ = params->web_preferences.enable_scroll_animator;
rockot067ca55f2016-09-30 22:00:152080 // When bringing in render_view, also bring in webkit's glue and jsbindings.
nickf7b38222016-11-22 21:59:352081 RenderViewImpl::Create(compositor_deps, *params,
2082 RenderWidget::ShowCallback());
rockot067ca55f2016-09-30 22:00:152083}
2084
rockot53be7caf2016-10-04 20:17:082085void RenderThreadImpl::CreateFrame(mojom::CreateFrameParamsPtr params) {
2086 // Debug cases of https://crbug.com/626802.
2087 base::debug::SetCrashKeyValue("newframe_routing_id",
2088 base::IntToString(params->routing_id));
2089 base::debug::SetCrashKeyValue("newframe_proxy_id",
2090 base::IntToString(params->proxy_routing_id));
2091 base::debug::SetCrashKeyValue("newframe_opener_id",
2092 base::IntToString(params->opener_routing_id));
2093 base::debug::SetCrashKeyValue("newframe_parent_id",
2094 base::IntToString(params->parent_routing_id));
2095 base::debug::SetCrashKeyValue("newframe_widget_id",
2096 base::IntToString(
2097 params->widget_params->routing_id));
2098 base::debug::SetCrashKeyValue("newframe_widget_hidden",
2099 params->widget_params->hidden ? "yes" : "no");
2100 base::debug::SetCrashKeyValue("newframe_replicated_origin",
2101 params->replication_state.origin.Serialize());
2102 base::debug::SetCrashKeyValue("newframe_oopifs_possible",
2103 SiteIsolationPolicy::AreCrossProcessFramesPossible() ? "yes" : "no");
2104 CompositorDependencies* compositor_deps = this;
2105 RenderFrameImpl::CreateFrame(
2106 params->routing_id, params->proxy_routing_id, params->opener_routing_id,
2107 params->parent_routing_id, params->previous_sibling_routing_id,
2108 params->replication_state, compositor_deps, *params->widget_params,
2109 params->frame_owner_properties);
2110}
2111
2112void RenderThreadImpl::CreateFrameProxy(
2113 int32_t routing_id,
2114 int32_t render_view_routing_id,
2115 int32_t opener_routing_id,
2116 int32_t parent_routing_id,
2117 const FrameReplicationState& replicated_state) {
2118 // Debug cases of https://crbug.com/575245.
2119 base::debug::SetCrashKeyValue("newproxy_proxy_id",
2120 base::IntToString(routing_id));
2121 base::debug::SetCrashKeyValue("newproxy_view_id",
2122 base::IntToString(render_view_routing_id));
2123 base::debug::SetCrashKeyValue("newproxy_opener_id",
2124 base::IntToString(opener_routing_id));
2125 base::debug::SetCrashKeyValue("newproxy_parent_id",
2126 base::IntToString(parent_routing_id));
nick3b5a21f2016-11-22 23:07:112127 RenderFrameProxy::CreateFrameProxy(
2128 routing_id, render_view_routing_id,
2129 RenderFrameImpl::ResolveOpener(opener_routing_id), parent_routing_id,
2130 replicated_state);
rockot53be7caf2016-10-04 20:17:082131}
2132
rockota2db0da2016-10-18 17:39:112133void RenderThreadImpl::OnNetworkConnectionChanged(
2134 net::NetworkChangeNotifier::ConnectionType type,
2135 double max_bandwidth_mbps) {
2136 bool online = type != net::NetworkChangeNotifier::CONNECTION_NONE;
2137 WebNetworkStateNotifier::setOnLine(online);
2138 for (auto& observer : observers_)
2139 observer.NetworkStateChanged(online);
2140 WebNetworkStateNotifier::setWebConnection(
2141 NetConnectionTypeToWebConnectionType(type), max_bandwidth_mbps);
2142}
2143
2144void RenderThreadImpl::SetWebKitSharedTimersSuspended(bool suspend) {
2145#if defined(OS_ANDROID)
2146 if (suspend) {
2147 renderer_scheduler_->SuspendTimerQueue();
2148 } else {
2149 renderer_scheduler_->ResumeTimerQueue();
2150 }
2151 webkit_shared_timer_suspended_ = suspend;
2152#else
2153 NOTREACHED();
2154#endif
2155}
2156
2157void RenderThreadImpl::UpdateScrollbarTheme(
2158 mojom::UpdateScrollbarThemeParamsPtr params) {
2159#if defined(OS_MACOSX)
2160 static_cast<WebScrollbarBehaviorImpl*>(
2161 blink_platform_impl_->scrollbarBehavior())
2162 ->set_jump_on_track_click(params->jump_on_track_click);
2163
2164 blink::WebScrollbarTheme::updateScrollbarsWithNSDefaults(
2165 params->initial_button_delay, params->autoscroll_button_delay,
2166 params->preferred_scroller_style, params->redraw,
2167 params->button_placement);
2168#else
2169 NOTREACHED();
2170#endif
2171}
2172
2173void RenderThreadImpl::OnSystemColorsChanged(
2174 int32_t aqua_color_variant,
2175 const std::string& highlight_text_color,
2176 const std::string& highlight_color) {
2177#if defined(OS_MACOSX)
2178 SystemColorsDidChange(aqua_color_variant, highlight_text_color,
2179 highlight_color);
2180#else
2181 NOTREACHED();
2182#endif
2183}
2184
2185void RenderThreadImpl::PurgePluginListCache(bool reload_pages) {
brettw4b461082016-11-19 18:55:162186#if BUILDFLAG(ENABLE_PLUGINS)
rockota2db0da2016-10-18 17:39:112187 // The call below will cause a GetPlugins call with refresh=true, but at this
2188 // point we already know that the browser has refreshed its list, so disable
2189 // refresh temporarily to prevent each renderer process causing the list to be
2190 // regenerated.
2191 blink_platform_impl_->set_plugin_refresh_allowed(false);
2192 blink::resetPluginCache(reload_pages);
2193 blink_platform_impl_->set_plugin_refresh_allowed(true);
2194
2195 for (auto& observer : observers_)
2196 observer.PluginListChanged();
2197#else
2198 NOTREACHED();
2199#endif
2200}
2201
[email protected]0ec90d522014-03-12 16:28:192202void RenderThreadImpl::OnCreateNewSharedWorker(
2203 const WorkerProcessMsg_CreateWorker_Params& params) {
2204 // EmbeddedSharedWorkerStub will self-destruct.
mkwstcfa98932016-03-09 13:06:192205 new EmbeddedSharedWorkerStub(
2206 params.url, params.name, params.content_security_policy,
2207 params.security_policy_type, params.creation_address_space,
2208 params.pause_on_start, params.route_id);
[email protected]0ec90d522014-03-12 16:28:192209}
2210
[email protected]5071cb22013-07-10 02:19:062211void RenderThreadImpl::OnMemoryPressure(
2212 base::MemoryPressureListener::MemoryPressureLevel memory_pressure_level) {
hong.zhengb28b5332016-05-11 02:33:392213 TRACE_EVENT0("memory","RenderThreadImpl::OnMemoryPressure");
rmcilroy7fbb3bd52015-02-17 19:02:142214 if (blink_platform_impl_) {
bashi5e843ac2016-06-17 07:44:352215 blink::WebMemoryCoordinator::onMemoryPressure(
bashic577bfc2016-01-08 03:42:352216 static_cast<blink::WebMemoryPressureLevel>(memory_pressure_level));
hajimehoshi7bb39582016-10-12 04:30:572217 }
2218 if (memory_pressure_level ==
2219 base::MemoryPressureListener::MEMORY_PRESSURE_LEVEL_CRITICAL) {
2220 ReleaseFreeMemory();
2221 ClearMemory();
2222 }
2223}
rmcilroyab967c972015-02-17 23:15:002224
hajimehoshi7bb39582016-10-12 04:30:572225void RenderThreadImpl::OnMemoryStateChange(base::MemoryState state) {
hajimehoshi7bb39582016-10-12 04:30:572226 if (blink_platform_impl_) {
2227 blink::WebMemoryCoordinator::onMemoryStateChange(
2228 static_cast<blink::MemoryState>(state));
2229 }
bashi233f65e2017-02-09 08:36:032230}
2231
2232void RenderThreadImpl::OnPurgeMemory() {
2233 OnTrimMemoryImmediately();
2234 ReleaseFreeMemory();
2235 ClearMemory();
2236 if (blink_platform_impl_)
2237 blink::WebMemoryCoordinator::onPurgeMemory();
hajimehoshi7bb39582016-10-12 04:30:572238}
2239
2240void RenderThreadImpl::ClearMemory() {
2241 // Do not call into blink if it is not initialized.
2242 if (blink_platform_impl_) {
2243 // Purge Skia font cache, by setting it to 0 and then again to the
2244 // previous limit.
2245 size_t font_cache_limit = SkGraphics::SetFontCacheLimit(0);
2246 SkGraphics::SetFontCacheLimit(font_cache_limit);
rmcilroy7fbb3bd52015-02-17 19:02:142247 }
[email protected]5071cb22013-07-10 02:19:062248}
2249
skyostil2d3b5bd2015-05-27 15:40:592250scoped_refptr<base::SingleThreadTaskRunner>
thestig529ad8a2016-07-08 20:30:122251RenderThreadImpl::GetFileThreadTaskRunner() {
fdoraye94d8642016-07-07 19:19:012252 DCHECK(message_loop()->task_runner()->BelongsToCurrentThread());
[email protected]59383c782013-04-17 16:43:272253 if (!file_thread_) {
[email protected]c6a7b862010-08-20 22:19:382254 file_thread_.reset(new base::Thread("Renderer::FILE"));
2255 file_thread_->Start();
2256 }
skyostil2d3b5bd2015-05-27 15:40:592257 return file_thread_->task_runner();
[email protected]c6a7b862010-08-20 22:19:382258}
[email protected]e9ff79c2012-10-19 21:31:262259
acolwellb4034942014-08-28 15:42:432260scoped_refptr<base::SingleThreadTaskRunner>
2261RenderThreadImpl::GetMediaThreadTaskRunner() {
fdoraye94d8642016-07-07 19:19:012262 DCHECK(message_loop()->task_runner()->BelongsToCurrentThread());
[email protected]c1330c82013-06-06 02:23:252263 if (!media_thread_) {
2264 media_thread_.reset(new base::Thread("Media"));
2265 media_thread_->Start();
2266 }
skyostil2d3b5bd2015-05-27 15:40:592267 return media_thread_->task_runner();
[email protected]c1330c82013-06-06 02:23:252268}
2269
dcastagna4517a182015-08-05 19:51:032270base::TaskRunner* RenderThreadImpl::GetWorkerTaskRunner() {
prashant.nfad657e2016-06-01 07:52:172271 return categorized_worker_pool_.get();
dcastagnab880e8f2015-06-30 20:16:062272}
2273
sadrul85cc5d82016-12-20 03:37:412274scoped_refptr<ui::ContextProviderCommandBuffer>
danakj0b4b94e32016-05-10 22:33:012275RenderThreadImpl::SharedCompositorWorkerContextProvider() {
revemand180dfc32015-09-24 00:19:432276 DCHECK(IsMainThread());
2277 // Try to reuse existing shared worker context provider.
revemand180dfc32015-09-24 00:19:432278 if (shared_worker_context_provider_) {
2279 // Note: If context is lost, delete reference after releasing the lock.
boliu11afa7e2016-04-18 18:04:142280 cc::ContextProvider::ScopedContextLock lock(
2281 shared_worker_context_provider_.get());
revemand180dfc32015-09-24 00:19:432282 if (shared_worker_context_provider_->ContextGL()
danakje8ec797e2016-04-19 04:08:432283 ->GetGraphicsResetStatusKHR() == GL_NO_ERROR)
2284 return shared_worker_context_provider_;
revemand180dfc32015-09-24 00:19:432285 }
danakje8ec797e2016-04-19 04:08:432286
sadrul6d310fa2016-08-04 02:12:162287 scoped_refptr<gpu::GpuChannelHost> gpu_channel_host(
2288 EstablishGpuChannelSync());
danakje8ec797e2016-04-19 04:08:432289 if (!gpu_channel_host) {
2290 shared_worker_context_provider_ = nullptr;
2291 return shared_worker_context_provider_;
revemand180dfc32015-09-24 00:19:432292 }
danakje8ec797e2016-04-19 04:08:432293
sunnypsd8ce1c22016-05-10 18:02:402294 int32_t stream_id = gpu::GPU_STREAM_DEFAULT;
2295 gpu::GpuStreamPriority stream_priority = gpu::GpuStreamPriority::NORMAL;
2296 if (is_async_worker_context_enabled_) {
2297 stream_id = gpu_channel_host->GenerateStreamID();
2298 stream_priority = gpu::GpuStreamPriority::LOW;
2299 }
2300
danakj9a04adc2016-05-16 22:45:072301 bool support_locking = true;
danakj0dd9e1e2016-05-11 22:15:092302 shared_worker_context_provider_ = CreateOffscreenContext(
danakj9a04adc2016-05-16 22:45:072303 std::move(gpu_channel_host), gpu::SharedMemoryLimits(), support_locking,
sadrul85cc5d82016-12-20 03:37:412304 ui::command_buffer_metrics::RENDER_WORKER_CONTEXT, stream_id,
danakj0dd9e1e2016-05-11 22:15:092305 stream_priority);
danakje8ec797e2016-04-19 04:08:432306 if (!shared_worker_context_provider_->BindToCurrentThread())
2307 shared_worker_context_provider_ = nullptr;
revemand180dfc32015-09-24 00:19:432308 return shared_worker_context_provider_;
2309}
2310
[email protected]180ef242013-11-07 06:50:462311void RenderThreadImpl::SampleGamepads(blink::WebGamepads* data) {
tfarina556a7232014-10-05 01:02:092312 blink_platform_impl_->sampleGamepads(*data);
[email protected]0ff736562014-05-09 09:09:472313}
2314
rmcilroyaa296052015-04-14 15:35:272315bool RenderThreadImpl::RendererIsHidden() const {
2316 return widget_count_ > 0 && hidden_widget_count_ == widget_count_;
2317}
2318
[email protected]b2db9272014-01-10 17:42:002319void RenderThreadImpl::WidgetCreated() {
rmcilroyaa296052015-04-14 15:35:272320 bool renderer_was_hidden = RendererIsHidden();
[email protected]b2db9272014-01-10 17:42:002321 widget_count_++;
rmcilroyaa296052015-04-14 15:35:272322 if (renderer_was_hidden)
2323 OnRendererVisible();
[email protected]b2db9272014-01-10 17:42:002324}
2325
2326void RenderThreadImpl::WidgetDestroyed() {
rmcilroyaa296052015-04-14 15:35:272327 // TODO(rmcilroy): Remove the restriction that destroyed widgets must be
2328 // unhidden before WidgetDestroyed is called.
2329 DCHECK_GT(widget_count_, 0);
2330 DCHECK_GT(widget_count_, hidden_widget_count_);
[email protected]b2db9272014-01-10 17:42:002331 widget_count_--;
rmcilroyaa296052015-04-14 15:35:272332 if (RendererIsHidden())
2333 OnRendererHidden();
[email protected]b2db9272014-01-10 17:42:002334}
2335
2336void RenderThreadImpl::WidgetHidden() {
2337 DCHECK_LT(hidden_widget_count_, widget_count_);
2338 hidden_widget_count_++;
rmcilroyaa296052015-04-14 15:35:272339 if (RendererIsHidden())
2340 OnRendererHidden();
[email protected]b2db9272014-01-10 17:42:002341}
2342
2343void RenderThreadImpl::WidgetRestored() {
rmcilroyaa296052015-04-14 15:35:272344 bool renderer_was_hidden = RendererIsHidden();
[email protected]b2db9272014-01-10 17:42:002345 DCHECK_GT(hidden_widget_count_, 0);
2346 hidden_widget_count_--;
rmcilroyaa296052015-04-14 15:35:272347 if (renderer_was_hidden)
2348 OnRendererVisible();
2349}
[email protected]b2db9272014-01-10 17:42:002350
rmcilroyaa296052015-04-14 15:35:272351void RenderThreadImpl::OnRendererHidden() {
ulan432cd6e42016-03-01 15:59:142352 blink::mainThreadIsolate()->IsolateInBackgroundNotification();
rmcilroyaa296052015-04-14 15:35:272353 // TODO(rmcilroy): Remove IdleHandler and replace it with an IdleTask
2354 // scheduled by the RendererScheduler - http://crbug.com/469210.
ulan4a385192015-11-11 10:59:182355 if (!GetContentClient()->renderer()->RunIdleHandlerWhenWidgetsHidden())
2356 return;
2357 ScheduleIdleHandler(kInitialIdleHandlerDelayMs);
rmcilroyaa296052015-04-14 15:35:272358}
2359
2360void RenderThreadImpl::OnRendererVisible() {
ulan432cd6e42016-03-01 15:59:142361 blink::mainThreadIsolate()->IsolateInForegroundNotification();
rmcilroyaa296052015-04-14 15:35:272362 if (!GetContentClient()->renderer()->RunIdleHandlerWhenWidgetsHidden())
[email protected]b2db9272014-01-10 17:42:002363 return;
[email protected]b2db9272014-01-10 17:42:002364 ScheduleIdleHandler(kLongIdleHandlerDelayMs);
2365}
2366
ssid0603ca9f2015-06-09 16:48:082367void RenderThreadImpl::ReleaseFreeMemory() {
2368 base::allocator::ReleaseFreeMemory();
penghuang342762b2016-12-02 21:04:582369 discardable_shared_memory_manager_->ReleaseFreeMemory();
ssid0603ca9f2015-06-09 16:48:082370
2371 if (blink_platform_impl_)
2372 blink::decommitFreeableMemory();
2373}
2374
ben76f52b242016-06-18 05:42:482375RenderThreadImpl::PendingFrameCreate::PendingFrameCreate(
rockotf8fdd9b2015-12-16 22:22:352376 int routing_id,
ben76f52b242016-06-18 05:42:482377 mojom::FrameRequest frame_request,
2378 mojom::FrameHostPtr frame_host)
rockotf8fdd9b2015-12-16 22:22:352379 : routing_id_(routing_id),
ben76f52b242016-06-18 05:42:482380 frame_request_(std::move(frame_request)),
2381 frame_host_(std::move(frame_host)) {
2382 // The RenderFrame may be deleted before the CreateFrame message is received.
2383 // In that case, the RenderFrameHost should cancel the create, which is
2384 // detected by setting an error handler on |frame_host_|.
2385 frame_host_.set_connection_error_handler(base::Bind(
2386 &RenderThreadImpl::PendingFrameCreate::OnConnectionError,
rockotf8fdd9b2015-12-16 22:22:352387 base::Unretained(this)));
2388}
2389
ben76f52b242016-06-18 05:42:482390RenderThreadImpl::PendingFrameCreate::~PendingFrameCreate() {
rockotf8fdd9b2015-12-16 22:22:352391}
2392
ben76f52b242016-06-18 05:42:482393void RenderThreadImpl::PendingFrameCreate::OnConnectionError() {
rockotf8fdd9b2015-12-16 22:22:352394 size_t erased =
ben76f52b242016-06-18 05:42:482395 RenderThreadImpl::current()->pending_frame_creates_.erase(routing_id_);
rockotf8fdd9b2015-12-16 22:22:352396 DCHECK_EQ(1u, erased);
2397}
2398
hong.zhengb28b5332016-05-11 02:33:392399void RenderThreadImpl::OnSyncMemoryPressure(
2400 base::MemoryPressureListener::MemoryPressureLevel memory_pressure_level) {
2401 if (!blink::mainThreadIsolate())
2402 return;
2403
2404 v8::MemoryPressureLevel v8_memory_pressure_level =
2405 static_cast<v8::MemoryPressureLevel>(memory_pressure_level);
2406
2407 // In order to reduce performance impact, translate critical level to
2408 // moderate level for foregroud renderer.
2409 if (!RendererIsHidden() &&
2410 v8_memory_pressure_level == v8::MemoryPressureLevel::kCritical)
2411 v8_memory_pressure_level = v8::MemoryPressureLevel::kModerate;
2412
2413 blink::mainThreadIsolate()->MemoryPressureNotification(
2414 v8_memory_pressure_level);
2415 blink::MemoryPressureNotificationToWorkerThreadIsolates(
2416 v8_memory_pressure_level);
2417}
2418
bashic4b4afcb2016-08-23 06:37:522419// Note that this would be called only when memory_coordinator is enabled.
2420// OnSyncMemoryPressure() is never called in that case.
2421void RenderThreadImpl::OnTrimMemoryImmediately() {
2422 if (blink::mainThreadIsolate()) {
2423 blink::mainThreadIsolate()->MemoryPressureNotification(
2424 v8::MemoryPressureLevel::kCritical);
2425 blink::MemoryPressureNotificationToWorkerThreadIsolates(
2426 v8::MemoryPressureLevel::kCritical);
2427 }
2428}
2429
rockot067ca55f2016-09-30 22:00:152430void RenderThreadImpl::OnRendererInterfaceRequest(
2431 mojom::RendererAssociatedRequest request) {
2432 DCHECK(!renderer_binding_.is_bound());
2433 renderer_binding_.Bind(std::move(request));
2434}
bashic4b4afcb2016-08-23 06:37:522435
[email protected]e9ff79c2012-10-19 21:31:262436} // namespace content