blob: 2b0492634064ff5f733f3cb2f9f30f1d25e86bc1 [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"
Gabriel Charette14520232018-04-30 23:27:2229#include "base/single_thread_task_runner.h"
[email protected]21aa99682013-06-11 07:17:0130#include "base/strings/string16.h"
[email protected]1e1d1e12014-01-17 16:14:2931#include "base/strings/string_number_conversions.h"
hablichd6a4f122015-10-28 11:34:4932#include "base/strings/string_split.h"
ccameron6728bae32015-01-09 20:18:0633#include "base/strings/sys_string_conversions.h"
[email protected]74ebfb12013-06-07 20:48:0034#include "base/strings/utf_string_conversions.h"
reveman34b7a1522015-03-23 20:27:4735#include "base/threading/simple_thread.h"
[email protected]1357c322010-12-30 22:18:5636#include "base/threading/thread_local.h"
[email protected]d293572a2013-05-23 18:50:4537#include "base/threading/thread_restrictions.h"
gab30f26df2016-05-11 19:37:5538#include "base/threading/thread_task_runner_handle.h"
ccameron9c48d1d42016-09-22 01:46:0139#include "base/trace_event/memory_dump_manager.h"
primiano9e38d552015-01-28 04:18:0140#include "base/trace_event/trace_event.h"
[email protected]7a4de7a62010-08-17 18:38:2441#include "base/values.h"
avi1023d012015-12-25 02:39:1442#include "build/build_config.h"
jbroman0d302162015-09-05 05:46:2343#include "cc/base/histograms.h"
[email protected]d72493152014-01-08 17:37:4544#include "cc/base/switches.h"
danakj7b631be2018-05-25 19:14:2045#include "cc/mojo_embedder/async_layer_tree_frame_sink.h"
danakj920156852015-05-18 20:22:2946#include "cc/raster/task_graph_runner.h"
danakjba65a0912017-09-21 16:38:4247#include "cc/trees/layer_tree_frame_sink.h"
vollick1050cc62015-12-03 07:04:5448#include "cc/trees/layer_tree_host_common.h"
loysoa6edaaff2015-05-25 03:26:4449#include "cc/trees/layer_tree_settings.h"
penghuangd81c1a62016-11-02 20:06:0650#include "components/discardable_memory/client/client_discardable_shared_memory_manager.h"
dalecurtis4a9839a2017-05-04 23:40:4751#include "components/metrics/public/interfaces/single_sample_metrics.mojom.h"
52#include "components/metrics/single_sample_metrics.h"
Valery Arkhangorodsky513ac8fd2017-08-02 23:09:2353#include "components/viz/client/hit_test_data_provider.h"
Ria Jiang28051112018-02-13 16:38:5254#include "components/viz/client/hit_test_data_provider_draw_quad.h"
samans7e6675cc2017-06-05 20:16:0855#include "components/viz/client/local_surface_id_provider.h"
Fady Samuel343a74952017-11-30 14:19:2056#include "components/viz/common/features.h"
danakjf20f4502017-09-26 17:13:3157#include "components/viz/common/frame_sinks/copy_output_request.h"
Sunny Sachanandani2c951c82018-05-23 20:39:3758#include "components/viz/common/switches.h"
[email protected]643255da2013-06-12 20:55:1359#include "content/child/runtime_features.h"
[email protected]57cf97882013-06-26 20:39:0160#include "content/child/thread_safe_sender.h"
Scott Violetc78fef732018-03-06 17:42:5361#include "content/common/buildflags.h"
[email protected]89c36f82013-07-17 06:23:2762#include "content/common/content_constants_internal.h"
[email protected]5f2aa722013-08-07 16:59:4163#include "content/common/dom_storage/dom_storage_messages.h"
[email protected]82307f6b2014-08-07 03:30:1264#include "content/common/frame_messages.h"
raymesbba82b32016-07-19 00:41:3865#include "content/common/frame_owner_properties.h"
sunnyps8f9139e2017-05-12 17:53:2566#include "content/common/gpu_stream_constants.h"
[email protected]778574e2011-03-21 22:03:5067#include "content/common/view_messages.h"
[email protected]a458504b2012-07-23 19:57:0668#include "content/public/common/content_constants.h"
bashia6264042016-09-15 04:49:5169#include "content/public/common/content_features.h"
[email protected]433df472012-03-07 20:33:3970#include "content/public/common/content_paths.h"
[email protected]c08950d22011-10-13 22:20:2971#include "content/public/common/content_switches.h"
[email protected]daf82f82011-10-31 22:35:3172#include "content/public/common/renderer_preferences.h"
Ben Goodgerf180ce12018-02-09 22:54:0173#include "content/public/common/resource_usage_reporter.mojom.h"
74#include "content/public/common/resource_usage_reporter_type_converters.h"
benbd9dc802017-04-19 01:37:4375#include "content/public/common/service_manager_connection.h"
ben649b3edd2017-03-23 00:32:0276#include "content/public/common/service_names.mojom.h"
benbd9dc802017-04-19 01:37:4377#include "content/public/common/simple_connection_filter.h"
[email protected]58436a12012-03-21 17:10:2678#include "content/public/common/url_constants.h"
[email protected]d344114c2011-10-01 01:24:3479#include "content/public/renderer/content_renderer_client.h"
tyoshino832a58a2016-04-18 08:14:0880#include "content/public/renderer/render_thread_observer.h"
[email protected]64ffa0442011-10-03 22:08:3681#include "content/public/renderer/render_view_visitor.h"
John Abd-El-Malekdcf1d1372017-10-22 06:39:4182#include "content/renderer/appcache/appcache_dispatcher.h"
83#include "content/renderer/appcache/appcache_frontend_impl.h"
fsamuel6c1dfeb2014-12-18 19:21:3384#include "content/renderer/browser_plugin/browser_plugin_manager.h"
prashant.nfad657e2016-06-01 07:52:1785#include "content/renderer/categorized_worker_pool.h"
[email protected]1910fe82012-05-10 00:04:1086#include "content/renderer/dom_storage/dom_storage_dispatcher.h"
87#include "content/renderer/dom_storage/webstoragearea_impl.h"
88#include "content/renderer/dom_storage/webstoragenamespace_impl.h"
tbansalb612c5d2017-05-25 18:53:0689#include "content/renderer/effective_connection_type_helper.h"
John Abd-El-Malekdcf1d1372017-10-22 06:39:4190#include "content/renderer/fileapi/file_system_dispatcher.h"
91#include "content/renderer/fileapi/webfilesystem_impl.h"
danakj83066a32016-06-21 02:34:4992#include "content/renderer/gpu/frame_swap_message_queue.h"
John Abd-El-Malekdcf1d1372017-10-22 06:39:4193#include "content/renderer/indexed_db/indexed_db_dispatcher.h"
Dave Tapuska63aa4622018-02-25 21:42:5694#include "content/renderer/input/widget_input_handler_manager.h"
John Abd-El-Malek6b56ef712017-10-21 22:52:4695#include "content/renderer/loader/resource_dispatcher.h"
[email protected]3958e972012-07-17 00:25:4196#include "content/renderer/media/audio_renderer_mixer_manager.h"
Miguel Casas-Sanchezcfcca5d52017-07-07 02:32:5997#include "content/renderer/media/gpu/gpu_video_accelerator_factories_impl.h"
Miguel Casasfff0ed52018-02-13 16:24:3598#include "content/renderer/media/midi/midi_message_filter.h"
xhwang194acae2014-11-12 22:46:3399#include "content/renderer/media/render_media_client.h"
Patrik Höglundb564859b2018-05-17 11:17:16100#include "content/renderer/media/stream/aec_dump_message_filter.h"
Miguel Casasa8c2c5a2018-02-12 18:51:03101#include "content/renderer/media/stream/media_stream_center.h"
[email protected]80b161a2011-06-27 17:42:11102#include "content/renderer/media/video_capture_impl_manager.h"
Patrik Höglundb564859b2018-05-17 11:17:16103#include "content/renderer/media/webrtc/peer_connection_dependency_factory.h"
104#include "content/renderer/media/webrtc/peer_connection_tracker.h"
105#include "content/renderer/media/webrtc/rtc_peer_connection_handler.h"
Stuart Langley849079a2017-08-28 02:02:50106#include "content/renderer/mus/render_widget_window_tree_client_factory.h"
107#include "content/renderer/mus/renderer_window_tree_client.h"
[email protected]d7ff5fb2014-05-29 19:50:25108#include "content/renderer/net_info_helper.h"
Patrik Höglundb564859b2018-05-17 11:17:16109#include "content/renderer/p2p/socket_dispatcher.h"
[email protected]82307f6b2014-08-07 03:30:12110#include "content/renderer/render_frame_proxy.h"
[email protected]8704f89b2011-04-15 00:30:05111#include "content/renderer/render_process_impl.h"
[email protected]310ebd6302011-10-10 19:06:28112#include "content/renderer/render_view_impl.h"
tfarina556a7232014-10-05 01:02:09113#include "content/renderer/renderer_blink_platform_impl.h"
shimazu5de409e42016-09-29 08:45:28114#include "content/renderer/service_worker/embedded_worker_instance_client_impl.h"
mek27c9d742015-07-16 18:30:18115#include "content/renderer/service_worker/service_worker_context_client.h"
[email protected]0ec90d522014-03-12 16:28:19116#include "content/renderer/shared_worker/embedded_shared_worker_stub.h"
Darin Fisherbcc33632017-09-26 00:57:16117#include "content/renderer/shared_worker/shared_worker_factory_impl.h"
John Abd-El-Malekf75a3192017-10-22 14:23:20118#include "content/renderer/web_database_observer_impl.h"
119#include "content/renderer/worker_thread_registry.h"
juncai2f298a82017-04-18 03:51:39120#include "device/gamepad/public/cpp/gamepads.h"
chunyang.daibe874c52014-11-14 06:45:05121#include "gin/public/debug.h"
dongseong.hwang72183b02014-12-08 10:41:55122#include "gpu/GLES2/gl2extchromium.h"
Victor Miura3a4ad4f82017-12-13 06:03:45123#include "gpu/command_buffer/client/gles2_interface.h"
124#include "gpu/command_buffer/client/raster_interface.h"
danakj6f4e1e22016-04-20 03:27:34125#include "gpu/command_buffer/client/shared_memory_limits.h"
Adrienne Walker436a7752017-08-28 23:33:09126#include "gpu/config/gpu_switches.h"
danakj870925d42016-05-03 20:07:38127#include "gpu/ipc/client/command_buffer_proxy_impl.h"
penghuang346a46f92016-03-31 21:37:52128#include "gpu/ipc/client/gpu_channel_host.h"
[email protected]46f36a492010-07-28 19:36:41129#include "ipc/ipc_channel_handle.h"
amistryd4aa70d2016-06-23 07:52:37130#include "ipc/ipc_channel_mojo.h"
[email protected]cb6037d2009-11-16 22:55:17131#include "ipc/ipc_platform_file.h"
[email protected]433df472012-03-07 20:33:39132#include "media/base/media.h"
chcunningham9a285ed2017-03-08 21:48:56133#include "media/base/media_switches.h"
Scott Violeta35f9a42018-03-22 22:00:44134#include "media/media_buildflags.h"
Dale Curtis863022e2017-08-19 02:05:34135#include "media/video/gpu_video_accelerator_factories.h"
rockot85dce0862015-11-13 01:33:59136#include "mojo/public/cpp/bindings/strong_binding.h"
Yuki Yamada68992b02017-07-31 06:13:45137#include "mojo/public/cpp/system/message_pipe.h"
[email protected]620161e2011-03-07 18:05:26138#include "net/base/net_errors.h"
eroman9ab64842015-07-21 05:07:52139#include "net/base/port_util.h"
hablichd6a4f122015-10-28 11:34:49140#include "net/base/registry_controlled_domains/registry_controlled_domain.h"
tfarina7a4a7fd2016-01-20 14:23:44141#include "net/base/url_util.h"
Scott Violet02e38b92018-03-27 23:42:14142#include "ppapi/buildflags/buildflags.h"
Khushal3e96e662017-10-30 23:16:50143#include "services/metrics/public/cpp/mojo_ukm_recorder.h"
penghuangd6843e42016-12-17 13:57:20144#include "services/service_manager/public/cpp/connector.h"
rockot734fb662016-10-15 16:41:30145#include "services/service_manager/public/cpp/interface_provider.h"
sadrul85cc5d82016-12-20 03:37:41146#include "services/ui/public/cpp/gpu/context_provider_command_buffer.h"
Stuart Langley849079a2017-08-28 02:02:50147#include "services/ui/public/cpp/gpu/gpu.h"
penghuangd6843e42016-12-17 13:57:20148#include "services/ui/public/interfaces/constants.mojom.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"
Yuta Kitamuradeb91bb2018-05-29 05:53:20151#include "third_party/blink/public/platform/scheduler/web_thread_scheduler.h"
Blink Reformata30d4232018-04-07 15:31:06152#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"
[email protected]2c62b562009-01-27 19:04:50171
[email protected]33b02992014-03-01 01:06:29172#if defined(OS_ANDROID)
173#include <cpu-features.h>
danakjc7afae52017-06-20 21:12:41174#include "content/renderer/android/synchronous_layer_tree_frame_sink.h"
boliue81d16132016-04-26 00:54:41175#include "content/renderer/media/android/stream_texture_factory.h"
dalecurtis88af3932016-02-20 00:12:20176#include "media/base/android/media_codec_util.h"
[email protected]33b02992014-03-01 01:06:29177#endif
178
179#if defined(OS_MACOSX)
ccamerona7644752014-12-30 01:16:31180#include "base/mac/mac_util.h"
rsesek1efb3c32015-09-29 15:39:50181#include "content/renderer/theme_helper_mac.h"
[email protected]33b02992014-03-01 01:06:29182#include "content/renderer/webscrollbarbehavior_impl_mac.h"
183#endif
184
[email protected]da00a2882009-03-09 17:51:19185#if defined(OS_WIN)
186#include <windows.h>
187#include <objbase.h>
188#endif
189
chunyang.daibe874c52014-11-14 06:45:05190#ifdef ENABLE_VTUNE_JIT_INTERFACE
191#include "v8/src/third_party/vtune/v8-vtune.h"
192#endif
193
ochangdd89a1e2016-06-08 16:39:01194#if defined(ENABLE_IPC_FUZZER)
195#include "content/common/external_ipc_dumper.h"
196#endif
197
tasakb46626a2016-10-18 05:54:44198#if defined(OS_MACOSX)
199#include <malloc/malloc.h>
200#else
201#include <malloc.h>
202#endif
203
[email protected]d293572a2013-05-23 18:50:45204using base::ThreadRestrictions;
[email protected]180ef242013-11-07 06:50:46205using blink::WebDocument;
206using blink::WebFrame;
207using blink::WebNetworkStateNotifier;
208using blink::WebRuntimeFeatures;
209using blink::WebScriptController;
210using blink::WebSecurityPolicy;
211using blink::WebString;
212using blink::WebView;
[email protected]e9ff79c2012-10-19 21:31:26213
214namespace content {
initial.commit09911bf2008-07-26 23:55:29215
[email protected]42f1d7822009-07-23 18:17:55216namespace {
[email protected]da9ccfb2012-01-28 00:34:40217
avi1023d012015-12-25 02:39:14218const int64_t kInitialIdleHandlerDelayMs = 1000;
219const int64_t kLongIdleHandlerDelayMs = 30 * 1000;
[email protected]bee16aab2009-08-26 15:55:03220
samans2040988b2017-04-11 23:58:35221#if defined(OS_ANDROID)
danakj83066a32016-06-21 02:34:49222// Unique identifier for each output surface created.
danakjc7afae52017-06-20 21:12:41223uint32_t g_next_layer_tree_frame_sink_id = 1;
samans2040988b2017-04-11 23:58:35224#endif
danakj83066a32016-06-21 02:34:49225
rockot5c478a72016-09-28 23:14:18226// An implementation of mojom::RenderMessageFilter which can be mocked out
227// for tests which may indirectly send messages over this interface.
228mojom::RenderMessageFilter* g_render_message_filter_for_testing;
229
olegmax045f7fb12017-05-19 07:58:55230// An implementation of RendererBlinkPlatformImpl which can be mocked out
231// for tests.
232RendererBlinkPlatformImpl* g_current_blink_platform_impl_for_testing;
233
[email protected]f1a29a02011-10-06 23:08:44234// Keep the global RenderThreadImpl in a TLS slot so it is impossible to access
[email protected]f3ede412010-06-21 22:52:16235// incorrectly from the wrong thread.
scottmg5e65e3a2017-03-08 08:48:46236base::LazyInstance<base::ThreadLocalPointer<RenderThreadImpl>>::DestructorAtExit
[email protected]6de0fd1d2011-11-15 13:31:49237 lazy_tls = LAZY_INSTANCE_INITIALIZER;
[email protected]1edc16b82009-04-07 17:45:54238
John Abd-El-Malekd4882642017-12-04 21:45:19239base::LazyInstance<scoped_refptr<base::SingleThreadTaskRunner>>::
240 DestructorAtExit g_main_task_runner = LAZY_INSTANCE_INITIALIZER;
241
hong.zhengb28b5332016-05-11 02:33:39242// v8::MemoryPressureLevel should correspond to base::MemoryPressureListener.
243static_assert(static_cast<v8::MemoryPressureLevel>(
244 base::MemoryPressureListener::MEMORY_PRESSURE_LEVEL_NONE) ==
245 v8::MemoryPressureLevel::kNone, "none level not align");
246static_assert(static_cast<v8::MemoryPressureLevel>(
247 base::MemoryPressureListener::MEMORY_PRESSURE_LEVEL_MODERATE) ==
248 v8::MemoryPressureLevel::kModerate, "moderate level not align");
249static_assert(static_cast<v8::MemoryPressureLevel>(
250 base::MemoryPressureListener::MEMORY_PRESSURE_LEVEL_CRITICAL) ==
251 v8::MemoryPressureLevel::kCritical, "critical level not align");
252
hong.zheng2e296f822016-06-29 02:47:44253// WebMemoryPressureLevel should correspond to base::MemoryPressureListener.
254static_assert(static_cast<blink::WebMemoryPressureLevel>(
Blink Reformat1c4d759e2017-04-09 16:34:54255 base::MemoryPressureListener::MEMORY_PRESSURE_LEVEL_NONE) ==
256 blink::kWebMemoryPressureLevelNone,
257 "blink::WebMemoryPressureLevelNone not align");
258static_assert(
259 static_cast<blink::WebMemoryPressureLevel>(
260 base::MemoryPressureListener::MEMORY_PRESSURE_LEVEL_MODERATE) ==
261 blink::kWebMemoryPressureLevelModerate,
262 "blink::WebMemoryPressureLevelModerate not align");
263static_assert(
264 static_cast<blink::WebMemoryPressureLevel>(
265 base::MemoryPressureListener::MEMORY_PRESSURE_LEVEL_CRITICAL) ==
266 blink::kWebMemoryPressureLevelCritical,
267 "blink::WebMemoryPressureLevelCritical not align");
hong.zheng2e296f822016-06-29 02:47:44268
[email protected]b2d98762012-09-03 17:04:06269void* CreateHistogram(
[email protected]d1b8fccc2011-08-03 01:20:13270 const char *name, int min, int max, size_t buckets) {
271 if (min <= 0)
272 min = 1;
[email protected]b2d98762012-09-03 17:04:06273 std::string histogram_name;
274 RenderThreadImpl* render_thread_impl = RenderThreadImpl::current();
275 if (render_thread_impl) { // Can be null in tests.
276 histogram_name = render_thread_impl->
277 histogram_customizer()->ConvertToCustomHistogramName(name);
278 } else {
279 histogram_name = std::string(name);
280 }
[email protected]de415552013-01-23 04:12:17281 base::HistogramBase* histogram = base::Histogram::FactoryGet(
[email protected]b2d98762012-09-03 17:04:06282 histogram_name, min, max, buckets,
283 base::Histogram::kUmaTargetedHistogramFlag);
[email protected]d1b8fccc2011-08-03 01:20:13284 return histogram;
285}
286
[email protected]b2d98762012-09-03 17:04:06287void AddHistogramSample(void* hist, int sample) {
[email protected]d1b8fccc2011-08-03 01:20:13288 base::Histogram* histogram = static_cast<base::Histogram*>(hist);
289 histogram->Add(sample);
290}
291
ben76f52b242016-06-18 05:42:48292class FrameFactoryImpl : public mojom::FrameFactory {
rockotf8fdd9b2015-12-16 22:22:35293 public:
benf28ce882017-05-02 16:15:49294 explicit FrameFactoryImpl(const service_manager::BindSourceInfo& source_info)
295 : source_info_(source_info), routing_id_highmark_(-1) {}
rockotf8fdd9b2015-12-16 22:22:35296
ben76f52b242016-06-18 05:42:48297 private:
298 // mojom::FrameFactory:
Balazs Engedyba034e72017-10-27 22:26:28299 void CreateFrame(int32_t frame_routing_id,
300 mojom::FrameRequest frame_request) override {
rockotf8fdd9b2015-12-16 22:22:35301 // TODO(morrita): This is for investigating http://crbug.com/415059 and
302 // should be removed once it is fixed.
303 CHECK_LT(routing_id_highmark_, frame_routing_id);
304 routing_id_highmark_ = frame_routing_id;
305
306 RenderFrameImpl* frame = RenderFrameImpl::FromRoutingID(frame_routing_id);
307 // We can receive a GetServiceProviderForFrame message for a frame not yet
rockot067ca55f2016-09-30 22:00:15308 // created due to a race between the message and a
309 // mojom::Renderer::CreateView IPC that triggers creation of the RenderFrame
310 // we want.
rockotf8fdd9b2015-12-16 22:22:35311 if (!frame) {
ben76f52b242016-06-18 05:42:48312 RenderThreadImpl::current()->RegisterPendingFrameCreate(
Balazs Engedyba034e72017-10-27 22:26:28313 source_info_, frame_routing_id, std::move(frame_request));
rockotf8fdd9b2015-12-16 22:22:35314 return;
315 }
316
Balazs Engedyba034e72017-10-27 22:26:28317 frame->BindFrame(source_info_, std::move(frame_request));
rockotf8fdd9b2015-12-16 22:22:35318 }
319
320 private:
benf28ce882017-05-02 16:15:49321 service_manager::BindSourceInfo source_info_;
rockotf8fdd9b2015-12-16 22:22:35322 int32_t routing_id_highmark_;
rockotf8fdd9b2015-12-16 22:22:35323};
324
Ben Goodger21ada1e2017-07-19 14:53:01325void CreateFrameFactory(mojom::FrameFactoryRequest request,
326 const service_manager::BindSourceInfo& source_info) {
Jeremy Roman04f27c372017-10-27 15:20:55327 mojo::MakeStrongBinding(std::make_unique<FrameFactoryImpl>(source_info),
rockot8e66a08d2016-09-13 00:48:21328 std::move(request));
rockotf8fdd9b2015-12-16 22:22:35329}
330
sadrul85cc5d82016-12-20 03:37:41331scoped_refptr<ui::ContextProviderCommandBuffer> CreateOffscreenContext(
danakjc3983552016-05-03 00:04:35332 scoped_refptr<gpu::GpuChannelHost> gpu_channel_host,
Antoine Labour5ac65db2017-12-19 18:02:58333 gpu::GpuMemoryBufferManager* gpu_memory_buffer_manager,
danakj0dd9e1e2016-05-11 22:15:09334 const gpu::SharedMemoryLimits& limits,
danakj9a04adc2016-05-16 22:45:07335 bool support_locking,
Victor Miura3a4ad4f82017-12-13 06:03:45336 bool support_gles2_interface,
337 bool support_raster_interface,
Adrienne Walker436a7752017-08-28 23:33:09338 bool support_oop_rasterization,
Justin Novosad7d3d2502018-03-27 18:55:38339 bool support_grcontext,
sadrul85cc5d82016-12-20 03:37:41340 ui::command_buffer_metrics::ContextType type,
sunnypsd8ce1c22016-05-10 18:02:40341 int32_t stream_id,
sunnyps8f9139e2017-05-12 17:53:25342 gpu::SchedulingPriority stream_priority) {
danakje8ec797e2016-04-19 04:08:43343 DCHECK(gpu_channel_host);
344 // This is used to create a few different offscreen contexts:
Victor Miura3a4ad4f82017-12-13 06:03:45345 // - The shared main thread context, used by blink for 2D Canvas.
346 // - The compositor worker context, used for GPU raster.
347 // - The media context, used for accelerated video decoding.
danakje8ec797e2016-04-19 04:08:43348 // This is for an offscreen context, so the default framebuffer doesn't need
349 // alpha, depth, stencil, antialiasing.
Antoine Labourfeab2392017-12-21 20:28:39350 gpu::ContextCreationAttribs attributes;
danakje8ec797e2016-04-19 04:08:43351 attributes.alpha_size = -1;
352 attributes.depth_size = 0;
353 attributes.stencil_size = 0;
354 attributes.samples = 0;
355 attributes.sample_buffers = 0;
356 attributes.bind_generates_resource = false;
357 attributes.lose_context_when_out_of_memory = true;
Victor Miura3a4ad4f82017-12-13 06:03:45358 attributes.enable_gles2_interface = support_gles2_interface;
359 attributes.enable_raster_interface = support_raster_interface;
Jonathan Backereba6af42018-05-03 22:47:43360 // Using RasterDecoder for OOP-R backend, so we need support_raster_interface
361 // and !support_gles2_interface.
362 attributes.enable_oop_rasterization = support_oop_rasterization &&
363 support_raster_interface &&
364 !support_gles2_interface;
Jonathan Backer4d51ebf2018-03-14 14:11:14365
sunnypsd8ce1c22016-05-10 18:02:40366 const bool automatic_flushes = false;
kylechar96f3eba2017-09-25 20:23:56367 return base::MakeRefCounted<ui::ContextProviderCommandBuffer>(
Antoine Labour5ac65db2017-12-19 18:02:58368 std::move(gpu_channel_host), gpu_memory_buffer_manager, stream_id,
369 stream_priority, gpu::kNullSurfaceHandle,
zmo09ea813b2017-01-20 23:38:36370 GURL("chrome://gpu/RenderThreadImpl::CreateOffscreenContext/" +
371 ui::command_buffer_metrics::ContextTypeToString(type)),
Justin Novosad7d3d2502018-03-27 18:55:38372 automatic_flushes, support_locking, support_grcontext, limits, attributes,
Jonathan Backerfa3a8452018-04-23 18:20:33373 type);
danakje8ec797e2016-04-19 04:08:43374}
375
dalecurtis4a9839a2017-05-04 23:40:47376// Hook that allows single-sample metric code from //components/metrics to
377// connect from the renderer process to the browser process.
378void CreateSingleSampleMetricsProvider(
379 scoped_refptr<base::SingleThreadTaskRunner> task_runner,
380 service_manager::Connector* connector,
381 metrics::mojom::SingleSampleMetricsProviderRequest request) {
382 if (task_runner->BelongsToCurrentThread()) {
383 connector->BindInterface(mojom::kBrowserServiceName, std::move(request));
384 return;
385 }
386
387 task_runner->PostTask(
388 FROM_HERE,
tzikff2a81a2017-09-15 05:10:06389 base::BindOnce(&CreateSingleSampleMetricsProvider, std::move(task_runner),
tzikccf160c2018-02-20 12:43:13390 connector, std::move(request)));
dalecurtis4a9839a2017-05-04 23:40:47391}
392
samans7e6675cc2017-06-05 20:16:08393class RendererLocalSurfaceIdProvider : public viz::LocalSurfaceIdProvider {
394 public:
Fady Samueld5c26182017-07-12 02:43:33395 const viz::LocalSurfaceId& GetLocalSurfaceIdForFrame(
danakj5e0a12b2017-09-25 17:26:49396 const viz::CompositorFrame& frame) override {
samans7e6675cc2017-06-05 20:16:08397 auto new_surface_properties =
398 RenderWidgetSurfaceProperties::FromCompositorFrame(frame);
Chris Blume45c5c212018-05-02 00:43:55399 if (new_surface_properties != surface_properties_) {
Chris Blume52b4d5be2018-04-26 17:34:18400 parent_local_surface_id_allocator_.GenerateId();
samans7e6675cc2017-06-05 20:16:08401 surface_properties_ = new_surface_properties;
402 }
Chris Blume52b4d5be2018-04-26 17:34:18403 return parent_local_surface_id_allocator_.GetCurrentLocalSurfaceId();
samans7e6675cc2017-06-05 20:16:08404 }
405
406 private:
Chris Blumeefd8f242017-12-08 00:24:27407 viz::ParentLocalSurfaceIdAllocator parent_local_surface_id_allocator_;
samans7e6675cc2017-06-05 20:16:08408 RenderWidgetSurfaceProperties surface_properties_;
409};
410
Khushal3e96e662017-10-30 23:16:50411// This factory is used to defer binding of the InterfacePtr to the compositor
412// thread.
413class UkmRecorderFactoryImpl : public cc::UkmRecorderFactory {
414 public:
Lukasz Anforowiczbb0cfd5e2017-12-14 22:39:46415 explicit UkmRecorderFactoryImpl(
416 std::unique_ptr<service_manager::Connector> connector)
Khushalda50f8152017-12-01 09:04:40417 : connector_(std::move(connector)) {
418 DCHECK(connector_);
Khushal3e96e662017-10-30 23:16:50419 }
420 ~UkmRecorderFactoryImpl() override = default;
421
422 std::unique_ptr<ukm::UkmRecorder> CreateRecorder() override {
Khushalda50f8152017-12-01 09:04:40423 return ukm::MojoUkmRecorder::Create(connector_.get());
Khushal3e96e662017-10-30 23:16:50424 }
425
426 private:
Khushalda50f8152017-12-01 09:04:40427 std::unique_ptr<service_manager::Connector> connector_;
Khushal3e96e662017-10-30 23:16:50428};
429
Ben Goodgerf180ce12018-02-09 22:54:01430static const int kWaitForWorkersStatsTimeoutMS = 20;
431
432class ResourceUsageReporterImpl : public content::mojom::ResourceUsageReporter {
433 public:
434 explicit ResourceUsageReporterImpl(base::WeakPtr<RenderThread> thread)
435 : workers_to_go_(0), thread_(thread), weak_factory_(this) {}
436 ~ResourceUsageReporterImpl() override {}
437
438 private:
439 static void CollectOnWorkerThread(
440 const scoped_refptr<base::TaskRunner>& master,
441 base::WeakPtr<ResourceUsageReporterImpl> impl) {
442 size_t total_bytes = 0;
443 size_t used_bytes = 0;
444 v8::Isolate* isolate = v8::Isolate::GetCurrent();
445 if (isolate) {
446 v8::HeapStatistics heap_stats;
447 isolate->GetHeapStatistics(&heap_stats);
448 total_bytes = heap_stats.total_heap_size();
449 used_bytes = heap_stats.used_heap_size();
450 }
451 master->PostTask(FROM_HERE,
452 base::BindOnce(&ResourceUsageReporterImpl::ReceiveStats,
453 impl, total_bytes, used_bytes));
454 }
455
456 void ReceiveStats(size_t total_bytes, size_t used_bytes) {
457 usage_data_->v8_bytes_allocated += total_bytes;
458 usage_data_->v8_bytes_used += used_bytes;
459 workers_to_go_--;
460 if (!workers_to_go_)
461 SendResults();
462 }
463
464 void SendResults() {
465 if (!callback_.is_null())
466 std::move(callback_).Run(std::move(usage_data_));
467 callback_.Reset();
468 weak_factory_.InvalidateWeakPtrs();
469 workers_to_go_ = 0;
470 }
471
472 void GetUsageData(GetUsageDataCallback callback) override {
473 DCHECK(callback_.is_null());
474 weak_factory_.InvalidateWeakPtrs();
475 usage_data_ = mojom::ResourceUsageData::New();
476 usage_data_->reports_v8_stats = true;
477 callback_ = std::move(callback);
478
479 // Since it is not safe to call any Blink or V8 functions until Blink has
480 // been initialized (which also initializes V8), early out and send 0 back
481 // for all resources.
482 if (!thread_) {
483 SendResults();
484 return;
485 }
486
487 blink::WebCache::ResourceTypeStats stats;
488 blink::WebCache::GetResourceTypeStats(&stats);
489 usage_data_->web_cache_stats = mojom::ResourceTypeStats::From(stats);
490
491 v8::Isolate* isolate = v8::Isolate::GetCurrent();
492 if (isolate) {
493 v8::HeapStatistics heap_stats;
494 isolate->GetHeapStatistics(&heap_stats);
495 usage_data_->v8_bytes_allocated = heap_stats.total_heap_size();
496 usage_data_->v8_bytes_used = heap_stats.used_heap_size();
497 }
498 base::RepeatingClosure collect = base::BindRepeating(
499 &ResourceUsageReporterImpl::CollectOnWorkerThread,
500 base::ThreadTaskRunnerHandle::Get(), weak_factory_.GetWeakPtr());
Tommy Nyquist4b749d02018-03-20 21:46:29501 workers_to_go_ =
502 RenderThread::Get()->PostTaskToAllWebWorkers(std::move(collect));
Ben Goodgerf180ce12018-02-09 22:54:01503 if (workers_to_go_) {
504 // The guard task to send out partial stats
505 // in case some workers are not responsive.
506 base::ThreadTaskRunnerHandle::Get()->PostDelayedTask(
507 FROM_HERE,
508 base::BindOnce(&ResourceUsageReporterImpl::SendResults,
509 weak_factory_.GetWeakPtr()),
510 base::TimeDelta::FromMilliseconds(kWaitForWorkersStatsTimeoutMS));
511 } else {
512 // No worker threads so just send out the main thread data right away.
513 SendResults();
514 }
515 }
516
517 mojom::ResourceUsageDataPtr usage_data_;
518 GetUsageDataCallback callback_;
519 int workers_to_go_;
520 base::WeakPtr<RenderThread> thread_;
521
522 base::WeakPtrFactory<ResourceUsageReporterImpl> weak_factory_;
523
524 DISALLOW_COPY_AND_ASSIGN(ResourceUsageReporterImpl);
525};
526
527void CreateResourceUsageReporter(base::WeakPtr<RenderThread> thread,
528 mojom::ResourceUsageReporterRequest request) {
Jeremy Roman42e81a62018-03-01 19:08:59529 mojo::MakeStrongBinding(std::make_unique<ResourceUsageReporterImpl>(thread),
Ben Goodgerf180ce12018-02-09 22:54:01530 std::move(request));
531}
532
[email protected]b2d98762012-09-03 17:04:06533} // namespace
534
[email protected]b2d98762012-09-03 17:04:06535RenderThreadImpl::HistogramCustomizer::HistogramCustomizer() {
536 custom_histograms_.insert("V8.MemoryExternalFragmentationTotal");
537 custom_histograms_.insert("V8.MemoryHeapSampleTotalCommitted");
538 custom_histograms_.insert("V8.MemoryHeapSampleTotalUsed");
hablich4598ddc2015-11-07 18:37:28539 custom_histograms_.insert("V8.MemoryHeapUsed");
540 custom_histograms_.insert("V8.MemoryHeapCommitted");
[email protected]b2d98762012-09-03 17:04:06541}
542
543RenderThreadImpl::HistogramCustomizer::~HistogramCustomizer() {}
544
545void RenderThreadImpl::HistogramCustomizer::RenderViewNavigatedToHost(
546 const std::string& host, size_t view_count) {
avi83883c82014-12-23 00:08:49547 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
548 switches::kDisableHistogramCustomizer)) {
[email protected]9baee832012-12-10 11:07:15549 return;
550 }
[email protected]b2d98762012-09-03 17:04:06551 // Check if all RenderViews are displaying a page from the same host. If there
552 // is only one RenderView, the common host is this view's host. If there are
553 // many, check if this one shares the common host of the other
554 // RenderViews. It's ok to not detect some cases where the RenderViews share a
555 // common host. This information is only used for producing custom histograms.
556 if (view_count == 1)
557 SetCommonHost(host);
558 else if (host != common_host_)
559 SetCommonHost(std::string());
560}
561
562std::string RenderThreadImpl::HistogramCustomizer::ConvertToCustomHistogramName(
563 const char* histogram_name) const {
564 std::string name(histogram_name);
565 if (!common_host_histogram_suffix_.empty() &&
566 custom_histograms_.find(name) != custom_histograms_.end())
567 name += common_host_histogram_suffix_;
568 return name;
569}
570
571void RenderThreadImpl::HistogramCustomizer::SetCommonHost(
572 const std::string& host) {
573 if (host != common_host_) {
574 common_host_ = host;
575 common_host_histogram_suffix_ = HostToCustomHistogramSuffix(host);
Blink Reformat1c4d759e2017-04-09 16:34:54576 blink::MainThreadIsolate()->SetCreateHistogramFunction(CreateHistogram);
[email protected]b2d98762012-09-03 17:04:06577 }
578}
579
hablichd6a4f122015-10-28 11:34:49580std::string RenderThreadImpl::HistogramCustomizer::HostToCustomHistogramSuffix(
581 const std::string& host) {
582 if (host == "mail.google.com")
583 return ".gmail";
584 if (host == "docs.google.com" || host == "drive.google.com")
585 return ".docs";
586 if (host == "plus.google.com")
587 return ".plus";
588 if (host == "inbox.google.com")
589 return ".inbox";
hpayerdd4def052016-02-06 19:06:10590 if (host == "calendar.google.com")
591 return ".calendar";
hablichd6a4f122015-10-28 11:34:49592 if (host == "www.youtube.com")
593 return ".youtube";
594 if (IsAlexaTop10NonGoogleSite(host))
595 return ".top10";
596
597 return std::string();
598}
599
600bool RenderThreadImpl::HistogramCustomizer::IsAlexaTop10NonGoogleSite(
601 const std::string& host) {
602 // The Top10 sites have different TLD and/or subdomains depending on the
603 // localization.
604 if (host == "sina.com.cn")
605 return true;
606
607 std::string sanitized_host =
608 net::registry_controlled_domains::GetDomainAndRegistry(
609 host, net::registry_controlled_domains::INCLUDE_PRIVATE_REGISTRIES);
610
611 if (sanitized_host == "facebook.com")
612 return true;
613 if (sanitized_host == "baidu.com")
614 return true;
615 if (sanitized_host == "qq.com")
616 return true;
617 if (sanitized_host == "twitter.com")
618 return true;
619 if (sanitized_host == "taobao.com")
620 return true;
621 if (sanitized_host == "live.com")
622 return true;
623
624 if (!sanitized_host.empty()) {
625 std::vector<base::StringPiece> host_tokens = base::SplitStringPiece(
626 sanitized_host, ".", base::TRIM_WHITESPACE, base::SPLIT_WANT_NONEMPTY);
627
628 if (host_tokens.size() >= 2) {
629 if ((host_tokens[0] == "yahoo") || (host_tokens[0] == "amazon") ||
630 (host_tokens[0] == "wikipedia")) {
631 return true;
632 }
633 }
634 }
635 return false;
636}
637
leon.han2c0f9f12015-07-11 02:01:19638// static
639RenderThreadImpl* RenderThreadImpl::Create(
Gabriel Charette08fd6532018-04-04 19:47:16640 const InProcessChildThreadParams& params,
641 base::MessageLoop* unowned_message_loop) {
Dmitry Skibaa2476cb92017-12-15 23:44:39642 TRACE_EVENT0("startup", "RenderThreadImpl::Create");
Yuta Kitamuradeb91bb2018-05-29 05:53:20643 std::unique_ptr<blink::scheduler::WebThreadScheduler> main_thread_scheduler =
644 blink::scheduler::WebThreadScheduler::CreateMainThreadScheduler();
jam75c44222016-03-23 05:34:24645 scoped_refptr<base::SingleThreadTaskRunner> test_task_counter;
Yuta Kitamura3331f5c2018-04-05 11:12:25646 return new RenderThreadImpl(params, std::move(main_thread_scheduler),
Gabriel Charette08fd6532018-04-04 19:47:16647 test_task_counter, unowned_message_loop);
leon.han2c0f9f12015-07-11 02:01:19648}
649
650// static
651RenderThreadImpl* RenderThreadImpl::Create(
dchengcedca5612016-04-09 01:40:15652 std::unique_ptr<base::MessageLoop> main_message_loop,
Yuta Kitamuradeb91bb2018-05-29 05:53:20653 std::unique_ptr<blink::scheduler::WebThreadScheduler>
Yuta Kitamura3331f5c2018-04-05 11:12:25654 main_thread_scheduler) {
Dmitry Skibaa2476cb92017-12-15 23:44:39655 TRACE_EVENT0("startup", "RenderThreadImpl::Create");
dcheng07945f632015-12-26 07:59:32656 return new RenderThreadImpl(std::move(main_message_loop),
Yuta Kitamura3331f5c2018-04-05 11:12:25657 std::move(main_thread_scheduler));
leon.han2c0f9f12015-07-11 02:01:19658}
659
rockot5c478a72016-09-28 23:14:18660// static
[email protected]f1a29a02011-10-06 23:08:44661RenderThreadImpl* RenderThreadImpl::current() {
[email protected]526476902011-10-06 20:34:06662 return lazy_tls.Pointer()->Get();
663}
664
rockot5c478a72016-09-28 23:14:18665// static
666mojom::RenderMessageFilter* RenderThreadImpl::current_render_message_filter() {
667 if (g_render_message_filter_for_testing)
668 return g_render_message_filter_for_testing;
669 DCHECK(current());
670 return current()->render_message_filter();
671}
672
673// static
olegmax045f7fb12017-05-19 07:58:55674RendererBlinkPlatformImpl* RenderThreadImpl::current_blink_platform_impl() {
675 if (g_current_blink_platform_impl_for_testing)
676 return g_current_blink_platform_impl_for_testing;
677 DCHECK(current());
678 return current()->blink_platform_impl();
679}
680
681// static
rockot5c478a72016-09-28 23:14:18682void RenderThreadImpl::SetRenderMessageFilterForTesting(
683 mojom::RenderMessageFilter* render_message_filter) {
684 g_render_message_filter_for_testing = render_message_filter;
685}
686
olegmax045f7fb12017-05-19 07:58:55687// static
688void RenderThreadImpl::SetRendererBlinkPlatformImplForTesting(
689 RendererBlinkPlatformImpl* blink_platform_impl) {
690 g_current_blink_platform_impl_for_testing = blink_platform_impl;
691}
692
John Abd-El-Malekd4882642017-12-04 21:45:19693// static
694scoped_refptr<base::SingleThreadTaskRunner>
Hajime Hoshi20578c62018-01-12 09:43:26695RenderThreadImpl::DeprecatedGetMainTaskRunner() {
John Abd-El-Malekd4882642017-12-04 21:45:19696 return g_main_task_runner.Get();
697}
698
staraz067f58242016-11-07 21:06:41699// In single-process mode used for debugging, we don't pass a renderer client
700// ID via command line because RenderThreadImpl lives in the same process as
701// the browser
leon.han2c0f9f12015-07-11 02:01:19702RenderThreadImpl::RenderThreadImpl(
703 const InProcessChildThreadParams& params,
Yuta Kitamuradeb91bb2018-05-29 05:53:20704 std::unique_ptr<blink::scheduler::WebThreadScheduler> scheduler,
Gabriel Charette08fd6532018-04-04 19:47:16705 const scoped_refptr<base::SingleThreadTaskRunner>& resource_task_queue,
706 base::MessageLoop* unowned_message_loop)
Hajime Hoshife11b132017-11-13 10:16:07707 : ChildThreadImpl(
708 Options::Builder()
709 .InBrowserProcess(params)
710 .AutoStartServiceManagerConnection(false)
711 .ConnectToBrowser(true)
712 .IPCTaskRunner(scheduler ? scheduler->IPCTaskRunner() : nullptr)
713 .Build()),
Yuta Kitamura3331f5c2018-04-05 11:12:25714 main_thread_scheduler_(std::move(scheduler)),
Gabriel Charette08fd6532018-04-04 19:47:16715 main_message_loop_(unowned_message_loop),
rockot067ca55f2016-09-30 22:00:15716 categorized_worker_pool_(new CategorizedWorkerPool()),
staraz067f58242016-11-07 21:06:41717 renderer_binding_(this),
danakjab9ef4d2017-10-31 23:38:33718 client_id_(1),
Ben Goodgerf180ce12018-02-09 22:54:01719 compositing_mode_watcher_binding_(this),
720 weak_factory_(this) {
jam75c44222016-03-23 05:34:24721 Init(resource_task_queue);
morritac6238ab2015-03-18 01:48:29722}
723
[email protected]42f1d7822009-07-23 18:17:55724// When we run plugins in process, we actually run them on the render thread,
725// which means that we need to make the render thread pump UI events.
haraken53f081d2014-11-11 01:03:40726RenderThreadImpl::RenderThreadImpl(
Gabriel Charette08fd6532018-04-04 19:47:16727 std::unique_ptr<base::MessageLoop> owned_message_loop,
Yuta Kitamuradeb91bb2018-05-29 05:53:20728 std::unique_ptr<blink::scheduler::WebThreadScheduler> scheduler)
Hajime Hoshia1626932017-11-30 09:50:59729 : ChildThreadImpl(
730 Options::Builder()
731 .AutoStartServiceManagerConnection(false)
732 .ConnectToBrowser(true)
733 .IPCTaskRunner(scheduler ? scheduler->IPCTaskRunner() : nullptr)
734 .Build()),
Yuta Kitamura3331f5c2018-04-05 11:12:25735 main_thread_scheduler_(std::move(scheduler)),
Gabriel Charette08fd6532018-04-04 19:47:16736 owned_message_loop_(std::move(owned_message_loop)),
737 main_message_loop_(owned_message_loop_.get()),
rockot067ca55f2016-09-30 22:00:15738 categorized_worker_pool_(new CategorizedWorkerPool()),
wjmaclean1d970622017-01-21 22:28:24739 is_scroll_animator_enabled_(false),
danakjab9ef4d2017-10-31 23:38:33740 renderer_binding_(this),
Ben Goodgerf180ce12018-02-09 22:54:01741 compositing_mode_watcher_binding_(this),
742 weak_factory_(this) {
jam75c44222016-03-23 05:34:24743 scoped_refptr<base::SingleThreadTaskRunner> test_task_counter;
staraz067f58242016-11-07 21:06:41744 DCHECK(base::CommandLine::ForCurrentProcess()->HasSwitch(
745 switches::kRendererClientId));
746 base::StringToInt(base::CommandLine::ForCurrentProcess()->GetSwitchValueASCII(
747 switches::kRendererClientId),
748 &client_id_);
jam75c44222016-03-23 05:34:24749 Init(test_task_counter);
haraken53f081d2014-11-11 01:03:40750}
751
jam75c44222016-03-23 05:34:24752void RenderThreadImpl::Init(
rockot97a86832016-12-10 04:53:06753 const scoped_refptr<base::SingleThreadTaskRunner>& resource_task_queue) {
fdorayf6d86242015-10-08 16:49:53754 TRACE_EVENT0("startup", "RenderThreadImpl::Init");
[email protected]a872ea1f2010-08-11 04:45:33755
Gabriel Charette08fd6532018-04-04 19:47:16756 // Whether owned or unowned, |main_message_loop_| needs to be initialized in
757 // all constructors.
758 DCHECK(main_message_loop_);
759
Mike Wittmanc1419ff2018-03-02 23:50:04760 GetContentClient()->renderer()->PostIOThreadCreated(GetIOTaskRunner().get());
761
ssidb2e3ece2015-02-09 16:02:20762 base::trace_event::TraceLog::GetInstance()->SetThreadSortIndex(
[email protected]91a2aea2013-07-08 23:14:39763 base::PlatformThread::CurrentId(),
764 kTraceEventRendererMainThreadSortIndex);
765
thakis18e426412017-03-15 12:06:37766#if BUILDFLAG(USE_EXTERNAL_POPUP_MENU)
sievers9dff72052015-11-16 18:35:57767 // On Mac and Android Java UI, the select popups are rendered by the browser.
Blink Reformat1c4d759e2017-04-09 16:34:54768 blink::WebView::SetUseExternalPopupMenus(true);
[email protected]53c607c2011-03-21 23:19:04769#endif
770
[email protected]94f9a0f682009-06-15 18:30:30771 lazy_tls.Pointer()->Set(this);
Gabriel Charette08fd6532018-04-04 19:47:16772 g_main_task_runner.Get() = main_message_loop_->task_runner();
[email protected]b3e83de2012-02-07 03:33:28773
[email protected]06c694d2012-02-01 22:26:16774 // Register this object as the main thread.
775 ChildProcess::current()->set_main_thread(this);
776
dalecurtis4a9839a2017-05-04 23:40:47777 metrics::InitializeSingleSampleMetricsFactory(
778 base::BindRepeating(&CreateSingleSampleMetricsProvider,
Gabriel Charettebbede162018-04-25 14:04:37779 main_thread_runner(), GetConnector()));
dalecurtis4a9839a2017-05-04 23:40:47780
Scott Violet8ff9c302018-02-22 22:28:35781 gpu_ = ui::Gpu::Create(GetConnector(),
782 base::FeatureList::IsEnabled(features::kMash)
783 ? ui::mojom::kServiceName
784 : mojom::kBrowserServiceName,
785 GetIOTaskRunner());
penghuange1d86512016-07-08 18:15:00786
Hajime Hoshi1711b522018-01-19 10:29:20787 resource_dispatcher_.reset(new ResourceDispatcher());
Yuzhu Shenfe5f3a52018-01-11 21:24:13788 url_loader_throttle_provider_ =
789 GetContentClient()->renderer()->CreateURLLoaderThrottleProvider(
790 URLLoaderThrottleProviderType::kFrame);
John Abd-El-Malek6b56ef712017-10-21 22:52:46791
Stuart Langley7b8dc772017-10-31 03:55:20792 auto registry = std::make_unique<service_manager::BinderRegistry>();
Ken Rockot510c5972017-12-05 16:37:04793 InitializeWebKit(resource_task_queue, registry.get());
Makoto Shimazu8199e092018-05-11 06:03:14794 blink_initialized_time_ = base::TimeTicks::Now();
jam75c44222016-03-23 05:34:24795
[email protected]31f87132010-04-21 23:36:21796 // In single process the single process is all there is.
Alexander Timin4b6152232017-10-17 20:34:06797 webkit_shared_timer_suspended_ = false;
[email protected]bee16aab2009-08-26 15:55:03798 widget_count_ = 0;
799 hidden_widget_count_ = 0;
[email protected]6593ae12011-11-14 12:09:44800 idle_notification_delay_in_ms_ = kInitialIdleHandlerDelayMs;
[email protected]1784b2f2011-11-24 10:53:48801 idle_notifications_to_skip_ = 0;
[email protected]8d86fce2009-02-26 23:37:55802
[email protected]d5b2fdf2013-06-05 09:36:55803 appcache_dispatcher_.reset(
Nicholas Verne07e9c6452017-12-13 04:12:55804 new AppCacheDispatcher(new AppCacheFrontendImpl()));
805 registry->AddInterface(
806 base::BindRepeating(&AppCacheDispatcher::Bind,
807 base::Unretained(appcache_dispatcher())),
Yuta Kitamura3331f5c2018-04-05 11:12:25808 GetWebMainThreadScheduler()->IPCTaskRunner());
[email protected]1910fe82012-05-10 00:04:10809 dom_storage_dispatcher_.reset(new DomStorageDispatcher());
reillyg39fb4662016-11-22 20:27:17810 main_thread_indexed_db_dispatcher_.reset(new IndexedDBDispatcher());
John Abd-El-Malekdcf1d1372017-10-22 06:39:41811 file_system_dispatcher_.reset(new FileSystemDispatcher());
[email protected]dd9241932010-02-24 19:23:13812
[email protected]45048072014-01-14 13:51:29813 vc_manager_.reset(new VideoCaptureImplManager());
[email protected]c9c43a02013-12-17 08:59:54814
fsamuel6c1dfeb2014-12-18 19:21:33815 browser_plugin_manager_.reset(new BrowserPluginManager());
816 AddObserver(browser_plugin_manager_.get());
817
[email protected]af089972013-01-10 04:04:40818 peer_connection_tracker_.reset(new PeerConnectionTracker());
819 AddObserver(peer_connection_tracker_.get());
820
thestig529ad8a2016-07-08 20:30:12821 p2p_socket_dispatcher_ = new P2PSocketDispatcher(GetIOTaskRunner().get());
[email protected]fc72bb12013-06-02 21:13:46822 AddFilter(p2p_socket_dispatcher_.get());
[email protected]921480f62013-07-20 03:42:57823
ivocadd54f0d2015-12-18 23:17:05824 peer_connection_factory_.reset(
825 new PeerConnectionDependencyFactory(p2p_socket_dispatcher_.get()));
826
Gabriel Charettebbede162018-04-25 14:04:37827 aec_dump_message_filter_ =
828 new AecDumpMessageFilter(GetIOTaskRunner(), main_thread_runner());
ivocadd54f0d2015-12-18 23:17:05829
[email protected]da9f30a2014-06-18 19:39:04830 AddFilter(aec_dump_message_filter_.get());
831
Gabriel Charettebbede162018-04-25 14:04:37832 audio_input_ipc_factory_.emplace(main_thread_runner(), GetIOTaskRunner());
[email protected]e25f4d72011-06-08 20:58:46833
Max Morin2c38c282018-04-17 07:01:42834 audio_output_ipc_factory_.emplace(GetIOTaskRunner());
[email protected]f7eb0a392011-07-12 10:19:51835
thestig529ad8a2016-07-08 20:30:12836 midi_message_filter_ = new MidiMessageFilter(GetIOTaskRunner());
[email protected]a9875152013-06-22 04:03:03837 AddFilter(midi_message_filter_.get());
838
sadrul943e3b32016-08-04 18:22:59839#if defined(USE_AURA)
James Cook486d9642018-05-08 17:44:21840 if (features::IsMashEnabled())
bend32292b2016-10-07 00:21:58841 CreateRenderWidgetWindowTreeClientFactory(GetServiceManagerConnection());
rockotcef38272016-07-15 22:47:47842#endif
843
Stuart Langley7b8dc772017-10-31 03:55:20844 registry->AddInterface(base::Bind(&SharedWorkerFactoryImpl::Create),
845 base::ThreadTaskRunnerHandle::Get());
Ben Goodgerf180ce12018-02-09 22:54:01846 registry->AddInterface(base::BindRepeating(CreateResourceUsageReporter,
847 weak_factory_.GetWeakPtr()),
848 base::ThreadTaskRunnerHandle::Get());
849
Stuart Langley7b8dc772017-10-31 03:55:20850 GetServiceManagerConnection()->AddConnectionFilter(
851 std::make_unique<SimpleConnectionFilter>(std::move(registry)));
Stuart Langley6771c902017-09-01 11:23:30852
Darin Fisherbcc33632017-09-26 00:57:16853 {
854 auto registry_with_source_info =
Jeremy Roman04f27c372017-10-27 15:20:55855 std::make_unique<service_manager::BinderRegistryWithArgs<
Darin Fisherbcc33632017-09-26 00:57:16856 const service_manager::BindSourceInfo&>>();
857 registry_with_source_info->AddInterface(
858 base::Bind(&CreateFrameFactory), base::ThreadTaskRunnerHandle::Get());
859 GetServiceManagerConnection()->AddConnectionFilter(
Jeremy Roman04f27c372017-10-27 15:20:55860 std::make_unique<SimpleConnectionFilterWithSourceInfo>(
Darin Fisherbcc33632017-09-26 00:57:16861 std::move(registry_with_source_info)));
862 }
rockotcef38272016-07-15 22:47:47863
[email protected]e9ff79c2012-10-19 21:31:26864 GetContentClient()->renderer()->RenderThreadStarted();
[email protected]6779aa12011-03-29 17:32:24865
benbd9dc802017-04-19 01:37:43866 StartServiceManagerConnection();
867
rockot067ca55f2016-09-30 22:00:15868 GetAssociatedInterfaceRegistry()->AddInterface(
869 base::Bind(&RenderThreadImpl::OnRendererInterfaceRequest,
870 base::Unretained(this)));
871
avi83883c82014-12-23 00:08:49872 const base::CommandLine& command_line =
873 *base::CommandLine::ForCurrentProcess();
[email protected]e54ab492012-06-12 19:40:01874
ochangdd89a1e2016-06-08 16:39:01875#if defined(ENABLE_IPC_FUZZER)
876 if (command_line.HasSwitch(switches::kIpcDumpDirectory)) {
877 base::FilePath dump_directory =
878 command_line.GetSwitchValuePath(switches::kIpcDumpDirectory);
879 IPC::ChannelProxy::OutgoingMessageFilter* filter =
880 LoadExternalIPCDumper(dump_directory);
881 GetChannel()->set_outgoing_message_filter(filter);
882 }
883#endif
884
jbroman0d302162015-09-05 05:46:23885 cc::SetClientNameForMetrics("Renderer");
loysoa6edaaff2015-05-25 03:26:44886
loyso65c93c602015-08-11 05:15:57887 is_threaded_animation_enabled_ =
888 !command_line.HasSwitch(cc::switches::kDisableThreadedAnimation);
889
reveman91a0a872014-11-04 03:40:32890 is_zero_copy_enabled_ = command_line.HasSwitch(switches::kEnableZeroCopy);
ericrk1d17f752015-10-20 03:03:07891 is_partial_raster_enabled_ =
dongseong.hwang23db47f2016-03-08 07:50:02892 !command_line.HasSwitch(switches::kDisablePartialRaster);
ccameronc7fcd132015-11-03 20:14:31893 is_gpu_memory_buffer_compositor_resources_enabled_ = command_line.HasSwitch(
894 switches::kEnableGpuMemoryBufferCompositorResources);
[email protected]a23530d2014-03-11 06:04:14895
Greg Kerra7b943b2017-07-24 23:17:17896// On macOS this value is adjusted in `UpdateScrollbarTheme()`,
897// but the system default is true.
898#if defined(OS_MACOSX)
899 is_elastic_overscroll_enabled_ = true;
ccamerona7644752014-12-30 01:16:31900#else
901 is_elastic_overscroll_enabled_ = false;
902#endif
903
[email protected]a23530d2014-03-11 06:04:14904 if (command_line.HasSwitch(switches::kDisableLCDText)) {
905 is_lcd_text_enabled_ = false;
906 } else if (command_line.HasSwitch(switches::kEnableLCDText)) {
907 is_lcd_text_enabled_ = true;
908 } else {
909#if defined(OS_ANDROID)
910 is_lcd_text_enabled_ = false;
911#else
912 is_lcd_text_enabled_ = true;
913#endif
914 }
915
danakjab9ef4d2017-10-31 23:38:33916 if (command_line.HasSwitch(switches::kDisableGpuCompositing))
917 is_gpu_compositing_disabled_ = true;
918
[email protected]b8d82c22014-03-31 20:12:46919 is_gpu_rasterization_forced_ =
920 command_line.HasSwitch(switches::kForceGpuRasterization);
[email protected]a23530d2014-03-11 06:04:14921
senorblancob60ba952015-01-27 19:12:36922 if (command_line.HasSwitch(switches::kGpuRasterizationMSAASampleCount)) {
923 std::string string_value = command_line.GetSwitchValueASCII(
924 switches::kGpuRasterizationMSAASampleCount);
925 bool parsed_msaa_sample_count =
926 base::StringToInt(string_value, &gpu_rasterization_msaa_sample_count_);
927 DCHECK(parsed_msaa_sample_count) << string_value;
928 DCHECK_GE(gpu_rasterization_msaa_sample_count_, 0);
929 } else {
senorblanco2a5b0e12015-08-14 21:55:37930 gpu_rasterization_msaa_sample_count_ = -1;
senorblancob60ba952015-01-27 19:12:36931 }
932
[email protected]433df472012-03-07 20:33:39933 // Note that under Linux, the media library will normally already have
934 // been initialized by the Zygote before this instance became a Renderer.
chcunninghamfd11b3c2015-06-09 02:09:42935 media::InitializeMediaLibrary();
[email protected]433df472012-03-07 20:33:39936
dalecurtis88af3932016-02-20 00:12:20937#if defined(OS_ANDROID)
938 if (!command_line.HasSwitch(switches::kDisableAcceleratedVideoDecode) &&
939 media::MediaCodecUtil::IsMediaCodecAvailable()) {
Zhenyao Mocdae4522018-02-09 20:10:26940 bool accelerated_video_decode_blacklisted = false;
941 if (!command_line.HasSwitch(switches::kIgnoreGpuBlacklist)) {
942 int32_t major_version = 0, minor_version = 0, bugfix_version = 0;
943 base::SysInfo::OperatingSystemVersionNumbers(
944 &major_version, &minor_version, &bugfix_version);
945 if (major_version < 5) {
946 // Currently accelerated video decode is only blacklisted on
947 // Android older than Lollipop.
948 scoped_refptr<gpu::GpuChannelHost> gpu_channel_host =
949 EstablishGpuChannelSync();
950 if (!gpu_channel_host ||
951 gpu_channel_host->gpu_feature_info().status_values
952 [gpu::GPU_FEATURE_TYPE_ACCELERATED_VIDEO_DECODE] !=
953 gpu::kGpuFeatureStatusEnabled) {
954 accelerated_video_decode_blacklisted = true;
955 }
956 }
957 }
958 if (!accelerated_video_decode_blacklisted)
959 media::EnablePlatformDecoderSupport();
dalecurtis88af3932016-02-20 00:12:20960 }
961#endif
962
bashi296ebda2017-03-28 03:27:09963 memory_pressure_listener_.reset(new base::MemoryPressureListener(
964 base::Bind(&RenderThreadImpl::OnMemoryPressure, base::Unretained(this)),
965 base::Bind(&RenderThreadImpl::OnSyncMemoryPressure,
966 base::Unretained(this))));
967
danakj16275d4c2015-06-11 19:23:51968 int num_raster_threads = 0;
969 std::string string_value =
970 command_line.GetSwitchValueASCII(switches::kNumRasterThreads);
971 bool parsed_num_raster_threads =
972 base::StringToInt(string_value, &num_raster_threads);
973 DCHECK(parsed_num_raster_threads) << string_value;
974 DCHECK_GT(num_raster_threads, 0);
vmiura78b69282015-02-14 00:01:17975
Sadrul Habib Chowdhury6928fde2018-04-20 16:02:51976#if defined(OS_LINUX)
977 categorized_worker_pool_->SetBackgroundingCallback(
978 main_thread_scheduler_->DefaultTaskRunner(),
979 base::BindOnce(
980 [](base::WeakPtr<RenderThreadImpl> render_thread,
981 base::PlatformThreadId thread_id) {
982 if (!render_thread)
983 return;
984 render_thread->render_message_filter()->SetThreadPriority(
985 thread_id, base::ThreadPriority::BACKGROUND);
986 },
987 weak_factory_.GetWeakPtr()));
988#endif
prashant.nfad657e2016-06-01 07:52:17989 categorized_worker_pool_->Start(num_raster_threads);
[email protected]1e1d1e12014-01-17 16:14:29990
penghuang342762b2016-12-02 21:04:58991 discardable_memory::mojom::DiscardableSharedMemoryManagerPtr manager_ptr;
James Cook486d9642018-05-08 17:44:21992 if (features::IsMashEnabled()) {
penghuangd6843e42016-12-17 13:57:20993#if defined(USE_AURA)
benbd3c2482017-01-07 05:48:21994 GetServiceManagerConnection()->GetConnector()->BindInterface(
penghuangd6843e42016-12-17 13:57:20995 ui::mojom::kServiceName, &manager_ptr);
996#else
997 NOTREACHED();
998#endif
999 } else {
ben649b3edd2017-03-23 00:32:021000 ChildThread::Get()->GetConnector()->BindInterface(
1001 mojom::kBrowserServiceName, mojo::MakeRequest(&manager_ptr));
penghuangd6843e42016-12-17 13:57:201002 }
1003
Jeremy Roman04f27c372017-10-27 15:20:551004 discardable_shared_memory_manager_ = std::make_unique<
penghuang342762b2016-12-02 21:04:581005 discardable_memory::ClientDiscardableSharedMemoryManager>(
1006 std::move(manager_ptr), GetIOTaskRunner());
1007
boliu9760e212015-06-23 22:49:061008 // TODO(boliu): In single process, browser main loop should set up the
1009 // discardable memory manager, and should skip this if kSingleProcess.
1010 // See crbug.com/503724.
1011 base::DiscardableMemoryAllocator::SetInstance(
penghuang342762b2016-12-02 21:04:581012 discardable_shared_memory_manager_.get());
revemancb5a66af2014-10-25 00:34:391013
ben649b3edd2017-03-23 00:32:021014 GetConnector()->BindInterface(mojom::kBrowserServiceName,
1015 mojo::MakeRequest(&storage_partition_service_));
hajimehoshi69093272016-05-13 08:30:581016
reveman7b97c322016-09-20 02:10:581017#if defined(OS_LINUX)
Nicholas Verne84dc55e2017-11-23 01:02:381018 render_message_filter()->SetThreadPriority(
1019 ChildProcess::current()->io_thread_id(), base::ThreadPriority::DISPLAY);
reveman7b97c322016-09-20 02:10:581020#endif
1021
tasakbb0640b2017-05-15 09:02:261022 process_foregrounded_count_ = 0;
tasakb95dbb50c2017-02-08 18:07:501023 needs_to_record_first_active_paint_ = false;
Takashi SAKAMOTO870f6262017-08-22 04:08:271024 was_backgrounded_time_ = base::TimeTicks::Min();
hajimehoshi7bb39582016-10-12 04:30:571025
1026 base::MemoryCoordinatorClientRegistry::GetInstance()->Register(this);
fdoray50a38342016-11-21 20:46:041027
samans2040988b2017-04-11 23:58:351028 GetConnector()->BindInterface(mojom::kBrowserServiceName,
1029 mojo::MakeRequest(&frame_sink_provider_));
danakjab9ef4d2017-10-31 23:38:331030
1031 if (!is_gpu_compositing_disabled_) {
1032 GetConnector()->BindInterface(
1033 mojom::kBrowserServiceName,
1034 mojo::MakeRequest(&compositing_mode_reporter_));
1035
1036 // Make |this| a CompositingModeWatcher for the
1037 // |compositing_mode_reporter_|.
1038 viz::mojom::CompositingModeWatcherPtr watcher_ptr;
1039 compositing_mode_watcher_binding_.Bind(mojo::MakeRequest(&watcher_ptr));
1040 compositing_mode_reporter_->AddCompositingModeWatcher(
1041 std::move(watcher_ptr));
1042 }
initial.commit09911bf2008-07-26 23:55:291043}
1044
John Abd-El-Malekd4882642017-12-04 21:45:191045RenderThreadImpl::~RenderThreadImpl() {
1046 g_main_task_runner.Get() = nullptr;
1047}
[email protected]ce79d8512013-04-22 22:44:411048
Nicholas Verne5420564d2017-10-27 07:37:541049void RenderThreadImpl::Shutdown() {
John Abd-El-Malekdcf1d1372017-10-22 06:39:411050 ChildThreadImpl::Shutdown();
1051 file_system_dispatcher_.reset();
1052 WebFileSystemImpl::DeleteThreadSpecificInstance();
harakenbbfdd9f02017-01-12 07:14:041053 // In a multi-process mode, we immediately exit the renderer.
1054 // Historically we had a graceful shutdown sequence here but it was
1055 // 1) a waste of performance and 2) a source of lots of complicated
1056 // crashes caused by shutdown ordering. Immediate exit eliminates
1057 // those problems.
cbrunia3f655b2017-03-20 11:36:411058
1059 // Give the V8 isolate a chance to dump internal stats useful for performance
1060 // evaluation and debugging.
Blink Reformat1c4d759e2017-04-09 16:34:541061 blink::MainThreadIsolate()->DumpAndResetStats();
cbrunia3f655b2017-03-20 11:36:411062
Adithya Srinivasandf421e82017-06-01 14:36:111063 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
1064 switches::kDumpBlinkRuntimeCallStats))
1065 blink::LogRuntimeCallStats();
1066
harakenbbfdd9f02017-01-12 07:14:041067 // In a single-process mode, we cannot call _exit(0) in Shutdown() because
1068 // it will exit the process before the browser side is ready to exit.
1069 if (!base::CommandLine::ForCurrentProcess()->HasSwitch(
1070 switches::kSingleProcess))
haraken940efb92017-02-08 05:58:151071 base::Process::TerminateCurrentProcessImmediately(0);
harakenbbfdd9f02017-01-12 07:14:041072}
[email protected]1223d6ef2011-03-28 16:47:501073
harakenbbfdd9f02017-01-12 07:14:041074bool RenderThreadImpl::ShouldBeDestroyed() {
1075 DCHECK(base::CommandLine::ForCurrentProcess()->HasSwitch(
1076 switches::kSingleProcess));
1077 // In a single-process mode, it is unsafe to destruct this renderer thread
1078 // because we haven't run the shutdown sequence. Hence we leak the render
1079 // thread.
1080 //
1081 // In this case, we also need to disable at-exit callbacks because some of
1082 // the at-exit callbacks are expected to run after the renderer thread
1083 // has been destructed.
1084 base::AtExitManager::DisableAllAtExitManagers();
1085 return false;
initial.commit09911bf2008-07-26 23:55:291086}
1087
[email protected]f1a29a02011-10-06 23:08:441088bool RenderThreadImpl::Send(IPC::Message* msg) {
changwan6ed4d432016-05-19 22:03:541089 // There are cases where we want to pump asynchronous messages while waiting
1090 // synchronously for the replies to the message to be sent here. However, this
1091 // may create an opportunity for re-entrancy into WebKit and other subsystems,
1092 // so we need to take care to disable callbacks, timers, and pending network
1093 // loads that could trigger such callbacks.
[email protected]38b592902011-04-16 02:08:421094 bool pumping_events = false;
[email protected]80fc08c52010-03-09 07:43:501095 if (msg->is_sync()) {
1096 if (msg->is_caller_pumping_messages()) {
1097 pumping_events = true;
[email protected]80fc08c52010-03-09 07:43:501098 }
[email protected]c1f50aa2010-02-18 03:46:571099 }
1100
Yuta Kitamuradeb91bb2018-05-29 05:53:201101 std::unique_ptr<blink::scheduler::WebThreadScheduler::RendererPauseHandle>
Yoland Yan25439ba2017-10-11 19:45:551102 renderer_paused_handle;
1103
[email protected]c1f50aa2010-02-18 03:46:571104 if (pumping_events) {
Yuta Kitamura3331f5c2018-04-05 11:12:251105 renderer_paused_handle = main_thread_scheduler_->PauseRenderer();
Blink Reformat1c4d759e2017-04-09 16:34:541106 WebView::WillEnterModalLoop();
[email protected]c1f50aa2010-02-18 03:46:571107 }
1108
jam8a021512a2015-02-03 18:16:081109 bool rv = ChildThreadImpl::Send(msg);
[email protected]c1f50aa2010-02-18 03:46:571110
Yoland Yan25439ba2017-10-11 19:45:551111 if (pumping_events)
Blink Reformat1c4d759e2017-04-09 16:34:541112 WebView::DidExitModalLoop();
[email protected]c1f50aa2010-02-18 03:46:571113
1114 return rv;
1115}
1116
[email protected]f1a29a02011-10-06 23:08:441117IPC::SyncChannel* RenderThreadImpl::GetChannel() {
[email protected]526476902011-10-06 20:34:061118 return channel();
1119}
1120
[email protected]f1a29a02011-10-06 23:08:441121std::string RenderThreadImpl::GetLocale() {
[email protected]526476902011-10-06 20:34:061122 // The browser process should have passed the locale to the renderer via the
[email protected]dfd53652012-10-25 00:20:021123 // --lang command line flag.
avi83883c82014-12-23 00:08:491124 const base::CommandLine& parsed_command_line =
1125 *base::CommandLine::ForCurrentProcess();
[email protected]526476902011-10-06 20:34:061126 const std::string& lang =
1127 parsed_command_line.GetSwitchValueASCII(switches::kLang);
[email protected]dfd53652012-10-25 00:20:021128 DCHECK(!lang.empty());
[email protected]526476902011-10-06 20:34:061129 return lang;
1130}
1131
[email protected]07bb6332012-01-21 01:07:571132IPC::SyncMessageFilter* RenderThreadImpl::GetSyncMessageFilter() {
1133 return sync_message_filter();
1134}
1135
avi1023d012015-12-25 02:39:141136void RenderThreadImpl::AddRoute(int32_t routing_id, IPC::Listener* listener) {
jam8a021512a2015-02-03 18:16:081137 ChildThreadImpl::GetRouter()->AddRoute(routing_id, listener);
ben76f52b242016-06-18 05:42:481138 auto it = pending_frame_creates_.find(routing_id);
1139 if (it == pending_frame_creates_.end())
rockotf8fdd9b2015-12-16 22:22:351140 return;
1141
1142 RenderFrameImpl* frame = RenderFrameImpl::FromRoutingID(routing_id);
1143 if (!frame)
1144 return;
1145
ben76f52b242016-06-18 05:42:481146 scoped_refptr<PendingFrameCreate> create(it->second);
Balazs Engedyba034e72017-10-27 22:26:281147 frame->BindFrame(it->second->browser_info(), it->second->TakeFrameRequest());
ben76f52b242016-06-18 05:42:481148 pending_frame_creates_.erase(it);
[email protected]c1f50aa2010-02-18 03:46:571149}
1150
avi1023d012015-12-25 02:39:141151void RenderThreadImpl::RemoveRoute(int32_t routing_id) {
jam8a021512a2015-02-03 18:16:081152 ChildThreadImpl::GetRouter()->RemoveRoute(routing_id);
[email protected]c1f50aa2010-02-18 03:46:571153}
[email protected]0ec90d522014-03-12 16:28:191154
ben76f52b242016-06-18 05:42:481155void RenderThreadImpl::RegisterPendingFrameCreate(
benf28ce882017-05-02 16:15:491156 const service_manager::BindSourceInfo& browser_info,
rockotf8fdd9b2015-12-16 22:22:351157 int routing_id,
Balazs Engedyba034e72017-10-27 22:26:281158 mojom::FrameRequest frame_request) {
ben76f52b242016-06-18 05:42:481159 std::pair<PendingFrameCreateMap::iterator, bool> result =
1160 pending_frame_creates_.insert(std::make_pair(
kylechar96f3eba2017-09-25 20:23:561161 routing_id, base::MakeRefCounted<PendingFrameCreate>(
Balazs Engedyba034e72017-10-27 22:26:281162 browser_info, routing_id, std::move(frame_request))));
rockotf8fdd9b2015-12-16 22:22:351163 CHECK(result.second) << "Inserting a duplicate item.";
1164}
1165
leon.han06e55662016-03-26 17:19:421166mojom::StoragePartitionService* RenderThreadImpl::GetStoragePartitionService() {
jamc912ca32016-02-24 20:17:311167 return storage_partition_service_.get();
1168}
1169
jam188f19f2017-06-07 03:56:241170mojom::RendererHost* RenderThreadImpl::GetRendererHost() {
Nicholas Verne06de8122017-11-16 04:47:381171 if (!renderer_host_) {
Joel Hockey3146d142017-11-15 22:27:401172 GetChannel()->GetRemoteAssociatedInterface(&renderer_host_);
Nicholas Verne06de8122017-11-16 04:47:381173 }
jam188f19f2017-06-07 03:56:241174 return renderer_host_.get();
1175}
1176
[email protected]77fc9b92011-10-15 16:20:371177int RenderThreadImpl::GenerateRoutingID() {
rockote261d2112016-09-21 22:22:231178 int32_t routing_id = MSG_ROUTING_NONE;
1179 render_message_filter()->GenerateRoutingID(&routing_id);
[email protected]77fc9b92011-10-15 16:20:371180 return routing_id;
1181}
1182
[email protected]74122042014-04-25 00:07:301183void RenderThreadImpl::AddFilter(IPC::MessageFilter* filter) {
[email protected]42f1d7822009-07-23 18:17:551184 channel()->AddFilter(filter);
1185}
1186
[email protected]74122042014-04-25 00:07:301187void RenderThreadImpl::RemoveFilter(IPC::MessageFilter* filter) {
[email protected]42f1d7822009-07-23 18:17:551188 channel()->RemoveFilter(filter);
1189}
1190
tyoshino832a58a2016-04-18 08:14:081191void RenderThreadImpl::AddObserver(RenderThreadObserver* observer) {
[email protected]526476902011-10-06 20:34:061192 observers_.AddObserver(observer);
nigeltao7cd8d5582016-12-12 06:05:281193 observer->RegisterMojoInterfaces(&associated_interfaces_);
[email protected]526476902011-10-06 20:34:061194}
1195
tyoshino832a58a2016-04-18 08:14:081196void RenderThreadImpl::RemoveObserver(RenderThreadObserver* observer) {
nigeltao7cd8d5582016-12-12 06:05:281197 observer->UnregisterMojoInterfaces(&associated_interfaces_);
[email protected]526476902011-10-06 20:34:061198 observers_.RemoveObserver(observer);
1199}
1200
[email protected]359dfa32011-10-12 01:10:151201void RenderThreadImpl::SetResourceDispatcherDelegate(
[email protected]e9ff79c2012-10-19 21:31:261202 ResourceDispatcherDelegate* delegate) {
John Abd-El-Malek6b56ef712017-10-21 22:52:461203 resource_dispatcher_->set_delegate(delegate);
[email protected]359dfa32011-10-12 01:10:151204}
1205
vollick1050cc62015-12-03 07:04:541206void RenderThreadImpl::InitializeCompositorThread() {
Alexander Timin053b6192018-03-15 14:13:341207 blink::WebThreadCreationParams params(
1208 blink::WebThreadType::kCompositorThread);
vollick1050cc62015-12-03 07:04:541209#if defined(OS_ANDROID)
Alexander Timin053b6192018-03-15 14:13:341210 params.thread_options.priority = base::ThreadPriority::DISPLAY;
vollick1050cc62015-12-03 07:04:541211#endif
altiminc7369bf2017-04-11 14:29:151212 compositor_thread_ =
Alexander Timin053b6192018-03-15 14:13:341213 blink::scheduler::WebThreadBase::CreateCompositorThread(params);
boliu66024c62016-04-20 04:00:411214 blink_platform_impl_->SetCompositorThread(compositor_thread_.get());
Yuta Kitamura5ee2b9b2018-02-14 09:00:311215 compositor_task_runner_ = compositor_thread_->GetTaskRunner();
boliu66024c62016-04-20 04:00:411216 compositor_task_runner_->PostTask(
1217 FROM_HERE,
tzikff2a81a2017-09-15 05:10:061218 base::BindOnce(base::IgnoreResult(&ThreadRestrictions::SetIOAllowed),
1219 false));
Sadrul Habib Chowdhury16b3a162018-02-03 01:43:181220 GetContentClient()->renderer()->PostCompositorThreadCreated(
1221 compositor_task_runner_.get());
reveman7b97c322016-09-20 02:10:581222#if defined(OS_LINUX)
Nicholas Verne84dc55e2017-11-23 01:02:381223 render_message_filter()->SetThreadPriority(compositor_thread_->ThreadId(),
1224 base::ThreadPriority::DISPLAY);
reveman7b97c322016-09-20 02:10:581225#endif
vollick1050cc62015-12-03 07:04:541226}
1227
jam75c44222016-03-23 05:34:241228void RenderThreadImpl::InitializeWebKit(
Stuart Langley7b8dc772017-10-31 03:55:201229 const scoped_refptr<base::SingleThreadTaskRunner>& resource_task_queue,
Ken Rockot510c5972017-12-05 16:37:041230 service_manager::BinderRegistry* registry) {
jam75c44222016-03-23 05:34:241231 DCHECK(!blink_platform_impl_);
[email protected]d1b8fccc2011-08-03 01:20:131232
avi83883c82014-12-23 00:08:491233 const base::CommandLine& command_line =
1234 *base::CommandLine::ForCurrentProcess();
chunyang.daibe874c52014-11-14 06:45:051235
1236#ifdef ENABLE_VTUNE_JIT_INTERFACE
1237 if (command_line.HasSwitch(switches::kEnableVtune))
1238 gin::Debug::SetJitCodeEventHandler(vTune::GetVtuneCodeEventHandler());
1239#endif
1240
Reilly Grant9944f162017-08-29 01:22:411241 blink_platform_impl_.reset(
Yuta Kitamura3331f5c2018-04-05 11:12:251242 new RendererBlinkPlatformImpl(main_thread_scheduler_.get()));
rmcilroy4073ae12015-01-08 13:08:101243 SetRuntimeFeaturesDefaultsAndUpdateFromArgs(command_line);
hlopko852ffcf2016-09-16 16:50:591244 GetContentClient()
1245 ->renderer()
1246 ->SetRuntimeFeaturesDefaultsBeforeBlinkInitialization();
Ken Rockot510c5972017-12-05 16:37:041247 blink::Initialize(blink_platform_impl_.get(), registry);
[email protected]d1b8fccc2011-08-03 01:20:131248
Blink Reformat1c4d759e2017-04-09 16:34:541249 v8::Isolate* isolate = blink::MainThreadIsolate();
[email protected]4b5340282014-07-08 11:37:341250 isolate->SetCreateHistogramFunction(CreateHistogram);
1251 isolate->SetAddHistogramSampleFunction(AddHistogramSample);
Yuta Kitamura3331f5c2018-04-05 11:12:251252 main_thread_scheduler_->SetRAILModeObserver(this);
[email protected]4b5340282014-07-08 11:37:341253
rmcilroy321f924d2014-11-06 00:56:001254 main_thread_compositor_task_runner_ =
Yuta Kitamura3331f5c2018-04-05 11:12:251255 main_thread_scheduler_->CompositorTaskRunner();
skyostilc30aa402014-10-10 13:49:091256
khushalsagard7178e42017-01-20 01:31:491257 if (!command_line.HasSwitch(switches::kDisableThreadedCompositing))
vollick1050cc62015-12-03 07:04:541258 InitializeCompositorThread();
[email protected]a9fb30aa2011-10-06 06:58:461259
skyostil2d3b5bd2015-05-27 15:40:591260 scoped_refptr<base::SingleThreadTaskRunner> compositor_impl_side_task_runner;
vollick1050cc62015-12-03 07:04:541261 if (compositor_task_runner_)
skyostil2d3b5bd2015-05-27 15:40:591262 compositor_impl_side_task_runner = compositor_task_runner_;
[email protected]7f1f63f2013-03-07 06:07:291263 else
skyostil2d3b5bd2015-05-27 15:40:591264 compositor_impl_side_task_runner = base::ThreadTaskRunnerHandle::Get();
[email protected]1842fe22012-08-13 23:24:351265
[email protected]58436a12012-03-21 17:10:261266 RenderThreadImpl::RegisterSchemes();
1267
xhwang194acae2014-11-12 22:46:331268 RenderMediaClient::Initialize();
1269
Yuta Kitamura3331f5c2018-04-05 11:12:251270 idle_timer_.SetTaskRunner(GetWebMainThreadScheduler()->DefaultTaskRunner());
Hajime Hoshi9b20bab2018-03-07 11:20:341271
ulan4a385192015-11-11 10:59:181272 if (GetContentClient()->renderer()->RunIdleHandlerWhenWidgetsHidden()) {
[email protected]1784b2f2011-11-24 10:53:481273 ScheduleIdleHandler(kLongIdleHandlerDelayMs);
ulan4a385192015-11-11 10:59:181274 } else {
1275 // If we do not track widget visibility, then assume conservatively that
1276 // the isolate is in background. This reduces memory usage.
1277 isolate->IsolateInBackgroundNotification();
1278 }
[email protected]2541d1a2013-07-10 07:33:271279
Hajime Hoshid99e8fc2018-04-25 03:23:001280 main_thread_scheduler_->SetFreezingWhenBackgroundedEnabled(
1281 GetContentClient()->renderer()->AllowFreezingWhenProcessBackgrounded());
jdduke73220f02015-09-04 17:03:511282
Khushala4e236f2018-06-01 03:00:461283 // Hook up blink's codecs so skia can call them. Since only the renderer
1284 // processes should be doing image decoding, this is not done in the common
1285 // skia initialization code for the GPU.
reed08cd16372017-02-21 22:11:411286 SkGraphics::SetImageGeneratorFromEncodedDataFactory(
Vladimir Levin325831d2017-08-30 15:03:221287 blink::WebImageGenerator::CreateAsSkImageGenerator);
reed6e5a72222015-08-06 20:37:161288
paritosh.in7e30c902015-04-15 17:04:071289 if (command_line.HasSwitch(switches::kExplicitlyAllowedPorts)) {
1290 std::string allowed_ports =
1291 command_line.GetSwitchValueASCII(switches::kExplicitlyAllowedPorts);
1292 net::SetExplicitlyAllowedPorts(allowed_ports);
1293 }
[email protected]d1b8fccc2011-08-03 01:20:131294}
1295
[email protected]58436a12012-03-21 17:10:261296void RenderThreadImpl::RegisterSchemes() {
mkwst8e94fb32015-05-20 05:05:141297 // chrome:
Blink Reformat1c4d759e2017-04-09 16:34:541298 WebString chrome_scheme(WebString::FromASCII(kChromeUIScheme));
1299 WebSecurityPolicy::RegisterURLSchemeAsDisplayIsolated(chrome_scheme);
1300 WebSecurityPolicy::RegisterURLSchemeAsNotAllowingJavascriptURLs(
mkwst8e94fb32015-05-20 05:05:141301 chrome_scheme);
mkwst8e94fb32015-05-20 05:05:141302
1303 // chrome-devtools:
Blink Reformat1c4d759e2017-04-09 16:34:541304 WebString devtools_scheme(WebString::FromASCII(kChromeDevToolsScheme));
1305 WebSecurityPolicy::RegisterURLSchemeAsDisplayIsolated(devtools_scheme);
meacerce6b66032016-06-02 20:56:051306
1307 // view-source:
Blink Reformat1c4d759e2017-04-09 16:34:541308 WebString view_source_scheme(WebString::FromASCII(kViewSourceScheme));
1309 WebSecurityPolicy::RegisterURLSchemeAsDisplayIsolated(view_source_scheme);
Alex Moshchuk71f485592017-08-16 16:20:001310
1311 // chrome-error:
1312 WebString error_scheme(WebString::FromASCII(kChromeErrorScheme));
1313 WebSecurityPolicy::RegisterURLSchemeAsDisplayIsolated(error_scheme);
1314 WebSecurityPolicy::RegisterURLSchemeAsNotAllowingJavascriptURLs(error_scheme);
[email protected]58436a12012-03-21 17:10:261315}
1316
[email protected]e6e30ac2014-01-13 21:24:391317void RenderThreadImpl::RecordAction(const base::UserMetricsAction& action) {
[email protected]97880c82013-12-04 07:09:211318 Send(new ViewHostMsg_UserMetricsRecordAction(action.str_));
1319}
1320
1321void RenderThreadImpl::RecordComputedAction(const std::string& action) {
[email protected]526476902011-10-06 20:34:061322 Send(new ViewHostMsg_UserMetricsRecordAction(action));
1323}
1324
dchengcedca5612016-04-09 01:40:151325std::unique_ptr<base::SharedMemory>
1326RenderThreadImpl::HostAllocateSharedMemoryBuffer(size_t size) {
sadrulee3ff1f2016-12-09 04:22:011327 return ChildThreadImpl::AllocateSharedMemory(size);
[email protected]00614a82011-10-07 22:39:311328}
1329
[email protected]f1a29a02011-10-06 23:08:441330void RenderThreadImpl::RegisterExtension(v8::Extension* extension) {
Blink Reformat1c4d759e2017-04-09 16:34:541331 WebScriptController::RegisterExtension(extension);
[email protected]526476902011-10-06 20:34:061332}
1333
avi1023d012015-12-25 02:39:141334void RenderThreadImpl::ScheduleIdleHandler(int64_t initial_delay_ms) {
[email protected]6593ae12011-11-14 12:09:441335 idle_notification_delay_in_ms_ = initial_delay_ms;
[email protected]526476902011-10-06 20:34:061336 idle_timer_.Stop();
1337 idle_timer_.Start(FROM_HERE,
[email protected]6593ae12011-11-14 12:09:441338 base::TimeDelta::FromMilliseconds(initial_delay_ms),
[email protected]f1a29a02011-10-06 23:08:441339 this, &RenderThreadImpl::IdleHandler);
[email protected]526476902011-10-06 20:34:061340}
1341
[email protected]f1a29a02011-10-06 23:08:441342void RenderThreadImpl::IdleHandler() {
[email protected]1784b2f2011-11-24 10:53:481343 bool run_in_foreground_tab = (widget_count_ > hidden_widget_count_) &&
[email protected]e9ff79c2012-10-19 21:31:261344 GetContentClient()->renderer()->
[email protected]1784b2f2011-11-24 10:53:481345 RunIdleHandlerWhenWidgetsHidden();
1346 if (run_in_foreground_tab) {
jochen5a32aaf2014-09-26 20:37:431347 if (idle_notifications_to_skip_ > 0) {
1348 --idle_notifications_to_skip_;
1349 } else {
ssid0603ca9f2015-06-09 16:48:081350 ReleaseFreeMemory();
jochen5a32aaf2014-09-26 20:37:431351 }
1352 ScheduleIdleHandler(kLongIdleHandlerDelayMs);
[email protected]1784b2f2011-11-24 10:53:481353 return;
1354 }
[email protected]237a14852012-04-28 02:56:381355
ssid0603ca9f2015-06-09 16:48:081356 ReleaseFreeMemory();
[email protected]526476902011-10-06 20:34:061357
[email protected]26e82322014-01-20 14:18:221358 // Continue the idle timer if the webkit shared timer is not suspended or
1359 // something is left to do.
Alexander Timin4b6152232017-10-17 20:34:061360 bool continue_timer = !webkit_shared_timer_suspended_;
[email protected]26e82322014-01-20 14:18:221361
sullivancd45a3e2014-09-19 14:39:181362 // Schedule next invocation. When the tab is originally hidden, an invocation
1363 // is scheduled for kInitialIdleHandlerDelayMs in
1364 // RenderThreadImpl::WidgetHidden in order to race to a minimal heap.
1365 // After that, idle calls can be much less frequent, so run at a maximum of
1366 // once every kLongIdleHandlerDelayMs.
[email protected]6593ae12011-11-14 12:09:441367 // Dampen the delay using the algorithm (if delay is in seconds):
[email protected]526476902011-10-06 20:34:061368 // delay = delay + 1 / (delay + 2)
1369 // Using floor(delay) has a dampening effect such as:
sullivancd45a3e2014-09-19 14:39:181370 // 30s, 30, 30, 31, 31, 31, 31, 32, 32, ...
[email protected]6593ae12011-11-14 12:09:441371 // If the delay is in milliseconds, the above formula is equivalent to:
1372 // delay_ms / 1000 = delay_ms / 1000 + 1 / (delay_ms / 1000 + 2)
1373 // which is equivalent to
1374 // delay_ms = delay_ms + 1000*1000 / (delay_ms + 2000).
[email protected]26e82322014-01-20 14:18:221375 if (continue_timer) {
sullivancd45a3e2014-09-19 14:39:181376 ScheduleIdleHandler(
1377 std::max(kLongIdleHandlerDelayMs,
1378 idle_notification_delay_in_ms_ +
1379 1000000 / (idle_notification_delay_in_ms_ + 2000)));
[email protected]26e82322014-01-20 14:18:221380
1381 } else {
1382 idle_timer_.Stop();
1383 }
[email protected]526476902011-10-06 20:34:061384
ericwilligers88e69742016-10-17 19:29:551385 for (auto& observer : observers_)
1386 observer.IdleNotification();
[email protected]526476902011-10-06 20:34:061387}
1388
avi1023d012015-12-25 02:39:141389int64_t RenderThreadImpl::GetIdleNotificationDelayInMs() const {
[email protected]6593ae12011-11-14 12:09:441390 return idle_notification_delay_in_ms_;
[email protected]526476902011-10-06 20:34:061391}
1392
[email protected]6593ae12011-11-14 12:09:441393void RenderThreadImpl::SetIdleNotificationDelayInMs(
avi1023d012015-12-25 02:39:141394 int64_t idle_notification_delay_in_ms) {
[email protected]6593ae12011-11-14 12:09:441395 idle_notification_delay_in_ms_ = idle_notification_delay_in_ms;
[email protected]4a7d6392011-09-19 20:55:081396}
1397
[email protected]5b18406362013-06-18 18:46:431398int RenderThreadImpl::PostTaskToAllWebWorkers(const base::Closure& closure) {
kinukoef647412015-12-23 06:10:431399 return WorkerThreadRegistry::Instance()->PostTaskToAllThreads(closure);
[email protected]a9bd323d2013-06-17 20:27:561400}
1401
[email protected]b02f5902012-12-19 07:33:001402bool RenderThreadImpl::ResolveProxy(const GURL& url, std::string* proxy_list) {
1403 bool result = false;
1404 Send(new ViewHostMsg_ResolveProxy(url, &result, proxy_list));
1405 return result;
1406}
1407
[email protected]1784b2f2011-11-24 10:53:481408void RenderThreadImpl::PostponeIdleNotification() {
1409 idle_notifications_to_skip_ = 2;
1410}
1411
dcastagna7f45dada2015-10-19 20:17:351412media::GpuVideoAcceleratorFactories* RenderThreadImpl::GetGpuFactories() {
[email protected]3bb8bb32013-07-11 13:13:031413 DCHECK(IsMainThread());
1414
dcastagna09bd6b32016-02-01 21:54:281415 if (!gpu_factories_.empty()) {
Emircan Uysalerb0f69fcf2018-03-29 03:23:531416 if (!gpu_factories_.back()->CheckContextProviderLost())
Daniele Castagnaa2338842018-03-15 23:23:161417 return gpu_factories_.back().get();
Miguel Casas5e1018052018-01-09 19:17:361418
Daniele Castagnaa2338842018-03-15 23:23:161419 GetMediaThreadTaskRunner()->PostTask(
1420 FROM_HERE,
1421 base::BindOnce(base::IgnoreResult(
1422 &GpuVideoAcceleratorFactoriesImpl::CheckContextLost),
1423 base::Unretained(gpu_factories_.back().get())));
dcastagna09bd6b32016-02-01 21:54:281424 }
dcastagna7f45dada2015-10-19 20:17:351425
tobiasjsca238b3b2015-06-24 22:53:541426 const base::CommandLine* cmd_line = base::CommandLine::ForCurrentProcess();
1427
danakj0b4b94e32016-05-10 22:33:011428 scoped_refptr<gpu::GpuChannelHost> gpu_channel_host =
sadrul6d310fa2016-08-04 02:12:161429 EstablishGpuChannelSync();
danakj0b4b94e32016-05-10 22:33:011430 if (!gpu_channel_host)
1431 return nullptr;
danakj0dd9e1e2016-05-11 22:15:091432 // This context is only used to create textures and mailbox them, so
1433 // use lower limits than the default.
1434 gpu::SharedMemoryLimits limits = gpu::SharedMemoryLimits::ForMailboxContext();
Daniele Castagnaa2338842018-03-15 23:23:161435 bool support_locking = false;
Victor Miura3a4ad4f82017-12-13 06:03:451436 bool support_gles2_interface = true;
1437 bool support_raster_interface = false;
Adrienne Walker436a7752017-08-28 23:33:091438 bool support_oop_rasterization = false;
Justin Novosad7d3d2502018-03-27 18:55:381439 bool support_grcontext = false;
sadrul85cc5d82016-12-20 03:37:411440 scoped_refptr<ui::ContextProviderCommandBuffer> media_context_provider =
Justin Novosad7d3d2502018-03-27 18:55:381441 CreateOffscreenContext(gpu_channel_host, GetGpuMemoryBufferManager(),
1442 limits, support_locking, support_gles2_interface,
1443 support_raster_interface,
1444 support_oop_rasterization, support_grcontext,
1445 ui::command_buffer_metrics::MEDIA_CONTEXT,
1446 kGpuStreamIdMedia, kGpuStreamPriorityMedia);
danakj0b4b94e32016-05-10 22:33:011447
danakj0b4b94e32016-05-10 22:33:011448 const bool enable_video_accelerator =
Zhenyao Mo16d39b82017-12-15 22:48:041449 !cmd_line->HasSwitch(switches::kDisableAcceleratedVideoDecode) &&
1450 (gpu_channel_host->gpu_feature_info()
1451 .status_values[gpu::GPU_FEATURE_TYPE_ACCELERATED_VIDEO_DECODE] ==
1452 gpu::kGpuFeatureStatusEnabled);
Emircan Uysaler08a80852018-04-13 01:13:211453 const bool enable_gpu_memory_buffers =
danakjab9ef4d2017-10-31 23:38:331454 !is_gpu_compositing_disabled_ &&
Emircan Uysaler08a80852018-04-13 01:13:211455#if defined(OS_MACOSX) || defined(OS_LINUX) || defined(OS_WIN)
danakjab9ef4d2017-10-31 23:38:331456 !cmd_line->HasSwitch(switches::kDisableGpuMemoryBufferVideoFrames);
dcastagnab65e6072015-09-05 07:18:421457#else
danakj0b4b94e32016-05-10 22:33:011458 cmd_line->HasSwitch(switches::kEnableGpuMemoryBufferVideoFrames);
Emircan Uysaler08a80852018-04-13 01:13:211459#endif // defined(OS_MACOSX) || defined(OS_LINUX) || defined(OS_WIN)
1460 const bool enable_media_stream_gpu_memory_buffers =
1461 enable_gpu_memory_buffers &&
1462 base::FeatureList::IsEnabled(
1463 features::kWebRtcUseGpuMemoryBufferVideoFrames);
1464 bool enable_video_gpu_memory_buffers = enable_gpu_memory_buffers;
1465#if defined(OS_WIN)
1466 enable_video_gpu_memory_buffers =
1467 enable_video_gpu_memory_buffers &&
1468 (cmd_line->HasSwitch(switches::kEnableGpuMemoryBufferVideoFrames) ||
1469 gpu_channel_host->gpu_info().supports_overlays);
1470#endif // defined(OS_WIN)
dcastagna5077d6d2016-01-27 00:07:051471
Miguel Casas-Sanchez7d464702017-07-29 14:19:211472 media::mojom::VideoEncodeAcceleratorProviderPtr vea_provider;
1473 gpu_->CreateVideoEncodeAcceleratorProvider(mojo::MakeRequest(&vea_provider));
Miguel Casas-Sanchezdaca32562017-07-11 08:05:451474
Miguel Casas-Sanchezcfcca5d52017-07-07 02:32:591475 gpu_factories_.push_back(GpuVideoAcceleratorFactoriesImpl::Create(
danakj0b4b94e32016-05-10 22:33:011476 std::move(gpu_channel_host), base::ThreadTaskRunnerHandle::Get(),
Daniele Castagnaa2338842018-03-15 23:23:161477 GetMediaThreadTaskRunner(), std::move(media_context_provider),
Emircan Uysaler08a80852018-04-13 01:13:211478 enable_video_gpu_memory_buffers, enable_media_stream_gpu_memory_buffers,
1479 enable_video_accelerator, vea_provider.PassInterface()));
Miguel Casas5e1018052018-01-09 19:17:361480 gpu_factories_.back()->SetRenderingColorSpace(rendering_color_space_);
leon.han21e0e482017-02-23 04:13:321481 return gpu_factories_.back().get();
[email protected]3bb8bb32013-07-11 13:13:031482}
1483
sadrul85cc5d82016-12-20 03:37:411484scoped_refptr<ui::ContextProviderCommandBuffer>
[email protected]f10dc472013-09-27 03:31:591485RenderThreadImpl::SharedMainThreadContextProvider() {
[email protected]e06e1122013-03-15 17:12:381486 DCHECK(IsMainThread());
danakje8ec797e2016-04-19 04:08:431487 if (shared_main_thread_contexts_ &&
1488 shared_main_thread_contexts_->ContextGL()->GetGraphicsResetStatusKHR() ==
1489 GL_NO_ERROR)
1490 return shared_main_thread_contexts_;
1491
sadrul6d310fa2016-08-04 02:12:161492 scoped_refptr<gpu::GpuChannelHost> gpu_channel_host(
1493 EstablishGpuChannelSync());
danakje8ec797e2016-04-19 04:08:431494 if (!gpu_channel_host) {
1495 shared_main_thread_contexts_ = nullptr;
1496 return nullptr;
[email protected]c29b7ff2013-03-06 03:51:041497 }
danakje8ec797e2016-04-19 04:08:431498
danakj9a04adc2016-05-16 22:45:071499 bool support_locking = false;
Victor Miura3a4ad4f82017-12-13 06:03:451500 bool support_gles2_interface = true;
Jonathan Backerf0d615dc2018-03-12 21:05:461501 bool support_raster_interface = false;
Adrienne Walker436a7752017-08-28 23:33:091502 bool support_oop_rasterization = false;
Justin Novosad7d3d2502018-03-27 18:55:381503 bool support_grcontext = true;
danakjc3983552016-05-03 00:04:351504 shared_main_thread_contexts_ = CreateOffscreenContext(
Antoine Labour5ac65db2017-12-19 18:02:581505 std::move(gpu_channel_host), GetGpuMemoryBufferManager(),
1506 gpu::SharedMemoryLimits(), support_locking, support_gles2_interface,
Justin Novosad7d3d2502018-03-27 18:55:381507 support_raster_interface, support_oop_rasterization, support_grcontext,
sadrul85cc5d82016-12-20 03:37:411508 ui::command_buffer_metrics::RENDERER_MAINTHREAD_CONTEXT,
sunnyps8f9139e2017-05-12 17:53:251509 kGpuStreamIdDefault, kGpuStreamPriorityDefault);
danakj45cfd232017-10-18 19:31:311510 auto result = shared_main_thread_contexts_->BindToCurrentThread();
1511 if (result != gpu::ContextResult::kSuccess)
danakje8ec797e2016-04-19 04:08:431512 shared_main_thread_contexts_ = nullptr;
[email protected]f10dc472013-09-27 03:31:591513 return shared_main_thread_contexts_;
[email protected]c29b7ff2013-03-06 03:51:041514}
1515
siva.gunturi5d4feb052015-11-15 16:15:311516#if defined(OS_ANDROID)
boliuf8753bf62016-02-11 20:09:421517
siva.gunturi5d4feb052015-11-15 16:15:311518scoped_refptr<StreamTextureFactory> RenderThreadImpl::GetStreamTexureFactory() {
1519 DCHECK(IsMainThread());
boliu30f1b262016-04-19 00:12:331520 if (!stream_texture_factory_.get() ||
1521 stream_texture_factory_->ContextGL()->GetGraphicsResetStatusKHR() !=
1522 GL_NO_ERROR) {
sadrul85cc5d82016-12-20 03:37:411523 scoped_refptr<ui::ContextProviderCommandBuffer> shared_context_provider =
piman9fc22f32016-05-02 22:21:221524 SharedMainThreadContextProvider();
1525 if (!shared_context_provider) {
penghuange1d86512016-07-08 18:15:001526 stream_texture_factory_ = nullptr;
1527 return nullptr;
siva.gunturi5d4feb052015-11-15 16:15:311528 }
piman9fc22f32016-05-02 22:21:221529 DCHECK(shared_context_provider->GetCommandBufferProxy());
1530 DCHECK(shared_context_provider->GetCommandBufferProxy()->channel());
1531 stream_texture_factory_ =
1532 StreamTextureFactory::Create(std::move(shared_context_provider));
siva.gunturi5d4feb052015-11-15 16:15:311533 }
1534 return stream_texture_factory_;
1535}
boliuf8753bf62016-02-11 20:09:421536
1537bool RenderThreadImpl::EnableStreamTextureCopy() {
Dave Tapuska63aa4622018-02-25 21:42:561538 return GetContentClient()->UsingSynchronousCompositing();
boliuf8753bf62016-02-11 20:09:421539}
1540
siva.gunturi5d4feb052015-11-15 16:15:311541#endif
1542
[email protected]e9ff79c2012-10-19 21:31:261543AudioRendererMixerManager* RenderThreadImpl::GetAudioRendererMixerManager() {
[email protected]59383c782013-04-17 16:43:271544 if (!audio_renderer_mixer_manager_) {
olka7a4679392016-05-27 15:32:581545 audio_renderer_mixer_manager_ = AudioRendererMixerManager::Create();
[email protected]3958e972012-07-17 00:25:411546 }
1547
1548 return audio_renderer_mixer_manager_.get();
1549}
1550
[email protected]73429ca2014-03-06 06:07:471551base::WaitableEvent* RenderThreadImpl::GetShutdownEvent() {
1552 return ChildProcess::current()->GetShutDownEvent();
1553}
1554
staraz067f58242016-11-07 21:06:411555int32_t RenderThreadImpl::GetClientId() {
1556 return client_id_;
1557}
1558
Karan Bhatiac89897f2017-08-10 01:06:401559void RenderThreadImpl::SetRendererProcessType(
1560 blink::scheduler::RendererProcessType type) {
Yuta Kitamura3331f5c2018-04-05 11:12:251561 main_thread_scheduler_->SetRendererProcessType(type);
Karan Bhatiac89897f2017-08-10 01:06:401562}
1563
Yutaka Hiranob0465f72018-05-17 05:48:251564blink::WebString RenderThreadImpl::GetUserAgent() const {
1565 DCHECK(!user_agent_.IsNull());
1566 return user_agent_;
1567}
1568
John Abd-El-Malek6b56ef712017-10-21 22:52:461569bool RenderThreadImpl::OnMessageReceived(const IPC::Message& msg) {
John Abd-El-Malekdcf1d1372017-10-22 06:39:411570 if (file_system_dispatcher_->OnMessageReceived(msg))
1571 return true;
John Abd-El-Malek6b56ef712017-10-21 22:52:461572 return ChildThreadImpl::OnMessageReceived(msg);
1573}
1574
rockot067ca55f2016-09-30 22:00:151575void RenderThreadImpl::OnAssociatedInterfaceRequest(
1576 const std::string& name,
1577 mojo::ScopedInterfaceEndpointHandle handle) {
rockot70bbb59492017-01-25 00:56:511578 if (associated_interfaces_.CanBindRequest(name))
1579 associated_interfaces_.BindRequest(name, std::move(handle));
1580 else
1581 ChildThreadImpl::OnAssociatedInterfaceRequest(name, std::move(handle));
rockot067ca55f2016-09-30 22:00:151582}
1583
weilifabbf7572017-05-22 19:05:161584scoped_refptr<base::SingleThreadTaskRunner>
1585RenderThreadImpl::GetIOTaskRunner() {
1586 return ChildProcess::current()->io_task_runner();
1587}
1588
danakj6e3bf8012014-12-16 18:27:531589bool RenderThreadImpl::IsGpuRasterizationForced() {
1590 return is_gpu_rasterization_forced_;
1591}
1592
senorblancob60ba952015-01-27 19:12:361593int RenderThreadImpl::GetGpuRasterizationMSAASampleCount() {
1594 return gpu_rasterization_msaa_sample_count_;
1595}
1596
danakj6e3bf8012014-12-16 18:27:531597bool RenderThreadImpl::IsLcdTextEnabled() {
1598 return is_lcd_text_enabled_;
1599}
1600
danakj6e3bf8012014-12-16 18:27:531601bool RenderThreadImpl::IsZeroCopyEnabled() {
1602 return is_zero_copy_enabled_;
1603}
1604
ericrk1d17f752015-10-20 03:03:071605bool RenderThreadImpl::IsPartialRasterEnabled() {
1606 return is_partial_raster_enabled_;
jbroman5f7f71932015-08-18 16:24:461607}
1608
ccameronc7fcd132015-11-03 20:14:311609bool RenderThreadImpl::IsGpuMemoryBufferCompositorResourcesEnabled() {
1610 return is_gpu_memory_buffer_compositor_resources_enabled_;
1611}
1612
ccamerona7644752014-12-30 01:16:311613bool RenderThreadImpl::IsElasticOverscrollEnabled() {
1614 return is_elastic_overscroll_enabled_;
1615}
1616
danakj6e3bf8012014-12-16 18:27:531617scoped_refptr<base::SingleThreadTaskRunner>
1618RenderThreadImpl::GetCompositorMainThreadTaskRunner() {
1619 return main_thread_compositor_task_runner_;
1620}
1621
1622scoped_refptr<base::SingleThreadTaskRunner>
1623RenderThreadImpl::GetCompositorImplThreadTaskRunner() {
skyostil2d3b5bd2015-05-27 15:40:591624 return compositor_task_runner_;
danakj6e3bf8012014-12-16 18:27:531625}
1626
1627gpu::GpuMemoryBufferManager* RenderThreadImpl::GetGpuMemoryBufferManager() {
sadrul53546592016-12-17 01:44:211628 return gpu_->gpu_memory_buffer_manager();
danakj6e3bf8012014-12-16 18:27:531629}
1630
Yuta Kitamuradeb91bb2018-05-29 05:53:201631blink::scheduler::WebThreadScheduler*
Yuta Kitamura3331f5c2018-04-05 11:12:251632RenderThreadImpl::GetWebMainThreadScheduler() {
1633 return main_thread_scheduler_.get();
danakj6e3bf8012014-12-16 18:27:531634}
1635
Fady Samuelc645ffe2017-07-24 17:28:201636std::unique_ptr<viz::SyntheticBeginFrameSource>
samans09812d32017-03-27 19:51:501637RenderThreadImpl::CreateSyntheticBeginFrameSource() {
1638 base::SingleThreadTaskRunner* compositor_impl_side_task_runner =
1639 compositor_task_runner_ ? compositor_task_runner_.get()
1640 : base::ThreadTaskRunnerHandle::Get().get();
Jeremy Roman04f27c372017-10-27 15:20:551641 return std::make_unique<viz::BackToBackBeginFrameSource>(
1642 std::make_unique<viz::DelayBasedTimeSource>(
samans09812d32017-03-27 19:51:501643 compositor_impl_side_task_runner));
1644}
1645
reveman34b7a1522015-03-23 20:27:471646cc::TaskGraphRunner* RenderThreadImpl::GetTaskGraphRunner() {
prashant.nfad657e2016-06-01 07:52:171647 return categorized_worker_pool_->GetTaskGraphRunner();
reveman34b7a1522015-03-23 20:27:471648}
1649
loyso65c93c602015-08-11 05:15:571650bool RenderThreadImpl::IsThreadedAnimationEnabled() {
1651 return is_threaded_animation_enabled_;
1652}
1653
wjmaclean1d970622017-01-21 22:28:241654bool RenderThreadImpl::IsScrollAnimatorEnabled() {
1655 return is_scroll_animator_enabled_;
1656}
1657
Khushal3e96e662017-10-30 23:16:501658std::unique_ptr<cc::UkmRecorderFactory>
1659RenderThreadImpl::CreateUkmRecorderFactory() {
Khushalda50f8152017-12-01 09:04:401660 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
1661 switches::kDisableCompositorUkmForTests)) {
1662 return nullptr;
1663 }
1664
1665 return std::make_unique<UkmRecorderFactoryImpl>(GetConnector()->Clone());
Khushal3e96e662017-10-30 23:16:501666}
1667
skyostila37c2a72016-06-29 17:30:071668void RenderThreadImpl::OnRAILModeChanged(v8::RAILMode rail_mode) {
Blink Reformat1c4d759e2017-04-09 16:34:541669 blink::MainThreadIsolate()->SetRAILMode(rail_mode);
1670 blink::SetRAILModeOnWorkerThreadIsolates(rail_mode);
skyostila37c2a72016-06-29 17:30:071671}
1672
[email protected]b3e83de2012-02-07 03:33:281673bool RenderThreadImpl::IsMainThread() {
1674 return !!current();
1675}
1676
torne88b66452016-05-03 13:22:141677void RenderThreadImpl::OnChannelError() {
1678 // In single-process mode, the renderer can't be restarted after shutdown.
1679 // So, if we get a channel error, crash the whole process right now to get a
1680 // more informative stack, since we will otherwise just crash later when we
1681 // try to restart it.
1682 CHECK(!base::CommandLine::ForCurrentProcess()->HasSwitch(
1683 switches::kSingleProcess));
1684 ChildThreadImpl::OnChannelError();
1685}
1686
Nicholas Verne06de8122017-11-16 04:47:381687void RenderThreadImpl::OnProcessFinalRelease() {
1688 if (on_channel_error_called())
1689 return;
1690 // The child process shutdown sequence is a request response based mechanism,
1691 // where we send out an initial feeler request to the child process host
1692 // instance in the browser to verify if it's ok to shutdown the child process.
1693 // The browser then sends back a response if it's ok to shutdown. This avoids
1694 // race conditions if the process refcount is 0 but there's an IPC message
1695 // inflight that would addref it.
1696 GetRendererHost()->ShutdownRequest();
1697}
1698
[email protected]f1a29a02011-10-06 23:08:441699bool RenderThreadImpl::OnControlMessageReceived(const IPC::Message& msg) {
dchenga2d442c22016-10-13 15:39:211700 for (auto& observer : observers_) {
1701 if (observer.OnControlMessageReceived(msg))
[email protected]1223d6ef2011-03-28 16:47:501702 return true;
1703 }
1704
[email protected]70c19a932010-05-14 12:59:111705 // Some messages are handled by delegates.
Nicholas Verne07e9c6452017-12-13 04:12:551706 if (dom_storage_dispatcher_->OnMessageReceived(msg)) {
[email protected]a95986a82010-12-24 06:19:281707 return true;
[email protected]1910fe82012-05-10 00:04:101708 }
Darin Fisherbcc33632017-09-26 00:57:161709 return false;
initial.commit09911bf2008-07-26 23:55:291710}
1711
Shubhie Panicker45ce80a82018-02-01 01:40:191712void RenderThreadImpl::SetSchedulerKeepActive(bool keep_active) {
Yuta Kitamura3331f5c2018-04-05 11:12:251713 main_thread_scheduler_->SetSchedulerKeepActive(keep_active);
Shubhie Panicker45ce80a82018-02-01 01:40:191714}
1715
Nicholas Verne5420564d2017-10-27 07:37:541716void RenderThreadImpl::SetProcessBackgrounded(bool backgrounded) {
1717 // Set timer slack to maximum on main thread when in background.
1718 base::TimerSlack timer_slack = base::TIMER_SLACK_NONE;
1719 if (backgrounded)
1720 timer_slack = base::TIMER_SLACK_MAXIMUM;
Gabriel Charette08fd6532018-04-04 19:47:161721 main_message_loop_->SetTimerSlack(timer_slack);
jdduke73220f02015-09-04 17:03:511722
Yuta Kitamura3331f5c2018-04-05 11:12:251723 main_thread_scheduler_->SetRendererBackgrounded(backgrounded);
hajimehoshi69093272016-05-13 08:30:581724 if (backgrounded) {
tasakb95dbb50c2017-02-08 18:07:501725 needs_to_record_first_active_paint_ = false;
Yuta Kitamura3331f5c2018-04-05 11:12:251726 GetWebMainThreadScheduler()->DefaultTaskRunner()->PostDelayedTask(
tasak335a1872017-06-14 09:50:231727 FROM_HERE,
tzikff2a81a2017-09-15 05:10:061728 base::BindOnce(&RenderThreadImpl::RecordMemoryUsageAfterBackgrounded,
1729 base::Unretained(this), "5min",
1730 process_foregrounded_count_),
tasak335a1872017-06-14 09:50:231731 base::TimeDelta::FromMinutes(5));
Yuta Kitamura3331f5c2018-04-05 11:12:251732 GetWebMainThreadScheduler()->DefaultTaskRunner()->PostDelayedTask(
tasak335a1872017-06-14 09:50:231733 FROM_HERE,
tzikff2a81a2017-09-15 05:10:061734 base::BindOnce(&RenderThreadImpl::RecordMemoryUsageAfterBackgrounded,
1735 base::Unretained(this), "10min",
1736 process_foregrounded_count_),
tasak335a1872017-06-14 09:50:231737 base::TimeDelta::FromMinutes(10));
Yuta Kitamura3331f5c2018-04-05 11:12:251738 GetWebMainThreadScheduler()->DefaultTaskRunner()->PostDelayedTask(
tasak335a1872017-06-14 09:50:231739 FROM_HERE,
tzikff2a81a2017-09-15 05:10:061740 base::BindOnce(&RenderThreadImpl::RecordMemoryUsageAfterBackgrounded,
1741 base::Unretained(this), "15min",
1742 process_foregrounded_count_),
tasak335a1872017-06-14 09:50:231743 base::TimeDelta::FromMinutes(15));
Takashi SAKAMOTO870f6262017-08-22 04:08:271744 was_backgrounded_time_ = base::TimeTicks::Now();
hajimehoshi69093272016-05-13 08:30:581745 } else {
tasakbb0640b2017-05-15 09:02:261746 process_foregrounded_count_++;
hajimehoshi69093272016-05-13 08:30:581747 }
1748}
1749
Nicholas Verne5420564d2017-10-27 07:37:541750void RenderThreadImpl::ProcessPurgeAndSuspend() {
tasak6ff44032016-11-07 06:45:251751 if (!RendererIsHidden())
hajimehoshi69093272016-05-13 08:30:581752 return;
tasakff1e62422016-12-22 04:53:551753
tasakc4de4672017-04-26 02:37:361754 if (!base::FeatureList::IsEnabled(features::kPurgeAndSuspend))
1755 return;
1756
1757 base::MemoryCoordinatorClientRegistry::GetInstance()->PurgeMemory();
tasakb95dbb50c2017-02-08 18:07:501758 needs_to_record_first_active_paint_ = true;
tasakc4de4672017-04-26 02:37:361759
1760 RendererMemoryMetrics memory_metrics;
1761 if (!GetRendererMemoryMetrics(&memory_metrics))
1762 return;
1763
1764 purge_and_suspend_memory_metrics_ = memory_metrics;
Yuta Kitamura3331f5c2018-04-05 11:12:251765 GetWebMainThreadScheduler()->DefaultTaskRunner()->PostDelayedTask(
tasaka27961a2017-05-24 07:33:251766 FROM_HERE,
tzikff2a81a2017-09-15 05:10:061767 base::BindOnce(
1768 &RenderThreadImpl::RecordPurgeAndSuspendMemoryGrowthMetrics,
1769 base::Unretained(this), "30min", process_foregrounded_count_),
tasaka27961a2017-05-24 07:33:251770 base::TimeDelta::FromMinutes(30));
Yuta Kitamura3331f5c2018-04-05 11:12:251771 GetWebMainThreadScheduler()->DefaultTaskRunner()->PostDelayedTask(
tasaka27961a2017-05-24 07:33:251772 FROM_HERE,
tzikff2a81a2017-09-15 05:10:061773 base::BindOnce(
1774 &RenderThreadImpl::RecordPurgeAndSuspendMemoryGrowthMetrics,
1775 base::Unretained(this), "60min", process_foregrounded_count_),
tasaka27961a2017-05-24 07:33:251776 base::TimeDelta::FromMinutes(60));
Yuta Kitamura3331f5c2018-04-05 11:12:251777 GetWebMainThreadScheduler()->DefaultTaskRunner()->PostDelayedTask(
tasaka27961a2017-05-24 07:33:251778 FROM_HERE,
tzikff2a81a2017-09-15 05:10:061779 base::BindOnce(
1780 &RenderThreadImpl::RecordPurgeAndSuspendMemoryGrowthMetrics,
1781 base::Unretained(this), "90min", process_foregrounded_count_),
tasaka27961a2017-05-24 07:33:251782 base::TimeDelta::FromMinutes(90));
tasakb46626a2016-10-18 05:54:441783}
1784
Nicolas Pena7c7847f2018-05-30 01:36:051785void RenderThreadImpl::SetIsLockedToSite() {
1786 DCHECK(blink_platform_impl_);
1787 blink_platform_impl_->SetIsLockedToSite();
1788}
1789
bashia0ba0d42017-04-03 08:11:061790bool RenderThreadImpl::GetRendererMemoryMetrics(
keishi51ed0d52017-01-12 10:04:461791 RendererMemoryMetrics* memory_metrics) const {
1792 DCHECK(memory_metrics);
1793
chrisha05e94f22017-04-05 22:06:041794 // Cache this result, as it can change while this code is running, and is used
1795 // as a divisor below.
1796 size_t render_view_count = RenderView::GetRenderViewCount();
1797
1798 // If there are no render views it doesn't make sense to calculate metrics
1799 // right now.
1800 if (render_view_count == 0)
bashia0ba0d42017-04-03 08:11:061801 return false;
1802
keishi51ed0d52017-01-12 10:04:461803 blink::WebMemoryStatistics blink_stats = blink::WebMemoryStatistics::Get();
1804 memory_metrics->partition_alloc_kb =
Blink Reformat1c4d759e2017-04-09 16:34:541805 blink_stats.partition_alloc_total_allocated_bytes / 1024;
1806 memory_metrics->blink_gc_kb =
1807 blink_stats.blink_gc_total_allocated_bytes / 1024;
keishi12b598b92017-06-20 10:25:261808 std::unique_ptr<base::ProcessMetrics> metric(
1809 base::ProcessMetrics::CreateCurrentProcessMetrics());
1810 size_t malloc_usage = metric->GetMallocUsage();
keishi51ed0d52017-01-12 10:04:461811 memory_metrics->malloc_mb = malloc_usage / 1024 / 1024;
1812
1813 discardable_memory::ClientDiscardableSharedMemoryManager::Statistics
1814 discardable_stats = discardable_shared_memory_manager_->GetStatistics();
1815 size_t discardable_usage =
1816 discardable_stats.total_size - discardable_stats.freelist_size;
1817 memory_metrics->discardable_kb = discardable_usage / 1024;
1818
1819 size_t v8_usage = 0;
Blink Reformat1c4d759e2017-04-09 16:34:541820 if (v8::Isolate* isolate = blink::MainThreadIsolate()) {
keishi51ed0d52017-01-12 10:04:461821 v8::HeapStatistics v8_heap_statistics;
1822 isolate->GetHeapStatistics(&v8_heap_statistics);
1823 v8_usage = v8_heap_statistics.total_heap_size();
1824 }
1825 // TODO(tasak): Currently only memory usage of mainThreadIsolate() is
1826 // reported. We should collect memory usages of all isolates using
1827 // memory-infra.
1828 memory_metrics->v8_main_thread_isolate_mb = v8_usage / 1024 / 1024;
Blink Reformat1c4d759e2017-04-09 16:34:541829 size_t total_allocated = blink_stats.partition_alloc_total_allocated_bytes +
1830 blink_stats.blink_gc_total_allocated_bytes +
keishi51ed0d52017-01-12 10:04:461831 malloc_usage + v8_usage + discardable_usage;
1832 memory_metrics->total_allocated_mb = total_allocated / 1024 / 1024;
1833 memory_metrics->non_discardable_total_allocated_mb =
1834 (total_allocated - discardable_usage) / 1024 / 1024;
1835 memory_metrics->total_allocated_per_render_view_mb =
chrisha05e94f22017-04-05 22:06:041836 total_allocated / render_view_count / 1024 / 1024;
bashia0ba0d42017-04-03 08:11:061837
1838 return true;
keishi51ed0d52017-01-12 10:04:461839}
1840
tasak335a1872017-06-14 09:50:231841static void RecordMemoryUsageAfterBackgroundedMB(const char* basename,
1842 const char* suffix,
1843 int memory_usage) {
1844 std::string histogram_name = base::StringPrintf("%s.%s", basename, suffix);
1845 base::UmaHistogramMemoryLargeMB(histogram_name, memory_usage);
1846}
1847
1848void RenderThreadImpl::RecordMemoryUsageAfterBackgrounded(
1849 const char* suffix,
1850 int foregrounded_count) {
1851 // If this renderer is resumed, we should not update UMA.
1852 if (!RendererIsHidden())
1853 return;
1854 // If this renderer was not kept backgrounded for 5/10/15 minutes,
1855 // we should not record current memory usage.
1856 if (foregrounded_count != process_foregrounded_count_)
1857 return;
1858
1859 RendererMemoryMetrics memory_metrics;
1860 if (!GetRendererMemoryMetrics(&memory_metrics))
1861 return;
1862 RecordMemoryUsageAfterBackgroundedMB(
1863 "Memory.Experimental.Renderer.PartitionAlloc.AfterBackgrounded", suffix,
1864 memory_metrics.partition_alloc_kb / 1024);
1865 RecordMemoryUsageAfterBackgroundedMB(
1866 "Memory.Experimental.Renderer.BlinkGC.AfterBackgrounded", suffix,
1867 memory_metrics.blink_gc_kb / 1024);
1868 RecordMemoryUsageAfterBackgroundedMB(
1869 "Memory.Experimental.Renderer.Malloc.AfterBackgrounded", suffix,
1870 memory_metrics.malloc_mb);
1871 RecordMemoryUsageAfterBackgroundedMB(
1872 "Memory.Experimental.Renderer.Discardable.AfterBackgrounded", suffix,
1873 memory_metrics.discardable_kb / 1024);
1874 RecordMemoryUsageAfterBackgroundedMB(
1875 "Memory.Experimental.Renderer.V8MainThreaIsolate.AfterBackgrounded",
1876 suffix, memory_metrics.v8_main_thread_isolate_mb);
1877 RecordMemoryUsageAfterBackgroundedMB(
1878 "Memory.Experimental.Renderer.TotalAllocated.AfterBackgrounded", suffix,
1879 memory_metrics.total_allocated_mb);
1880}
1881
tasak72f64042017-01-19 14:02:531882#define GET_MEMORY_GROWTH(current, previous, allocator) \
1883 (current.allocator > previous.allocator \
1884 ? current.allocator - previous.allocator \
1885 : 0)
1886
tasaka27961a2017-05-24 07:33:251887static void RecordPurgeAndSuspendMemoryGrowthKB(const char* basename,
1888 const char* suffix,
1889 int memory_usage) {
1890 std::string histogram_name = base::StringPrintf("%s.%s", basename, suffix);
1891 base::UmaHistogramMemoryKB(histogram_name, memory_usage);
1892}
tasakbb0640b2017-05-15 09:02:261893
1894void RenderThreadImpl::RecordPurgeAndSuspendMemoryGrowthMetrics(
1895 const char* suffix,
1896 int foregrounded_count_when_purged) {
tasak72f64042017-01-19 14:02:531897 // If this renderer is resumed, we should not update UMA.
1898 if (!RendererIsHidden())
1899 return;
tasakbb0640b2017-05-15 09:02:261900 if (foregrounded_count_when_purged != process_foregrounded_count_)
1901 return;
tasak72f64042017-01-19 14:02:531902
1903 RendererMemoryMetrics memory_metrics;
bashia0ba0d42017-04-03 08:11:061904 if (!GetRendererMemoryMetrics(&memory_metrics))
1905 return;
1906
tasaka27961a2017-05-24 07:33:251907 RecordPurgeAndSuspendMemoryGrowthKB(
tasakbb0640b2017-05-15 09:02:261908 "PurgeAndSuspend.Experimental.MemoryGrowth.PartitionAllocKB", suffix,
tasak72f64042017-01-19 14:02:531909 GET_MEMORY_GROWTH(memory_metrics, purge_and_suspend_memory_metrics_,
1910 partition_alloc_kb));
tasaka27961a2017-05-24 07:33:251911 RecordPurgeAndSuspendMemoryGrowthKB(
tasakbb0640b2017-05-15 09:02:261912 "PurgeAndSuspend.Experimental.MemoryGrowth.BlinkGCKB", suffix,
tasak72f64042017-01-19 14:02:531913 GET_MEMORY_GROWTH(memory_metrics, purge_and_suspend_memory_metrics_,
1914 blink_gc_kb));
tasaka27961a2017-05-24 07:33:251915 RecordPurgeAndSuspendMemoryGrowthKB(
tasakbb0640b2017-05-15 09:02:261916 "PurgeAndSuspend.Experimental.MemoryGrowth.MallocKB", suffix,
tasak72f64042017-01-19 14:02:531917 GET_MEMORY_GROWTH(memory_metrics, purge_and_suspend_memory_metrics_,
tasakbb0640b2017-05-15 09:02:261918 malloc_mb) *
1919 1024);
tasaka27961a2017-05-24 07:33:251920 RecordPurgeAndSuspendMemoryGrowthKB(
tasakbb0640b2017-05-15 09:02:261921 "PurgeAndSuspend.Experimental.MemoryGrowth.DiscardableKB", suffix,
tasak72f64042017-01-19 14:02:531922 GET_MEMORY_GROWTH(memory_metrics, purge_and_suspend_memory_metrics_,
1923 discardable_kb));
tasaka27961a2017-05-24 07:33:251924 RecordPurgeAndSuspendMemoryGrowthKB(
tasakbb0640b2017-05-15 09:02:261925 "PurgeAndSuspend.Experimental.MemoryGrowth.V8MainThreadIsolateKB", suffix,
tasak72f64042017-01-19 14:02:531926 GET_MEMORY_GROWTH(memory_metrics, purge_and_suspend_memory_metrics_,
tasakbb0640b2017-05-15 09:02:261927 v8_main_thread_isolate_mb) *
1928 1024);
tasaka27961a2017-05-24 07:33:251929 RecordPurgeAndSuspendMemoryGrowthKB(
tasakbb0640b2017-05-15 09:02:261930 "PurgeAndSuspend.Experimental.MemoryGrowth.TotalAllocatedKB", suffix,
tasak72f64042017-01-19 14:02:531931 GET_MEMORY_GROWTH(memory_metrics, purge_and_suspend_memory_metrics_,
tasakbb0640b2017-05-15 09:02:261932 total_allocated_mb) *
1933 1024);
jdduke73220f02015-09-04 17:03:511934}
1935
danakjab9ef4d2017-10-31 23:38:331936void RenderThreadImpl::CompositingModeFallbackToSoftware() {
Antoine Labour7fcbc782017-11-14 16:59:581937 gpu_->LoseChannel();
danakjab9ef4d2017-10-31 23:38:331938 is_gpu_compositing_disabled_ = true;
1939}
1940
Bo Liud1ef1c32017-12-08 06:15:501941scoped_refptr<gpu::GpuChannelHost> RenderThreadImpl::EstablishGpuChannelSync() {
[email protected]d13f35d2012-05-18 02:28:151942 TRACE_EVENT0("gpu", "RenderThreadImpl::EstablishGpuChannelSync");
1943
Antoine Labour7fcbc782017-11-14 16:59:581944 scoped_refptr<gpu::GpuChannelHost> gpu_channel =
Bo Liud1ef1c32017-12-08 06:15:501945 gpu_->EstablishGpuChannelSync();
Antoine Labour7fcbc782017-11-14 16:59:581946 if (gpu_channel)
1947 GetContentClient()->SetGpuInfo(gpu_channel->gpu_info());
1948 return gpu_channel;
[email protected]3bf4d532010-03-27 00:23:341949}
1950
danakjc7afae52017-06-20 21:12:411951void RenderThreadImpl::RequestNewLayerTreeFrameSink(
danakj83066a32016-06-21 02:34:491952 int routing_id,
1953 scoped_refptr<FrameSwapMessageQueue> frame_swap_message_queue,
fsamuelcf3002e2017-03-20 23:13:471954 const GURL& url,
jonrossa2ff4f82018-02-16 17:27:461955 const LayerTreeFrameSinkCallback& callback,
1956 mojom::RenderFrameMetadataObserverClientRequest
1957 render_frame_metadata_observer_client_request,
1958 mojom::RenderFrameMetadataObserverPtr render_frame_metadata_observer_ptr) {
danakj946e3172017-11-06 23:46:511959 // Misconfigured bots (eg. crbug.com/780757) could run layout tests on a
1960 // machine where gpu compositing doesn't work. Don't crash in that case.
1961 if (layout_test_mode() && is_gpu_compositing_disabled_) {
1962 LOG(FATAL) << "Layout tests require gpu compositing, but it is disabled.";
1963 return;
1964 }
1965
danakj83066a32016-06-21 02:34:491966 const base::CommandLine& command_line =
1967 *base::CommandLine::ForCurrentProcess();
danakj7b631be2018-05-25 19:14:201968 cc::mojo_embedder::AsyncLayerTreeFrameSink::InitParams params;
Sunny Sachanandani158d26d2017-12-12 19:44:101969 params.compositor_task_runner = compositor_task_runner_;
Xu Xing48e1b322017-09-25 10:48:011970 params.enable_surface_synchronization =
Fady Samuel343a74952017-11-30 14:19:201971 features::IsSurfaceSynchronizationEnabled();
Xu Xing48e1b322017-09-25 10:48:011972 params.local_surface_id_provider =
Jeremy Roman04f27c372017-10-27 15:20:551973 std::make_unique<RendererLocalSurfaceIdProvider>();
Ria Jiang4bbc6182018-02-12 19:02:191974 if (features::IsVizHitTestingDrawQuadEnabled()) {
Gary Klassen2c346fb2018-02-07 18:08:401975 params.hit_test_data_provider =
Ria Jiang28051112018-02-13 16:38:521976 std::make_unique<viz::HitTestDataProviderDrawQuad>(
1977 true /* should_ask_for_child_region */);
Gary Klassen2c346fb2018-02-07 18:08:401978 }
Fady Samuel0c4b4bf2017-08-22 00:06:461979
Eric Seckler8af8c0e52018-01-17 23:45:531980 // The renderer runs animations and layout for animate_only BeginFrames.
1981 params.wants_animate_only_begin_frames = true;
1982
Sunny Sachanandani2c951c82018-05-23 20:39:371983 // In disable frame rate limit mode, also let the renderer tick as fast as it
1984 // can. The top level begin frame source will also be running as a back to
1985 // back begin frame source, but using a synthetic begin frame source here
1986 // reduces latency when in this mode (at least for frames starting--it
1987 // potentially increases it for input on the other hand.)
1988 if (command_line.HasSwitch(switches::kDisableFrameRateLimit))
Xu Xing48e1b322017-09-25 10:48:011989 params.synthetic_begin_frame_source = CreateSyntheticBeginFrameSource();
samans09812d32017-03-27 19:51:501990
sadrul943e3b32016-08-04 18:22:591991#if defined(USE_AURA)
Scott Violet8ff9c302018-02-22 22:28:351992 if (base::FeatureList::IsEnabled(features::kMash)) {
Scott Violet986ac472017-08-10 16:38:341993 if (!RendererWindowTreeClient::Get(routing_id)) {
1994 callback.Run(nullptr);
1995 return;
1996 }
Bo Liud1ef1c32017-12-08 06:15:501997 scoped_refptr<gpu::GpuChannelHost> channel = EstablishGpuChannelSync();
sadrulbe22c4f2017-03-14 06:59:251998 // If the channel could not be established correctly, then return null. This
1999 // would cause the compositor to wait and try again at a later time.
fsamuelcf3002e2017-03-20 23:13:472000 if (!channel) {
2001 callback.Run(nullptr);
2002 return;
2003 }
fsamuel95c974eb2017-03-22 10:00:252004 RendererWindowTreeClient::Get(routing_id)
danakjc7afae52017-06-20 21:12:412005 ->RequestLayerTreeFrameSink(
fsamuel95c974eb2017-03-22 10:00:252006 gpu_->CreateContextProvider(std::move(channel)),
2007 GetGpuMemoryBufferManager(), callback);
Fady Samuelca9ecb72018-05-05 05:59:272008 frame_sink_provider_->RegisterRenderFrameMetadataObserver(
2009 routing_id, std::move(render_frame_metadata_observer_client_request),
2010 std::move(render_frame_metadata_observer_ptr));
fsamuelcf3002e2017-03-20 23:13:472011 return;
danakj83066a32016-06-21 02:34:492012 }
2013#endif
2014
jonrossa2ff4f82018-02-16 17:27:462015 viz::mojom::CompositorFrameSinkRequest compositor_frame_sink_request =
kylecharb82991b2017-10-04 22:40:082016 mojo::MakeRequest(&params.pipes.compositor_frame_sink_info);
jonrossa2ff4f82018-02-16 17:27:462017 viz::mojom::CompositorFrameSinkClientPtr compositor_frame_sink_client;
2018 params.pipes.client_request =
2019 mojo::MakeRequest(&compositor_frame_sink_client);
samansa61ab212017-05-24 12:11:432020
danakjab9ef4d2017-10-31 23:38:332021 if (is_gpu_compositing_disabled_) {
danakj83066a32016-06-21 02:34:492022 DCHECK(!layout_test_mode());
jonrossa2ff4f82018-02-16 17:27:462023 frame_sink_provider_->CreateForWidget(
2024 routing_id, std::move(compositor_frame_sink_request),
Fady Samuelca9ecb72018-05-05 05:59:272025 std::move(compositor_frame_sink_client));
2026 frame_sink_provider_->RegisterRenderFrameMetadataObserver(
2027 routing_id, std::move(render_frame_metadata_observer_client_request),
jonrossa2ff4f82018-02-16 17:27:462028 std::move(render_frame_metadata_observer_ptr));
danakj7b631be2018-05-25 19:14:202029 callback.Run(std::make_unique<cc::mojo_embedder::AsyncLayerTreeFrameSink>(
Xu Xing48e1b322017-09-25 10:48:012030 nullptr, nullptr, &params));
fsamuelcf3002e2017-03-20 23:13:472031 return;
danakj83066a32016-06-21 02:34:492032 }
2033
danakjab9ef4d2017-10-31 23:38:332034 scoped_refptr<gpu::GpuChannelHost> gpu_channel_host =
Bo Liud1ef1c32017-12-08 06:15:502035 EstablishGpuChannelSync();
danakjab9ef4d2017-10-31 23:38:332036 if (!gpu_channel_host) {
2037 // Wait and try again. We may hear that the compositing mode has switched
2038 // to software in the meantime.
2039 callback.Run(nullptr);
2040 return;
2041 }
2042
Victor Miuraff6488612017-12-21 04:16:152043 scoped_refptr<viz::RasterContextProvider> worker_context_provider =
danakj83066a32016-06-21 02:34:492044 SharedCompositorWorkerContextProvider();
2045 if (!worker_context_provider) {
2046 // Cause the compositor to wait and try again.
fsamuelcf3002e2017-03-20 23:13:472047 callback.Run(nullptr);
2048 return;
danakj83066a32016-06-21 02:34:492049 }
2050
2051 // The renderer compositor context doesn't do a lot of stuff, so we don't
2052 // expect it to need a lot of space for commands or transfer. Raster and
2053 // uploads happen on the worker context instead.
2054 gpu::SharedMemoryLimits limits = gpu::SharedMemoryLimits::ForMailboxContext();
2055
2056 // This is for an offscreen context for the compositor. So the default
2057 // framebuffer doesn't need alpha, depth, stencil, antialiasing.
Antoine Labourfeab2392017-12-21 20:28:392058 gpu::ContextCreationAttribs attributes;
danakj83066a32016-06-21 02:34:492059 attributes.alpha_size = -1;
2060 attributes.depth_size = 0;
2061 attributes.stencil_size = 0;
2062 attributes.samples = 0;
2063 attributes.sample_buffers = 0;
2064 attributes.bind_generates_resource = false;
2065 attributes.lose_context_when_out_of_memory = true;
Victor Miura3a4ad4f82017-12-13 06:03:452066 attributes.enable_gles2_interface = true;
2067 attributes.enable_raster_interface = false;
2068 attributes.enable_oop_rasterization = false;
danakj83066a32016-06-21 02:34:492069
2070 constexpr bool automatic_flushes = false;
2071 constexpr bool support_locking = false;
Roger Johannesson905b8ca2018-05-31 13:28:542072 constexpr bool support_grcontext = true;
danakj83066a32016-06-21 02:34:492073
sadrul85cc5d82016-12-20 03:37:412074 scoped_refptr<ui::ContextProviderCommandBuffer> context_provider(
2075 new ui::ContextProviderCommandBuffer(
Antoine Labour5ac65db2017-12-19 18:02:582076 gpu_channel_host, GetGpuMemoryBufferManager(), kGpuStreamIdDefault,
2077 kGpuStreamPriorityDefault, gpu::kNullSurfaceHandle, url,
Justin Novosad7d3d2502018-03-27 18:55:382078 automatic_flushes, support_locking, support_grcontext, limits,
Jonathan Backerfa3a8452018-04-23 18:20:332079 attributes, ui::command_buffer_metrics::RENDER_COMPOSITOR_CONTEXT));
danakj83066a32016-06-21 02:34:492080
danakj83066a32016-06-21 02:34:492081 if (layout_test_deps_) {
Vladimir Levind29618c2018-04-17 21:49:012082 if (!layout_test_deps_->UseDisplayCompositorPixelDump()) {
2083 callback.Run(layout_test_deps_->CreateLayerTreeFrameSink(
2084 routing_id, std::move(gpu_channel_host), std::move(context_provider),
2085 std::move(worker_context_provider), GetGpuMemoryBufferManager(),
2086 this));
2087 return;
2088 } else if (!params.compositor_task_runner) {
2089 // The frame sink provider expects a compositor task runner, but we might
2090 // not have that if we're running layout tests in single threaded mode.
2091 // Set it to be our thread's task runner instead.
2092 params.compositor_task_runner = GetCompositorMainThreadTaskRunner();
2093 }
danakj83066a32016-06-21 02:34:492094 }
2095
2096#if defined(OS_ANDROID)
Dave Tapuska63aa4622018-02-25 21:42:562097 if (GetContentClient()->UsingSynchronousCompositing()) {
Dave Tapuska04bc5ee92018-04-17 19:03:312098 RenderViewImpl* view = RenderViewImpl::FromRoutingID(routing_id);
2099 if (view) {
Dave Tapuska63aa4622018-02-25 21:42:562100 callback.Run(std::make_unique<SynchronousLayerTreeFrameSink>(
2101 std::move(context_provider), std::move(worker_context_provider),
2102 compositor_task_runner_, GetGpuMemoryBufferManager(),
Dave Tapuska04bc5ee92018-04-17 19:03:312103 sync_message_filter(), routing_id, g_next_layer_tree_frame_sink_id++,
Dave Tapuska63aa4622018-02-25 21:42:562104 std::move(params.synthetic_begin_frame_source),
Albert J. Wong7fcddfa2018-05-29 22:13:212105 view->GetWidget()
2106 ->widget_input_handler_manager()
Dave Tapuska04bc5ee92018-04-17 19:03:312107 ->GetSynchronousCompositorRegistry(),
Dave Tapuska63aa4622018-02-25 21:42:562108 std::move(frame_swap_message_queue)));
2109 return;
Dave Tapuska04bc5ee92018-04-17 19:03:312110 } else {
2111 NOTREACHED();
Dave Tapuska63aa4622018-02-25 21:42:562112 }
danakj83066a32016-06-21 02:34:492113 }
2114#endif
jonrossa2ff4f82018-02-16 17:27:462115 frame_sink_provider_->CreateForWidget(
2116 routing_id, std::move(compositor_frame_sink_request),
Fady Samuelca9ecb72018-05-05 05:59:272117 std::move(compositor_frame_sink_client));
2118 frame_sink_provider_->RegisterRenderFrameMetadataObserver(
2119 routing_id, std::move(render_frame_metadata_observer_client_request),
jonrossa2ff4f82018-02-16 17:27:462120 std::move(render_frame_metadata_observer_ptr));
Xu Xing48e1b322017-09-25 10:48:012121 params.gpu_memory_buffer_manager = GetGpuMemoryBufferManager();
danakj7b631be2018-05-25 19:14:202122 callback.Run(std::make_unique<cc::mojo_embedder::AsyncLayerTreeFrameSink>(
samans2040988b2017-04-11 23:58:352123 std::move(context_provider), std::move(worker_context_provider),
Xu Xing48e1b322017-09-25 10:48:012124 &params));
danakj83066a32016-06-21 02:34:492125}
2126
Sam McNally52e50282017-11-29 00:54:022127blink::AssociatedInterfaceRegistry*
rockot067ca55f2016-09-30 22:00:152128RenderThreadImpl::GetAssociatedInterfaceRegistry() {
2129 return &associated_interfaces_;
2130}
2131
jbroman6ccbc7d472016-07-27 04:45:412132std::unique_ptr<cc::SwapPromise>
2133RenderThreadImpl::RequestCopyOfOutputForLayoutTest(
2134 int32_t routing_id,
Fady Samueldfecb7d2017-07-26 11:41:042135 std::unique_ptr<viz::CopyOutputRequest> request) {
Vladimir Levind29618c2018-04-17 21:49:012136 DCHECK(layout_test_deps_ &&
2137 !layout_test_deps_->UseDisplayCompositorPixelDump());
jbroman6ccbc7d472016-07-27 04:45:412138 return layout_test_deps_->RequestCopyOfOutput(routing_id, std::move(request));
2139}
2140
altimineb6bd1962017-05-03 14:52:382141std::unique_ptr<blink::WebMediaStreamCenter>
2142RenderThreadImpl::CreateMediaStreamCenter(
[email protected]180ef242013-11-07 06:50:462143 blink::WebMediaStreamCenterClient* client) {
altimineb6bd1962017-05-03 14:52:382144 std::unique_ptr<blink::WebMediaStreamCenter> media_stream_center;
altimineb6bd1962017-05-03 14:52:382145 if (!media_stream_center) {
Harald Alvestrand4931caa2017-11-08 16:53:352146 media_stream_center = std::make_unique<MediaStreamCenter>(
2147 client, GetPeerConnectionDependencyFactory());
[email protected]68e5fee2013-02-18 10:04:222148 }
altimineb6bd1962017-05-03 14:52:382149 return media_stream_center;
[email protected]d8cd8372012-03-09 10:49:512150}
2151
[email protected]0107d8a2014-05-16 10:20:342152PeerConnectionDependencyFactory*
2153RenderThreadImpl::GetPeerConnectionDependencyFactory() {
[email protected]83e0a482014-05-22 18:07:182154 return peer_connection_factory_.get();
[email protected]6ee10bd2012-09-13 09:01:532155}
[email protected]6ee10bd2012-09-13 09:01:532156
rockot1587e332016-07-27 17:44:142157mojom::RenderFrameMessageFilter*
2158RenderThreadImpl::render_frame_message_filter() {
2159 if (!render_frame_message_filter_)
2160 GetChannel()->GetRemoteAssociatedInterface(&render_frame_message_filter_);
2161 return render_frame_message_filter_.get();
2162}
2163
rockote261d2112016-09-21 22:22:232164mojom::RenderMessageFilter* RenderThreadImpl::render_message_filter() {
2165 if (!render_message_filter_)
2166 GetChannel()->GetRemoteAssociatedInterface(&render_message_filter_);
2167 return render_message_filter_.get();
2168}
2169
penghuang346a46f92016-03-31 21:37:522170gpu::GpuChannelHost* RenderThreadImpl::GetGpuChannel() {
Antoine Labour7fcbc782017-11-14 16:59:582171 return gpu_->GetGpuChannel().get();
[email protected]6217d392010-03-25 22:08:352172}
2173
Ben Goodger16331302018-01-23 00:43:212174void RenderThreadImpl::CreateEmbedderRendererService(
2175 service_manager::mojom::ServiceRequest service_request) {
2176 GetContentClient()->renderer()->CreateRendererService(
2177 std::move(service_request));
2178}
2179
rockot067ca55f2016-09-30 22:00:152180void RenderThreadImpl::CreateView(mojom::CreateViewParamsPtr params) {
2181 CompositorDependencies* compositor_deps = this;
wjmaclean1d970622017-01-21 22:28:242182 is_scroll_animator_enabled_ = params->web_preferences.enable_scroll_animator;
rockot067ca55f2016-09-30 22:00:152183 // When bringing in render_view, also bring in webkit's glue and jsbindings.
Balazs Engedyba034e72017-10-27 22:26:282184 RenderViewImpl::Create(compositor_deps, std::move(params),
Hajime Hoshiabb3c8f2017-12-04 18:41:392185 RenderWidget::ShowCallback(),
Yuta Kitamura3331f5c2018-04-05 11:12:252186 GetWebMainThreadScheduler()->DefaultTaskRunner());
rockot067ca55f2016-09-30 22:00:152187}
2188
rockot53be7caf2016-10-04 20:17:082189void RenderThreadImpl::CreateFrame(mojom::CreateFrameParamsPtr params) {
rockot53be7caf2016-10-04 20:17:082190 CompositorDependencies* compositor_deps = this;
Ken Rockot26efbd62017-11-16 04:39:492191 service_manager::mojom::InterfaceProviderPtr interface_provider(
2192 std::move(params->interface_provider));
rockot53be7caf2016-10-04 20:17:082193 RenderFrameImpl::CreateFrame(
Ken Rockot26efbd62017-11-16 04:39:492194 params->routing_id, std::move(interface_provider),
Balazs Engedyba034e72017-10-27 22:26:282195 params->proxy_routing_id, params->opener_routing_id,
rockot53be7caf2016-10-04 20:17:082196 params->parent_routing_id, params->previous_sibling_routing_id,
Pavel Feldman25234722017-10-11 02:49:062197 params->devtools_frame_token, params->replication_state, compositor_deps,
Daniel Chenge0555e192018-01-18 20:00:052198 *params->widget_params, params->frame_owner_properties,
2199 params->has_committed_real_load);
rockot53be7caf2016-10-04 20:17:082200}
2201
2202void RenderThreadImpl::CreateFrameProxy(
2203 int32_t routing_id,
2204 int32_t render_view_routing_id,
2205 int32_t opener_routing_id,
2206 int32_t parent_routing_id,
Dmitry Gozman89361212018-02-13 16:10:442207 const FrameReplicationState& replicated_state,
2208 const base::UnguessableToken& devtools_frame_token) {
nick3b5a21f2016-11-22 23:07:112209 RenderFrameProxy::CreateFrameProxy(
2210 routing_id, render_view_routing_id,
2211 RenderFrameImpl::ResolveOpener(opener_routing_id), parent_routing_id,
Dmitry Gozman89361212018-02-13 16:10:442212 replicated_state, devtools_frame_token);
rockot53be7caf2016-10-04 20:17:082213}
2214
Makoto Shimazu8199e092018-05-11 06:03:142215void RenderThreadImpl::SetUpEmbeddedWorkerChannelForServiceWorker(
2216 mojom::EmbeddedWorkerInstanceClientRequest client_request) {
2217 EmbeddedWorkerInstanceClientImpl::Create(
2218 blink_initialized_time_, GetIOTaskRunner(), std::move(client_request));
2219}
2220
rockota2db0da2016-10-18 17:39:112221void RenderThreadImpl::OnNetworkConnectionChanged(
2222 net::NetworkChangeNotifier::ConnectionType type,
2223 double max_bandwidth_mbps) {
2224 bool online = type != net::NetworkChangeNotifier::CONNECTION_NONE;
Blink Reformat1c4d759e2017-04-09 16:34:542225 WebNetworkStateNotifier::SetOnLine(online);
rockota2db0da2016-10-18 17:39:112226 for (auto& observer : observers_)
2227 observer.NetworkStateChanged(online);
Blink Reformat1c4d759e2017-04-09 16:34:542228 WebNetworkStateNotifier::SetWebConnection(
rockota2db0da2016-10-18 17:39:112229 NetConnectionTypeToWebConnectionType(type), max_bandwidth_mbps);
2230}
2231
tbansal15973c32017-05-10 18:40:442232void RenderThreadImpl::OnNetworkQualityChanged(
tbansalb612c5d2017-05-25 18:53:062233 net::EffectiveConnectionType type,
tbansal99d8aeb2017-05-22 19:12:582234 base::TimeDelta http_rtt,
2235 base::TimeDelta transport_rtt,
tbansal15973c32017-05-10 18:40:442236 double downlink_throughput_kbps) {
2237 UMA_HISTOGRAM_BOOLEAN("NQE.RenderThreadNotified", true);
tbansalb612c5d2017-05-25 18:53:062238 WebNetworkStateNotifier::SetNetworkQuality(
2239 EffectiveConnectionTypeToWebEffectiveConnectionType(type), http_rtt,
2240 transport_rtt, downlink_throughput_kbps);
tbansal15973c32017-05-10 18:40:442241}
2242
rockota2db0da2016-10-18 17:39:112243void RenderThreadImpl::SetWebKitSharedTimersSuspended(bool suspend) {
2244#if defined(OS_ANDROID)
2245 if (suspend) {
Yuta Kitamura3331f5c2018-04-05 11:12:252246 main_thread_scheduler_->PauseTimersForAndroidWebView();
rockota2db0da2016-10-18 17:39:112247 } else {
Yuta Kitamura3331f5c2018-04-05 11:12:252248 main_thread_scheduler_->ResumeTimersForAndroidWebView();
rockota2db0da2016-10-18 17:39:112249 }
Alexander Timin4b6152232017-10-17 20:34:062250 webkit_shared_timer_suspended_ = suspend;
rockota2db0da2016-10-18 17:39:112251#else
2252 NOTREACHED();
2253#endif
2254}
2255
Yutaka Hiranob0465f72018-05-17 05:48:252256void RenderThreadImpl::SetUserAgent(const std::string& user_agent) {
2257 DCHECK(user_agent_.IsNull());
2258 user_agent_ = WebString::FromUTF8(user_agent);
2259}
2260
rockota2db0da2016-10-18 17:39:112261void RenderThreadImpl::UpdateScrollbarTheme(
2262 mojom::UpdateScrollbarThemeParamsPtr params) {
2263#if defined(OS_MACOSX)
2264 static_cast<WebScrollbarBehaviorImpl*>(
Blink Reformat1c4d759e2017-04-09 16:34:542265 blink_platform_impl_->ScrollbarBehavior())
rockota2db0da2016-10-18 17:39:112266 ->set_jump_on_track_click(params->jump_on_track_click);
2267
Blink Reformat1c4d759e2017-04-09 16:34:542268 blink::WebScrollbarTheme::UpdateScrollbarsWithNSDefaults(
rockota2db0da2016-10-18 17:39:112269 params->initial_button_delay, params->autoscroll_button_delay,
2270 params->preferred_scroller_style, params->redraw,
2271 params->button_placement);
Greg Kerra7b943b2017-07-24 23:17:172272
2273 is_elastic_overscroll_enabled_ = params->scroll_view_rubber_banding;
rockota2db0da2016-10-18 17:39:112274#else
2275 NOTREACHED();
2276#endif
2277}
2278
2279void RenderThreadImpl::OnSystemColorsChanged(
2280 int32_t aqua_color_variant,
2281 const std::string& highlight_text_color,
2282 const std::string& highlight_color) {
2283#if defined(OS_MACOSX)
2284 SystemColorsDidChange(aqua_color_variant, highlight_text_color,
2285 highlight_color);
2286#else
2287 NOTREACHED();
2288#endif
2289}
2290
2291void RenderThreadImpl::PurgePluginListCache(bool reload_pages) {
brettw4b461082016-11-19 18:55:162292#if BUILDFLAG(ENABLE_PLUGINS)
Blink Reformat1c4d759e2017-04-09 16:34:542293 blink::ResetPluginCache(reload_pages);
rockota2db0da2016-10-18 17:39:112294
2295 for (auto& observer : observers_)
2296 observer.PluginListChanged();
2297#else
2298 NOTREACHED();
2299#endif
2300}
2301
[email protected]5071cb22013-07-10 02:19:062302void RenderThreadImpl::OnMemoryPressure(
2303 base::MemoryPressureListener::MemoryPressureLevel memory_pressure_level) {
kylecharb82991b2017-10-04 22:40:082304 TRACE_EVENT0("memory", "RenderThreadImpl::OnMemoryPressure");
rmcilroy7fbb3bd52015-02-17 19:02:142305 if (blink_platform_impl_) {
Blink Reformat1c4d759e2017-04-09 16:34:542306 blink::WebMemoryCoordinator::OnMemoryPressure(
bashic577bfc2016-01-08 03:42:352307 static_cast<blink::WebMemoryPressureLevel>(memory_pressure_level));
hajimehoshi7bb39582016-10-12 04:30:572308 }
2309 if (memory_pressure_level ==
Gyuyoung Kim7b96fa72018-03-05 01:44:252310 base::MemoryPressureListener::MEMORY_PRESSURE_LEVEL_CRITICAL)
hajimehoshi7bb39582016-10-12 04:30:572311 ReleaseFreeMemory();
hajimehoshi7bb39582016-10-12 04:30:572312}
rmcilroyab967c972015-02-17 23:15:002313
hajimehoshi7bb39582016-10-12 04:30:572314void RenderThreadImpl::OnMemoryStateChange(base::MemoryState state) {
hajimehoshi7bb39582016-10-12 04:30:572315 if (blink_platform_impl_) {
Blink Reformat1c4d759e2017-04-09 16:34:542316 blink::WebMemoryCoordinator::OnMemoryStateChange(
hajimehoshi7bb39582016-10-12 04:30:572317 static_cast<blink::MemoryState>(state));
2318 }
bashi233f65e2017-02-09 08:36:032319}
2320
2321void RenderThreadImpl::OnPurgeMemory() {
bashib9058f282017-03-30 01:55:242322 // Record amount of purged memory after 2 seconds. 2 seconds is arbitrary
2323 // but it works most cases.
2324 RendererMemoryMetrics metrics;
bashia0ba0d42017-04-03 08:11:062325 if (!GetRendererMemoryMetrics(&metrics))
2326 return;
2327
Yuta Kitamura3331f5c2018-04-05 11:12:252328 GetWebMainThreadScheduler()->DefaultTaskRunner()->PostDelayedTask(
bashib9058f282017-03-30 01:55:242329 FROM_HERE,
tzikff2a81a2017-09-15 05:10:062330 base::BindOnce(&RenderThreadImpl::RecordPurgeMemory,
2331 base::Unretained(this), std::move(metrics)),
bashib9058f282017-03-30 01:55:242332 base::TimeDelta::FromSeconds(2));
2333
bashi233f65e2017-02-09 08:36:032334 OnTrimMemoryImmediately();
2335 ReleaseFreeMemory();
hajimehoshi7bb39582016-10-12 04:30:572336}
2337
bashib9058f282017-03-30 01:55:242338void RenderThreadImpl::RecordPurgeMemory(RendererMemoryMetrics before) {
2339 RendererMemoryMetrics after;
bashia0ba0d42017-04-03 08:11:062340 if (!GetRendererMemoryMetrics(&after))
2341 return;
bashib9058f282017-03-30 01:55:242342 int64_t mbytes = static_cast<int64_t>(before.total_allocated_mb) -
2343 static_cast<int64_t>(after.total_allocated_mb);
2344 if (mbytes < 0)
2345 mbytes = 0;
2346 UMA_HISTOGRAM_MEMORY_LARGE_MB("Memory.Experimental.Renderer.PurgedMemory",
2347 mbytes);
2348}
2349
acolwellb4034942014-08-28 15:42:432350scoped_refptr<base::SingleThreadTaskRunner>
2351RenderThreadImpl::GetMediaThreadTaskRunner() {
Gabriel Charettebbede162018-04-25 14:04:372352 DCHECK(main_thread_runner()->BelongsToCurrentThread());
[email protected]c1330c82013-06-06 02:23:252353 if (!media_thread_) {
2354 media_thread_.reset(new base::Thread("Media"));
2355 media_thread_->Start();
2356 }
skyostil2d3b5bd2015-05-27 15:40:592357 return media_thread_->task_runner();
[email protected]c1330c82013-06-06 02:23:252358}
2359
dcastagna4517a182015-08-05 19:51:032360base::TaskRunner* RenderThreadImpl::GetWorkerTaskRunner() {
prashant.nfad657e2016-06-01 07:52:172361 return categorized_worker_pool_.get();
dcastagnab880e8f2015-06-30 20:16:062362}
2363
Victor Miuraff6488612017-12-21 04:16:152364scoped_refptr<viz::RasterContextProvider>
danakj0b4b94e32016-05-10 22:33:012365RenderThreadImpl::SharedCompositorWorkerContextProvider() {
revemand180dfc32015-09-24 00:19:432366 DCHECK(IsMainThread());
2367 // Try to reuse existing shared worker context provider.
revemand180dfc32015-09-24 00:19:432368 if (shared_worker_context_provider_) {
2369 // Note: If context is lost, delete reference after releasing the lock.
Victor Miura29b7ea3d2017-12-19 20:23:592370 viz::RasterContextProvider::ScopedRasterContextLock lock(
boliu11afa7e2016-04-18 18:04:142371 shared_worker_context_provider_.get());
Victor Miura29b7ea3d2017-12-19 20:23:592372 if (lock.RasterInterface()->GetGraphicsResetStatusKHR() == GL_NO_ERROR)
danakje8ec797e2016-04-19 04:08:432373 return shared_worker_context_provider_;
revemand180dfc32015-09-24 00:19:432374 }
danakje8ec797e2016-04-19 04:08:432375
sadrul6d310fa2016-08-04 02:12:162376 scoped_refptr<gpu::GpuChannelHost> gpu_channel_host(
2377 EstablishGpuChannelSync());
danakje8ec797e2016-04-19 04:08:432378 if (!gpu_channel_host) {
2379 shared_worker_context_provider_ = nullptr;
2380 return shared_worker_context_provider_;
revemand180dfc32015-09-24 00:19:432381 }
danakje8ec797e2016-04-19 04:08:432382
danakj9a04adc2016-05-16 22:45:072383 bool support_locking = true;
Jonathan Backera57031b2018-06-04 15:44:322384 // TODO(backer): Remove checking the command line. GpuInfo is coming
2385 // from a trusted source so the command line check is unnecessary.
Adrienne Walker436a7752017-08-28 23:33:092386 bool support_oop_rasterization =
Jonathan Backera57031b2018-06-04 15:44:322387 gpu_channel_host->gpu_info().oop_rasterization_supported &&
Adrienne Walker436a7752017-08-28 23:33:092388 base::CommandLine::ForCurrentProcess()->HasSwitch(
2389 switches::kEnableOOPRasterization);
Victor Miura589575e2018-02-14 21:37:542390 bool support_gles2_interface = !support_oop_rasterization;
Victor Miura3a4ad4f82017-12-13 06:03:452391 bool support_raster_interface = true;
Justin Novosad7d3d2502018-03-27 18:55:382392 bool support_grcontext = !support_oop_rasterization;
danakj0dd9e1e2016-05-11 22:15:092393 shared_worker_context_provider_ = CreateOffscreenContext(
Antoine Labour5ac65db2017-12-19 18:02:582394 std::move(gpu_channel_host), GetGpuMemoryBufferManager(),
2395 gpu::SharedMemoryLimits(), support_locking, support_gles2_interface,
Justin Novosad7d3d2502018-03-27 18:55:382396 support_raster_interface, support_oop_rasterization, support_grcontext,
Victor Miuraff6488612017-12-21 04:16:152397 ui::command_buffer_metrics::RENDER_WORKER_CONTEXT, kGpuStreamIdWorker,
2398 kGpuStreamPriorityWorker);
danakj45cfd232017-10-18 19:31:312399 auto result = shared_worker_context_provider_->BindToCurrentThread();
2400 if (result != gpu::ContextResult::kSuccess)
danakje8ec797e2016-04-19 04:08:432401 shared_worker_context_provider_ = nullptr;
revemand180dfc32015-09-24 00:19:432402 return shared_worker_context_provider_;
2403}
2404
juncai2f298a82017-04-18 03:51:392405void RenderThreadImpl::SampleGamepads(device::Gamepads* data) {
Blink Reformat1c4d759e2017-04-09 16:34:542406 blink_platform_impl_->SampleGamepads(*data);
[email protected]0ff736562014-05-09 09:09:472407}
2408
rmcilroyaa296052015-04-14 15:35:272409bool RenderThreadImpl::RendererIsHidden() const {
2410 return widget_count_ > 0 && hidden_widget_count_ == widget_count_;
2411}
2412
[email protected]b2db9272014-01-10 17:42:002413void RenderThreadImpl::WidgetCreated() {
rmcilroyaa296052015-04-14 15:35:272414 bool renderer_was_hidden = RendererIsHidden();
[email protected]b2db9272014-01-10 17:42:002415 widget_count_++;
rmcilroyaa296052015-04-14 15:35:272416 if (renderer_was_hidden)
2417 OnRendererVisible();
[email protected]b2db9272014-01-10 17:42:002418}
2419
2420void RenderThreadImpl::WidgetDestroyed() {
rmcilroyaa296052015-04-14 15:35:272421 // TODO(rmcilroy): Remove the restriction that destroyed widgets must be
2422 // unhidden before WidgetDestroyed is called.
2423 DCHECK_GT(widget_count_, 0);
2424 DCHECK_GT(widget_count_, hidden_widget_count_);
[email protected]b2db9272014-01-10 17:42:002425 widget_count_--;
rmcilroyaa296052015-04-14 15:35:272426 if (RendererIsHidden())
2427 OnRendererHidden();
[email protected]b2db9272014-01-10 17:42:002428}
2429
2430void RenderThreadImpl::WidgetHidden() {
2431 DCHECK_LT(hidden_widget_count_, widget_count_);
2432 hidden_widget_count_++;
rmcilroyaa296052015-04-14 15:35:272433 if (RendererIsHidden())
2434 OnRendererHidden();
[email protected]b2db9272014-01-10 17:42:002435}
2436
2437void RenderThreadImpl::WidgetRestored() {
rmcilroyaa296052015-04-14 15:35:272438 bool renderer_was_hidden = RendererIsHidden();
[email protected]b2db9272014-01-10 17:42:002439 DCHECK_GT(hidden_widget_count_, 0);
2440 hidden_widget_count_--;
rmcilroyaa296052015-04-14 15:35:272441 if (renderer_was_hidden)
2442 OnRendererVisible();
2443}
[email protected]b2db9272014-01-10 17:42:002444
rmcilroyaa296052015-04-14 15:35:272445void RenderThreadImpl::OnRendererHidden() {
Blink Reformat1c4d759e2017-04-09 16:34:542446 blink::MainThreadIsolate()->IsolateInBackgroundNotification();
rmcilroyaa296052015-04-14 15:35:272447 // TODO(rmcilroy): Remove IdleHandler and replace it with an IdleTask
2448 // scheduled by the RendererScheduler - http://crbug.com/469210.
ulan4a385192015-11-11 10:59:182449 if (!GetContentClient()->renderer()->RunIdleHandlerWhenWidgetsHidden())
2450 return;
Yuta Kitamura3331f5c2018-04-05 11:12:252451 main_thread_scheduler_->SetRendererHidden(true);
ulan4a385192015-11-11 10:59:182452 ScheduleIdleHandler(kInitialIdleHandlerDelayMs);
rmcilroyaa296052015-04-14 15:35:272453}
2454
2455void RenderThreadImpl::OnRendererVisible() {
Blink Reformat1c4d759e2017-04-09 16:34:542456 blink::MainThreadIsolate()->IsolateInForegroundNotification();
rmcilroyaa296052015-04-14 15:35:272457 if (!GetContentClient()->renderer()->RunIdleHandlerWhenWidgetsHidden())
[email protected]b2db9272014-01-10 17:42:002458 return;
Yuta Kitamura3331f5c2018-04-05 11:12:252459 main_thread_scheduler_->SetRendererHidden(false);
[email protected]b2db9272014-01-10 17:42:002460 ScheduleIdleHandler(kLongIdleHandlerDelayMs);
2461}
2462
ssid0603ca9f2015-06-09 16:48:082463void RenderThreadImpl::ReleaseFreeMemory() {
2464 base::allocator::ReleaseFreeMemory();
penghuang342762b2016-12-02 21:04:582465 discardable_shared_memory_manager_->ReleaseFreeMemory();
ssid0603ca9f2015-06-09 16:48:082466
Gyuyoung Kim7b96fa72018-03-05 01:44:252467 // Do not call into blink if it is not initialized.
2468 if (blink_platform_impl_) {
2469 // Purge Skia font cache, resource cache, and image filter.
2470 SkGraphics::PurgeAllCaches();
Gyuyoung Kimf3ab72b2018-06-05 01:26:012471 blink::WebMemoryCoordinator::OnPurgeMemory();
Gyuyoung Kim7b96fa72018-03-05 01:44:252472 }
ssid0603ca9f2015-06-09 16:48:082473}
2474
ben76f52b242016-06-18 05:42:482475RenderThreadImpl::PendingFrameCreate::PendingFrameCreate(
benf28ce882017-05-02 16:15:492476 const service_manager::BindSourceInfo& browser_info,
rockotf8fdd9b2015-12-16 22:22:352477 int routing_id,
Balazs Engedyba034e72017-10-27 22:26:282478 mojom::FrameRequest frame_request)
benf28ce882017-05-02 16:15:492479 : browser_info_(browser_info),
2480 routing_id_(routing_id),
Balazs Engedyba034e72017-10-27 22:26:282481 frame_request_(std::move(frame_request)) {}
rockotf8fdd9b2015-12-16 22:22:352482
ben76f52b242016-06-18 05:42:482483RenderThreadImpl::PendingFrameCreate::~PendingFrameCreate() {
rockotf8fdd9b2015-12-16 22:22:352484}
2485
ben76f52b242016-06-18 05:42:482486void RenderThreadImpl::PendingFrameCreate::OnConnectionError() {
rockotf8fdd9b2015-12-16 22:22:352487 size_t erased =
ben76f52b242016-06-18 05:42:482488 RenderThreadImpl::current()->pending_frame_creates_.erase(routing_id_);
rockotf8fdd9b2015-12-16 22:22:352489 DCHECK_EQ(1u, erased);
2490}
2491
hong.zhengb28b5332016-05-11 02:33:392492void RenderThreadImpl::OnSyncMemoryPressure(
2493 base::MemoryPressureListener::MemoryPressureLevel memory_pressure_level) {
Blink Reformat1c4d759e2017-04-09 16:34:542494 if (!blink::MainThreadIsolate())
hong.zhengb28b5332016-05-11 02:33:392495 return;
2496
2497 v8::MemoryPressureLevel v8_memory_pressure_level =
2498 static_cast<v8::MemoryPressureLevel>(memory_pressure_level);
2499
Luke Halliwell16136de2017-07-05 21:15:562500#if !BUILDFLAG(ALLOW_CRITICAL_MEMORY_PRESSURE_HANDLING_IN_FOREGROUND)
hong.zhengb28b5332016-05-11 02:33:392501 // In order to reduce performance impact, translate critical level to
Luke Halliwell16136de2017-07-05 21:15:562502 // moderate level for foreground renderer.
hong.zhengb28b5332016-05-11 02:33:392503 if (!RendererIsHidden() &&
2504 v8_memory_pressure_level == v8::MemoryPressureLevel::kCritical)
2505 v8_memory_pressure_level = v8::MemoryPressureLevel::kModerate;
Luke Halliwell16136de2017-07-05 21:15:562506#endif // !BUILDFLAG(ALLOW_CRITICAL_MEMORY_PRESSURE_HANDLING_IN_FOREGROUND)
hong.zhengb28b5332016-05-11 02:33:392507
Blink Reformat1c4d759e2017-04-09 16:34:542508 blink::MainThreadIsolate()->MemoryPressureNotification(
hong.zhengb28b5332016-05-11 02:33:392509 v8_memory_pressure_level);
2510 blink::MemoryPressureNotificationToWorkerThreadIsolates(
2511 v8_memory_pressure_level);
2512}
2513
bashic4b4afcb2016-08-23 06:37:522514// Note that this would be called only when memory_coordinator is enabled.
2515// OnSyncMemoryPressure() is never called in that case.
2516void RenderThreadImpl::OnTrimMemoryImmediately() {
Blink Reformat1c4d759e2017-04-09 16:34:542517 if (blink::MainThreadIsolate()) {
2518 blink::MainThreadIsolate()->MemoryPressureNotification(
bashic4b4afcb2016-08-23 06:37:522519 v8::MemoryPressureLevel::kCritical);
2520 blink::MemoryPressureNotificationToWorkerThreadIsolates(
2521 v8::MemoryPressureLevel::kCritical);
2522 }
2523}
2524
rockot067ca55f2016-09-30 22:00:152525void RenderThreadImpl::OnRendererInterfaceRequest(
2526 mojom::RendererAssociatedRequest request) {
2527 DCHECK(!renderer_binding_.is_bound());
Hajime Hoshif21f20c2018-03-27 04:07:032528 renderer_binding_.Bind(std::move(request),
Yuta Kitamura3331f5c2018-04-05 11:12:252529 GetWebMainThreadScheduler()->IPCTaskRunner());
rockot067ca55f2016-09-30 22:00:152530}
bashic4b4afcb2016-08-23 06:37:522531
Takashi SAKAMOTO870f6262017-08-22 04:08:272532bool RenderThreadImpl::NeedsToRecordFirstActivePaint(
2533 int ttfap_metric_type) const {
2534 if (ttfap_metric_type == RenderWidget::TTFAP_AFTER_PURGED)
2535 return needs_to_record_first_active_paint_;
2536
2537 if (was_backgrounded_time_.is_min())
2538 return false;
2539 base::TimeDelta passed = base::TimeTicks::Now() - was_backgrounded_time_;
2540 return passed.InMinutes() >= 5;
2541}
2542
Miguel Casas5e1018052018-01-09 19:17:362543void RenderThreadImpl::SetRenderingColorSpace(
2544 const gfx::ColorSpace& color_space) {
2545 DCHECK(IsMainThread());
2546 rendering_color_space_ = color_space;
2547
2548 for (const auto& factories : gpu_factories_) {
2549 if (factories)
2550 factories->SetRenderingColorSpace(color_space);
2551 }
2552}
2553
[email protected]e9ff79c2012-10-19 21:31:262554} // namespace content