blob: 3f3830356dd9530d2f01dc14eec70d13f1063da7 [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"
[email protected]94f9a0f682009-06-15 18:30:3016#include "base/lazy_instance.h"
[email protected]bee16aab2009-08-26 15:55:0317#include "base/logging.h"
avi1023d012015-12-25 02:39:1418#include "base/macros.h"
reveman1af05cb32015-03-17 23:18:1619#include "base/memory/discardable_memory_allocator.h"
hajimehoshi7bb39582016-10-12 04:30:5720#include "base/memory/memory_coordinator_client_registry.h"
[email protected]8bac37b2013-07-18 19:13:5621#include "base/memory/shared_memory.h"
gabf64a25e2017-05-12 19:42:5622#include "base/message_loop/message_loop.h"
[email protected]835d7c82010-10-14 04:38:3823#include "base/metrics/field_trial.h"
tasaka27961a2017-05-24 07:33:2524#include "base/metrics/histogram_functions.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"
reveman34b7a1522015-03-23 20:27:4734#include "base/threading/simple_thread.h"
[email protected]1357c322010-12-30 22:18:5635#include "base/threading/thread_local.h"
[email protected]d293572a2013-05-23 18:50:4536#include "base/threading/thread_restrictions.h"
gab30f26df2016-05-11 19:37:5537#include "base/threading/thread_task_runner_handle.h"
ccameron9c48d1d42016-09-22 01:46:0138#include "base/trace_event/memory_dump_manager.h"
primiano9e38d552015-01-28 04:18:0139#include "base/trace_event/trace_event.h"
[email protected]7a4de7a62010-08-17 18:38:2440#include "base/values.h"
avi1023d012015-12-25 02:39:1441#include "build/build_config.h"
jbroman0d302162015-09-05 05:46:2342#include "cc/base/histograms.h"
[email protected]d72493152014-01-08 17:37:4543#include "cc/base/switches.h"
[email protected]38564622014-08-19 02:47:1844#include "cc/blink/web_layer_impl.h"
danakj920156852015-05-18 20:22:2945#include "cc/raster/task_graph_runner.h"
danakjba65a0912017-09-21 16:38:4246#include "cc/trees/layer_tree_frame_sink.h"
vollick1050cc62015-12-03 07:04:5447#include "cc/trees/layer_tree_host_common.h"
loysoa6edaaff2015-05-25 03:26:4448#include "cc/trees/layer_tree_settings.h"
penghuangd81c1a62016-11-02 20:06:0649#include "components/discardable_memory/client/client_discardable_shared_memory_manager.h"
dalecurtis4a9839a2017-05-04 23:40:4750#include "components/metrics/public/interfaces/single_sample_metrics.mojom.h"
51#include "components/metrics/single_sample_metrics.h"
danakjc7afae52017-06-20 21:12:4152#include "components/viz/client/client_layer_tree_frame_sink.h"
danakj92429852017-06-29 00:19:0353#include "components/viz/client/client_shared_bitmap_manager.h"
Valery Arkhangorodsky513ac8fd2017-08-02 23:09:2354#include "components/viz/client/hit_test_data_provider.h"
Ria Jiang28051112018-02-13 16:38:5255#include "components/viz/client/hit_test_data_provider_draw_quad.h"
sunxd26e9bae2018-03-22 19:32:3356#include "components/viz/client/hit_test_data_provider_surface_layer.h"
samans7e6675cc2017-06-05 20:16:0857#include "components/viz/client/local_surface_id_provider.h"
Fady Samuel343a74952017-11-30 14:19:2058#include "components/viz/common/features.h"
danakjf20f4502017-09-26 17:13:3159#include "components/viz/common/frame_sinks/copy_output_request.h"
bashia6264042016-09-15 04:49:5160#include "content/child/memory/child_memory_coordinator_impl.h"
[email protected]643255da2013-06-12 20:55:1361#include "content/child/runtime_features.h"
[email protected]57cf97882013-06-26 20:39:0162#include "content/child/thread_safe_sender.h"
Scott Violetc78fef732018-03-06 17:42:5363#include "content/common/buildflags.h"
[email protected]89c36f82013-07-17 06:23:2764#include "content/common/content_constants_internal.h"
[email protected]5f2aa722013-08-07 16:59:4165#include "content/common/dom_storage/dom_storage_messages.h"
[email protected]82307f6b2014-08-07 03:30:1266#include "content/common/frame_messages.h"
raymesbba82b32016-07-19 00:41:3867#include "content/common/frame_owner_properties.h"
sunnyps8f9139e2017-05-12 17:53:2568#include "content/common/gpu_stream_constants.h"
[email protected]778574e2011-03-21 22:03:5069#include "content/common/view_messages.h"
[email protected]a458504b2012-07-23 19:57:0670#include "content/public/common/content_constants.h"
bashia6264042016-09-15 04:49:5171#include "content/public/common/content_features.h"
[email protected]433df472012-03-07 20:33:3972#include "content/public/common/content_paths.h"
[email protected]c08950d22011-10-13 22:20:2973#include "content/public/common/content_switches.h"
[email protected]daf82f82011-10-31 22:35:3174#include "content/public/common/renderer_preferences.h"
Ben Goodgerf180ce12018-02-09 22:54:0175#include "content/public/common/resource_usage_reporter.mojom.h"
76#include "content/public/common/resource_usage_reporter_type_converters.h"
benbd9dc802017-04-19 01:37:4377#include "content/public/common/service_manager_connection.h"
ben649b3edd2017-03-23 00:32:0278#include "content/public/common/service_names.mojom.h"
benbd9dc802017-04-19 01:37:4379#include "content/public/common/simple_connection_filter.h"
[email protected]58436a12012-03-21 17:10:2680#include "content/public/common/url_constants.h"
[email protected]d344114c2011-10-01 01:24:3481#include "content/public/renderer/content_renderer_client.h"
tyoshino832a58a2016-04-18 08:14:0882#include "content/public/renderer/render_thread_observer.h"
[email protected]64ffa0442011-10-03 22:08:3683#include "content/public/renderer/render_view_visitor.h"
John Abd-El-Malekdcf1d1372017-10-22 06:39:4184#include "content/renderer/appcache/appcache_dispatcher.h"
85#include "content/renderer/appcache/appcache_frontend_impl.h"
fsamuel6c1dfeb2014-12-18 19:21:3386#include "content/renderer/browser_plugin/browser_plugin_manager.h"
prashant.nfad657e2016-06-01 07:52:1787#include "content/renderer/categorized_worker_pool.h"
[email protected]1910fe82012-05-10 00:04:1088#include "content/renderer/dom_storage/dom_storage_dispatcher.h"
89#include "content/renderer/dom_storage/webstoragearea_impl.h"
90#include "content/renderer/dom_storage/webstoragenamespace_impl.h"
tbansalb612c5d2017-05-25 18:53:0691#include "content/renderer/effective_connection_type_helper.h"
John Abd-El-Malekdcf1d1372017-10-22 06:39:4192#include "content/renderer/fileapi/file_system_dispatcher.h"
93#include "content/renderer/fileapi/webfilesystem_impl.h"
danakj83066a32016-06-21 02:34:4994#include "content/renderer/gpu/frame_swap_message_queue.h"
John Abd-El-Malekdcf1d1372017-10-22 06:39:4195#include "content/renderer/indexed_db/indexed_db_dispatcher.h"
Dave Tapuska63aa4622018-02-25 21:42:5696#include "content/renderer/input/widget_input_handler_manager.h"
John Abd-El-Malek6b56ef712017-10-21 22:52:4697#include "content/renderer/loader/resource_dispatcher.h"
[email protected]3958e972012-07-17 00:25:4198#include "content/renderer/media/audio_renderer_mixer_manager.h"
Miguel Casas-Sanchezcfcca5d52017-07-07 02:32:5999#include "content/renderer/media/gpu/gpu_video_accelerator_factories_impl.h"
Miguel Casasfff0ed52018-02-13 16:24:35100#include "content/renderer/media/midi/midi_message_filter.h"
xhwang194acae2014-11-12 22:46:33101#include "content/renderer/media/render_media_client.h"
Miguel Casasa8c2c5a2018-02-12 18:51:03102#include "content/renderer/media/stream/media_stream_center.h"
[email protected]80b161a2011-06-27 17:42:11103#include "content/renderer/media/video_capture_impl_manager.h"
Stuart Langley849079a2017-08-28 02:02:50104#include "content/renderer/mus/render_widget_window_tree_client_factory.h"
105#include "content/renderer/mus/renderer_window_tree_client.h"
[email protected]d7ff5fb2014-05-29 19:50:25106#include "content/renderer/net_info_helper.h"
John Abd-El-Malekf9f86c12017-10-21 07:22:23107#include "content/renderer/notifications/notification_dispatcher.h"
[email protected]82307f6b2014-08-07 03:30:12108#include "content/renderer/render_frame_proxy.h"
[email protected]8704f89b2011-04-15 00:30:05109#include "content/renderer/render_process_impl.h"
[email protected]310ebd6302011-10-10 19:06:28110#include "content/renderer/render_view_impl.h"
tfarina556a7232014-10-05 01:02:09111#include "content/renderer/renderer_blink_platform_impl.h"
shimazu5de409e42016-09-29 08:45:28112#include "content/renderer/service_worker/embedded_worker_instance_client_impl.h"
mek27c9d742015-07-16 18:30:18113#include "content/renderer/service_worker/service_worker_context_client.h"
John Abd-El-Maleke1d4de32017-10-21 16:14:29114#include "content/renderer/service_worker/service_worker_message_filter.h"
[email protected]0ec90d522014-03-12 16:28:19115#include "content/renderer/shared_worker/embedded_shared_worker_stub.h"
Darin Fisherbcc33632017-09-26 00:57:16116#include "content/renderer/shared_worker/shared_worker_factory_impl.h"
John Abd-El-Malekf75a3192017-10-22 14:23:20117#include "content/renderer/web_database_observer_impl.h"
118#include "content/renderer/worker_thread_registry.h"
juncai2f298a82017-04-18 03:51:39119#include "device/gamepad/public/cpp/gamepads.h"
chunyang.daibe874c52014-11-14 06:45:05120#include "gin/public/debug.h"
dongseong.hwang72183b02014-12-08 10:41:55121#include "gpu/GLES2/gl2extchromium.h"
Victor Miura3a4ad4f82017-12-13 06:03:45122#include "gpu/command_buffer/client/gles2_interface.h"
123#include "gpu/command_buffer/client/raster_interface.h"
danakj6f4e1e22016-04-20 03:27:34124#include "gpu/command_buffer/client/shared_memory_limits.h"
Adrienne Walker436a7752017-08-28 23:33:09125#include "gpu/config/gpu_switches.h"
danakj870925d42016-05-03 20:07:38126#include "gpu/ipc/client/command_buffer_proxy_impl.h"
penghuang346a46f92016-03-31 21:37:52127#include "gpu/ipc/client/gpu_channel_host.h"
[email protected]46f36a492010-07-28 19:36:41128#include "ipc/ipc_channel_handle.h"
amistryd4aa70d2016-06-23 07:52:37129#include "ipc/ipc_channel_mojo.h"
[email protected]cb6037d2009-11-16 22:55:17130#include "ipc/ipc_platform_file.h"
[email protected]433df472012-03-07 20:33:39131#include "media/base/media.h"
chcunningham9a285ed2017-03-08 21:48:56132#include "media/base/media_switches.h"
Scott Violeta35f9a42018-03-22 22:00:44133#include "media/media_buildflags.h"
Dale Curtis863022e2017-08-19 02:05:34134#include "media/video/gpu_video_accelerator_factories.h"
rockot85dce0862015-11-13 01:33:59135#include "mojo/public/cpp/bindings/strong_binding.h"
Yuki Yamada68992b02017-07-31 06:13:45136#include "mojo/public/cpp/system/message_pipe.h"
[email protected]620161e2011-03-07 18:05:26137#include "net/base/net_errors.h"
eroman9ab64842015-07-21 05:07:52138#include "net/base/port_util.h"
hablichd6a4f122015-10-28 11:34:49139#include "net/base/registry_controlled_domains/registry_controlled_domain.h"
tfarina7a4a7fd2016-01-20 14:23:44140#include "net/base/url_util.h"
Scott Violet02e38b92018-03-27 23:42:14141#include "ppapi/buildflags/buildflags.h"
Khushal3e96e662017-10-30 23:16:50142#include "services/metrics/public/cpp/mojo_ukm_recorder.h"
penghuangd6843e42016-12-17 13:57:20143#include "services/service_manager/public/cpp/connector.h"
rockot734fb662016-10-15 16:41:30144#include "services/service_manager/public/cpp/interface_provider.h"
sadrul85cc5d82016-12-20 03:37:41145#include "services/ui/public/cpp/gpu/context_provider_command_buffer.h"
Stuart Langley849079a2017-08-28 02:02:50146#include "services/ui/public/cpp/gpu/gpu.h"
penghuangd6843e42016-12-17 13:57:20147#include "services/ui/public/interfaces/constants.mojom.h"
[email protected]b48c53ad2014-02-05 21:59:18148#include "skia/ext/event_tracer_impl.h"
ssid59c969162015-07-28 13:02:58149#include "skia/ext/skia_memory_dump_provider.h"
Blink Reformata30d4232018-04-07 15:31:06150#include "third_party/blink/public/platform/scheduler/child/webthread_base.h"
151#include "third_party/blink/public/platform/scheduler/web_main_thread_scheduler.h"
152#include "third_party/blink/public/platform/web_cache.h"
153#include "third_party/blink/public/platform/web_image_generator.h"
154#include "third_party/blink/public/platform/web_memory_coordinator.h"
155#include "third_party/blink/public/platform/web_network_state_notifier.h"
156#include "third_party/blink/public/platform/web_runtime_features.h"
157#include "third_party/blink/public/platform/web_string.h"
158#include "third_party/blink/public/platform/web_thread.h"
159#include "third_party/blink/public/web/blink.h"
160#include "third_party/blink/public/web/web_document.h"
161#include "third_party/blink/public/web/web_frame.h"
162#include "third_party/blink/public/web/web_script_controller.h"
163#include "third_party/blink/public/web/web_security_policy.h"
164#include "third_party/blink/public/web/web_view.h"
David Benjaminb946811c2017-06-26 23:34:29165#include "third_party/boringssl/src/include/openssl/evp.h"
[email protected]ddbb53342014-01-06 10:59:47166#include "third_party/skia/include/core/SkGraphics.h"
[email protected]c49201a2012-05-24 11:04:57167#include "ui/base/layout.h"
Scott Violet8ff9c302018-02-22 22:28:35168#include "ui/base/ui_base_features.h"
[email protected]18ad6772011-09-20 21:51:32169#include "ui/base/ui_base_switches.h"
mlamouri7c149652017-03-24 00:00:09170#include "ui/display/display_switches.h"
ennee292bdc2016-09-15 19:57:15171#include "ui/gl/gl_switches.h"
[email protected]2c62b562009-01-27 19:04:50172
Ramin Halavati4aaa3f52018-02-07 07:41:50173#if BUILDFLAG(ENABLE_WEBRTC)
174#include "content/renderer/p2p/socket_dispatcher.h"
175#endif
176
[email protected]33b02992014-03-01 01:06:29177#if defined(OS_ANDROID)
178#include <cpu-features.h>
danakjc7afae52017-06-20 21:12:41179#include "content/renderer/android/synchronous_layer_tree_frame_sink.h"
boliue81d16132016-04-26 00:54:41180#include "content/renderer/media/android/stream_texture_factory.h"
dalecurtis88af3932016-02-20 00:12:20181#include "media/base/android/media_codec_util.h"
[email protected]33b02992014-03-01 01:06:29182#endif
183
184#if defined(OS_MACOSX)
ccamerona7644752014-12-30 01:16:31185#include "base/mac/mac_util.h"
rsesek1efb3c32015-09-29 15:39:50186#include "content/renderer/theme_helper_mac.h"
[email protected]33b02992014-03-01 01:06:29187#include "content/renderer/webscrollbarbehavior_impl_mac.h"
188#endif
189
[email protected]da00a2882009-03-09 17:51:19190#if defined(OS_WIN)
191#include <windows.h>
192#include <objbase.h>
193#endif
194
Brett Wilson0748bf412016-11-22 17:55:46195#if BUILDFLAG(ENABLE_WEBRTC)
Miguel Casasa8c2c5a2018-02-12 18:51:03196#include "content/renderer/media/stream/aec_dump_message_filter.h"
[email protected]22fe91d2014-08-12 17:07:12197#include "content/renderer/media/webrtc/peer_connection_dependency_factory.h"
Miguel Casasee42e702018-02-09 19:07:03198#include "content/renderer/media/webrtc/peer_connection_tracker.h"
199#include "content/renderer/media/webrtc/rtc_peer_connection_handler.h"
[email protected]22fe91d2014-08-12 17:07:12200#endif
201
chunyang.daibe874c52014-11-14 06:45:05202#ifdef ENABLE_VTUNE_JIT_INTERFACE
203#include "v8/src/third_party/vtune/v8-vtune.h"
204#endif
205
ochangdd89a1e2016-06-08 16:39:01206#if defined(ENABLE_IPC_FUZZER)
207#include "content/common/external_ipc_dumper.h"
208#endif
209
tasakb46626a2016-10-18 05:54:44210#if defined(OS_MACOSX)
211#include <malloc/malloc.h>
212#else
213#include <malloc.h>
214#endif
215
[email protected]d293572a2013-05-23 18:50:45216using base::ThreadRestrictions;
[email protected]180ef242013-11-07 06:50:46217using blink::WebDocument;
218using blink::WebFrame;
219using blink::WebNetworkStateNotifier;
220using blink::WebRuntimeFeatures;
221using blink::WebScriptController;
222using blink::WebSecurityPolicy;
223using blink::WebString;
224using blink::WebView;
[email protected]e9ff79c2012-10-19 21:31:26225
226namespace content {
initial.commit09911bf2008-07-26 23:55:29227
[email protected]42f1d7822009-07-23 18:17:55228namespace {
[email protected]da9ccfb2012-01-28 00:34:40229
avi1023d012015-12-25 02:39:14230const int64_t kInitialIdleHandlerDelayMs = 1000;
231const int64_t kLongIdleHandlerDelayMs = 30 * 1000;
[email protected]bee16aab2009-08-26 15:55:03232
[email protected]dd2c1022014-07-22 23:13:57233// Maximum allocation size allowed for image scaling filters that
234// require pre-scaling. Skia will fallback to a filter that doesn't
235// require pre-scaling if the default filter would require an
236// allocation that exceeds this limit.
237const size_t kImageCacheSingleAllocationByteLimit = 64 * 1024 * 1024;
238
samans2040988b2017-04-11 23:58:35239#if defined(OS_ANDROID)
danakj83066a32016-06-21 02:34:49240// Unique identifier for each output surface created.
danakjc7afae52017-06-20 21:12:41241uint32_t g_next_layer_tree_frame_sink_id = 1;
samans2040988b2017-04-11 23:58:35242#endif
danakj83066a32016-06-21 02:34:49243
rockot5c478a72016-09-28 23:14:18244// An implementation of mojom::RenderMessageFilter which can be mocked out
245// for tests which may indirectly send messages over this interface.
246mojom::RenderMessageFilter* g_render_message_filter_for_testing;
247
olegmax045f7fb12017-05-19 07:58:55248// An implementation of RendererBlinkPlatformImpl which can be mocked out
249// for tests.
250RendererBlinkPlatformImpl* g_current_blink_platform_impl_for_testing;
251
[email protected]f1a29a02011-10-06 23:08:44252// Keep the global RenderThreadImpl in a TLS slot so it is impossible to access
[email protected]f3ede412010-06-21 22:52:16253// incorrectly from the wrong thread.
scottmg5e65e3a2017-03-08 08:48:46254base::LazyInstance<base::ThreadLocalPointer<RenderThreadImpl>>::DestructorAtExit
[email protected]6de0fd1d2011-11-15 13:31:49255 lazy_tls = LAZY_INSTANCE_INITIALIZER;
[email protected]1edc16b82009-04-07 17:45:54256
John Abd-El-Malekd4882642017-12-04 21:45:19257base::LazyInstance<scoped_refptr<base::SingleThreadTaskRunner>>::
258 DestructorAtExit g_main_task_runner = LAZY_INSTANCE_INITIALIZER;
259
hong.zhengb28b5332016-05-11 02:33:39260// v8::MemoryPressureLevel should correspond to base::MemoryPressureListener.
261static_assert(static_cast<v8::MemoryPressureLevel>(
262 base::MemoryPressureListener::MEMORY_PRESSURE_LEVEL_NONE) ==
263 v8::MemoryPressureLevel::kNone, "none level not align");
264static_assert(static_cast<v8::MemoryPressureLevel>(
265 base::MemoryPressureListener::MEMORY_PRESSURE_LEVEL_MODERATE) ==
266 v8::MemoryPressureLevel::kModerate, "moderate level not align");
267static_assert(static_cast<v8::MemoryPressureLevel>(
268 base::MemoryPressureListener::MEMORY_PRESSURE_LEVEL_CRITICAL) ==
269 v8::MemoryPressureLevel::kCritical, "critical level not align");
270
hong.zheng2e296f822016-06-29 02:47:44271// WebMemoryPressureLevel should correspond to base::MemoryPressureListener.
272static_assert(static_cast<blink::WebMemoryPressureLevel>(
Blink Reformat1c4d759e2017-04-09 16:34:54273 base::MemoryPressureListener::MEMORY_PRESSURE_LEVEL_NONE) ==
274 blink::kWebMemoryPressureLevelNone,
275 "blink::WebMemoryPressureLevelNone not align");
276static_assert(
277 static_cast<blink::WebMemoryPressureLevel>(
278 base::MemoryPressureListener::MEMORY_PRESSURE_LEVEL_MODERATE) ==
279 blink::kWebMemoryPressureLevelModerate,
280 "blink::WebMemoryPressureLevelModerate not align");
281static_assert(
282 static_cast<blink::WebMemoryPressureLevel>(
283 base::MemoryPressureListener::MEMORY_PRESSURE_LEVEL_CRITICAL) ==
284 blink::kWebMemoryPressureLevelCritical,
285 "blink::WebMemoryPressureLevelCritical not align");
hong.zheng2e296f822016-06-29 02:47:44286
[email protected]b2d98762012-09-03 17:04:06287void* CreateHistogram(
[email protected]d1b8fccc2011-08-03 01:20:13288 const char *name, int min, int max, size_t buckets) {
289 if (min <= 0)
290 min = 1;
[email protected]b2d98762012-09-03 17:04:06291 std::string histogram_name;
292 RenderThreadImpl* render_thread_impl = RenderThreadImpl::current();
293 if (render_thread_impl) { // Can be null in tests.
294 histogram_name = render_thread_impl->
295 histogram_customizer()->ConvertToCustomHistogramName(name);
296 } else {
297 histogram_name = std::string(name);
298 }
[email protected]de415552013-01-23 04:12:17299 base::HistogramBase* histogram = base::Histogram::FactoryGet(
[email protected]b2d98762012-09-03 17:04:06300 histogram_name, min, max, buckets,
301 base::Histogram::kUmaTargetedHistogramFlag);
[email protected]d1b8fccc2011-08-03 01:20:13302 return histogram;
303}
304
[email protected]b2d98762012-09-03 17:04:06305void AddHistogramSample(void* hist, int sample) {
[email protected]d1b8fccc2011-08-03 01:20:13306 base::Histogram* histogram = static_cast<base::Histogram*>(hist);
307 histogram->Add(sample);
308}
309
ben76f52b242016-06-18 05:42:48310class FrameFactoryImpl : public mojom::FrameFactory {
rockotf8fdd9b2015-12-16 22:22:35311 public:
benf28ce882017-05-02 16:15:49312 explicit FrameFactoryImpl(const service_manager::BindSourceInfo& source_info)
313 : source_info_(source_info), routing_id_highmark_(-1) {}
rockotf8fdd9b2015-12-16 22:22:35314
ben76f52b242016-06-18 05:42:48315 private:
316 // mojom::FrameFactory:
Balazs Engedyba034e72017-10-27 22:26:28317 void CreateFrame(int32_t frame_routing_id,
318 mojom::FrameRequest frame_request) override {
rockotf8fdd9b2015-12-16 22:22:35319 // TODO(morrita): This is for investigating http://crbug.com/415059 and
320 // should be removed once it is fixed.
321 CHECK_LT(routing_id_highmark_, frame_routing_id);
322 routing_id_highmark_ = frame_routing_id;
323
324 RenderFrameImpl* frame = RenderFrameImpl::FromRoutingID(frame_routing_id);
325 // We can receive a GetServiceProviderForFrame message for a frame not yet
rockot067ca55f2016-09-30 22:00:15326 // created due to a race between the message and a
327 // mojom::Renderer::CreateView IPC that triggers creation of the RenderFrame
328 // we want.
rockotf8fdd9b2015-12-16 22:22:35329 if (!frame) {
ben76f52b242016-06-18 05:42:48330 RenderThreadImpl::current()->RegisterPendingFrameCreate(
Balazs Engedyba034e72017-10-27 22:26:28331 source_info_, frame_routing_id, std::move(frame_request));
rockotf8fdd9b2015-12-16 22:22:35332 return;
333 }
334
Balazs Engedyba034e72017-10-27 22:26:28335 frame->BindFrame(source_info_, std::move(frame_request));
rockotf8fdd9b2015-12-16 22:22:35336 }
337
338 private:
benf28ce882017-05-02 16:15:49339 service_manager::BindSourceInfo source_info_;
rockotf8fdd9b2015-12-16 22:22:35340 int32_t routing_id_highmark_;
rockotf8fdd9b2015-12-16 22:22:35341};
342
Ben Goodger21ada1e2017-07-19 14:53:01343void CreateFrameFactory(mojom::FrameFactoryRequest request,
344 const service_manager::BindSourceInfo& source_info) {
Jeremy Roman04f27c372017-10-27 15:20:55345 mojo::MakeStrongBinding(std::make_unique<FrameFactoryImpl>(source_info),
rockot8e66a08d2016-09-13 00:48:21346 std::move(request));
rockotf8fdd9b2015-12-16 22:22:35347}
348
sadrul85cc5d82016-12-20 03:37:41349scoped_refptr<ui::ContextProviderCommandBuffer> CreateOffscreenContext(
danakjc3983552016-05-03 00:04:35350 scoped_refptr<gpu::GpuChannelHost> gpu_channel_host,
Antoine Labour5ac65db2017-12-19 18:02:58351 gpu::GpuMemoryBufferManager* gpu_memory_buffer_manager,
danakj0dd9e1e2016-05-11 22:15:09352 const gpu::SharedMemoryLimits& limits,
danakj9a04adc2016-05-16 22:45:07353 bool support_locking,
Victor Miura3a4ad4f82017-12-13 06:03:45354 bool support_gles2_interface,
355 bool support_raster_interface,
Adrienne Walker436a7752017-08-28 23:33:09356 bool support_oop_rasterization,
Justin Novosad7d3d2502018-03-27 18:55:38357 bool support_grcontext,
sadrul85cc5d82016-12-20 03:37:41358 ui::command_buffer_metrics::ContextType type,
sunnypsd8ce1c22016-05-10 18:02:40359 int32_t stream_id,
sunnyps8f9139e2017-05-12 17:53:25360 gpu::SchedulingPriority stream_priority) {
danakje8ec797e2016-04-19 04:08:43361 DCHECK(gpu_channel_host);
362 // This is used to create a few different offscreen contexts:
Victor Miura3a4ad4f82017-12-13 06:03:45363 // - The shared main thread context, used by blink for 2D Canvas.
364 // - The compositor worker context, used for GPU raster.
365 // - The media context, used for accelerated video decoding.
danakje8ec797e2016-04-19 04:08:43366 // This is for an offscreen context, so the default framebuffer doesn't need
367 // alpha, depth, stencil, antialiasing.
Antoine Labourfeab2392017-12-21 20:28:39368 gpu::ContextCreationAttribs attributes;
danakje8ec797e2016-04-19 04:08:43369 attributes.alpha_size = -1;
370 attributes.depth_size = 0;
371 attributes.stencil_size = 0;
372 attributes.samples = 0;
373 attributes.sample_buffers = 0;
374 attributes.bind_generates_resource = false;
375 attributes.lose_context_when_out_of_memory = true;
Victor Miura3a4ad4f82017-12-13 06:03:45376 attributes.enable_gles2_interface = support_gles2_interface;
377 attributes.enable_raster_interface = support_raster_interface;
Adrienne Walker436a7752017-08-28 23:33:09378 attributes.enable_oop_rasterization = support_oop_rasterization;
379
Jonathan Backer4d51ebf2018-03-14 14:11:14380 bool enable_raster_decoder =
381 base::CommandLine::ForCurrentProcess()->HasSwitch(
382 switches::kEnableRasterDecoder);
383 // --enable-raster-decoder supports raster interface, but not
384 // gles2 interface
385 attributes.enable_raster_decoder = enable_raster_decoder &&
386 support_raster_interface &&
387 !support_gles2_interface;
388
sunnypsd8ce1c22016-05-10 18:02:40389 const bool automatic_flushes = false;
kylechar96f3eba2017-09-25 20:23:56390 return base::MakeRefCounted<ui::ContextProviderCommandBuffer>(
Antoine Labour5ac65db2017-12-19 18:02:58391 std::move(gpu_channel_host), gpu_memory_buffer_manager, stream_id,
392 stream_priority, gpu::kNullSurfaceHandle,
zmo09ea813b2017-01-20 23:38:36393 GURL("chrome://gpu/RenderThreadImpl::CreateOffscreenContext/" +
394 ui::command_buffer_metrics::ContextTypeToString(type)),
Justin Novosad7d3d2502018-03-27 18:55:38395 automatic_flushes, support_locking, support_grcontext, limits, attributes,
Victor Miuraff6488612017-12-21 04:16:15396 nullptr /* share_context */, type);
danakje8ec797e2016-04-19 04:08:43397}
398
dalecurtis4a9839a2017-05-04 23:40:47399// Hook that allows single-sample metric code from //components/metrics to
400// connect from the renderer process to the browser process.
401void CreateSingleSampleMetricsProvider(
402 scoped_refptr<base::SingleThreadTaskRunner> task_runner,
403 service_manager::Connector* connector,
404 metrics::mojom::SingleSampleMetricsProviderRequest request) {
405 if (task_runner->BelongsToCurrentThread()) {
406 connector->BindInterface(mojom::kBrowserServiceName, std::move(request));
407 return;
408 }
409
410 task_runner->PostTask(
411 FROM_HERE,
tzikff2a81a2017-09-15 05:10:06412 base::BindOnce(&CreateSingleSampleMetricsProvider, std::move(task_runner),
tzikccf160c2018-02-20 12:43:13413 connector, std::move(request)));
dalecurtis4a9839a2017-05-04 23:40:47414}
415
samans7e6675cc2017-06-05 20:16:08416class RendererLocalSurfaceIdProvider : public viz::LocalSurfaceIdProvider {
417 public:
Fady Samueld5c26182017-07-12 02:43:33418 const viz::LocalSurfaceId& GetLocalSurfaceIdForFrame(
danakj5e0a12b2017-09-25 17:26:49419 const viz::CompositorFrame& frame) override {
samans7e6675cc2017-06-05 20:16:08420 auto new_surface_properties =
421 RenderWidgetSurfaceProperties::FromCompositorFrame(frame);
422 if (!local_surface_id_.is_valid() ||
423 new_surface_properties != surface_properties_) {
Chris Blumeefd8f242017-12-08 00:24:27424 local_surface_id_ = parent_local_surface_id_allocator_.GenerateId();
samans7e6675cc2017-06-05 20:16:08425 surface_properties_ = new_surface_properties;
426 }
427 return local_surface_id_;
428 }
429
430 private:
Chris Blumeefd8f242017-12-08 00:24:27431 viz::ParentLocalSurfaceIdAllocator parent_local_surface_id_allocator_;
Fady Samueld5c26182017-07-12 02:43:33432 viz::LocalSurfaceId local_surface_id_;
samans7e6675cc2017-06-05 20:16:08433 RenderWidgetSurfaceProperties surface_properties_;
434};
435
Khushal3e96e662017-10-30 23:16:50436// This factory is used to defer binding of the InterfacePtr to the compositor
437// thread.
438class UkmRecorderFactoryImpl : public cc::UkmRecorderFactory {
439 public:
Lukasz Anforowiczbb0cfd5e2017-12-14 22:39:46440 explicit UkmRecorderFactoryImpl(
441 std::unique_ptr<service_manager::Connector> connector)
Khushalda50f8152017-12-01 09:04:40442 : connector_(std::move(connector)) {
443 DCHECK(connector_);
Khushal3e96e662017-10-30 23:16:50444 }
445 ~UkmRecorderFactoryImpl() override = default;
446
447 std::unique_ptr<ukm::UkmRecorder> CreateRecorder() override {
Khushalda50f8152017-12-01 09:04:40448 return ukm::MojoUkmRecorder::Create(connector_.get());
Khushal3e96e662017-10-30 23:16:50449 }
450
451 private:
Khushalda50f8152017-12-01 09:04:40452 std::unique_ptr<service_manager::Connector> connector_;
Khushal3e96e662017-10-30 23:16:50453};
454
Ben Goodgerf180ce12018-02-09 22:54:01455static const int kWaitForWorkersStatsTimeoutMS = 20;
456
457class ResourceUsageReporterImpl : public content::mojom::ResourceUsageReporter {
458 public:
459 explicit ResourceUsageReporterImpl(base::WeakPtr<RenderThread> thread)
460 : workers_to_go_(0), thread_(thread), weak_factory_(this) {}
461 ~ResourceUsageReporterImpl() override {}
462
463 private:
464 static void CollectOnWorkerThread(
465 const scoped_refptr<base::TaskRunner>& master,
466 base::WeakPtr<ResourceUsageReporterImpl> impl) {
467 size_t total_bytes = 0;
468 size_t used_bytes = 0;
469 v8::Isolate* isolate = v8::Isolate::GetCurrent();
470 if (isolate) {
471 v8::HeapStatistics heap_stats;
472 isolate->GetHeapStatistics(&heap_stats);
473 total_bytes = heap_stats.total_heap_size();
474 used_bytes = heap_stats.used_heap_size();
475 }
476 master->PostTask(FROM_HERE,
477 base::BindOnce(&ResourceUsageReporterImpl::ReceiveStats,
478 impl, total_bytes, used_bytes));
479 }
480
481 void ReceiveStats(size_t total_bytes, size_t used_bytes) {
482 usage_data_->v8_bytes_allocated += total_bytes;
483 usage_data_->v8_bytes_used += used_bytes;
484 workers_to_go_--;
485 if (!workers_to_go_)
486 SendResults();
487 }
488
489 void SendResults() {
490 if (!callback_.is_null())
491 std::move(callback_).Run(std::move(usage_data_));
492 callback_.Reset();
493 weak_factory_.InvalidateWeakPtrs();
494 workers_to_go_ = 0;
495 }
496
497 void GetUsageData(GetUsageDataCallback callback) override {
498 DCHECK(callback_.is_null());
499 weak_factory_.InvalidateWeakPtrs();
500 usage_data_ = mojom::ResourceUsageData::New();
501 usage_data_->reports_v8_stats = true;
502 callback_ = std::move(callback);
503
504 // Since it is not safe to call any Blink or V8 functions until Blink has
505 // been initialized (which also initializes V8), early out and send 0 back
506 // for all resources.
507 if (!thread_) {
508 SendResults();
509 return;
510 }
511
512 blink::WebCache::ResourceTypeStats stats;
513 blink::WebCache::GetResourceTypeStats(&stats);
514 usage_data_->web_cache_stats = mojom::ResourceTypeStats::From(stats);
515
516 v8::Isolate* isolate = v8::Isolate::GetCurrent();
517 if (isolate) {
518 v8::HeapStatistics heap_stats;
519 isolate->GetHeapStatistics(&heap_stats);
520 usage_data_->v8_bytes_allocated = heap_stats.total_heap_size();
521 usage_data_->v8_bytes_used = heap_stats.used_heap_size();
522 }
523 base::RepeatingClosure collect = base::BindRepeating(
524 &ResourceUsageReporterImpl::CollectOnWorkerThread,
525 base::ThreadTaskRunnerHandle::Get(), weak_factory_.GetWeakPtr());
Tommy Nyquist4b749d02018-03-20 21:46:29526 workers_to_go_ =
527 RenderThread::Get()->PostTaskToAllWebWorkers(std::move(collect));
Ben Goodgerf180ce12018-02-09 22:54:01528 if (workers_to_go_) {
529 // The guard task to send out partial stats
530 // in case some workers are not responsive.
531 base::ThreadTaskRunnerHandle::Get()->PostDelayedTask(
532 FROM_HERE,
533 base::BindOnce(&ResourceUsageReporterImpl::SendResults,
534 weak_factory_.GetWeakPtr()),
535 base::TimeDelta::FromMilliseconds(kWaitForWorkersStatsTimeoutMS));
536 } else {
537 // No worker threads so just send out the main thread data right away.
538 SendResults();
539 }
540 }
541
542 mojom::ResourceUsageDataPtr usage_data_;
543 GetUsageDataCallback callback_;
544 int workers_to_go_;
545 base::WeakPtr<RenderThread> thread_;
546
547 base::WeakPtrFactory<ResourceUsageReporterImpl> weak_factory_;
548
549 DISALLOW_COPY_AND_ASSIGN(ResourceUsageReporterImpl);
550};
551
552void CreateResourceUsageReporter(base::WeakPtr<RenderThread> thread,
553 mojom::ResourceUsageReporterRequest request) {
Jeremy Roman42e81a62018-03-01 19:08:59554 mojo::MakeStrongBinding(std::make_unique<ResourceUsageReporterImpl>(thread),
Ben Goodgerf180ce12018-02-09 22:54:01555 std::move(request));
556}
557
[email protected]b2d98762012-09-03 17:04:06558} // namespace
559
[email protected]b2d98762012-09-03 17:04:06560RenderThreadImpl::HistogramCustomizer::HistogramCustomizer() {
561 custom_histograms_.insert("V8.MemoryExternalFragmentationTotal");
562 custom_histograms_.insert("V8.MemoryHeapSampleTotalCommitted");
563 custom_histograms_.insert("V8.MemoryHeapSampleTotalUsed");
hablich4598ddc2015-11-07 18:37:28564 custom_histograms_.insert("V8.MemoryHeapUsed");
565 custom_histograms_.insert("V8.MemoryHeapCommitted");
[email protected]b2d98762012-09-03 17:04:06566}
567
568RenderThreadImpl::HistogramCustomizer::~HistogramCustomizer() {}
569
570void RenderThreadImpl::HistogramCustomizer::RenderViewNavigatedToHost(
571 const std::string& host, size_t view_count) {
avi83883c82014-12-23 00:08:49572 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
573 switches::kDisableHistogramCustomizer)) {
[email protected]9baee832012-12-10 11:07:15574 return;
575 }
[email protected]b2d98762012-09-03 17:04:06576 // Check if all RenderViews are displaying a page from the same host. If there
577 // is only one RenderView, the common host is this view's host. If there are
578 // many, check if this one shares the common host of the other
579 // RenderViews. It's ok to not detect some cases where the RenderViews share a
580 // common host. This information is only used for producing custom histograms.
581 if (view_count == 1)
582 SetCommonHost(host);
583 else if (host != common_host_)
584 SetCommonHost(std::string());
585}
586
587std::string RenderThreadImpl::HistogramCustomizer::ConvertToCustomHistogramName(
588 const char* histogram_name) const {
589 std::string name(histogram_name);
590 if (!common_host_histogram_suffix_.empty() &&
591 custom_histograms_.find(name) != custom_histograms_.end())
592 name += common_host_histogram_suffix_;
593 return name;
594}
595
596void RenderThreadImpl::HistogramCustomizer::SetCommonHost(
597 const std::string& host) {
598 if (host != common_host_) {
599 common_host_ = host;
600 common_host_histogram_suffix_ = HostToCustomHistogramSuffix(host);
Blink Reformat1c4d759e2017-04-09 16:34:54601 blink::MainThreadIsolate()->SetCreateHistogramFunction(CreateHistogram);
[email protected]b2d98762012-09-03 17:04:06602 }
603}
604
hablichd6a4f122015-10-28 11:34:49605std::string RenderThreadImpl::HistogramCustomizer::HostToCustomHistogramSuffix(
606 const std::string& host) {
607 if (host == "mail.google.com")
608 return ".gmail";
609 if (host == "docs.google.com" || host == "drive.google.com")
610 return ".docs";
611 if (host == "plus.google.com")
612 return ".plus";
613 if (host == "inbox.google.com")
614 return ".inbox";
hpayerdd4def052016-02-06 19:06:10615 if (host == "calendar.google.com")
616 return ".calendar";
hablichd6a4f122015-10-28 11:34:49617 if (host == "www.youtube.com")
618 return ".youtube";
619 if (IsAlexaTop10NonGoogleSite(host))
620 return ".top10";
621
622 return std::string();
623}
624
625bool RenderThreadImpl::HistogramCustomizer::IsAlexaTop10NonGoogleSite(
626 const std::string& host) {
627 // The Top10 sites have different TLD and/or subdomains depending on the
628 // localization.
629 if (host == "sina.com.cn")
630 return true;
631
632 std::string sanitized_host =
633 net::registry_controlled_domains::GetDomainAndRegistry(
634 host, net::registry_controlled_domains::INCLUDE_PRIVATE_REGISTRIES);
635
636 if (sanitized_host == "facebook.com")
637 return true;
638 if (sanitized_host == "baidu.com")
639 return true;
640 if (sanitized_host == "qq.com")
641 return true;
642 if (sanitized_host == "twitter.com")
643 return true;
644 if (sanitized_host == "taobao.com")
645 return true;
646 if (sanitized_host == "live.com")
647 return true;
648
649 if (!sanitized_host.empty()) {
650 std::vector<base::StringPiece> host_tokens = base::SplitStringPiece(
651 sanitized_host, ".", base::TRIM_WHITESPACE, base::SPLIT_WANT_NONEMPTY);
652
653 if (host_tokens.size() >= 2) {
654 if ((host_tokens[0] == "yahoo") || (host_tokens[0] == "amazon") ||
655 (host_tokens[0] == "wikipedia")) {
656 return true;
657 }
658 }
659 }
660 return false;
661}
662
leon.han2c0f9f12015-07-11 02:01:19663// static
664RenderThreadImpl* RenderThreadImpl::Create(
Gabriel Charette08fd6532018-04-04 19:47:16665 const InProcessChildThreadParams& params,
666 base::MessageLoop* unowned_message_loop) {
Dmitry Skibaa2476cb92017-12-15 23:44:39667 TRACE_EVENT0("startup", "RenderThreadImpl::Create");
Yuta Kitamura3331f5c2018-04-05 11:12:25668 std::unique_ptr<blink::scheduler::WebMainThreadScheduler>
669 main_thread_scheduler =
670 blink::scheduler::WebMainThreadScheduler::Create();
jam75c44222016-03-23 05:34:24671 scoped_refptr<base::SingleThreadTaskRunner> test_task_counter;
Yuta Kitamura3331f5c2018-04-05 11:12:25672 return new RenderThreadImpl(params, std::move(main_thread_scheduler),
Gabriel Charette08fd6532018-04-04 19:47:16673 test_task_counter, unowned_message_loop);
leon.han2c0f9f12015-07-11 02:01:19674}
675
676// static
677RenderThreadImpl* RenderThreadImpl::Create(
dchengcedca5612016-04-09 01:40:15678 std::unique_ptr<base::MessageLoop> main_message_loop,
Yuta Kitamura3331f5c2018-04-05 11:12:25679 std::unique_ptr<blink::scheduler::WebMainThreadScheduler>
680 main_thread_scheduler) {
Dmitry Skibaa2476cb92017-12-15 23:44:39681 TRACE_EVENT0("startup", "RenderThreadImpl::Create");
dcheng07945f632015-12-26 07:59:32682 return new RenderThreadImpl(std::move(main_message_loop),
Yuta Kitamura3331f5c2018-04-05 11:12:25683 std::move(main_thread_scheduler));
leon.han2c0f9f12015-07-11 02:01:19684}
685
rockot5c478a72016-09-28 23:14:18686// static
[email protected]f1a29a02011-10-06 23:08:44687RenderThreadImpl* RenderThreadImpl::current() {
[email protected]526476902011-10-06 20:34:06688 return lazy_tls.Pointer()->Get();
689}
690
rockot5c478a72016-09-28 23:14:18691// static
692mojom::RenderMessageFilter* RenderThreadImpl::current_render_message_filter() {
693 if (g_render_message_filter_for_testing)
694 return g_render_message_filter_for_testing;
695 DCHECK(current());
696 return current()->render_message_filter();
697}
698
699// static
olegmax045f7fb12017-05-19 07:58:55700RendererBlinkPlatformImpl* RenderThreadImpl::current_blink_platform_impl() {
701 if (g_current_blink_platform_impl_for_testing)
702 return g_current_blink_platform_impl_for_testing;
703 DCHECK(current());
704 return current()->blink_platform_impl();
705}
706
707// static
rockot5c478a72016-09-28 23:14:18708void RenderThreadImpl::SetRenderMessageFilterForTesting(
709 mojom::RenderMessageFilter* render_message_filter) {
710 g_render_message_filter_for_testing = render_message_filter;
711}
712
olegmax045f7fb12017-05-19 07:58:55713// static
714void RenderThreadImpl::SetRendererBlinkPlatformImplForTesting(
715 RendererBlinkPlatformImpl* blink_platform_impl) {
716 g_current_blink_platform_impl_for_testing = blink_platform_impl;
717}
718
John Abd-El-Malekd4882642017-12-04 21:45:19719// static
720scoped_refptr<base::SingleThreadTaskRunner>
Hajime Hoshi20578c62018-01-12 09:43:26721RenderThreadImpl::DeprecatedGetMainTaskRunner() {
John Abd-El-Malekd4882642017-12-04 21:45:19722 return g_main_task_runner.Get();
723}
724
staraz067f58242016-11-07 21:06:41725// In single-process mode used for debugging, we don't pass a renderer client
726// ID via command line because RenderThreadImpl lives in the same process as
727// the browser
leon.han2c0f9f12015-07-11 02:01:19728RenderThreadImpl::RenderThreadImpl(
729 const InProcessChildThreadParams& params,
Yuta Kitamura3331f5c2018-04-05 11:12:25730 std::unique_ptr<blink::scheduler::WebMainThreadScheduler> scheduler,
Gabriel Charette08fd6532018-04-04 19:47:16731 const scoped_refptr<base::SingleThreadTaskRunner>& resource_task_queue,
732 base::MessageLoop* unowned_message_loop)
Hajime Hoshife11b132017-11-13 10:16:07733 : ChildThreadImpl(
734 Options::Builder()
735 .InBrowserProcess(params)
736 .AutoStartServiceManagerConnection(false)
737 .ConnectToBrowser(true)
738 .IPCTaskRunner(scheduler ? scheduler->IPCTaskRunner() : nullptr)
739 .Build()),
Yuta Kitamura3331f5c2018-04-05 11:12:25740 main_thread_scheduler_(std::move(scheduler)),
Gabriel Charette08fd6532018-04-04 19:47:16741 main_message_loop_(unowned_message_loop),
rockot067ca55f2016-09-30 22:00:15742 categorized_worker_pool_(new CategorizedWorkerPool()),
staraz067f58242016-11-07 21:06:41743 renderer_binding_(this),
danakjab9ef4d2017-10-31 23:38:33744 client_id_(1),
Ben Goodgerf180ce12018-02-09 22:54:01745 compositing_mode_watcher_binding_(this),
746 weak_factory_(this) {
jam75c44222016-03-23 05:34:24747 Init(resource_task_queue);
morritac6238ab2015-03-18 01:48:29748}
749
[email protected]42f1d7822009-07-23 18:17:55750// When we run plugins in process, we actually run them on the render thread,
751// which means that we need to make the render thread pump UI events.
haraken53f081d2014-11-11 01:03:40752RenderThreadImpl::RenderThreadImpl(
Gabriel Charette08fd6532018-04-04 19:47:16753 std::unique_ptr<base::MessageLoop> owned_message_loop,
Yuta Kitamura3331f5c2018-04-05 11:12:25754 std::unique_ptr<blink::scheduler::WebMainThreadScheduler> scheduler)
Hajime Hoshia1626932017-11-30 09:50:59755 : ChildThreadImpl(
756 Options::Builder()
757 .AutoStartServiceManagerConnection(false)
758 .ConnectToBrowser(true)
759 .IPCTaskRunner(scheduler ? scheduler->IPCTaskRunner() : nullptr)
760 .Build()),
Yuta Kitamura3331f5c2018-04-05 11:12:25761 main_thread_scheduler_(std::move(scheduler)),
Gabriel Charette08fd6532018-04-04 19:47:16762 owned_message_loop_(std::move(owned_message_loop)),
763 main_message_loop_(owned_message_loop_.get()),
rockot067ca55f2016-09-30 22:00:15764 categorized_worker_pool_(new CategorizedWorkerPool()),
wjmaclean1d970622017-01-21 22:28:24765 is_scroll_animator_enabled_(false),
danakjab9ef4d2017-10-31 23:38:33766 renderer_binding_(this),
Ben Goodgerf180ce12018-02-09 22:54:01767 compositing_mode_watcher_binding_(this),
768 weak_factory_(this) {
jam75c44222016-03-23 05:34:24769 scoped_refptr<base::SingleThreadTaskRunner> test_task_counter;
staraz067f58242016-11-07 21:06:41770 DCHECK(base::CommandLine::ForCurrentProcess()->HasSwitch(
771 switches::kRendererClientId));
772 base::StringToInt(base::CommandLine::ForCurrentProcess()->GetSwitchValueASCII(
773 switches::kRendererClientId),
774 &client_id_);
jam75c44222016-03-23 05:34:24775 Init(test_task_counter);
haraken53f081d2014-11-11 01:03:40776}
777
jam75c44222016-03-23 05:34:24778void RenderThreadImpl::Init(
rockot97a86832016-12-10 04:53:06779 const scoped_refptr<base::SingleThreadTaskRunner>& resource_task_queue) {
fdorayf6d86242015-10-08 16:49:53780 TRACE_EVENT0("startup", "RenderThreadImpl::Init");
[email protected]a872ea1f2010-08-11 04:45:33781
Gabriel Charette08fd6532018-04-04 19:47:16782 // Whether owned or unowned, |main_message_loop_| needs to be initialized in
783 // all constructors.
784 DCHECK(main_message_loop_);
785
Mike Wittmanc1419ff2018-03-02 23:50:04786 GetContentClient()->renderer()->PostIOThreadCreated(GetIOTaskRunner().get());
787
ssidb2e3ece2015-02-09 16:02:20788 base::trace_event::TraceLog::GetInstance()->SetThreadSortIndex(
[email protected]91a2aea2013-07-08 23:14:39789 base::PlatformThread::CurrentId(),
790 kTraceEventRendererMainThreadSortIndex);
791
thakis18e426412017-03-15 12:06:37792#if BUILDFLAG(USE_EXTERNAL_POPUP_MENU)
sievers9dff72052015-11-16 18:35:57793 // On Mac and Android Java UI, the select popups are rendered by the browser.
Blink Reformat1c4d759e2017-04-09 16:34:54794 blink::WebView::SetUseExternalPopupMenus(true);
[email protected]53c607c2011-03-21 23:19:04795#endif
796
[email protected]94f9a0f682009-06-15 18:30:30797 lazy_tls.Pointer()->Set(this);
Gabriel Charette08fd6532018-04-04 19:47:16798 g_main_task_runner.Get() = main_message_loop_->task_runner();
[email protected]b3e83de2012-02-07 03:33:28799
[email protected]06c694d2012-02-01 22:26:16800 // Register this object as the main thread.
801 ChildProcess::current()->set_main_thread(this);
802
dalecurtis4a9839a2017-05-04 23:40:47803 metrics::InitializeSingleSampleMetricsFactory(
804 base::BindRepeating(&CreateSingleSampleMetricsProvider,
805 message_loop()->task_runner(), GetConnector()));
806
Scott Violet8ff9c302018-02-22 22:28:35807 gpu_ = ui::Gpu::Create(GetConnector(),
808 base::FeatureList::IsEnabled(features::kMash)
809 ? ui::mojom::kServiceName
810 : mojom::kBrowserServiceName,
811 GetIOTaskRunner());
penghuange1d86512016-07-08 18:15:00812
Gary Klassenb78686272017-08-11 22:38:13813 viz::mojom::SharedBitmapAllocationNotifierPtr
danakj92429852017-06-29 00:19:03814 shared_bitmap_allocation_notifier_ptr;
Saman Sami9b768542017-07-14 20:42:34815 GetConnector()->BindInterface(
816 mojom::kBrowserServiceName,
danakj92429852017-06-29 00:19:03817 mojo::MakeRequest(&shared_bitmap_allocation_notifier_ptr));
Jeremy Roman04f27c372017-10-27 15:20:55818 shared_bitmap_manager_ = std::make_unique<viz::ClientSharedBitmapManager>(
Gary Klassenb78686272017-08-11 22:38:13819 viz::mojom::ThreadSafeSharedBitmapAllocationNotifierPtr::Create(
danakj92429852017-06-29 00:19:03820 shared_bitmap_allocation_notifier_ptr.PassInterface(),
821 GetChannel()->ipc_task_runner_refptr()));
jcivelli0f21bd52016-12-07 21:21:33822
Hajime Hoshi605413f2018-03-02 11:49:54823 notification_dispatcher_ = new NotificationDispatcher(
Yuta Kitamura3331f5c2018-04-05 11:12:25824 thread_safe_sender(), GetWebMainThreadScheduler()->IPCTaskRunner());
John Abd-El-Malekf9f86c12017-10-21 07:22:23825 AddFilter(notification_dispatcher_->GetFilter());
826
Hajime Hoshi1711b522018-01-19 10:29:20827 resource_dispatcher_.reset(new ResourceDispatcher());
Yuzhu Shenfe5f3a52018-01-11 21:24:13828 url_loader_throttle_provider_ =
829 GetContentClient()->renderer()->CreateURLLoaderThrottleProvider(
830 URLLoaderThrottleProviderType::kFrame);
John Abd-El-Malek6b56ef712017-10-21 22:52:46831
Stuart Langley7b8dc772017-10-31 03:55:20832 auto registry = std::make_unique<service_manager::BinderRegistry>();
Ken Rockot510c5972017-12-05 16:37:04833 InitializeWebKit(resource_task_queue, registry.get());
jam75c44222016-03-23 05:34:24834
[email protected]31f87132010-04-21 23:36:21835 // In single process the single process is all there is.
Alexander Timin4b6152232017-10-17 20:34:06836 webkit_shared_timer_suspended_ = false;
[email protected]bee16aab2009-08-26 15:55:03837 widget_count_ = 0;
838 hidden_widget_count_ = 0;
[email protected]6593ae12011-11-14 12:09:44839 idle_notification_delay_in_ms_ = kInitialIdleHandlerDelayMs;
[email protected]1784b2f2011-11-24 10:53:48840 idle_notifications_to_skip_ = 0;
[email protected]8d86fce2009-02-26 23:37:55841
[email protected]d5b2fdf2013-06-05 09:36:55842 appcache_dispatcher_.reset(
Nicholas Verne07e9c6452017-12-13 04:12:55843 new AppCacheDispatcher(new AppCacheFrontendImpl()));
844 registry->AddInterface(
845 base::BindRepeating(&AppCacheDispatcher::Bind,
846 base::Unretained(appcache_dispatcher())),
Yuta Kitamura3331f5c2018-04-05 11:12:25847 GetWebMainThreadScheduler()->IPCTaskRunner());
[email protected]1910fe82012-05-10 00:04:10848 dom_storage_dispatcher_.reset(new DomStorageDispatcher());
reillyg39fb4662016-11-22 20:27:17849 main_thread_indexed_db_dispatcher_.reset(new IndexedDBDispatcher());
John Abd-El-Malekdcf1d1372017-10-22 06:39:41850 file_system_dispatcher_.reset(new FileSystemDispatcher());
[email protected]dd9241932010-02-24 19:23:13851
[email protected]45048072014-01-14 13:51:29852 vc_manager_.reset(new VideoCaptureImplManager());
[email protected]c9c43a02013-12-17 08:59:54853
fsamuel6c1dfeb2014-12-18 19:21:33854 browser_plugin_manager_.reset(new BrowserPluginManager());
855 AddObserver(browser_plugin_manager_.get());
856
Brett Wilson0748bf412016-11-22 17:55:46857#if BUILDFLAG(ENABLE_WEBRTC)
[email protected]af089972013-01-10 04:04:40858 peer_connection_tracker_.reset(new PeerConnectionTracker());
859 AddObserver(peer_connection_tracker_.get());
860
thestig529ad8a2016-07-08 20:30:12861 p2p_socket_dispatcher_ = new P2PSocketDispatcher(GetIOTaskRunner().get());
[email protected]fc72bb12013-06-02 21:13:46862 AddFilter(p2p_socket_dispatcher_.get());
[email protected]921480f62013-07-20 03:42:57863
ivocadd54f0d2015-12-18 23:17:05864 peer_connection_factory_.reset(
865 new PeerConnectionDependencyFactory(p2p_socket_dispatcher_.get()));
866
skyostil2d3b5bd2015-05-27 15:40:59867 aec_dump_message_filter_ = new AecDumpMessageFilter(
thestig529ad8a2016-07-08 20:30:12868 GetIOTaskRunner(), message_loop()->task_runner());
ivocadd54f0d2015-12-18 23:17:05869
[email protected]da9f30a2014-06-18 19:39:04870 AddFilter(aec_dump_message_filter_.get());
871
Brett Wilson0748bf412016-11-22 17:55:46872#endif // BUILDFLAG(ENABLE_WEBRTC)
Max Morin2c38c282018-04-17 07:01:42873 audio_input_ipc_factory_.emplace(message_loop()->task_runner(),
874 GetIOTaskRunner());
[email protected]e25f4d72011-06-08 20:58:46875
Max Morin2c38c282018-04-17 07:01:42876 audio_output_ipc_factory_.emplace(GetIOTaskRunner());
[email protected]f7eb0a392011-07-12 10:19:51877
thestig529ad8a2016-07-08 20:30:12878 midi_message_filter_ = new MidiMessageFilter(GetIOTaskRunner());
[email protected]a9875152013-06-22 04:03:03879 AddFilter(midi_message_filter_.get());
880
sadrul943e3b32016-08-04 18:22:59881#if defined(USE_AURA)
Scott Violet8ff9c302018-02-22 22:28:35882 if (features::IsMusEnabled())
bend32292b2016-10-07 00:21:58883 CreateRenderWidgetWindowTreeClientFactory(GetServiceManagerConnection());
rockotcef38272016-07-15 22:47:47884#endif
885
Stuart Langley7b8dc772017-10-31 03:55:20886 registry->AddInterface(base::Bind(&SharedWorkerFactoryImpl::Create),
887 base::ThreadTaskRunnerHandle::Get());
Ben Goodgerf180ce12018-02-09 22:54:01888 registry->AddInterface(base::BindRepeating(CreateResourceUsageReporter,
889 weak_factory_.GetWeakPtr()),
890 base::ThreadTaskRunnerHandle::Get());
Han Leond24f8b2a2018-04-17 15:39:25891 registry->AddInterface(
892 base::BindRepeating(&EmbeddedWorkerInstanceClientImpl::Create,
893 base::TimeTicks::Now(), GetIOTaskRunner()),
894 GetWebMainThreadScheduler()->IPCTaskRunner());
Ben Goodgerf180ce12018-02-09 22:54:01895
Stuart Langley7b8dc772017-10-31 03:55:20896 GetServiceManagerConnection()->AddConnectionFilter(
897 std::make_unique<SimpleConnectionFilter>(std::move(registry)));
Stuart Langley6771c902017-09-01 11:23:30898
Darin Fisherbcc33632017-09-26 00:57:16899 {
900 auto registry_with_source_info =
Jeremy Roman04f27c372017-10-27 15:20:55901 std::make_unique<service_manager::BinderRegistryWithArgs<
Darin Fisherbcc33632017-09-26 00:57:16902 const service_manager::BindSourceInfo&>>();
903 registry_with_source_info->AddInterface(
904 base::Bind(&CreateFrameFactory), base::ThreadTaskRunnerHandle::Get());
905 GetServiceManagerConnection()->AddConnectionFilter(
Jeremy Roman04f27c372017-10-27 15:20:55906 std::make_unique<SimpleConnectionFilterWithSourceInfo>(
Darin Fisherbcc33632017-09-26 00:57:16907 std::move(registry_with_source_info)));
908 }
rockotcef38272016-07-15 22:47:47909
[email protected]e9ff79c2012-10-19 21:31:26910 GetContentClient()->renderer()->RenderThreadStarted();
[email protected]6779aa12011-03-29 17:32:24911
benbd9dc802017-04-19 01:37:43912 StartServiceManagerConnection();
913
rockot067ca55f2016-09-30 22:00:15914 GetAssociatedInterfaceRegistry()->AddInterface(
915 base::Bind(&RenderThreadImpl::OnRendererInterfaceRequest,
916 base::Unretained(this)));
917
[email protected]b48c53ad2014-02-05 21:59:18918 InitSkiaEventTracer();
ssid59c969162015-07-28 13:02:58919 base::trace_event::MemoryDumpManager::GetInstance()->RegisterDumpProvider(
primiano186d6bfe2015-10-30 13:21:40920 skia::SkiaMemoryDumpProvider::GetInstance(), "Skia", nullptr);
[email protected]b48c53ad2014-02-05 21:59:18921
avi83883c82014-12-23 00:08:49922 const base::CommandLine& command_line =
923 *base::CommandLine::ForCurrentProcess();
[email protected]e54ab492012-06-12 19:40:01924
ochangdd89a1e2016-06-08 16:39:01925#if defined(ENABLE_IPC_FUZZER)
926 if (command_line.HasSwitch(switches::kIpcDumpDirectory)) {
927 base::FilePath dump_directory =
928 command_line.GetSwitchValuePath(switches::kIpcDumpDirectory);
929 IPC::ChannelProxy::OutgoingMessageFilter* filter =
930 LoadExternalIPCDumper(dump_directory);
931 GetChannel()->set_outgoing_message_filter(filter);
932 }
933#endif
934
jbroman0d302162015-09-05 05:46:23935 cc::SetClientNameForMetrics("Renderer");
loysoa6edaaff2015-05-25 03:26:44936
loyso65c93c602015-08-11 05:15:57937 is_threaded_animation_enabled_ =
938 !command_line.HasSwitch(cc::switches::kDisableThreadedAnimation);
939
reveman91a0a872014-11-04 03:40:32940 is_zero_copy_enabled_ = command_line.HasSwitch(switches::kEnableZeroCopy);
ericrk1d17f752015-10-20 03:03:07941 is_partial_raster_enabled_ =
dongseong.hwang23db47f2016-03-08 07:50:02942 !command_line.HasSwitch(switches::kDisablePartialRaster);
ccameronc7fcd132015-11-03 20:14:31943 is_gpu_memory_buffer_compositor_resources_enabled_ = command_line.HasSwitch(
944 switches::kEnableGpuMemoryBufferCompositorResources);
[email protected]a23530d2014-03-11 06:04:14945
Greg Kerra7b943b2017-07-24 23:17:17946// On macOS this value is adjusted in `UpdateScrollbarTheme()`,
947// but the system default is true.
948#if defined(OS_MACOSX)
949 is_elastic_overscroll_enabled_ = true;
ccamerona7644752014-12-30 01:16:31950#else
951 is_elastic_overscroll_enabled_ = false;
952#endif
953
[email protected]a23530d2014-03-11 06:04:14954 if (command_line.HasSwitch(switches::kDisableLCDText)) {
955 is_lcd_text_enabled_ = false;
956 } else if (command_line.HasSwitch(switches::kEnableLCDText)) {
957 is_lcd_text_enabled_ = true;
958 } else {
959#if defined(OS_ANDROID)
960 is_lcd_text_enabled_ = false;
961#else
962 is_lcd_text_enabled_ = true;
963#endif
964 }
965
danakjab9ef4d2017-10-31 23:38:33966 if (command_line.HasSwitch(switches::kDisableGpuCompositing))
967 is_gpu_compositing_disabled_ = true;
968
[email protected]b8d82c22014-03-31 20:12:46969 is_gpu_rasterization_forced_ =
970 command_line.HasSwitch(switches::kForceGpuRasterization);
[email protected]a23530d2014-03-11 06:04:14971
senorblancob60ba952015-01-27 19:12:36972 if (command_line.HasSwitch(switches::kGpuRasterizationMSAASampleCount)) {
973 std::string string_value = command_line.GetSwitchValueASCII(
974 switches::kGpuRasterizationMSAASampleCount);
975 bool parsed_msaa_sample_count =
976 base::StringToInt(string_value, &gpu_rasterization_msaa_sample_count_);
977 DCHECK(parsed_msaa_sample_count) << string_value;
978 DCHECK_GE(gpu_rasterization_msaa_sample_count_, 0);
979 } else {
senorblanco2a5b0e12015-08-14 21:55:37980 gpu_rasterization_msaa_sample_count_ = -1;
senorblancob60ba952015-01-27 19:12:36981 }
982
[email protected]433df472012-03-07 20:33:39983 // Note that under Linux, the media library will normally already have
984 // been initialized by the Zygote before this instance became a Renderer.
chcunninghamfd11b3c2015-06-09 02:09:42985 media::InitializeMediaLibrary();
[email protected]433df472012-03-07 20:33:39986
dalecurtis88af3932016-02-20 00:12:20987#if defined(OS_ANDROID)
988 if (!command_line.HasSwitch(switches::kDisableAcceleratedVideoDecode) &&
989 media::MediaCodecUtil::IsMediaCodecAvailable()) {
Zhenyao Mocdae4522018-02-09 20:10:26990 bool accelerated_video_decode_blacklisted = false;
991 if (!command_line.HasSwitch(switches::kIgnoreGpuBlacklist)) {
992 int32_t major_version = 0, minor_version = 0, bugfix_version = 0;
993 base::SysInfo::OperatingSystemVersionNumbers(
994 &major_version, &minor_version, &bugfix_version);
995 if (major_version < 5) {
996 // Currently accelerated video decode is only blacklisted on
997 // Android older than Lollipop.
998 scoped_refptr<gpu::GpuChannelHost> gpu_channel_host =
999 EstablishGpuChannelSync();
1000 if (!gpu_channel_host ||
1001 gpu_channel_host->gpu_feature_info().status_values
1002 [gpu::GPU_FEATURE_TYPE_ACCELERATED_VIDEO_DECODE] !=
1003 gpu::kGpuFeatureStatusEnabled) {
1004 accelerated_video_decode_blacklisted = true;
1005 }
1006 }
1007 }
1008 if (!accelerated_video_decode_blacklisted)
1009 media::EnablePlatformDecoderSupport();
dalecurtis88af3932016-02-20 00:12:201010 }
1011#endif
1012
bashi296ebda2017-03-28 03:27:091013 memory_pressure_listener_.reset(new base::MemoryPressureListener(
1014 base::Bind(&RenderThreadImpl::OnMemoryPressure, base::Unretained(this)),
1015 base::Bind(&RenderThreadImpl::OnSyncMemoryPressure,
1016 base::Unretained(this))));
1017
1018 if (base::FeatureList::IsEnabled(features::kMemoryCoordinator)) {
1019 // Disable MemoryPressureListener when memory coordinator is enabled.
1020 base::MemoryPressureListener::SetNotificationsSuppressed(true);
1021
1022 // TODO(bashi): Revisit how to manage the lifetime of
1023 // ChildMemoryCoordinatorImpl.
1024 // https://codereview.chromium.org/2094583002/#msg52
1025 mojom::MemoryCoordinatorHandlePtr parent_coordinator;
1026 GetConnector()->BindInterface(mojom::kBrowserServiceName,
1027 mojo::MakeRequest(&parent_coordinator));
1028 memory_coordinator_ = CreateChildMemoryCoordinator(
1029 std::move(parent_coordinator), this);
1030 }
1031
danakj16275d4c2015-06-11 19:23:511032 int num_raster_threads = 0;
1033 std::string string_value =
1034 command_line.GetSwitchValueASCII(switches::kNumRasterThreads);
1035 bool parsed_num_raster_threads =
1036 base::StringToInt(string_value, &num_raster_threads);
1037 DCHECK(parsed_num_raster_threads) << string_value;
1038 DCHECK_GT(num_raster_threads, 0);
vmiura78b69282015-02-14 00:01:171039
Sadrul Habib Chowdhury6928fde2018-04-20 16:02:511040#if defined(OS_LINUX)
1041 categorized_worker_pool_->SetBackgroundingCallback(
1042 main_thread_scheduler_->DefaultTaskRunner(),
1043 base::BindOnce(
1044 [](base::WeakPtr<RenderThreadImpl> render_thread,
1045 base::PlatformThreadId thread_id) {
1046 if (!render_thread)
1047 return;
1048 render_thread->render_message_filter()->SetThreadPriority(
1049 thread_id, base::ThreadPriority::BACKGROUND);
1050 },
1051 weak_factory_.GetWeakPtr()));
1052#endif
prashant.nfad657e2016-06-01 07:52:171053 categorized_worker_pool_->Start(num_raster_threads);
[email protected]1e1d1e12014-01-17 16:14:291054
penghuang342762b2016-12-02 21:04:581055 discardable_memory::mojom::DiscardableSharedMemoryManagerPtr manager_ptr;
Scott Violet8ff9c302018-02-22 22:28:351056 if (features::IsMusEnabled()) {
penghuangd6843e42016-12-17 13:57:201057#if defined(USE_AURA)
benbd3c2482017-01-07 05:48:211058 GetServiceManagerConnection()->GetConnector()->BindInterface(
penghuangd6843e42016-12-17 13:57:201059 ui::mojom::kServiceName, &manager_ptr);
1060#else
1061 NOTREACHED();
1062#endif
1063 } else {
ben649b3edd2017-03-23 00:32:021064 ChildThread::Get()->GetConnector()->BindInterface(
1065 mojom::kBrowserServiceName, mojo::MakeRequest(&manager_ptr));
penghuangd6843e42016-12-17 13:57:201066 }
1067
Jeremy Roman04f27c372017-10-27 15:20:551068 discardable_shared_memory_manager_ = std::make_unique<
penghuang342762b2016-12-02 21:04:581069 discardable_memory::ClientDiscardableSharedMemoryManager>(
1070 std::move(manager_ptr), GetIOTaskRunner());
1071
boliu9760e212015-06-23 22:49:061072 // TODO(boliu): In single process, browser main loop should set up the
1073 // discardable memory manager, and should skip this if kSingleProcess.
1074 // See crbug.com/503724.
1075 base::DiscardableMemoryAllocator::SetInstance(
penghuang342762b2016-12-02 21:04:581076 discardable_shared_memory_manager_.get());
revemancb5a66af2014-10-25 00:34:391077
ben649b3edd2017-03-23 00:32:021078 GetConnector()->BindInterface(mojom::kBrowserServiceName,
1079 mojo::MakeRequest(&storage_partition_service_));
hajimehoshi69093272016-05-13 08:30:581080
reveman7b97c322016-09-20 02:10:581081#if defined(OS_LINUX)
Nicholas Verne84dc55e2017-11-23 01:02:381082 render_message_filter()->SetThreadPriority(
1083 ChildProcess::current()->io_thread_id(), base::ThreadPriority::DISPLAY);
reveman7b97c322016-09-20 02:10:581084#endif
1085
tasakbb0640b2017-05-15 09:02:261086 process_foregrounded_count_ = 0;
tasakb95dbb50c2017-02-08 18:07:501087 needs_to_record_first_active_paint_ = false;
Takashi SAKAMOTO870f6262017-08-22 04:08:271088 was_backgrounded_time_ = base::TimeTicks::Min();
hajimehoshi7bb39582016-10-12 04:30:571089
1090 base::MemoryCoordinatorClientRegistry::GetInstance()->Register(this);
fdoray50a38342016-11-21 20:46:041091
samans2040988b2017-04-11 23:58:351092 GetConnector()->BindInterface(mojom::kBrowserServiceName,
1093 mojo::MakeRequest(&frame_sink_provider_));
danakjab9ef4d2017-10-31 23:38:331094
1095 if (!is_gpu_compositing_disabled_) {
1096 GetConnector()->BindInterface(
1097 mojom::kBrowserServiceName,
1098 mojo::MakeRequest(&compositing_mode_reporter_));
1099
1100 // Make |this| a CompositingModeWatcher for the
1101 // |compositing_mode_reporter_|.
1102 viz::mojom::CompositingModeWatcherPtr watcher_ptr;
1103 compositing_mode_watcher_binding_.Bind(mojo::MakeRequest(&watcher_ptr));
1104 compositing_mode_reporter_->AddCompositingModeWatcher(
1105 std::move(watcher_ptr));
1106 }
initial.commit09911bf2008-07-26 23:55:291107}
1108
John Abd-El-Malekd4882642017-12-04 21:45:191109RenderThreadImpl::~RenderThreadImpl() {
1110 g_main_task_runner.Get() = nullptr;
1111}
[email protected]ce79d8512013-04-22 22:44:411112
Nicholas Verne5420564d2017-10-27 07:37:541113void RenderThreadImpl::Shutdown() {
John Abd-El-Malekdcf1d1372017-10-22 06:39:411114 ChildThreadImpl::Shutdown();
1115 file_system_dispatcher_.reset();
1116 WebFileSystemImpl::DeleteThreadSpecificInstance();
harakenbbfdd9f02017-01-12 07:14:041117 // In a multi-process mode, we immediately exit the renderer.
1118 // Historically we had a graceful shutdown sequence here but it was
1119 // 1) a waste of performance and 2) a source of lots of complicated
1120 // crashes caused by shutdown ordering. Immediate exit eliminates
1121 // those problems.
cbrunia3f655b2017-03-20 11:36:411122
1123 // Give the V8 isolate a chance to dump internal stats useful for performance
1124 // evaluation and debugging.
Blink Reformat1c4d759e2017-04-09 16:34:541125 blink::MainThreadIsolate()->DumpAndResetStats();
cbrunia3f655b2017-03-20 11:36:411126
Adithya Srinivasandf421e82017-06-01 14:36:111127 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
1128 switches::kDumpBlinkRuntimeCallStats))
1129 blink::LogRuntimeCallStats();
1130
harakenbbfdd9f02017-01-12 07:14:041131 // In a single-process mode, we cannot call _exit(0) in Shutdown() because
1132 // it will exit the process before the browser side is ready to exit.
1133 if (!base::CommandLine::ForCurrentProcess()->HasSwitch(
1134 switches::kSingleProcess))
haraken940efb92017-02-08 05:58:151135 base::Process::TerminateCurrentProcessImmediately(0);
harakenbbfdd9f02017-01-12 07:14:041136}
[email protected]1223d6ef2011-03-28 16:47:501137
harakenbbfdd9f02017-01-12 07:14:041138bool RenderThreadImpl::ShouldBeDestroyed() {
1139 DCHECK(base::CommandLine::ForCurrentProcess()->HasSwitch(
1140 switches::kSingleProcess));
1141 // In a single-process mode, it is unsafe to destruct this renderer thread
1142 // because we haven't run the shutdown sequence. Hence we leak the render
1143 // thread.
1144 //
1145 // In this case, we also need to disable at-exit callbacks because some of
1146 // the at-exit callbacks are expected to run after the renderer thread
1147 // has been destructed.
1148 base::AtExitManager::DisableAllAtExitManagers();
1149 return false;
initial.commit09911bf2008-07-26 23:55:291150}
1151
[email protected]f1a29a02011-10-06 23:08:441152bool RenderThreadImpl::Send(IPC::Message* msg) {
changwan6ed4d432016-05-19 22:03:541153 // There are cases where we want to pump asynchronous messages while waiting
1154 // synchronously for the replies to the message to be sent here. However, this
1155 // may create an opportunity for re-entrancy into WebKit and other subsystems,
1156 // so we need to take care to disable callbacks, timers, and pending network
1157 // loads that could trigger such callbacks.
[email protected]38b592902011-04-16 02:08:421158 bool pumping_events = false;
[email protected]80fc08c52010-03-09 07:43:501159 if (msg->is_sync()) {
1160 if (msg->is_caller_pumping_messages()) {
1161 pumping_events = true;
[email protected]80fc08c52010-03-09 07:43:501162 }
[email protected]c1f50aa2010-02-18 03:46:571163 }
1164
Yuta Kitamura3331f5c2018-04-05 11:12:251165 std::unique_ptr<blink::scheduler::WebMainThreadScheduler::RendererPauseHandle>
Yoland Yan25439ba2017-10-11 19:45:551166 renderer_paused_handle;
1167
[email protected]c1f50aa2010-02-18 03:46:571168 if (pumping_events) {
Yuta Kitamura3331f5c2018-04-05 11:12:251169 renderer_paused_handle = main_thread_scheduler_->PauseRenderer();
Blink Reformat1c4d759e2017-04-09 16:34:541170 WebView::WillEnterModalLoop();
[email protected]c1f50aa2010-02-18 03:46:571171 }
1172
jam8a021512a2015-02-03 18:16:081173 bool rv = ChildThreadImpl::Send(msg);
[email protected]c1f50aa2010-02-18 03:46:571174
Yoland Yan25439ba2017-10-11 19:45:551175 if (pumping_events)
Blink Reformat1c4d759e2017-04-09 16:34:541176 WebView::DidExitModalLoop();
[email protected]c1f50aa2010-02-18 03:46:571177
1178 return rv;
1179}
1180
[email protected]f1a29a02011-10-06 23:08:441181IPC::SyncChannel* RenderThreadImpl::GetChannel() {
[email protected]526476902011-10-06 20:34:061182 return channel();
1183}
1184
[email protected]f1a29a02011-10-06 23:08:441185std::string RenderThreadImpl::GetLocale() {
[email protected]526476902011-10-06 20:34:061186 // The browser process should have passed the locale to the renderer via the
[email protected]dfd53652012-10-25 00:20:021187 // --lang command line flag.
avi83883c82014-12-23 00:08:491188 const base::CommandLine& parsed_command_line =
1189 *base::CommandLine::ForCurrentProcess();
[email protected]526476902011-10-06 20:34:061190 const std::string& lang =
1191 parsed_command_line.GetSwitchValueASCII(switches::kLang);
[email protected]dfd53652012-10-25 00:20:021192 DCHECK(!lang.empty());
[email protected]526476902011-10-06 20:34:061193 return lang;
1194}
1195
[email protected]07bb6332012-01-21 01:07:571196IPC::SyncMessageFilter* RenderThreadImpl::GetSyncMessageFilter() {
1197 return sync_message_filter();
1198}
1199
avi1023d012015-12-25 02:39:141200void RenderThreadImpl::AddRoute(int32_t routing_id, IPC::Listener* listener) {
jam8a021512a2015-02-03 18:16:081201 ChildThreadImpl::GetRouter()->AddRoute(routing_id, listener);
ben76f52b242016-06-18 05:42:481202 auto it = pending_frame_creates_.find(routing_id);
1203 if (it == pending_frame_creates_.end())
rockotf8fdd9b2015-12-16 22:22:351204 return;
1205
1206 RenderFrameImpl* frame = RenderFrameImpl::FromRoutingID(routing_id);
1207 if (!frame)
1208 return;
1209
ben76f52b242016-06-18 05:42:481210 scoped_refptr<PendingFrameCreate> create(it->second);
Balazs Engedyba034e72017-10-27 22:26:281211 frame->BindFrame(it->second->browser_info(), it->second->TakeFrameRequest());
ben76f52b242016-06-18 05:42:481212 pending_frame_creates_.erase(it);
[email protected]c1f50aa2010-02-18 03:46:571213}
1214
avi1023d012015-12-25 02:39:141215void RenderThreadImpl::RemoveRoute(int32_t routing_id) {
jam8a021512a2015-02-03 18:16:081216 ChildThreadImpl::GetRouter()->RemoveRoute(routing_id);
[email protected]c1f50aa2010-02-18 03:46:571217}
[email protected]0ec90d522014-03-12 16:28:191218
ben76f52b242016-06-18 05:42:481219void RenderThreadImpl::RegisterPendingFrameCreate(
benf28ce882017-05-02 16:15:491220 const service_manager::BindSourceInfo& browser_info,
rockotf8fdd9b2015-12-16 22:22:351221 int routing_id,
Balazs Engedyba034e72017-10-27 22:26:281222 mojom::FrameRequest frame_request) {
ben76f52b242016-06-18 05:42:481223 std::pair<PendingFrameCreateMap::iterator, bool> result =
1224 pending_frame_creates_.insert(std::make_pair(
kylechar96f3eba2017-09-25 20:23:561225 routing_id, base::MakeRefCounted<PendingFrameCreate>(
Balazs Engedyba034e72017-10-27 22:26:281226 browser_info, routing_id, std::move(frame_request))));
rockotf8fdd9b2015-12-16 22:22:351227 CHECK(result.second) << "Inserting a duplicate item.";
1228}
1229
leon.han06e55662016-03-26 17:19:421230mojom::StoragePartitionService* RenderThreadImpl::GetStoragePartitionService() {
jamc912ca32016-02-24 20:17:311231 return storage_partition_service_.get();
1232}
1233
jam188f19f2017-06-07 03:56:241234mojom::RendererHost* RenderThreadImpl::GetRendererHost() {
Nicholas Verne06de8122017-11-16 04:47:381235 if (!renderer_host_) {
Joel Hockey3146d142017-11-15 22:27:401236 GetChannel()->GetRemoteAssociatedInterface(&renderer_host_);
Nicholas Verne06de8122017-11-16 04:47:381237 }
jam188f19f2017-06-07 03:56:241238 return renderer_host_.get();
1239}
1240
[email protected]77fc9b92011-10-15 16:20:371241int RenderThreadImpl::GenerateRoutingID() {
rockote261d2112016-09-21 22:22:231242 int32_t routing_id = MSG_ROUTING_NONE;
1243 render_message_filter()->GenerateRoutingID(&routing_id);
[email protected]77fc9b92011-10-15 16:20:371244 return routing_id;
1245}
1246
[email protected]74122042014-04-25 00:07:301247void RenderThreadImpl::AddFilter(IPC::MessageFilter* filter) {
[email protected]42f1d7822009-07-23 18:17:551248 channel()->AddFilter(filter);
1249}
1250
[email protected]74122042014-04-25 00:07:301251void RenderThreadImpl::RemoveFilter(IPC::MessageFilter* filter) {
[email protected]42f1d7822009-07-23 18:17:551252 channel()->RemoveFilter(filter);
1253}
1254
tyoshino832a58a2016-04-18 08:14:081255void RenderThreadImpl::AddObserver(RenderThreadObserver* observer) {
[email protected]526476902011-10-06 20:34:061256 observers_.AddObserver(observer);
nigeltao7cd8d5582016-12-12 06:05:281257 observer->RegisterMojoInterfaces(&associated_interfaces_);
[email protected]526476902011-10-06 20:34:061258}
1259
tyoshino832a58a2016-04-18 08:14:081260void RenderThreadImpl::RemoveObserver(RenderThreadObserver* observer) {
nigeltao7cd8d5582016-12-12 06:05:281261 observer->UnregisterMojoInterfaces(&associated_interfaces_);
[email protected]526476902011-10-06 20:34:061262 observers_.RemoveObserver(observer);
1263}
1264
[email protected]359dfa32011-10-12 01:10:151265void RenderThreadImpl::SetResourceDispatcherDelegate(
[email protected]e9ff79c2012-10-19 21:31:261266 ResourceDispatcherDelegate* delegate) {
John Abd-El-Malek6b56ef712017-10-21 22:52:461267 resource_dispatcher_->set_delegate(delegate);
[email protected]359dfa32011-10-12 01:10:151268}
1269
vollick1050cc62015-12-03 07:04:541270void RenderThreadImpl::InitializeCompositorThread() {
Alexander Timin053b6192018-03-15 14:13:341271 blink::WebThreadCreationParams params(
1272 blink::WebThreadType::kCompositorThread);
vollick1050cc62015-12-03 07:04:541273#if defined(OS_ANDROID)
Alexander Timin053b6192018-03-15 14:13:341274 params.thread_options.priority = base::ThreadPriority::DISPLAY;
vollick1050cc62015-12-03 07:04:541275#endif
altiminc7369bf2017-04-11 14:29:151276 compositor_thread_ =
Alexander Timin053b6192018-03-15 14:13:341277 blink::scheduler::WebThreadBase::CreateCompositorThread(params);
boliu66024c62016-04-20 04:00:411278 blink_platform_impl_->SetCompositorThread(compositor_thread_.get());
Yuta Kitamura5ee2b9b2018-02-14 09:00:311279 compositor_task_runner_ = compositor_thread_->GetTaskRunner();
boliu66024c62016-04-20 04:00:411280 compositor_task_runner_->PostTask(
1281 FROM_HERE,
tzikff2a81a2017-09-15 05:10:061282 base::BindOnce(base::IgnoreResult(&ThreadRestrictions::SetIOAllowed),
1283 false));
Sadrul Habib Chowdhury16b3a162018-02-03 01:43:181284 GetContentClient()->renderer()->PostCompositorThreadCreated(
1285 compositor_task_runner_.get());
reveman7b97c322016-09-20 02:10:581286#if defined(OS_LINUX)
Nicholas Verne84dc55e2017-11-23 01:02:381287 render_message_filter()->SetThreadPriority(compositor_thread_->ThreadId(),
1288 base::ThreadPriority::DISPLAY);
reveman7b97c322016-09-20 02:10:581289#endif
vollick1050cc62015-12-03 07:04:541290}
1291
jam75c44222016-03-23 05:34:241292void RenderThreadImpl::InitializeWebKit(
Stuart Langley7b8dc772017-10-31 03:55:201293 const scoped_refptr<base::SingleThreadTaskRunner>& resource_task_queue,
Ken Rockot510c5972017-12-05 16:37:041294 service_manager::BinderRegistry* registry) {
jam75c44222016-03-23 05:34:241295 DCHECK(!blink_platform_impl_);
[email protected]d1b8fccc2011-08-03 01:20:131296
avi83883c82014-12-23 00:08:491297 const base::CommandLine& command_line =
1298 *base::CommandLine::ForCurrentProcess();
chunyang.daibe874c52014-11-14 06:45:051299
1300#ifdef ENABLE_VTUNE_JIT_INTERFACE
1301 if (command_line.HasSwitch(switches::kEnableVtune))
1302 gin::Debug::SetJitCodeEventHandler(vTune::GetVtuneCodeEventHandler());
1303#endif
1304
Reilly Grant9944f162017-08-29 01:22:411305 blink_platform_impl_.reset(
Yuta Kitamura3331f5c2018-04-05 11:12:251306 new RendererBlinkPlatformImpl(main_thread_scheduler_.get()));
rmcilroy4073ae12015-01-08 13:08:101307 SetRuntimeFeaturesDefaultsAndUpdateFromArgs(command_line);
hlopko852ffcf2016-09-16 16:50:591308 GetContentClient()
1309 ->renderer()
1310 ->SetRuntimeFeaturesDefaultsBeforeBlinkInitialization();
Ken Rockot510c5972017-12-05 16:37:041311 blink::Initialize(blink_platform_impl_.get(), registry);
[email protected]d1b8fccc2011-08-03 01:20:131312
Blink Reformat1c4d759e2017-04-09 16:34:541313 v8::Isolate* isolate = blink::MainThreadIsolate();
[email protected]4b5340282014-07-08 11:37:341314 isolate->SetCreateHistogramFunction(CreateHistogram);
1315 isolate->SetAddHistogramSampleFunction(AddHistogramSample);
Yuta Kitamura3331f5c2018-04-05 11:12:251316 main_thread_scheduler_->SetRAILModeObserver(this);
[email protected]4b5340282014-07-08 11:37:341317
rmcilroy321f924d2014-11-06 00:56:001318 main_thread_compositor_task_runner_ =
Yuta Kitamura3331f5c2018-04-05 11:12:251319 main_thread_scheduler_->CompositorTaskRunner();
skyostilc30aa402014-10-10 13:49:091320
khushalsagard7178e42017-01-20 01:31:491321 if (!command_line.HasSwitch(switches::kDisableThreadedCompositing))
vollick1050cc62015-12-03 07:04:541322 InitializeCompositorThread();
[email protected]a9fb30aa2011-10-06 06:58:461323
skyostil2d3b5bd2015-05-27 15:40:591324 scoped_refptr<base::SingleThreadTaskRunner> compositor_impl_side_task_runner;
vollick1050cc62015-12-03 07:04:541325 if (compositor_task_runner_)
skyostil2d3b5bd2015-05-27 15:40:591326 compositor_impl_side_task_runner = compositor_task_runner_;
[email protected]7f1f63f2013-03-07 06:07:291327 else
skyostil2d3b5bd2015-05-27 15:40:591328 compositor_impl_side_task_runner = base::ThreadTaskRunnerHandle::Get();
[email protected]1842fe22012-08-13 23:24:351329
[email protected]58436a12012-03-21 17:10:261330 RenderThreadImpl::RegisterSchemes();
1331
xhwang194acae2014-11-12 22:46:331332 RenderMediaClient::Initialize();
1333
Yuta Kitamura3331f5c2018-04-05 11:12:251334 idle_timer_.SetTaskRunner(GetWebMainThreadScheduler()->DefaultTaskRunner());
Hajime Hoshi9b20bab2018-03-07 11:20:341335
ulan4a385192015-11-11 10:59:181336 if (GetContentClient()->renderer()->RunIdleHandlerWhenWidgetsHidden()) {
[email protected]1784b2f2011-11-24 10:53:481337 ScheduleIdleHandler(kLongIdleHandlerDelayMs);
ulan4a385192015-11-11 10:59:181338 } else {
1339 // If we do not track widget visibility, then assume conservatively that
1340 // the isolate is in background. This reduces memory usage.
1341 isolate->IsolateInBackgroundNotification();
1342 }
[email protected]2541d1a2013-07-10 07:33:271343
Hajime Hoshi605413f2018-03-02 11:49:541344 service_worker_message_filter_ = new ServiceWorkerMessageFilter(
Yuta Kitamura3331f5c2018-04-05 11:12:251345 thread_safe_sender(), GetWebMainThreadScheduler()->IPCTaskRunner());
John Abd-El-Maleke1d4de32017-10-21 16:14:291346 AddFilter(service_worker_message_filter_->GetFilter());
1347
Yuta Kitamura3331f5c2018-04-05 11:12:251348 main_thread_scheduler_->SetStoppingWhenBackgroundedEnabled(
Shubhie Panicker11a8e6a2017-09-19 09:29:231349 GetContentClient()->renderer()->AllowStoppingWhenProcessBackgrounded());
jdduke73220f02015-09-04 17:03:511350
reedccf98c52014-10-03 16:40:381351 SkGraphics::SetResourceCacheSingleAllocationByteLimit(
[email protected]dd2c1022014-07-22 23:13:571352 kImageCacheSingleAllocationByteLimit);
1353
reed6e5a72222015-08-06 20:37:161354 // Hook up blink's codecs so skia can call them
reed08cd16372017-02-21 22:11:411355 SkGraphics::SetImageGeneratorFromEncodedDataFactory(
Vladimir Levin325831d2017-08-30 15:03:221356 blink::WebImageGenerator::CreateAsSkImageGenerator);
reed6e5a72222015-08-06 20:37:161357
paritosh.in7e30c902015-04-15 17:04:071358 if (command_line.HasSwitch(switches::kExplicitlyAllowedPorts)) {
1359 std::string allowed_ports =
1360 command_line.GetSwitchValueASCII(switches::kExplicitlyAllowedPorts);
1361 net::SetExplicitlyAllowedPorts(allowed_ports);
1362 }
[email protected]d1b8fccc2011-08-03 01:20:131363}
1364
[email protected]58436a12012-03-21 17:10:261365void RenderThreadImpl::RegisterSchemes() {
mkwst8e94fb32015-05-20 05:05:141366 // chrome:
Blink Reformat1c4d759e2017-04-09 16:34:541367 WebString chrome_scheme(WebString::FromASCII(kChromeUIScheme));
1368 WebSecurityPolicy::RegisterURLSchemeAsDisplayIsolated(chrome_scheme);
1369 WebSecurityPolicy::RegisterURLSchemeAsNotAllowingJavascriptURLs(
mkwst8e94fb32015-05-20 05:05:141370 chrome_scheme);
mkwst8e94fb32015-05-20 05:05:141371
1372 // chrome-devtools:
Blink Reformat1c4d759e2017-04-09 16:34:541373 WebString devtools_scheme(WebString::FromASCII(kChromeDevToolsScheme));
1374 WebSecurityPolicy::RegisterURLSchemeAsDisplayIsolated(devtools_scheme);
meacerce6b66032016-06-02 20:56:051375
1376 // view-source:
Blink Reformat1c4d759e2017-04-09 16:34:541377 WebString view_source_scheme(WebString::FromASCII(kViewSourceScheme));
1378 WebSecurityPolicy::RegisterURLSchemeAsDisplayIsolated(view_source_scheme);
Alex Moshchuk71f485592017-08-16 16:20:001379
1380 // chrome-error:
1381 WebString error_scheme(WebString::FromASCII(kChromeErrorScheme));
1382 WebSecurityPolicy::RegisterURLSchemeAsDisplayIsolated(error_scheme);
1383 WebSecurityPolicy::RegisterURLSchemeAsNotAllowingJavascriptURLs(error_scheme);
[email protected]58436a12012-03-21 17:10:261384}
1385
[email protected]e6e30ac2014-01-13 21:24:391386void RenderThreadImpl::RecordAction(const base::UserMetricsAction& action) {
[email protected]97880c82013-12-04 07:09:211387 Send(new ViewHostMsg_UserMetricsRecordAction(action.str_));
1388}
1389
1390void RenderThreadImpl::RecordComputedAction(const std::string& action) {
[email protected]526476902011-10-06 20:34:061391 Send(new ViewHostMsg_UserMetricsRecordAction(action));
1392}
1393
dchengcedca5612016-04-09 01:40:151394std::unique_ptr<base::SharedMemory>
1395RenderThreadImpl::HostAllocateSharedMemoryBuffer(size_t size) {
sadrulee3ff1f2016-12-09 04:22:011396 return ChildThreadImpl::AllocateSharedMemory(size);
[email protected]00614a82011-10-07 22:39:311397}
1398
[email protected]f1a29a02011-10-06 23:08:441399void RenderThreadImpl::RegisterExtension(v8::Extension* extension) {
Blink Reformat1c4d759e2017-04-09 16:34:541400 WebScriptController::RegisterExtension(extension);
[email protected]526476902011-10-06 20:34:061401}
1402
avi1023d012015-12-25 02:39:141403void RenderThreadImpl::ScheduleIdleHandler(int64_t initial_delay_ms) {
[email protected]6593ae12011-11-14 12:09:441404 idle_notification_delay_in_ms_ = initial_delay_ms;
[email protected]526476902011-10-06 20:34:061405 idle_timer_.Stop();
1406 idle_timer_.Start(FROM_HERE,
[email protected]6593ae12011-11-14 12:09:441407 base::TimeDelta::FromMilliseconds(initial_delay_ms),
[email protected]f1a29a02011-10-06 23:08:441408 this, &RenderThreadImpl::IdleHandler);
[email protected]526476902011-10-06 20:34:061409}
1410
[email protected]f1a29a02011-10-06 23:08:441411void RenderThreadImpl::IdleHandler() {
[email protected]1784b2f2011-11-24 10:53:481412 bool run_in_foreground_tab = (widget_count_ > hidden_widget_count_) &&
[email protected]e9ff79c2012-10-19 21:31:261413 GetContentClient()->renderer()->
[email protected]1784b2f2011-11-24 10:53:481414 RunIdleHandlerWhenWidgetsHidden();
1415 if (run_in_foreground_tab) {
jochen5a32aaf2014-09-26 20:37:431416 if (idle_notifications_to_skip_ > 0) {
1417 --idle_notifications_to_skip_;
1418 } else {
ssid0603ca9f2015-06-09 16:48:081419 ReleaseFreeMemory();
jochen5a32aaf2014-09-26 20:37:431420 }
1421 ScheduleIdleHandler(kLongIdleHandlerDelayMs);
[email protected]1784b2f2011-11-24 10:53:481422 return;
1423 }
[email protected]237a14852012-04-28 02:56:381424
ssid0603ca9f2015-06-09 16:48:081425 ReleaseFreeMemory();
[email protected]526476902011-10-06 20:34:061426
[email protected]26e82322014-01-20 14:18:221427 // Continue the idle timer if the webkit shared timer is not suspended or
1428 // something is left to do.
Alexander Timin4b6152232017-10-17 20:34:061429 bool continue_timer = !webkit_shared_timer_suspended_;
[email protected]26e82322014-01-20 14:18:221430
sullivancd45a3e2014-09-19 14:39:181431 // Schedule next invocation. When the tab is originally hidden, an invocation
1432 // is scheduled for kInitialIdleHandlerDelayMs in
1433 // RenderThreadImpl::WidgetHidden in order to race to a minimal heap.
1434 // After that, idle calls can be much less frequent, so run at a maximum of
1435 // once every kLongIdleHandlerDelayMs.
[email protected]6593ae12011-11-14 12:09:441436 // Dampen the delay using the algorithm (if delay is in seconds):
[email protected]526476902011-10-06 20:34:061437 // delay = delay + 1 / (delay + 2)
1438 // Using floor(delay) has a dampening effect such as:
sullivancd45a3e2014-09-19 14:39:181439 // 30s, 30, 30, 31, 31, 31, 31, 32, 32, ...
[email protected]6593ae12011-11-14 12:09:441440 // If the delay is in milliseconds, the above formula is equivalent to:
1441 // delay_ms / 1000 = delay_ms / 1000 + 1 / (delay_ms / 1000 + 2)
1442 // which is equivalent to
1443 // delay_ms = delay_ms + 1000*1000 / (delay_ms + 2000).
[email protected]26e82322014-01-20 14:18:221444 if (continue_timer) {
sullivancd45a3e2014-09-19 14:39:181445 ScheduleIdleHandler(
1446 std::max(kLongIdleHandlerDelayMs,
1447 idle_notification_delay_in_ms_ +
1448 1000000 / (idle_notification_delay_in_ms_ + 2000)));
[email protected]26e82322014-01-20 14:18:221449
1450 } else {
1451 idle_timer_.Stop();
1452 }
[email protected]526476902011-10-06 20:34:061453
ericwilligers88e69742016-10-17 19:29:551454 for (auto& observer : observers_)
1455 observer.IdleNotification();
[email protected]526476902011-10-06 20:34:061456}
1457
avi1023d012015-12-25 02:39:141458int64_t RenderThreadImpl::GetIdleNotificationDelayInMs() const {
[email protected]6593ae12011-11-14 12:09:441459 return idle_notification_delay_in_ms_;
[email protected]526476902011-10-06 20:34:061460}
1461
[email protected]6593ae12011-11-14 12:09:441462void RenderThreadImpl::SetIdleNotificationDelayInMs(
avi1023d012015-12-25 02:39:141463 int64_t idle_notification_delay_in_ms) {
[email protected]6593ae12011-11-14 12:09:441464 idle_notification_delay_in_ms_ = idle_notification_delay_in_ms;
[email protected]4a7d6392011-09-19 20:55:081465}
1466
[email protected]5b18406362013-06-18 18:46:431467int RenderThreadImpl::PostTaskToAllWebWorkers(const base::Closure& closure) {
kinukoef647412015-12-23 06:10:431468 return WorkerThreadRegistry::Instance()->PostTaskToAllThreads(closure);
[email protected]a9bd323d2013-06-17 20:27:561469}
1470
[email protected]b02f5902012-12-19 07:33:001471bool RenderThreadImpl::ResolveProxy(const GURL& url, std::string* proxy_list) {
1472 bool result = false;
1473 Send(new ViewHostMsg_ResolveProxy(url, &result, proxy_list));
1474 return result;
1475}
1476
[email protected]1784b2f2011-11-24 10:53:481477void RenderThreadImpl::PostponeIdleNotification() {
1478 idle_notifications_to_skip_ = 2;
1479}
1480
dcastagna7f45dada2015-10-19 20:17:351481media::GpuVideoAcceleratorFactories* RenderThreadImpl::GetGpuFactories() {
[email protected]3bb8bb32013-07-11 13:13:031482 DCHECK(IsMainThread());
1483
dcastagna09bd6b32016-02-01 21:54:281484 if (!gpu_factories_.empty()) {
Emircan Uysalerb0f69fcf2018-03-29 03:23:531485 if (!gpu_factories_.back()->CheckContextProviderLost())
Daniele Castagnaa2338842018-03-15 23:23:161486 return gpu_factories_.back().get();
Miguel Casas5e1018052018-01-09 19:17:361487
Daniele Castagnaa2338842018-03-15 23:23:161488 GetMediaThreadTaskRunner()->PostTask(
1489 FROM_HERE,
1490 base::BindOnce(base::IgnoreResult(
1491 &GpuVideoAcceleratorFactoriesImpl::CheckContextLost),
1492 base::Unretained(gpu_factories_.back().get())));
dcastagna09bd6b32016-02-01 21:54:281493 }
dcastagna7f45dada2015-10-19 20:17:351494
tobiasjsca238b3b2015-06-24 22:53:541495 const base::CommandLine* cmd_line = base::CommandLine::ForCurrentProcess();
1496
danakj0b4b94e32016-05-10 22:33:011497 scoped_refptr<gpu::GpuChannelHost> gpu_channel_host =
sadrul6d310fa2016-08-04 02:12:161498 EstablishGpuChannelSync();
danakj0b4b94e32016-05-10 22:33:011499 if (!gpu_channel_host)
1500 return nullptr;
danakj0dd9e1e2016-05-11 22:15:091501 // This context is only used to create textures and mailbox them, so
1502 // use lower limits than the default.
1503 gpu::SharedMemoryLimits limits = gpu::SharedMemoryLimits::ForMailboxContext();
Daniele Castagnaa2338842018-03-15 23:23:161504 bool support_locking = false;
Victor Miura3a4ad4f82017-12-13 06:03:451505 bool support_gles2_interface = true;
1506 bool support_raster_interface = false;
Adrienne Walker436a7752017-08-28 23:33:091507 bool support_oop_rasterization = false;
Justin Novosad7d3d2502018-03-27 18:55:381508 bool support_grcontext = false;
sadrul85cc5d82016-12-20 03:37:411509 scoped_refptr<ui::ContextProviderCommandBuffer> media_context_provider =
Justin Novosad7d3d2502018-03-27 18:55:381510 CreateOffscreenContext(gpu_channel_host, GetGpuMemoryBufferManager(),
1511 limits, support_locking, support_gles2_interface,
1512 support_raster_interface,
1513 support_oop_rasterization, support_grcontext,
1514 ui::command_buffer_metrics::MEDIA_CONTEXT,
1515 kGpuStreamIdMedia, kGpuStreamPriorityMedia);
danakj0b4b94e32016-05-10 22:33:011516
danakj0b4b94e32016-05-10 22:33:011517 const bool enable_video_accelerator =
Zhenyao Mo16d39b82017-12-15 22:48:041518 !cmd_line->HasSwitch(switches::kDisableAcceleratedVideoDecode) &&
1519 (gpu_channel_host->gpu_feature_info()
1520 .status_values[gpu::GPU_FEATURE_TYPE_ACCELERATED_VIDEO_DECODE] ==
1521 gpu::kGpuFeatureStatusEnabled);
Emircan Uysaler08a80852018-04-13 01:13:211522 const bool enable_gpu_memory_buffers =
danakjab9ef4d2017-10-31 23:38:331523 !is_gpu_compositing_disabled_ &&
Emircan Uysaler08a80852018-04-13 01:13:211524#if defined(OS_MACOSX) || defined(OS_LINUX) || defined(OS_WIN)
danakjab9ef4d2017-10-31 23:38:331525 !cmd_line->HasSwitch(switches::kDisableGpuMemoryBufferVideoFrames);
dcastagnab65e6072015-09-05 07:18:421526#else
danakj0b4b94e32016-05-10 22:33:011527 cmd_line->HasSwitch(switches::kEnableGpuMemoryBufferVideoFrames);
Emircan Uysaler08a80852018-04-13 01:13:211528#endif // defined(OS_MACOSX) || defined(OS_LINUX) || defined(OS_WIN)
1529 const bool enable_media_stream_gpu_memory_buffers =
1530 enable_gpu_memory_buffers &&
1531 base::FeatureList::IsEnabled(
1532 features::kWebRtcUseGpuMemoryBufferVideoFrames);
1533 bool enable_video_gpu_memory_buffers = enable_gpu_memory_buffers;
1534#if defined(OS_WIN)
1535 enable_video_gpu_memory_buffers =
1536 enable_video_gpu_memory_buffers &&
1537 (cmd_line->HasSwitch(switches::kEnableGpuMemoryBufferVideoFrames) ||
1538 gpu_channel_host->gpu_info().supports_overlays);
1539#endif // defined(OS_WIN)
dcastagna5077d6d2016-01-27 00:07:051540
Miguel Casas-Sanchez7d464702017-07-29 14:19:211541 media::mojom::VideoEncodeAcceleratorProviderPtr vea_provider;
1542 gpu_->CreateVideoEncodeAcceleratorProvider(mojo::MakeRequest(&vea_provider));
Miguel Casas-Sanchezdaca32562017-07-11 08:05:451543
Miguel Casas-Sanchezcfcca5d52017-07-07 02:32:591544 gpu_factories_.push_back(GpuVideoAcceleratorFactoriesImpl::Create(
danakj0b4b94e32016-05-10 22:33:011545 std::move(gpu_channel_host), base::ThreadTaskRunnerHandle::Get(),
Daniele Castagnaa2338842018-03-15 23:23:161546 GetMediaThreadTaskRunner(), std::move(media_context_provider),
Emircan Uysaler08a80852018-04-13 01:13:211547 enable_video_gpu_memory_buffers, enable_media_stream_gpu_memory_buffers,
1548 enable_video_accelerator, vea_provider.PassInterface()));
Miguel Casas5e1018052018-01-09 19:17:361549 gpu_factories_.back()->SetRenderingColorSpace(rendering_color_space_);
leon.han21e0e482017-02-23 04:13:321550 return gpu_factories_.back().get();
[email protected]3bb8bb32013-07-11 13:13:031551}
1552
sadrul85cc5d82016-12-20 03:37:411553scoped_refptr<ui::ContextProviderCommandBuffer>
[email protected]f10dc472013-09-27 03:31:591554RenderThreadImpl::SharedMainThreadContextProvider() {
[email protected]e06e1122013-03-15 17:12:381555 DCHECK(IsMainThread());
danakje8ec797e2016-04-19 04:08:431556 if (shared_main_thread_contexts_ &&
1557 shared_main_thread_contexts_->ContextGL()->GetGraphicsResetStatusKHR() ==
1558 GL_NO_ERROR)
1559 return shared_main_thread_contexts_;
1560
sadrul6d310fa2016-08-04 02:12:161561 scoped_refptr<gpu::GpuChannelHost> gpu_channel_host(
1562 EstablishGpuChannelSync());
danakje8ec797e2016-04-19 04:08:431563 if (!gpu_channel_host) {
1564 shared_main_thread_contexts_ = nullptr;
1565 return nullptr;
[email protected]c29b7ff2013-03-06 03:51:041566 }
danakje8ec797e2016-04-19 04:08:431567
danakj9a04adc2016-05-16 22:45:071568 bool support_locking = false;
Victor Miura3a4ad4f82017-12-13 06:03:451569 bool support_gles2_interface = true;
Jonathan Backerf0d615dc2018-03-12 21:05:461570 bool support_raster_interface = false;
Adrienne Walker436a7752017-08-28 23:33:091571 bool support_oop_rasterization = false;
Justin Novosad7d3d2502018-03-27 18:55:381572 bool support_grcontext = true;
danakjc3983552016-05-03 00:04:351573 shared_main_thread_contexts_ = CreateOffscreenContext(
Antoine Labour5ac65db2017-12-19 18:02:581574 std::move(gpu_channel_host), GetGpuMemoryBufferManager(),
1575 gpu::SharedMemoryLimits(), support_locking, support_gles2_interface,
Justin Novosad7d3d2502018-03-27 18:55:381576 support_raster_interface, support_oop_rasterization, support_grcontext,
sadrul85cc5d82016-12-20 03:37:411577 ui::command_buffer_metrics::RENDERER_MAINTHREAD_CONTEXT,
sunnyps8f9139e2017-05-12 17:53:251578 kGpuStreamIdDefault, kGpuStreamPriorityDefault);
danakj45cfd232017-10-18 19:31:311579 auto result = shared_main_thread_contexts_->BindToCurrentThread();
1580 if (result != gpu::ContextResult::kSuccess)
danakje8ec797e2016-04-19 04:08:431581 shared_main_thread_contexts_ = nullptr;
[email protected]f10dc472013-09-27 03:31:591582 return shared_main_thread_contexts_;
[email protected]c29b7ff2013-03-06 03:51:041583}
1584
siva.gunturi5d4feb052015-11-15 16:15:311585#if defined(OS_ANDROID)
boliuf8753bf62016-02-11 20:09:421586
siva.gunturi5d4feb052015-11-15 16:15:311587scoped_refptr<StreamTextureFactory> RenderThreadImpl::GetStreamTexureFactory() {
1588 DCHECK(IsMainThread());
boliu30f1b262016-04-19 00:12:331589 if (!stream_texture_factory_.get() ||
1590 stream_texture_factory_->ContextGL()->GetGraphicsResetStatusKHR() !=
1591 GL_NO_ERROR) {
sadrul85cc5d82016-12-20 03:37:411592 scoped_refptr<ui::ContextProviderCommandBuffer> shared_context_provider =
piman9fc22f32016-05-02 22:21:221593 SharedMainThreadContextProvider();
1594 if (!shared_context_provider) {
penghuange1d86512016-07-08 18:15:001595 stream_texture_factory_ = nullptr;
1596 return nullptr;
siva.gunturi5d4feb052015-11-15 16:15:311597 }
piman9fc22f32016-05-02 22:21:221598 DCHECK(shared_context_provider->GetCommandBufferProxy());
1599 DCHECK(shared_context_provider->GetCommandBufferProxy()->channel());
1600 stream_texture_factory_ =
1601 StreamTextureFactory::Create(std::move(shared_context_provider));
siva.gunturi5d4feb052015-11-15 16:15:311602 }
1603 return stream_texture_factory_;
1604}
boliuf8753bf62016-02-11 20:09:421605
1606bool RenderThreadImpl::EnableStreamTextureCopy() {
Dave Tapuska63aa4622018-02-25 21:42:561607 return GetContentClient()->UsingSynchronousCompositing();
boliuf8753bf62016-02-11 20:09:421608}
1609
siva.gunturi5d4feb052015-11-15 16:15:311610#endif
1611
[email protected]e9ff79c2012-10-19 21:31:261612AudioRendererMixerManager* RenderThreadImpl::GetAudioRendererMixerManager() {
[email protected]59383c782013-04-17 16:43:271613 if (!audio_renderer_mixer_manager_) {
olka7a4679392016-05-27 15:32:581614 audio_renderer_mixer_manager_ = AudioRendererMixerManager::Create();
[email protected]3958e972012-07-17 00:25:411615 }
1616
1617 return audio_renderer_mixer_manager_.get();
1618}
1619
[email protected]73429ca2014-03-06 06:07:471620base::WaitableEvent* RenderThreadImpl::GetShutdownEvent() {
1621 return ChildProcess::current()->GetShutDownEvent();
1622}
1623
staraz067f58242016-11-07 21:06:411624int32_t RenderThreadImpl::GetClientId() {
1625 return client_id_;
1626}
1627
Karan Bhatiac89897f2017-08-10 01:06:401628void RenderThreadImpl::SetRendererProcessType(
1629 blink::scheduler::RendererProcessType type) {
Yuta Kitamura3331f5c2018-04-05 11:12:251630 main_thread_scheduler_->SetRendererProcessType(type);
Karan Bhatiac89897f2017-08-10 01:06:401631}
1632
John Abd-El-Malek6b56ef712017-10-21 22:52:461633bool RenderThreadImpl::OnMessageReceived(const IPC::Message& msg) {
John Abd-El-Malekdcf1d1372017-10-22 06:39:411634 if (file_system_dispatcher_->OnMessageReceived(msg))
1635 return true;
John Abd-El-Malek6b56ef712017-10-21 22:52:461636 return ChildThreadImpl::OnMessageReceived(msg);
1637}
1638
rockot067ca55f2016-09-30 22:00:151639void RenderThreadImpl::OnAssociatedInterfaceRequest(
1640 const std::string& name,
1641 mojo::ScopedInterfaceEndpointHandle handle) {
rockot70bbb59492017-01-25 00:56:511642 if (associated_interfaces_.CanBindRequest(name))
1643 associated_interfaces_.BindRequest(name, std::move(handle));
1644 else
1645 ChildThreadImpl::OnAssociatedInterfaceRequest(name, std::move(handle));
rockot067ca55f2016-09-30 22:00:151646}
1647
weilifabbf7572017-05-22 19:05:161648scoped_refptr<base::SingleThreadTaskRunner>
1649RenderThreadImpl::GetIOTaskRunner() {
1650 return ChildProcess::current()->io_task_runner();
1651}
1652
danakj6e3bf8012014-12-16 18:27:531653bool RenderThreadImpl::IsGpuRasterizationForced() {
1654 return is_gpu_rasterization_forced_;
1655}
1656
senorblancob60ba952015-01-27 19:12:361657int RenderThreadImpl::GetGpuRasterizationMSAASampleCount() {
1658 return gpu_rasterization_msaa_sample_count_;
1659}
1660
danakj6e3bf8012014-12-16 18:27:531661bool RenderThreadImpl::IsLcdTextEnabled() {
1662 return is_lcd_text_enabled_;
1663}
1664
danakj6e3bf8012014-12-16 18:27:531665bool RenderThreadImpl::IsZeroCopyEnabled() {
1666 return is_zero_copy_enabled_;
1667}
1668
ericrk1d17f752015-10-20 03:03:071669bool RenderThreadImpl::IsPartialRasterEnabled() {
1670 return is_partial_raster_enabled_;
jbroman5f7f71932015-08-18 16:24:461671}
1672
ccameronc7fcd132015-11-03 20:14:311673bool RenderThreadImpl::IsGpuMemoryBufferCompositorResourcesEnabled() {
1674 return is_gpu_memory_buffer_compositor_resources_enabled_;
1675}
1676
ccamerona7644752014-12-30 01:16:311677bool RenderThreadImpl::IsElasticOverscrollEnabled() {
1678 return is_elastic_overscroll_enabled_;
1679}
1680
danakj6e3bf8012014-12-16 18:27:531681scoped_refptr<base::SingleThreadTaskRunner>
1682RenderThreadImpl::GetCompositorMainThreadTaskRunner() {
1683 return main_thread_compositor_task_runner_;
1684}
1685
1686scoped_refptr<base::SingleThreadTaskRunner>
1687RenderThreadImpl::GetCompositorImplThreadTaskRunner() {
skyostil2d3b5bd2015-05-27 15:40:591688 return compositor_task_runner_;
danakj6e3bf8012014-12-16 18:27:531689}
1690
1691gpu::GpuMemoryBufferManager* RenderThreadImpl::GetGpuMemoryBufferManager() {
sadrul53546592016-12-17 01:44:211692 return gpu_->gpu_memory_buffer_manager();
danakj6e3bf8012014-12-16 18:27:531693}
1694
Yuta Kitamura3331f5c2018-04-05 11:12:251695blink::scheduler::WebMainThreadScheduler*
1696RenderThreadImpl::GetWebMainThreadScheduler() {
1697 return main_thread_scheduler_.get();
danakj6e3bf8012014-12-16 18:27:531698}
1699
Fady Samuelc645ffe2017-07-24 17:28:201700std::unique_ptr<viz::SyntheticBeginFrameSource>
samans09812d32017-03-27 19:51:501701RenderThreadImpl::CreateSyntheticBeginFrameSource() {
1702 base::SingleThreadTaskRunner* compositor_impl_side_task_runner =
1703 compositor_task_runner_ ? compositor_task_runner_.get()
1704 : base::ThreadTaskRunnerHandle::Get().get();
Jeremy Roman04f27c372017-10-27 15:20:551705 return std::make_unique<viz::BackToBackBeginFrameSource>(
1706 std::make_unique<viz::DelayBasedTimeSource>(
samans09812d32017-03-27 19:51:501707 compositor_impl_side_task_runner));
1708}
1709
reveman34b7a1522015-03-23 20:27:471710cc::TaskGraphRunner* RenderThreadImpl::GetTaskGraphRunner() {
prashant.nfad657e2016-06-01 07:52:171711 return categorized_worker_pool_->GetTaskGraphRunner();
reveman34b7a1522015-03-23 20:27:471712}
1713
loyso65c93c602015-08-11 05:15:571714bool RenderThreadImpl::IsThreadedAnimationEnabled() {
1715 return is_threaded_animation_enabled_;
1716}
1717
wjmaclean1d970622017-01-21 22:28:241718bool RenderThreadImpl::IsScrollAnimatorEnabled() {
1719 return is_scroll_animator_enabled_;
1720}
1721
Khushal3e96e662017-10-30 23:16:501722std::unique_ptr<cc::UkmRecorderFactory>
1723RenderThreadImpl::CreateUkmRecorderFactory() {
Khushalda50f8152017-12-01 09:04:401724 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
1725 switches::kDisableCompositorUkmForTests)) {
1726 return nullptr;
1727 }
1728
1729 return std::make_unique<UkmRecorderFactoryImpl>(GetConnector()->Clone());
Khushal3e96e662017-10-30 23:16:501730}
1731
skyostila37c2a72016-06-29 17:30:071732void RenderThreadImpl::OnRAILModeChanged(v8::RAILMode rail_mode) {
Blink Reformat1c4d759e2017-04-09 16:34:541733 blink::MainThreadIsolate()->SetRAILMode(rail_mode);
1734 blink::SetRAILModeOnWorkerThreadIsolates(rail_mode);
skyostila37c2a72016-06-29 17:30:071735}
1736
[email protected]b3e83de2012-02-07 03:33:281737bool RenderThreadImpl::IsMainThread() {
1738 return !!current();
1739}
1740
torne88b66452016-05-03 13:22:141741void RenderThreadImpl::OnChannelError() {
1742 // In single-process mode, the renderer can't be restarted after shutdown.
1743 // So, if we get a channel error, crash the whole process right now to get a
1744 // more informative stack, since we will otherwise just crash later when we
1745 // try to restart it.
1746 CHECK(!base::CommandLine::ForCurrentProcess()->HasSwitch(
1747 switches::kSingleProcess));
1748 ChildThreadImpl::OnChannelError();
1749}
1750
Nicholas Verne06de8122017-11-16 04:47:381751void RenderThreadImpl::OnProcessFinalRelease() {
1752 if (on_channel_error_called())
1753 return;
1754 // The child process shutdown sequence is a request response based mechanism,
1755 // where we send out an initial feeler request to the child process host
1756 // instance in the browser to verify if it's ok to shutdown the child process.
1757 // The browser then sends back a response if it's ok to shutdown. This avoids
1758 // race conditions if the process refcount is 0 but there's an IPC message
1759 // inflight that would addref it.
1760 GetRendererHost()->ShutdownRequest();
1761}
1762
[email protected]f1a29a02011-10-06 23:08:441763bool RenderThreadImpl::OnControlMessageReceived(const IPC::Message& msg) {
dchenga2d442c22016-10-13 15:39:211764 for (auto& observer : observers_) {
1765 if (observer.OnControlMessageReceived(msg))
[email protected]1223d6ef2011-03-28 16:47:501766 return true;
1767 }
1768
[email protected]70c19a932010-05-14 12:59:111769 // Some messages are handled by delegates.
Nicholas Verne07e9c6452017-12-13 04:12:551770 if (dom_storage_dispatcher_->OnMessageReceived(msg)) {
[email protected]a95986a82010-12-24 06:19:281771 return true;
[email protected]1910fe82012-05-10 00:04:101772 }
Darin Fisherbcc33632017-09-26 00:57:161773 return false;
initial.commit09911bf2008-07-26 23:55:291774}
1775
Shubhie Panicker45ce80a82018-02-01 01:40:191776void RenderThreadImpl::SetSchedulerKeepActive(bool keep_active) {
Yuta Kitamura3331f5c2018-04-05 11:12:251777 main_thread_scheduler_->SetSchedulerKeepActive(keep_active);
Shubhie Panicker45ce80a82018-02-01 01:40:191778}
1779
Nicholas Verne5420564d2017-10-27 07:37:541780void RenderThreadImpl::SetProcessBackgrounded(bool backgrounded) {
1781 // Set timer slack to maximum on main thread when in background.
1782 base::TimerSlack timer_slack = base::TIMER_SLACK_NONE;
1783 if (backgrounded)
1784 timer_slack = base::TIMER_SLACK_MAXIMUM;
Gabriel Charette08fd6532018-04-04 19:47:161785 main_message_loop_->SetTimerSlack(timer_slack);
jdduke73220f02015-09-04 17:03:511786
Yuta Kitamura3331f5c2018-04-05 11:12:251787 main_thread_scheduler_->SetRendererBackgrounded(backgrounded);
hajimehoshi69093272016-05-13 08:30:581788 if (backgrounded) {
tasakb95dbb50c2017-02-08 18:07:501789 needs_to_record_first_active_paint_ = false;
Yuta Kitamura3331f5c2018-04-05 11:12:251790 GetWebMainThreadScheduler()->DefaultTaskRunner()->PostDelayedTask(
tasak335a1872017-06-14 09:50:231791 FROM_HERE,
tzikff2a81a2017-09-15 05:10:061792 base::BindOnce(&RenderThreadImpl::RecordMemoryUsageAfterBackgrounded,
1793 base::Unretained(this), "5min",
1794 process_foregrounded_count_),
tasak335a1872017-06-14 09:50:231795 base::TimeDelta::FromMinutes(5));
Yuta Kitamura3331f5c2018-04-05 11:12:251796 GetWebMainThreadScheduler()->DefaultTaskRunner()->PostDelayedTask(
tasak335a1872017-06-14 09:50:231797 FROM_HERE,
tzikff2a81a2017-09-15 05:10:061798 base::BindOnce(&RenderThreadImpl::RecordMemoryUsageAfterBackgrounded,
1799 base::Unretained(this), "10min",
1800 process_foregrounded_count_),
tasak335a1872017-06-14 09:50:231801 base::TimeDelta::FromMinutes(10));
Yuta Kitamura3331f5c2018-04-05 11:12:251802 GetWebMainThreadScheduler()->DefaultTaskRunner()->PostDelayedTask(
tasak335a1872017-06-14 09:50:231803 FROM_HERE,
tzikff2a81a2017-09-15 05:10:061804 base::BindOnce(&RenderThreadImpl::RecordMemoryUsageAfterBackgrounded,
1805 base::Unretained(this), "15min",
1806 process_foregrounded_count_),
tasak335a1872017-06-14 09:50:231807 base::TimeDelta::FromMinutes(15));
Takashi SAKAMOTO870f6262017-08-22 04:08:271808 was_backgrounded_time_ = base::TimeTicks::Now();
hajimehoshi69093272016-05-13 08:30:581809 } else {
tasakbb0640b2017-05-15 09:02:261810 process_foregrounded_count_++;
hajimehoshi69093272016-05-13 08:30:581811 }
1812}
1813
Nicholas Verne5420564d2017-10-27 07:37:541814void RenderThreadImpl::ProcessPurgeAndSuspend() {
tasak6ff44032016-11-07 06:45:251815 if (!RendererIsHidden())
hajimehoshi69093272016-05-13 08:30:581816 return;
tasakff1e62422016-12-22 04:53:551817
tasakc4de4672017-04-26 02:37:361818 if (!base::FeatureList::IsEnabled(features::kPurgeAndSuspend))
1819 return;
1820
1821 base::MemoryCoordinatorClientRegistry::GetInstance()->PurgeMemory();
tasakb95dbb50c2017-02-08 18:07:501822 needs_to_record_first_active_paint_ = true;
tasakc4de4672017-04-26 02:37:361823
1824 RendererMemoryMetrics memory_metrics;
1825 if (!GetRendererMemoryMetrics(&memory_metrics))
1826 return;
1827
1828 purge_and_suspend_memory_metrics_ = memory_metrics;
Yuta Kitamura3331f5c2018-04-05 11:12:251829 GetWebMainThreadScheduler()->DefaultTaskRunner()->PostDelayedTask(
tasaka27961a2017-05-24 07:33:251830 FROM_HERE,
tzikff2a81a2017-09-15 05:10:061831 base::BindOnce(
1832 &RenderThreadImpl::RecordPurgeAndSuspendMemoryGrowthMetrics,
1833 base::Unretained(this), "30min", process_foregrounded_count_),
tasaka27961a2017-05-24 07:33:251834 base::TimeDelta::FromMinutes(30));
Yuta Kitamura3331f5c2018-04-05 11:12:251835 GetWebMainThreadScheduler()->DefaultTaskRunner()->PostDelayedTask(
tasaka27961a2017-05-24 07:33:251836 FROM_HERE,
tzikff2a81a2017-09-15 05:10:061837 base::BindOnce(
1838 &RenderThreadImpl::RecordPurgeAndSuspendMemoryGrowthMetrics,
1839 base::Unretained(this), "60min", process_foregrounded_count_),
tasaka27961a2017-05-24 07:33:251840 base::TimeDelta::FromMinutes(60));
Yuta Kitamura3331f5c2018-04-05 11:12:251841 GetWebMainThreadScheduler()->DefaultTaskRunner()->PostDelayedTask(
tasaka27961a2017-05-24 07:33:251842 FROM_HERE,
tzikff2a81a2017-09-15 05:10:061843 base::BindOnce(
1844 &RenderThreadImpl::RecordPurgeAndSuspendMemoryGrowthMetrics,
1845 base::Unretained(this), "90min", process_foregrounded_count_),
tasaka27961a2017-05-24 07:33:251846 base::TimeDelta::FromMinutes(90));
tasakb46626a2016-10-18 05:54:441847}
1848
bashia0ba0d42017-04-03 08:11:061849bool RenderThreadImpl::GetRendererMemoryMetrics(
keishi51ed0d52017-01-12 10:04:461850 RendererMemoryMetrics* memory_metrics) const {
1851 DCHECK(memory_metrics);
1852
chrisha05e94f22017-04-05 22:06:041853 // Cache this result, as it can change while this code is running, and is used
1854 // as a divisor below.
1855 size_t render_view_count = RenderView::GetRenderViewCount();
1856
1857 // If there are no render views it doesn't make sense to calculate metrics
1858 // right now.
1859 if (render_view_count == 0)
bashia0ba0d42017-04-03 08:11:061860 return false;
1861
keishi51ed0d52017-01-12 10:04:461862 blink::WebMemoryStatistics blink_stats = blink::WebMemoryStatistics::Get();
1863 memory_metrics->partition_alloc_kb =
Blink Reformat1c4d759e2017-04-09 16:34:541864 blink_stats.partition_alloc_total_allocated_bytes / 1024;
1865 memory_metrics->blink_gc_kb =
1866 blink_stats.blink_gc_total_allocated_bytes / 1024;
keishi12b598b92017-06-20 10:25:261867 std::unique_ptr<base::ProcessMetrics> metric(
1868 base::ProcessMetrics::CreateCurrentProcessMetrics());
1869 size_t malloc_usage = metric->GetMallocUsage();
keishi51ed0d52017-01-12 10:04:461870 memory_metrics->malloc_mb = malloc_usage / 1024 / 1024;
1871
1872 discardable_memory::ClientDiscardableSharedMemoryManager::Statistics
1873 discardable_stats = discardable_shared_memory_manager_->GetStatistics();
1874 size_t discardable_usage =
1875 discardable_stats.total_size - discardable_stats.freelist_size;
1876 memory_metrics->discardable_kb = discardable_usage / 1024;
1877
1878 size_t v8_usage = 0;
Blink Reformat1c4d759e2017-04-09 16:34:541879 if (v8::Isolate* isolate = blink::MainThreadIsolate()) {
keishi51ed0d52017-01-12 10:04:461880 v8::HeapStatistics v8_heap_statistics;
1881 isolate->GetHeapStatistics(&v8_heap_statistics);
1882 v8_usage = v8_heap_statistics.total_heap_size();
1883 }
1884 // TODO(tasak): Currently only memory usage of mainThreadIsolate() is
1885 // reported. We should collect memory usages of all isolates using
1886 // memory-infra.
1887 memory_metrics->v8_main_thread_isolate_mb = v8_usage / 1024 / 1024;
Blink Reformat1c4d759e2017-04-09 16:34:541888 size_t total_allocated = blink_stats.partition_alloc_total_allocated_bytes +
1889 blink_stats.blink_gc_total_allocated_bytes +
keishi51ed0d52017-01-12 10:04:461890 malloc_usage + v8_usage + discardable_usage;
1891 memory_metrics->total_allocated_mb = total_allocated / 1024 / 1024;
1892 memory_metrics->non_discardable_total_allocated_mb =
1893 (total_allocated - discardable_usage) / 1024 / 1024;
1894 memory_metrics->total_allocated_per_render_view_mb =
chrisha05e94f22017-04-05 22:06:041895 total_allocated / render_view_count / 1024 / 1024;
bashia0ba0d42017-04-03 08:11:061896
1897 return true;
keishi51ed0d52017-01-12 10:04:461898}
1899
tasak335a1872017-06-14 09:50:231900static void RecordMemoryUsageAfterBackgroundedMB(const char* basename,
1901 const char* suffix,
1902 int memory_usage) {
1903 std::string histogram_name = base::StringPrintf("%s.%s", basename, suffix);
1904 base::UmaHistogramMemoryLargeMB(histogram_name, memory_usage);
1905}
1906
1907void RenderThreadImpl::RecordMemoryUsageAfterBackgrounded(
1908 const char* suffix,
1909 int foregrounded_count) {
1910 // If this renderer is resumed, we should not update UMA.
1911 if (!RendererIsHidden())
1912 return;
1913 // If this renderer was not kept backgrounded for 5/10/15 minutes,
1914 // we should not record current memory usage.
1915 if (foregrounded_count != process_foregrounded_count_)
1916 return;
1917
1918 RendererMemoryMetrics memory_metrics;
1919 if (!GetRendererMemoryMetrics(&memory_metrics))
1920 return;
1921 RecordMemoryUsageAfterBackgroundedMB(
1922 "Memory.Experimental.Renderer.PartitionAlloc.AfterBackgrounded", suffix,
1923 memory_metrics.partition_alloc_kb / 1024);
1924 RecordMemoryUsageAfterBackgroundedMB(
1925 "Memory.Experimental.Renderer.BlinkGC.AfterBackgrounded", suffix,
1926 memory_metrics.blink_gc_kb / 1024);
1927 RecordMemoryUsageAfterBackgroundedMB(
1928 "Memory.Experimental.Renderer.Malloc.AfterBackgrounded", suffix,
1929 memory_metrics.malloc_mb);
1930 RecordMemoryUsageAfterBackgroundedMB(
1931 "Memory.Experimental.Renderer.Discardable.AfterBackgrounded", suffix,
1932 memory_metrics.discardable_kb / 1024);
1933 RecordMemoryUsageAfterBackgroundedMB(
1934 "Memory.Experimental.Renderer.V8MainThreaIsolate.AfterBackgrounded",
1935 suffix, memory_metrics.v8_main_thread_isolate_mb);
1936 RecordMemoryUsageAfterBackgroundedMB(
1937 "Memory.Experimental.Renderer.TotalAllocated.AfterBackgrounded", suffix,
1938 memory_metrics.total_allocated_mb);
1939}
1940
tasak72f64042017-01-19 14:02:531941#define GET_MEMORY_GROWTH(current, previous, allocator) \
1942 (current.allocator > previous.allocator \
1943 ? current.allocator - previous.allocator \
1944 : 0)
1945
tasaka27961a2017-05-24 07:33:251946static void RecordPurgeAndSuspendMemoryGrowthKB(const char* basename,
1947 const char* suffix,
1948 int memory_usage) {
1949 std::string histogram_name = base::StringPrintf("%s.%s", basename, suffix);
1950 base::UmaHistogramMemoryKB(histogram_name, memory_usage);
1951}
tasakbb0640b2017-05-15 09:02:261952
1953void RenderThreadImpl::RecordPurgeAndSuspendMemoryGrowthMetrics(
1954 const char* suffix,
1955 int foregrounded_count_when_purged) {
tasak72f64042017-01-19 14:02:531956 // If this renderer is resumed, we should not update UMA.
1957 if (!RendererIsHidden())
1958 return;
tasakbb0640b2017-05-15 09:02:261959 if (foregrounded_count_when_purged != process_foregrounded_count_)
1960 return;
tasak72f64042017-01-19 14:02:531961
1962 RendererMemoryMetrics memory_metrics;
bashia0ba0d42017-04-03 08:11:061963 if (!GetRendererMemoryMetrics(&memory_metrics))
1964 return;
1965
tasaka27961a2017-05-24 07:33:251966 RecordPurgeAndSuspendMemoryGrowthKB(
tasakbb0640b2017-05-15 09:02:261967 "PurgeAndSuspend.Experimental.MemoryGrowth.PartitionAllocKB", suffix,
tasak72f64042017-01-19 14:02:531968 GET_MEMORY_GROWTH(memory_metrics, purge_and_suspend_memory_metrics_,
1969 partition_alloc_kb));
tasaka27961a2017-05-24 07:33:251970 RecordPurgeAndSuspendMemoryGrowthKB(
tasakbb0640b2017-05-15 09:02:261971 "PurgeAndSuspend.Experimental.MemoryGrowth.BlinkGCKB", suffix,
tasak72f64042017-01-19 14:02:531972 GET_MEMORY_GROWTH(memory_metrics, purge_and_suspend_memory_metrics_,
1973 blink_gc_kb));
tasaka27961a2017-05-24 07:33:251974 RecordPurgeAndSuspendMemoryGrowthKB(
tasakbb0640b2017-05-15 09:02:261975 "PurgeAndSuspend.Experimental.MemoryGrowth.MallocKB", suffix,
tasak72f64042017-01-19 14:02:531976 GET_MEMORY_GROWTH(memory_metrics, purge_and_suspend_memory_metrics_,
tasakbb0640b2017-05-15 09:02:261977 malloc_mb) *
1978 1024);
tasaka27961a2017-05-24 07:33:251979 RecordPurgeAndSuspendMemoryGrowthKB(
tasakbb0640b2017-05-15 09:02:261980 "PurgeAndSuspend.Experimental.MemoryGrowth.DiscardableKB", suffix,
tasak72f64042017-01-19 14:02:531981 GET_MEMORY_GROWTH(memory_metrics, purge_and_suspend_memory_metrics_,
1982 discardable_kb));
tasaka27961a2017-05-24 07:33:251983 RecordPurgeAndSuspendMemoryGrowthKB(
tasakbb0640b2017-05-15 09:02:261984 "PurgeAndSuspend.Experimental.MemoryGrowth.V8MainThreadIsolateKB", suffix,
tasak72f64042017-01-19 14:02:531985 GET_MEMORY_GROWTH(memory_metrics, purge_and_suspend_memory_metrics_,
tasakbb0640b2017-05-15 09:02:261986 v8_main_thread_isolate_mb) *
1987 1024);
tasaka27961a2017-05-24 07:33:251988 RecordPurgeAndSuspendMemoryGrowthKB(
tasakbb0640b2017-05-15 09:02:261989 "PurgeAndSuspend.Experimental.MemoryGrowth.TotalAllocatedKB", suffix,
tasak72f64042017-01-19 14:02:531990 GET_MEMORY_GROWTH(memory_metrics, purge_and_suspend_memory_metrics_,
tasakbb0640b2017-05-15 09:02:261991 total_allocated_mb) *
1992 1024);
jdduke73220f02015-09-04 17:03:511993}
1994
danakjab9ef4d2017-10-31 23:38:331995void RenderThreadImpl::CompositingModeFallbackToSoftware() {
Antoine Labour7fcbc782017-11-14 16:59:581996 gpu_->LoseChannel();
danakjab9ef4d2017-10-31 23:38:331997 is_gpu_compositing_disabled_ = true;
1998}
1999
Bo Liud1ef1c32017-12-08 06:15:502000scoped_refptr<gpu::GpuChannelHost> RenderThreadImpl::EstablishGpuChannelSync() {
[email protected]d13f35d2012-05-18 02:28:152001 TRACE_EVENT0("gpu", "RenderThreadImpl::EstablishGpuChannelSync");
2002
Antoine Labour7fcbc782017-11-14 16:59:582003 scoped_refptr<gpu::GpuChannelHost> gpu_channel =
Bo Liud1ef1c32017-12-08 06:15:502004 gpu_->EstablishGpuChannelSync();
Antoine Labour7fcbc782017-11-14 16:59:582005 if (gpu_channel)
2006 GetContentClient()->SetGpuInfo(gpu_channel->gpu_info());
2007 return gpu_channel;
[email protected]3bf4d532010-03-27 00:23:342008}
2009
danakjc7afae52017-06-20 21:12:412010void RenderThreadImpl::RequestNewLayerTreeFrameSink(
danakj83066a32016-06-21 02:34:492011 int routing_id,
2012 scoped_refptr<FrameSwapMessageQueue> frame_swap_message_queue,
fsamuelcf3002e2017-03-20 23:13:472013 const GURL& url,
jonrossa2ff4f82018-02-16 17:27:462014 const LayerTreeFrameSinkCallback& callback,
2015 mojom::RenderFrameMetadataObserverClientRequest
2016 render_frame_metadata_observer_client_request,
2017 mojom::RenderFrameMetadataObserverPtr render_frame_metadata_observer_ptr) {
danakj946e3172017-11-06 23:46:512018 // Misconfigured bots (eg. crbug.com/780757) could run layout tests on a
2019 // machine where gpu compositing doesn't work. Don't crash in that case.
2020 if (layout_test_mode() && is_gpu_compositing_disabled_) {
2021 LOG(FATAL) << "Layout tests require gpu compositing, but it is disabled.";
2022 return;
2023 }
2024
danakj83066a32016-06-21 02:34:492025 const base::CommandLine& command_line =
2026 *base::CommandLine::ForCurrentProcess();
Xu Xing48e1b322017-09-25 10:48:012027 viz::ClientLayerTreeFrameSink::InitParams params;
Sunny Sachanandani158d26d2017-12-12 19:44:102028 params.compositor_task_runner = compositor_task_runner_;
Xu Xing48e1b322017-09-25 10:48:012029 params.enable_surface_synchronization =
Fady Samuel343a74952017-11-30 14:19:202030 features::IsSurfaceSynchronizationEnabled();
Xu Xing48e1b322017-09-25 10:48:012031 params.local_surface_id_provider =
Jeremy Roman04f27c372017-10-27 15:20:552032 std::make_unique<RendererLocalSurfaceIdProvider>();
Ria Jiang4bbc6182018-02-12 19:02:192033 if (features::IsVizHitTestingDrawQuadEnabled()) {
Gary Klassen2c346fb2018-02-07 18:08:402034 params.hit_test_data_provider =
Ria Jiang28051112018-02-13 16:38:522035 std::make_unique<viz::HitTestDataProviderDrawQuad>(
2036 true /* should_ask_for_child_region */);
sunxd26e9bae2018-03-22 19:32:332037 } else if (features::IsVizHitTestingSurfaceLayerEnabled()) {
2038 params.hit_test_data_provider =
2039 std::make_unique<viz::HitTestDataProviderSurfaceLayer>();
Gary Klassen2c346fb2018-02-07 18:08:402040 }
Fady Samuel0c4b4bf2017-08-22 00:06:462041
Eric Seckler8af8c0e52018-01-17 23:45:532042 // The renderer runs animations and layout for animate_only BeginFrames.
2043 params.wants_animate_only_begin_frames = true;
2044
samans09812d32017-03-27 19:51:502045 // In disable gpu vsync mode, also let the renderer tick as fast as it
2046 // can. The top level begin frame source will also be running as a back
2047 // to back begin frame source, but using a synthetic begin frame source
2048 // here reduces latency when in this mode (at least for frames
2049 // starting--it potentially increases it for input on the other hand.)
samans09812d32017-03-27 19:51:502050 if (command_line.HasSwitch(switches::kDisableGpuVsync) &&
2051 command_line.GetSwitchValueASCII(switches::kDisableGpuVsync) != "gpu") {
Xu Xing48e1b322017-09-25 10:48:012052 params.synthetic_begin_frame_source = CreateSyntheticBeginFrameSource();
samans09812d32017-03-27 19:51:502053 }
2054
sadrul943e3b32016-08-04 18:22:592055#if defined(USE_AURA)
Scott Violet8ff9c302018-02-22 22:28:352056 if (base::FeatureList::IsEnabled(features::kMash)) {
Scott Violet986ac472017-08-10 16:38:342057 if (!RendererWindowTreeClient::Get(routing_id)) {
2058 callback.Run(nullptr);
2059 return;
2060 }
Bo Liud1ef1c32017-12-08 06:15:502061 scoped_refptr<gpu::GpuChannelHost> channel = EstablishGpuChannelSync();
sadrulbe22c4f2017-03-14 06:59:252062 // If the channel could not be established correctly, then return null. This
2063 // would cause the compositor to wait and try again at a later time.
fsamuelcf3002e2017-03-20 23:13:472064 if (!channel) {
2065 callback.Run(nullptr);
2066 return;
2067 }
fsamuel95c974eb2017-03-22 10:00:252068 RendererWindowTreeClient::Get(routing_id)
danakjc7afae52017-06-20 21:12:412069 ->RequestLayerTreeFrameSink(
fsamuel95c974eb2017-03-22 10:00:252070 gpu_->CreateContextProvider(std::move(channel)),
2071 GetGpuMemoryBufferManager(), callback);
fsamuelcf3002e2017-03-20 23:13:472072 return;
danakj83066a32016-06-21 02:34:492073 }
2074#endif
2075
jonrossa2ff4f82018-02-16 17:27:462076 viz::mojom::CompositorFrameSinkRequest compositor_frame_sink_request =
kylecharb82991b2017-10-04 22:40:082077 mojo::MakeRequest(&params.pipes.compositor_frame_sink_info);
jonrossa2ff4f82018-02-16 17:27:462078 viz::mojom::CompositorFrameSinkClientPtr compositor_frame_sink_client;
2079 params.pipes.client_request =
2080 mojo::MakeRequest(&compositor_frame_sink_client);
samansa61ab212017-05-24 12:11:432081
danakjab9ef4d2017-10-31 23:38:332082 if (is_gpu_compositing_disabled_) {
danakj83066a32016-06-21 02:34:492083 DCHECK(!layout_test_mode());
jonrossa2ff4f82018-02-16 17:27:462084 frame_sink_provider_->CreateForWidget(
2085 routing_id, std::move(compositor_frame_sink_request),
2086 std::move(compositor_frame_sink_client),
2087 std::move(render_frame_metadata_observer_client_request),
2088 std::move(render_frame_metadata_observer_ptr));
Xu Xing48e1b322017-09-25 10:48:012089 params.shared_bitmap_manager = shared_bitmap_manager();
Jeremy Roman04f27c372017-10-27 15:20:552090 callback.Run(std::make_unique<viz::ClientLayerTreeFrameSink>(
Xu Xing48e1b322017-09-25 10:48:012091 nullptr, nullptr, &params));
fsamuelcf3002e2017-03-20 23:13:472092 return;
danakj83066a32016-06-21 02:34:492093 }
2094
danakjab9ef4d2017-10-31 23:38:332095 scoped_refptr<gpu::GpuChannelHost> gpu_channel_host =
Bo Liud1ef1c32017-12-08 06:15:502096 EstablishGpuChannelSync();
danakjab9ef4d2017-10-31 23:38:332097 if (!gpu_channel_host) {
2098 // Wait and try again. We may hear that the compositing mode has switched
2099 // to software in the meantime.
2100 callback.Run(nullptr);
2101 return;
2102 }
2103
Victor Miuraff6488612017-12-21 04:16:152104 scoped_refptr<viz::RasterContextProvider> worker_context_provider =
danakj83066a32016-06-21 02:34:492105 SharedCompositorWorkerContextProvider();
2106 if (!worker_context_provider) {
2107 // Cause the compositor to wait and try again.
fsamuelcf3002e2017-03-20 23:13:472108 callback.Run(nullptr);
2109 return;
danakj83066a32016-06-21 02:34:492110 }
2111
2112 // The renderer compositor context doesn't do a lot of stuff, so we don't
2113 // expect it to need a lot of space for commands or transfer. Raster and
2114 // uploads happen on the worker context instead.
2115 gpu::SharedMemoryLimits limits = gpu::SharedMemoryLimits::ForMailboxContext();
2116
2117 // This is for an offscreen context for the compositor. So the default
2118 // framebuffer doesn't need alpha, depth, stencil, antialiasing.
Antoine Labourfeab2392017-12-21 20:28:392119 gpu::ContextCreationAttribs attributes;
danakj83066a32016-06-21 02:34:492120 attributes.alpha_size = -1;
2121 attributes.depth_size = 0;
2122 attributes.stencil_size = 0;
2123 attributes.samples = 0;
2124 attributes.sample_buffers = 0;
2125 attributes.bind_generates_resource = false;
2126 attributes.lose_context_when_out_of_memory = true;
Victor Miura3a4ad4f82017-12-13 06:03:452127 attributes.enable_gles2_interface = true;
2128 attributes.enable_raster_interface = false;
2129 attributes.enable_oop_rasterization = false;
danakj83066a32016-06-21 02:34:492130
2131 constexpr bool automatic_flushes = false;
2132 constexpr bool support_locking = false;
Justin Novosad7d3d2502018-03-27 18:55:382133 constexpr bool support_grcontext = false;
danakj83066a32016-06-21 02:34:492134
sadrul85cc5d82016-12-20 03:37:412135 scoped_refptr<ui::ContextProviderCommandBuffer> context_provider(
2136 new ui::ContextProviderCommandBuffer(
Antoine Labour5ac65db2017-12-19 18:02:582137 gpu_channel_host, GetGpuMemoryBufferManager(), kGpuStreamIdDefault,
2138 kGpuStreamPriorityDefault, gpu::kNullSurfaceHandle, url,
Justin Novosad7d3d2502018-03-27 18:55:382139 automatic_flushes, support_locking, support_grcontext, limits,
2140 attributes, nullptr /* share_context */,
sadrul85cc5d82016-12-20 03:37:412141 ui::command_buffer_metrics::RENDER_COMPOSITOR_CONTEXT));
danakj83066a32016-06-21 02:34:492142
danakj83066a32016-06-21 02:34:492143 if (layout_test_deps_) {
Vladimir Levind29618c2018-04-17 21:49:012144 if (!layout_test_deps_->UseDisplayCompositorPixelDump()) {
2145 callback.Run(layout_test_deps_->CreateLayerTreeFrameSink(
2146 routing_id, std::move(gpu_channel_host), std::move(context_provider),
2147 std::move(worker_context_provider), GetGpuMemoryBufferManager(),
2148 this));
2149 return;
2150 } else if (!params.compositor_task_runner) {
2151 // The frame sink provider expects a compositor task runner, but we might
2152 // not have that if we're running layout tests in single threaded mode.
2153 // Set it to be our thread's task runner instead.
2154 params.compositor_task_runner = GetCompositorMainThreadTaskRunner();
2155 }
danakj83066a32016-06-21 02:34:492156 }
2157
2158#if defined(OS_ANDROID)
Dave Tapuska63aa4622018-02-25 21:42:562159 if (GetContentClient()->UsingSynchronousCompositing()) {
Dave Tapuska04bc5ee92018-04-17 19:03:312160 RenderViewImpl* view = RenderViewImpl::FromRoutingID(routing_id);
2161 if (view) {
Dave Tapuska63aa4622018-02-25 21:42:562162 callback.Run(std::make_unique<SynchronousLayerTreeFrameSink>(
2163 std::move(context_provider), std::move(worker_context_provider),
2164 compositor_task_runner_, GetGpuMemoryBufferManager(),
Dave Tapuska04bc5ee92018-04-17 19:03:312165 sync_message_filter(), routing_id, g_next_layer_tree_frame_sink_id++,
Dave Tapuska63aa4622018-02-25 21:42:562166 std::move(params.synthetic_begin_frame_source),
Dave Tapuska04bc5ee92018-04-17 19:03:312167 view->widget_input_handler_manager()
2168 ->GetSynchronousCompositorRegistry(),
Dave Tapuska63aa4622018-02-25 21:42:562169 std::move(frame_swap_message_queue)));
2170 return;
Dave Tapuska04bc5ee92018-04-17 19:03:312171 } else {
2172 NOTREACHED();
Dave Tapuska63aa4622018-02-25 21:42:562173 }
danakj83066a32016-06-21 02:34:492174 }
2175#endif
jonrossa2ff4f82018-02-16 17:27:462176 frame_sink_provider_->CreateForWidget(
2177 routing_id, std::move(compositor_frame_sink_request),
2178 std::move(compositor_frame_sink_client),
2179 std::move(render_frame_metadata_observer_client_request),
2180 std::move(render_frame_metadata_observer_ptr));
Xu Xing48e1b322017-09-25 10:48:012181 params.gpu_memory_buffer_manager = GetGpuMemoryBufferManager();
Jeremy Roman04f27c372017-10-27 15:20:552182 callback.Run(std::make_unique<viz::ClientLayerTreeFrameSink>(
samans2040988b2017-04-11 23:58:352183 std::move(context_provider), std::move(worker_context_provider),
Xu Xing48e1b322017-09-25 10:48:012184 &params));
danakj83066a32016-06-21 02:34:492185}
2186
Sam McNally52e50282017-11-29 00:54:022187blink::AssociatedInterfaceRegistry*
rockot067ca55f2016-09-30 22:00:152188RenderThreadImpl::GetAssociatedInterfaceRegistry() {
2189 return &associated_interfaces_;
2190}
2191
jbroman6ccbc7d472016-07-27 04:45:412192std::unique_ptr<cc::SwapPromise>
2193RenderThreadImpl::RequestCopyOfOutputForLayoutTest(
2194 int32_t routing_id,
Fady Samueldfecb7d2017-07-26 11:41:042195 std::unique_ptr<viz::CopyOutputRequest> request) {
Vladimir Levind29618c2018-04-17 21:49:012196 DCHECK(layout_test_deps_ &&
2197 !layout_test_deps_->UseDisplayCompositorPixelDump());
jbroman6ccbc7d472016-07-27 04:45:412198 return layout_test_deps_->RequestCopyOfOutput(routing_id, std::move(request));
2199}
2200
altimineb6bd1962017-05-03 14:52:382201std::unique_ptr<blink::WebMediaStreamCenter>
2202RenderThreadImpl::CreateMediaStreamCenter(
[email protected]180ef242013-11-07 06:50:462203 blink::WebMediaStreamCenterClient* client) {
altimineb6bd1962017-05-03 14:52:382204 std::unique_ptr<blink::WebMediaStreamCenter> media_stream_center;
Brett Wilson0748bf412016-11-22 17:55:462205#if BUILDFLAG(ENABLE_WEBRTC)
altimineb6bd1962017-05-03 14:52:382206 if (!media_stream_center) {
Harald Alvestrand4931caa2017-11-08 16:53:352207 media_stream_center = std::make_unique<MediaStreamCenter>(
2208 client, GetPeerConnectionDependencyFactory());
[email protected]68e5fee2013-02-18 10:04:222209 }
[email protected]d8cd8372012-03-09 10:49:512210#endif
altimineb6bd1962017-05-03 14:52:382211 return media_stream_center;
[email protected]d8cd8372012-03-09 10:49:512212}
2213
Brett Wilson0748bf412016-11-22 17:55:462214#if BUILDFLAG(ENABLE_WEBRTC)
[email protected]0107d8a2014-05-16 10:20:342215PeerConnectionDependencyFactory*
2216RenderThreadImpl::GetPeerConnectionDependencyFactory() {
[email protected]83e0a482014-05-22 18:07:182217 return peer_connection_factory_.get();
[email protected]6ee10bd2012-09-13 09:01:532218}
[email protected]22fe91d2014-08-12 17:07:122219#endif
[email protected]6ee10bd2012-09-13 09:01:532220
rockot1587e332016-07-27 17:44:142221mojom::RenderFrameMessageFilter*
2222RenderThreadImpl::render_frame_message_filter() {
2223 if (!render_frame_message_filter_)
2224 GetChannel()->GetRemoteAssociatedInterface(&render_frame_message_filter_);
2225 return render_frame_message_filter_.get();
2226}
2227
rockote261d2112016-09-21 22:22:232228mojom::RenderMessageFilter* RenderThreadImpl::render_message_filter() {
2229 if (!render_message_filter_)
2230 GetChannel()->GetRemoteAssociatedInterface(&render_message_filter_);
2231 return render_message_filter_.get();
2232}
2233
penghuang346a46f92016-03-31 21:37:522234gpu::GpuChannelHost* RenderThreadImpl::GetGpuChannel() {
Antoine Labour7fcbc782017-11-14 16:59:582235 return gpu_->GetGpuChannel().get();
[email protected]6217d392010-03-25 22:08:352236}
2237
Ben Goodger16331302018-01-23 00:43:212238void RenderThreadImpl::CreateEmbedderRendererService(
2239 service_manager::mojom::ServiceRequest service_request) {
2240 GetContentClient()->renderer()->CreateRendererService(
2241 std::move(service_request));
2242}
2243
rockot067ca55f2016-09-30 22:00:152244void RenderThreadImpl::CreateView(mojom::CreateViewParamsPtr params) {
2245 CompositorDependencies* compositor_deps = this;
wjmaclean1d970622017-01-21 22:28:242246 is_scroll_animator_enabled_ = params->web_preferences.enable_scroll_animator;
rockot067ca55f2016-09-30 22:00:152247 // When bringing in render_view, also bring in webkit's glue and jsbindings.
Balazs Engedyba034e72017-10-27 22:26:282248 RenderViewImpl::Create(compositor_deps, std::move(params),
Hajime Hoshiabb3c8f2017-12-04 18:41:392249 RenderWidget::ShowCallback(),
Yuta Kitamura3331f5c2018-04-05 11:12:252250 GetWebMainThreadScheduler()->DefaultTaskRunner());
rockot067ca55f2016-09-30 22:00:152251}
2252
rockot53be7caf2016-10-04 20:17:082253void RenderThreadImpl::CreateFrame(mojom::CreateFrameParamsPtr params) {
rockot53be7caf2016-10-04 20:17:082254 CompositorDependencies* compositor_deps = this;
Ken Rockot26efbd62017-11-16 04:39:492255 service_manager::mojom::InterfaceProviderPtr interface_provider(
2256 std::move(params->interface_provider));
rockot53be7caf2016-10-04 20:17:082257 RenderFrameImpl::CreateFrame(
Ken Rockot26efbd62017-11-16 04:39:492258 params->routing_id, std::move(interface_provider),
Balazs Engedyba034e72017-10-27 22:26:282259 params->proxy_routing_id, params->opener_routing_id,
rockot53be7caf2016-10-04 20:17:082260 params->parent_routing_id, params->previous_sibling_routing_id,
Pavel Feldman25234722017-10-11 02:49:062261 params->devtools_frame_token, params->replication_state, compositor_deps,
Daniel Chenge0555e192018-01-18 20:00:052262 *params->widget_params, params->frame_owner_properties,
2263 params->has_committed_real_load);
rockot53be7caf2016-10-04 20:17:082264}
2265
rockot53be7caf2016-10-04 20:17:082266void RenderThreadImpl::CreateFrameProxy(
2267 int32_t routing_id,
2268 int32_t render_view_routing_id,
2269 int32_t opener_routing_id,
2270 int32_t parent_routing_id,
Dmitry Gozman89361212018-02-13 16:10:442271 const FrameReplicationState& replicated_state,
2272 const base::UnguessableToken& devtools_frame_token) {
nick3b5a21f2016-11-22 23:07:112273 RenderFrameProxy::CreateFrameProxy(
2274 routing_id, render_view_routing_id,
2275 RenderFrameImpl::ResolveOpener(opener_routing_id), parent_routing_id,
Dmitry Gozman89361212018-02-13 16:10:442276 replicated_state, devtools_frame_token);
rockot53be7caf2016-10-04 20:17:082277}
2278
rockota2db0da2016-10-18 17:39:112279void RenderThreadImpl::OnNetworkConnectionChanged(
2280 net::NetworkChangeNotifier::ConnectionType type,
2281 double max_bandwidth_mbps) {
2282 bool online = type != net::NetworkChangeNotifier::CONNECTION_NONE;
Blink Reformat1c4d759e2017-04-09 16:34:542283 WebNetworkStateNotifier::SetOnLine(online);
rockota2db0da2016-10-18 17:39:112284 for (auto& observer : observers_)
2285 observer.NetworkStateChanged(online);
Blink Reformat1c4d759e2017-04-09 16:34:542286 WebNetworkStateNotifier::SetWebConnection(
rockota2db0da2016-10-18 17:39:112287 NetConnectionTypeToWebConnectionType(type), max_bandwidth_mbps);
2288}
2289
tbansal15973c32017-05-10 18:40:442290void RenderThreadImpl::OnNetworkQualityChanged(
tbansalb612c5d2017-05-25 18:53:062291 net::EffectiveConnectionType type,
tbansal99d8aeb2017-05-22 19:12:582292 base::TimeDelta http_rtt,
2293 base::TimeDelta transport_rtt,
tbansal15973c32017-05-10 18:40:442294 double downlink_throughput_kbps) {
2295 UMA_HISTOGRAM_BOOLEAN("NQE.RenderThreadNotified", true);
tbansalb612c5d2017-05-25 18:53:062296 WebNetworkStateNotifier::SetNetworkQuality(
2297 EffectiveConnectionTypeToWebEffectiveConnectionType(type), http_rtt,
2298 transport_rtt, downlink_throughput_kbps);
tbansal15973c32017-05-10 18:40:442299}
2300
rockota2db0da2016-10-18 17:39:112301void RenderThreadImpl::SetWebKitSharedTimersSuspended(bool suspend) {
2302#if defined(OS_ANDROID)
2303 if (suspend) {
Yuta Kitamura3331f5c2018-04-05 11:12:252304 main_thread_scheduler_->PauseTimersForAndroidWebView();
rockota2db0da2016-10-18 17:39:112305 } else {
Yuta Kitamura3331f5c2018-04-05 11:12:252306 main_thread_scheduler_->ResumeTimersForAndroidWebView();
rockota2db0da2016-10-18 17:39:112307 }
Alexander Timin4b6152232017-10-17 20:34:062308 webkit_shared_timer_suspended_ = suspend;
rockota2db0da2016-10-18 17:39:112309#else
2310 NOTREACHED();
2311#endif
2312}
2313
2314void RenderThreadImpl::UpdateScrollbarTheme(
2315 mojom::UpdateScrollbarThemeParamsPtr params) {
2316#if defined(OS_MACOSX)
2317 static_cast<WebScrollbarBehaviorImpl*>(
Blink Reformat1c4d759e2017-04-09 16:34:542318 blink_platform_impl_->ScrollbarBehavior())
rockota2db0da2016-10-18 17:39:112319 ->set_jump_on_track_click(params->jump_on_track_click);
2320
Blink Reformat1c4d759e2017-04-09 16:34:542321 blink::WebScrollbarTheme::UpdateScrollbarsWithNSDefaults(
rockota2db0da2016-10-18 17:39:112322 params->initial_button_delay, params->autoscroll_button_delay,
2323 params->preferred_scroller_style, params->redraw,
2324 params->button_placement);
Greg Kerra7b943b2017-07-24 23:17:172325
2326 is_elastic_overscroll_enabled_ = params->scroll_view_rubber_banding;
rockota2db0da2016-10-18 17:39:112327#else
2328 NOTREACHED();
2329#endif
2330}
2331
2332void RenderThreadImpl::OnSystemColorsChanged(
2333 int32_t aqua_color_variant,
2334 const std::string& highlight_text_color,
2335 const std::string& highlight_color) {
2336#if defined(OS_MACOSX)
2337 SystemColorsDidChange(aqua_color_variant, highlight_text_color,
2338 highlight_color);
2339#else
2340 NOTREACHED();
2341#endif
2342}
2343
2344void RenderThreadImpl::PurgePluginListCache(bool reload_pages) {
brettw4b461082016-11-19 18:55:162345#if BUILDFLAG(ENABLE_PLUGINS)
rockota2db0da2016-10-18 17:39:112346 // The call below will cause a GetPlugins call with refresh=true, but at this
2347 // point we already know that the browser has refreshed its list, so disable
2348 // refresh temporarily to prevent each renderer process causing the list to be
2349 // regenerated.
2350 blink_platform_impl_->set_plugin_refresh_allowed(false);
Blink Reformat1c4d759e2017-04-09 16:34:542351 blink::ResetPluginCache(reload_pages);
rockota2db0da2016-10-18 17:39:112352 blink_platform_impl_->set_plugin_refresh_allowed(true);
2353
2354 for (auto& observer : observers_)
2355 observer.PluginListChanged();
2356#else
2357 NOTREACHED();
2358#endif
2359}
2360
[email protected]5071cb22013-07-10 02:19:062361void RenderThreadImpl::OnMemoryPressure(
2362 base::MemoryPressureListener::MemoryPressureLevel memory_pressure_level) {
kylecharb82991b2017-10-04 22:40:082363 TRACE_EVENT0("memory", "RenderThreadImpl::OnMemoryPressure");
rmcilroy7fbb3bd52015-02-17 19:02:142364 if (blink_platform_impl_) {
Blink Reformat1c4d759e2017-04-09 16:34:542365 blink::WebMemoryCoordinator::OnMemoryPressure(
bashic577bfc2016-01-08 03:42:352366 static_cast<blink::WebMemoryPressureLevel>(memory_pressure_level));
hajimehoshi7bb39582016-10-12 04:30:572367 }
2368 if (memory_pressure_level ==
Gyuyoung Kim7b96fa72018-03-05 01:44:252369 base::MemoryPressureListener::MEMORY_PRESSURE_LEVEL_CRITICAL)
hajimehoshi7bb39582016-10-12 04:30:572370 ReleaseFreeMemory();
hajimehoshi7bb39582016-10-12 04:30:572371}
rmcilroyab967c972015-02-17 23:15:002372
hajimehoshi7bb39582016-10-12 04:30:572373void RenderThreadImpl::OnMemoryStateChange(base::MemoryState state) {
hajimehoshi7bb39582016-10-12 04:30:572374 if (blink_platform_impl_) {
Blink Reformat1c4d759e2017-04-09 16:34:542375 blink::WebMemoryCoordinator::OnMemoryStateChange(
hajimehoshi7bb39582016-10-12 04:30:572376 static_cast<blink::MemoryState>(state));
2377 }
bashi233f65e2017-02-09 08:36:032378}
2379
2380void RenderThreadImpl::OnPurgeMemory() {
bashib9058f282017-03-30 01:55:242381 // Record amount of purged memory after 2 seconds. 2 seconds is arbitrary
2382 // but it works most cases.
2383 RendererMemoryMetrics metrics;
bashia0ba0d42017-04-03 08:11:062384 if (!GetRendererMemoryMetrics(&metrics))
2385 return;
2386
Yuta Kitamura3331f5c2018-04-05 11:12:252387 GetWebMainThreadScheduler()->DefaultTaskRunner()->PostDelayedTask(
bashib9058f282017-03-30 01:55:242388 FROM_HERE,
tzikff2a81a2017-09-15 05:10:062389 base::BindOnce(&RenderThreadImpl::RecordPurgeMemory,
2390 base::Unretained(this), std::move(metrics)),
bashib9058f282017-03-30 01:55:242391 base::TimeDelta::FromSeconds(2));
2392
bashi233f65e2017-02-09 08:36:032393 OnTrimMemoryImmediately();
2394 ReleaseFreeMemory();
bashi233f65e2017-02-09 08:36:032395 if (blink_platform_impl_)
Blink Reformat1c4d759e2017-04-09 16:34:542396 blink::WebMemoryCoordinator::OnPurgeMemory();
hajimehoshi7bb39582016-10-12 04:30:572397}
2398
bashib9058f282017-03-30 01:55:242399void RenderThreadImpl::RecordPurgeMemory(RendererMemoryMetrics before) {
2400 RendererMemoryMetrics after;
bashia0ba0d42017-04-03 08:11:062401 if (!GetRendererMemoryMetrics(&after))
2402 return;
bashib9058f282017-03-30 01:55:242403 int64_t mbytes = static_cast<int64_t>(before.total_allocated_mb) -
2404 static_cast<int64_t>(after.total_allocated_mb);
2405 if (mbytes < 0)
2406 mbytes = 0;
2407 UMA_HISTOGRAM_MEMORY_LARGE_MB("Memory.Experimental.Renderer.PurgedMemory",
2408 mbytes);
2409}
2410
acolwellb4034942014-08-28 15:42:432411scoped_refptr<base::SingleThreadTaskRunner>
2412RenderThreadImpl::GetMediaThreadTaskRunner() {
fdoraye94d8642016-07-07 19:19:012413 DCHECK(message_loop()->task_runner()->BelongsToCurrentThread());
[email protected]c1330c82013-06-06 02:23:252414 if (!media_thread_) {
2415 media_thread_.reset(new base::Thread("Media"));
2416 media_thread_->Start();
2417 }
skyostil2d3b5bd2015-05-27 15:40:592418 return media_thread_->task_runner();
[email protected]c1330c82013-06-06 02:23:252419}
2420
dcastagna4517a182015-08-05 19:51:032421base::TaskRunner* RenderThreadImpl::GetWorkerTaskRunner() {
prashant.nfad657e2016-06-01 07:52:172422 return categorized_worker_pool_.get();
dcastagnab880e8f2015-06-30 20:16:062423}
2424
Victor Miuraff6488612017-12-21 04:16:152425scoped_refptr<viz::RasterContextProvider>
danakj0b4b94e32016-05-10 22:33:012426RenderThreadImpl::SharedCompositorWorkerContextProvider() {
revemand180dfc32015-09-24 00:19:432427 DCHECK(IsMainThread());
2428 // Try to reuse existing shared worker context provider.
revemand180dfc32015-09-24 00:19:432429 if (shared_worker_context_provider_) {
2430 // Note: If context is lost, delete reference after releasing the lock.
Victor Miura29b7ea3d2017-12-19 20:23:592431 viz::RasterContextProvider::ScopedRasterContextLock lock(
boliu11afa7e2016-04-18 18:04:142432 shared_worker_context_provider_.get());
Victor Miura29b7ea3d2017-12-19 20:23:592433 if (lock.RasterInterface()->GetGraphicsResetStatusKHR() == GL_NO_ERROR)
danakje8ec797e2016-04-19 04:08:432434 return shared_worker_context_provider_;
revemand180dfc32015-09-24 00:19:432435 }
danakje8ec797e2016-04-19 04:08:432436
sadrul6d310fa2016-08-04 02:12:162437 scoped_refptr<gpu::GpuChannelHost> gpu_channel_host(
2438 EstablishGpuChannelSync());
danakje8ec797e2016-04-19 04:08:432439 if (!gpu_channel_host) {
2440 shared_worker_context_provider_ = nullptr;
2441 return shared_worker_context_provider_;
revemand180dfc32015-09-24 00:19:432442 }
danakje8ec797e2016-04-19 04:08:432443
danakj9a04adc2016-05-16 22:45:072444 bool support_locking = true;
Adrienne Walker436a7752017-08-28 23:33:092445 bool support_oop_rasterization =
2446 base::CommandLine::ForCurrentProcess()->HasSwitch(
2447 switches::kEnableOOPRasterization);
Victor Miura589575e2018-02-14 21:37:542448 bool support_gles2_interface = !support_oop_rasterization;
Victor Miura3a4ad4f82017-12-13 06:03:452449 bool support_raster_interface = true;
Justin Novosad7d3d2502018-03-27 18:55:382450 bool support_grcontext = !support_oop_rasterization;
danakj0dd9e1e2016-05-11 22:15:092451 shared_worker_context_provider_ = CreateOffscreenContext(
Antoine Labour5ac65db2017-12-19 18:02:582452 std::move(gpu_channel_host), GetGpuMemoryBufferManager(),
2453 gpu::SharedMemoryLimits(), support_locking, support_gles2_interface,
Justin Novosad7d3d2502018-03-27 18:55:382454 support_raster_interface, support_oop_rasterization, support_grcontext,
Victor Miuraff6488612017-12-21 04:16:152455 ui::command_buffer_metrics::RENDER_WORKER_CONTEXT, kGpuStreamIdWorker,
2456 kGpuStreamPriorityWorker);
danakj45cfd232017-10-18 19:31:312457 auto result = shared_worker_context_provider_->BindToCurrentThread();
2458 if (result != gpu::ContextResult::kSuccess)
danakje8ec797e2016-04-19 04:08:432459 shared_worker_context_provider_ = nullptr;
revemand180dfc32015-09-24 00:19:432460 return shared_worker_context_provider_;
2461}
2462
juncai2f298a82017-04-18 03:51:392463void RenderThreadImpl::SampleGamepads(device::Gamepads* data) {
Blink Reformat1c4d759e2017-04-09 16:34:542464 blink_platform_impl_->SampleGamepads(*data);
[email protected]0ff736562014-05-09 09:09:472465}
2466
rmcilroyaa296052015-04-14 15:35:272467bool RenderThreadImpl::RendererIsHidden() const {
2468 return widget_count_ > 0 && hidden_widget_count_ == widget_count_;
2469}
2470
[email protected]b2db9272014-01-10 17:42:002471void RenderThreadImpl::WidgetCreated() {
rmcilroyaa296052015-04-14 15:35:272472 bool renderer_was_hidden = RendererIsHidden();
[email protected]b2db9272014-01-10 17:42:002473 widget_count_++;
rmcilroyaa296052015-04-14 15:35:272474 if (renderer_was_hidden)
2475 OnRendererVisible();
[email protected]b2db9272014-01-10 17:42:002476}
2477
2478void RenderThreadImpl::WidgetDestroyed() {
rmcilroyaa296052015-04-14 15:35:272479 // TODO(rmcilroy): Remove the restriction that destroyed widgets must be
2480 // unhidden before WidgetDestroyed is called.
2481 DCHECK_GT(widget_count_, 0);
2482 DCHECK_GT(widget_count_, hidden_widget_count_);
[email protected]b2db9272014-01-10 17:42:002483 widget_count_--;
rmcilroyaa296052015-04-14 15:35:272484 if (RendererIsHidden())
2485 OnRendererHidden();
[email protected]b2db9272014-01-10 17:42:002486}
2487
2488void RenderThreadImpl::WidgetHidden() {
2489 DCHECK_LT(hidden_widget_count_, widget_count_);
2490 hidden_widget_count_++;
rmcilroyaa296052015-04-14 15:35:272491 if (RendererIsHidden())
2492 OnRendererHidden();
[email protected]b2db9272014-01-10 17:42:002493}
2494
2495void RenderThreadImpl::WidgetRestored() {
rmcilroyaa296052015-04-14 15:35:272496 bool renderer_was_hidden = RendererIsHidden();
[email protected]b2db9272014-01-10 17:42:002497 DCHECK_GT(hidden_widget_count_, 0);
2498 hidden_widget_count_--;
rmcilroyaa296052015-04-14 15:35:272499 if (renderer_was_hidden)
2500 OnRendererVisible();
2501}
[email protected]b2db9272014-01-10 17:42:002502
rmcilroyaa296052015-04-14 15:35:272503void RenderThreadImpl::OnRendererHidden() {
Blink Reformat1c4d759e2017-04-09 16:34:542504 blink::MainThreadIsolate()->IsolateInBackgroundNotification();
rmcilroyaa296052015-04-14 15:35:272505 // TODO(rmcilroy): Remove IdleHandler and replace it with an IdleTask
2506 // scheduled by the RendererScheduler - http://crbug.com/469210.
ulan4a385192015-11-11 10:59:182507 if (!GetContentClient()->renderer()->RunIdleHandlerWhenWidgetsHidden())
2508 return;
Yuta Kitamura3331f5c2018-04-05 11:12:252509 main_thread_scheduler_->SetRendererHidden(true);
ulan4a385192015-11-11 10:59:182510 ScheduleIdleHandler(kInitialIdleHandlerDelayMs);
rmcilroyaa296052015-04-14 15:35:272511}
2512
2513void RenderThreadImpl::OnRendererVisible() {
Blink Reformat1c4d759e2017-04-09 16:34:542514 blink::MainThreadIsolate()->IsolateInForegroundNotification();
rmcilroyaa296052015-04-14 15:35:272515 if (!GetContentClient()->renderer()->RunIdleHandlerWhenWidgetsHidden())
[email protected]b2db9272014-01-10 17:42:002516 return;
Yuta Kitamura3331f5c2018-04-05 11:12:252517 main_thread_scheduler_->SetRendererHidden(false);
[email protected]b2db9272014-01-10 17:42:002518 ScheduleIdleHandler(kLongIdleHandlerDelayMs);
2519}
2520
ssid0603ca9f2015-06-09 16:48:082521void RenderThreadImpl::ReleaseFreeMemory() {
2522 base::allocator::ReleaseFreeMemory();
penghuang342762b2016-12-02 21:04:582523 discardable_shared_memory_manager_->ReleaseFreeMemory();
ssid0603ca9f2015-06-09 16:48:082524
Gyuyoung Kim7b96fa72018-03-05 01:44:252525 // Do not call into blink if it is not initialized.
2526 if (blink_platform_impl_) {
2527 // Purge Skia font cache, resource cache, and image filter.
2528 SkGraphics::PurgeAllCaches();
Blink Reformat1c4d759e2017-04-09 16:34:542529 blink::DecommitFreeableMemory();
Gyuyoung Kim7b96fa72018-03-05 01:44:252530 }
ssid0603ca9f2015-06-09 16:48:082531}
2532
ben76f52b242016-06-18 05:42:482533RenderThreadImpl::PendingFrameCreate::PendingFrameCreate(
benf28ce882017-05-02 16:15:492534 const service_manager::BindSourceInfo& browser_info,
rockotf8fdd9b2015-12-16 22:22:352535 int routing_id,
Balazs Engedyba034e72017-10-27 22:26:282536 mojom::FrameRequest frame_request)
benf28ce882017-05-02 16:15:492537 : browser_info_(browser_info),
2538 routing_id_(routing_id),
Balazs Engedyba034e72017-10-27 22:26:282539 frame_request_(std::move(frame_request)) {}
rockotf8fdd9b2015-12-16 22:22:352540
ben76f52b242016-06-18 05:42:482541RenderThreadImpl::PendingFrameCreate::~PendingFrameCreate() {
rockotf8fdd9b2015-12-16 22:22:352542}
2543
ben76f52b242016-06-18 05:42:482544void RenderThreadImpl::PendingFrameCreate::OnConnectionError() {
rockotf8fdd9b2015-12-16 22:22:352545 size_t erased =
ben76f52b242016-06-18 05:42:482546 RenderThreadImpl::current()->pending_frame_creates_.erase(routing_id_);
rockotf8fdd9b2015-12-16 22:22:352547 DCHECK_EQ(1u, erased);
2548}
2549
hong.zhengb28b5332016-05-11 02:33:392550void RenderThreadImpl::OnSyncMemoryPressure(
2551 base::MemoryPressureListener::MemoryPressureLevel memory_pressure_level) {
Blink Reformat1c4d759e2017-04-09 16:34:542552 if (!blink::MainThreadIsolate())
hong.zhengb28b5332016-05-11 02:33:392553 return;
2554
2555 v8::MemoryPressureLevel v8_memory_pressure_level =
2556 static_cast<v8::MemoryPressureLevel>(memory_pressure_level);
2557
Luke Halliwell16136de2017-07-05 21:15:562558#if !BUILDFLAG(ALLOW_CRITICAL_MEMORY_PRESSURE_HANDLING_IN_FOREGROUND)
hong.zhengb28b5332016-05-11 02:33:392559 // In order to reduce performance impact, translate critical level to
Luke Halliwell16136de2017-07-05 21:15:562560 // moderate level for foreground renderer.
hong.zhengb28b5332016-05-11 02:33:392561 if (!RendererIsHidden() &&
2562 v8_memory_pressure_level == v8::MemoryPressureLevel::kCritical)
2563 v8_memory_pressure_level = v8::MemoryPressureLevel::kModerate;
Luke Halliwell16136de2017-07-05 21:15:562564#endif // !BUILDFLAG(ALLOW_CRITICAL_MEMORY_PRESSURE_HANDLING_IN_FOREGROUND)
hong.zhengb28b5332016-05-11 02:33:392565
Blink Reformat1c4d759e2017-04-09 16:34:542566 blink::MainThreadIsolate()->MemoryPressureNotification(
hong.zhengb28b5332016-05-11 02:33:392567 v8_memory_pressure_level);
2568 blink::MemoryPressureNotificationToWorkerThreadIsolates(
2569 v8_memory_pressure_level);
2570}
2571
bashic4b4afcb2016-08-23 06:37:522572// Note that this would be called only when memory_coordinator is enabled.
2573// OnSyncMemoryPressure() is never called in that case.
2574void RenderThreadImpl::OnTrimMemoryImmediately() {
Blink Reformat1c4d759e2017-04-09 16:34:542575 if (blink::MainThreadIsolate()) {
2576 blink::MainThreadIsolate()->MemoryPressureNotification(
bashic4b4afcb2016-08-23 06:37:522577 v8::MemoryPressureLevel::kCritical);
2578 blink::MemoryPressureNotificationToWorkerThreadIsolates(
2579 v8::MemoryPressureLevel::kCritical);
2580 }
2581}
2582
rockot067ca55f2016-09-30 22:00:152583void RenderThreadImpl::OnRendererInterfaceRequest(
2584 mojom::RendererAssociatedRequest request) {
2585 DCHECK(!renderer_binding_.is_bound());
Hajime Hoshif21f20c2018-03-27 04:07:032586 renderer_binding_.Bind(std::move(request),
Yuta Kitamura3331f5c2018-04-05 11:12:252587 GetWebMainThreadScheduler()->IPCTaskRunner());
rockot067ca55f2016-09-30 22:00:152588}
bashic4b4afcb2016-08-23 06:37:522589
Takashi SAKAMOTO870f6262017-08-22 04:08:272590bool RenderThreadImpl::NeedsToRecordFirstActivePaint(
2591 int ttfap_metric_type) const {
2592 if (ttfap_metric_type == RenderWidget::TTFAP_AFTER_PURGED)
2593 return needs_to_record_first_active_paint_;
2594
2595 if (was_backgrounded_time_.is_min())
2596 return false;
2597 base::TimeDelta passed = base::TimeTicks::Now() - was_backgrounded_time_;
2598 return passed.InMinutes() >= 5;
2599}
2600
Miguel Casas5e1018052018-01-09 19:17:362601void RenderThreadImpl::SetRenderingColorSpace(
2602 const gfx::ColorSpace& color_space) {
2603 DCHECK(IsMainThread());
2604 rendering_color_space_ = color_space;
2605
2606 for (const auto& factories : gpu_factories_) {
2607 if (factories)
2608 factories->SetRenderingColorSpace(color_space);
2609 }
2610}
2611
[email protected]e9ff79c2012-10-19 21:31:262612} // namespace content