blob: 0e89e64a4c9f542859e2907a9c1693d32b9c2f83 [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"
dchengcedca5612016-04-09 01:40:1521#include "base/memory/ptr_util.h"
[email protected]8bac37b2013-07-18 19:13:5622#include "base/memory/shared_memory.h"
gabf64a25e2017-05-12 19:42:5623#include "base/message_loop/message_loop.h"
[email protected]835d7c82010-10-14 04:38:3824#include "base/metrics/field_trial.h"
tasaka27961a2017-05-24 07:33:2525#include "base/metrics/histogram_functions.h"
asvitkine8d51e9d2016-09-02 23:55:4326#include "base/metrics/histogram_macros.h"
[email protected]433df472012-03-07 20:33:3927#include "base/path_service.h"
tasakb46626a2016-10-18 05:54:4428#include "base/process/process_metrics.h"
fdoray2df4a9e2016-07-18 23:47:1629#include "base/run_loop.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"
fdoray50a38342016-11-21 20:46:0435#include "base/threading/sequenced_worker_pool.h"
reveman34b7a1522015-03-23 20:27:4736#include "base/threading/simple_thread.h"
[email protected]1357c322010-12-30 22:18:5637#include "base/threading/thread_local.h"
[email protected]d293572a2013-05-23 18:50:4538#include "base/threading/thread_restrictions.h"
gab30f26df2016-05-11 19:37:5539#include "base/threading/thread_task_runner_handle.h"
ccameron9c48d1d42016-09-22 01:46:0140#include "base/trace_event/memory_dump_manager.h"
primiano9e38d552015-01-28 04:18:0141#include "base/trace_event/trace_event.h"
[email protected]7a4de7a62010-08-17 18:38:2442#include "base/values.h"
avi1023d012015-12-25 02:39:1443#include "build/build_config.h"
jbroman0d302162015-09-05 05:46:2344#include "cc/base/histograms.h"
[email protected]d72493152014-01-08 17:37:4545#include "cc/base/switches.h"
[email protected]38564622014-08-19 02:47:1846#include "cc/blink/web_layer_impl.h"
danakj920156852015-05-18 20:22:2947#include "cc/raster/task_graph_runner.h"
danakjba65a0912017-09-21 16:38:4248#include "cc/trees/layer_tree_frame_sink.h"
vollick1050cc62015-12-03 07:04:5449#include "cc/trees/layer_tree_host_common.h"
loysoa6edaaff2015-05-25 03:26:4450#include "cc/trees/layer_tree_settings.h"
penghuangd81c1a62016-11-02 20:06:0651#include "components/discardable_memory/client/client_discardable_shared_memory_manager.h"
dalecurtis4a9839a2017-05-04 23:40:4752#include "components/metrics/public/interfaces/single_sample_metrics.mojom.h"
53#include "components/metrics/single_sample_metrics.h"
danakjc7afae52017-06-20 21:12:4154#include "components/viz/client/client_layer_tree_frame_sink.h"
danakj92429852017-06-29 00:19:0355#include "components/viz/client/client_shared_bitmap_manager.h"
Valery Arkhangorodsky513ac8fd2017-08-02 23:09:2356#include "components/viz/client/hit_test_data_provider.h"
Ria Jiang28051112018-02-13 16:38:5257#include "components/viz/client/hit_test_data_provider_draw_quad.h"
samans7e6675cc2017-06-05 20:16:0858#include "components/viz/client/local_surface_id_provider.h"
Fady Samuel343a74952017-11-30 14:19:2059#include "components/viz/common/features.h"
danakjf20f4502017-09-26 17:13:3160#include "components/viz/common/frame_sinks/copy_output_request.h"
Alex Zhang1f159572017-08-23 20:14:2061#include "components/viz/common/gpu/vulkan_in_process_context_provider.h"
bashia6264042016-09-15 04:49:5162#include "content/child/memory/child_memory_coordinator_impl.h"
[email protected]643255da2013-06-12 20:55:1363#include "content/child/runtime_features.h"
[email protected]57cf97882013-06-26 20:39:0164#include "content/child/thread_safe_sender.h"
[email protected]89c36f82013-07-17 06:23:2765#include "content/common/content_constants_internal.h"
[email protected]5f2aa722013-08-07 16:59:4166#include "content/common/dom_storage/dom_storage_messages.h"
thakis18e426412017-03-15 12:06:3767#include "content/common/features.h"
[email protected]82307f6b2014-08-07 03:30:1268#include "content/common/frame_messages.h"
raymesbba82b32016-07-19 00:41:3869#include "content/common/frame_owner_properties.h"
sunnyps8f9139e2017-05-12 17:53:2570#include "content/common/gpu_stream_constants.h"
[email protected]778574e2011-03-21 22:03:5071#include "content/common/view_messages.h"
[email protected]a458504b2012-07-23 19:57:0672#include "content/public/common/content_constants.h"
bashia6264042016-09-15 04:49:5173#include "content/public/common/content_features.h"
[email protected]433df472012-03-07 20:33:3974#include "content/public/common/content_paths.h"
[email protected]c08950d22011-10-13 22:20:2975#include "content/public/common/content_switches.h"
[email protected]daf82f82011-10-31 22:35:3176#include "content/public/common/renderer_preferences.h"
Ben Goodgerf180ce12018-02-09 22:54:0177#include "content/public/common/resource_usage_reporter.mojom.h"
78#include "content/public/common/resource_usage_reporter_type_converters.h"
benbd9dc802017-04-19 01:37:4379#include "content/public/common/service_manager_connection.h"
ben649b3edd2017-03-23 00:32:0280#include "content/public/common/service_names.mojom.h"
benbd9dc802017-04-19 01:37:4381#include "content/public/common/simple_connection_filter.h"
[email protected]58436a12012-03-21 17:10:2682#include "content/public/common/url_constants.h"
[email protected]d344114c2011-10-01 01:24:3483#include "content/public/renderer/content_renderer_client.h"
tyoshino832a58a2016-04-18 08:14:0884#include "content/public/renderer/render_thread_observer.h"
[email protected]64ffa0442011-10-03 22:08:3685#include "content/public/renderer/render_view_visitor.h"
John Abd-El-Malekdcf1d1372017-10-22 06:39:4186#include "content/renderer/appcache/appcache_dispatcher.h"
87#include "content/renderer/appcache/appcache_frontend_impl.h"
fsamuel6c1dfeb2014-12-18 19:21:3388#include "content/renderer/browser_plugin/browser_plugin_manager.h"
jsbell279efb42015-03-31 17:02:4689#include "content/renderer/cache_storage/cache_storage_dispatcher.h"
90#include "content/renderer/cache_storage/cache_storage_message_filter.h"
prashant.nfad657e2016-06-01 07:52:1791#include "content/renderer/categorized_worker_pool.h"
[email protected]1910fe82012-05-10 00:04:1092#include "content/renderer/dom_storage/dom_storage_dispatcher.h"
93#include "content/renderer/dom_storage/webstoragearea_impl.h"
94#include "content/renderer/dom_storage/webstoragenamespace_impl.h"
tbansalb612c5d2017-05-25 18:53:0695#include "content/renderer/effective_connection_type_helper.h"
John Abd-El-Malekdcf1d1372017-10-22 06:39:4196#include "content/renderer/fileapi/file_system_dispatcher.h"
97#include "content/renderer/fileapi/webfilesystem_impl.h"
danakj83066a32016-06-21 02:34:4998#include "content/renderer/gpu/frame_swap_message_queue.h"
John Abd-El-Malekdcf1d1372017-10-22 06:39:4199#include "content/renderer/indexed_db/indexed_db_dispatcher.h"
[email protected]7a72d452013-12-13 10:01:13100#include "content/renderer/input/input_event_filter.h"
101#include "content/renderer/input/input_handler_manager.h"
jdduke691dd572014-12-02 20:47:52102#include "content/renderer/input/main_thread_input_event_filter.h"
John Abd-El-Malek6b56ef712017-10-21 22:52:46103#include "content/renderer/loader/resource_dispatcher.h"
Scott Violet1098538e2017-10-05 19:23:33104#include "content/renderer/mash_util.h"
[email protected]f7eb0a392011-07-12 10:19:51105#include "content/renderer/media/audio_input_message_filter.h"
106#include "content/renderer/media/audio_message_filter.h"
[email protected]3958e972012-07-17 00:25:41107#include "content/renderer/media/audio_renderer_mixer_manager.h"
Miguel Casas-Sanchezcfcca5d52017-07-07 02:32:59108#include "content/renderer/media/gpu/gpu_video_accelerator_factories_impl.h"
Miguel Casasfff0ed52018-02-13 16:24:35109#include "content/renderer/media/midi/midi_message_filter.h"
xhwang194acae2014-11-12 22:46:33110#include "content/renderer/media/render_media_client.h"
Miguel Casasa8c2c5a2018-02-12 18:51:03111#include "content/renderer/media/stream/media_stream_center.h"
[email protected]80b161a2011-06-27 17:42:11112#include "content/renderer/media/video_capture_impl_manager.h"
Stuart Langley849079a2017-08-28 02:02:50113#include "content/renderer/mus/render_widget_window_tree_client_factory.h"
114#include "content/renderer/mus/renderer_window_tree_client.h"
[email protected]d7ff5fb2014-05-29 19:50:25115#include "content/renderer/net_info_helper.h"
John Abd-El-Malekf9f86c12017-10-21 07:22:23116#include "content/renderer/notifications/notification_dispatcher.h"
[email protected]82307f6b2014-08-07 03:30:12117#include "content/renderer/render_frame_proxy.h"
[email protected]8704f89b2011-04-15 00:30:05118#include "content/renderer/render_process_impl.h"
[email protected]310ebd6302011-10-10 19:06:28119#include "content/renderer/render_view_impl.h"
tfarina556a7232014-10-05 01:02:09120#include "content/renderer/renderer_blink_platform_impl.h"
shimazu5de409e42016-09-29 08:45:28121#include "content/renderer/service_worker/embedded_worker_instance_client_impl.h"
mek27c9d742015-07-16 18:30:18122#include "content/renderer/service_worker/service_worker_context_client.h"
John Abd-El-Maleke1d4de32017-10-21 16:14:29123#include "content/renderer/service_worker/service_worker_message_filter.h"
[email protected]0ec90d522014-03-12 16:28:19124#include "content/renderer/shared_worker/embedded_shared_worker_stub.h"
Darin Fisherbcc33632017-09-26 00:57:16125#include "content/renderer/shared_worker/shared_worker_factory_impl.h"
John Abd-El-Malekf75a3192017-10-22 14:23:20126#include "content/renderer/web_database_observer_impl.h"
127#include "content/renderer/worker_thread_registry.h"
juncai2f298a82017-04-18 03:51:39128#include "device/gamepad/public/cpp/gamepads.h"
chunyang.daibe874c52014-11-14 06:45:05129#include "gin/public/debug.h"
dongseong.hwang72183b02014-12-08 10:41:55130#include "gpu/GLES2/gl2extchromium.h"
Victor Miura3a4ad4f82017-12-13 06:03:45131#include "gpu/command_buffer/client/gles2_interface.h"
132#include "gpu/command_buffer/client/raster_interface.h"
danakj6f4e1e22016-04-20 03:27:34133#include "gpu/command_buffer/client/shared_memory_limits.h"
Adrienne Walker436a7752017-08-28 23:33:09134#include "gpu/config/gpu_switches.h"
danakj870925d42016-05-03 20:07:38135#include "gpu/ipc/client/command_buffer_proxy_impl.h"
penghuang346a46f92016-03-31 21:37:52136#include "gpu/ipc/client/gpu_channel_host.h"
[email protected]46f36a492010-07-28 19:36:41137#include "ipc/ipc_channel_handle.h"
amistryd4aa70d2016-06-23 07:52:37138#include "ipc/ipc_channel_mojo.h"
[email protected]cb6037d2009-11-16 22:55:17139#include "ipc/ipc_platform_file.h"
[email protected]433df472012-03-07 20:33:39140#include "media/base/media.h"
chcunningham9a285ed2017-03-08 21:48:56141#include "media/base/media_switches.h"
Brett Wilson0748bf412016-11-22 17:55:46142#include "media/media_features.h"
Dale Curtis863022e2017-08-19 02:05:34143#include "media/video/gpu_video_accelerator_factories.h"
rockot85dce0862015-11-13 01:33:59144#include "mojo/public/cpp/bindings/strong_binding.h"
Yuki Yamada68992b02017-07-31 06:13:45145#include "mojo/public/cpp/system/message_pipe.h"
[email protected]620161e2011-03-07 18:05:26146#include "net/base/net_errors.h"
eroman9ab64842015-07-21 05:07:52147#include "net/base/port_util.h"
hablichd6a4f122015-10-28 11:34:49148#include "net/base/registry_controlled_domains/registry_controlled_domain.h"
tfarina7a4a7fd2016-01-20 14:23:44149#include "net/base/url_util.h"
brettw4b461082016-11-19 18:55:16150#include "ppapi/features/features.h"
Khushal3e96e662017-10-30 23:16:50151#include "services/metrics/public/cpp/mojo_ukm_recorder.h"
penghuangd6843e42016-12-17 13:57:20152#include "services/service_manager/public/cpp/connector.h"
rockot734fb662016-10-15 16:41:30153#include "services/service_manager/public/cpp/interface_provider.h"
sadrul85cc5d82016-12-20 03:37:41154#include "services/ui/public/cpp/gpu/context_provider_command_buffer.h"
Stuart Langley849079a2017-08-28 02:02:50155#include "services/ui/public/cpp/gpu/gpu.h"
penghuangd6843e42016-12-17 13:57:20156#include "services/ui/public/interfaces/constants.mojom.h"
[email protected]b48c53ad2014-02-05 21:59:18157#include "skia/ext/event_tracer_impl.h"
ssid59c969162015-07-28 13:02:58158#include "skia/ext/skia_memory_dump_provider.h"
kinukoed1ed1d2017-02-08 09:13:43159#include "third_party/WebKit/public/platform/WebCache.h"
reed6e5a72222015-08-06 20:37:16160#include "third_party/WebKit/public/platform/WebImageGenerator.h"
bashi5f4c78922016-08-18 23:06:08161#include "third_party/WebKit/public/platform/WebMemoryCoordinator.h"
kinukofbfee762017-03-08 04:01:06162#include "third_party/WebKit/public/platform/WebNetworkStateNotifier.h"
nverne61d2da872017-05-24 10:15:30163#include "third_party/WebKit/public/platform/WebRuntimeFeatures.h"
[email protected]89c36f82013-07-17 06:23:27164#include "third_party/WebKit/public/platform/WebString.h"
skyostil457b0a12014-09-09 10:12:07165#include "third_party/WebKit/public/platform/WebThread.h"
altiminc7369bf2017-04-11 14:29:15166#include "third_party/WebKit/public/platform/scheduler/child/webthread_base.h"
skyostil529caa292016-08-10 17:44:51167#include "third_party/WebKit/public/platform/scheduler/renderer/renderer_scheduler.h"
[email protected]2255a9332013-06-17 05:12:31168#include "third_party/WebKit/public/web/WebDocument.h"
169#include "third_party/WebKit/public/web/WebFrame.h"
170#include "third_party/WebKit/public/web/WebKit.h"
[email protected]2255a9332013-06-17 05:12:31171#include "third_party/WebKit/public/web/WebScriptController.h"
172#include "third_party/WebKit/public/web/WebSecurityPolicy.h"
[email protected]2255a9332013-06-17 05:12:31173#include "third_party/WebKit/public/web/WebView.h"
David Benjaminb946811c2017-06-26 23:34:29174#include "third_party/boringssl/src/include/openssl/evp.h"
[email protected]ddbb53342014-01-06 10:59:47175#include "third_party/skia/include/core/SkGraphics.h"
[email protected]c49201a2012-05-24 11:04:57176#include "ui/base/layout.h"
[email protected]18ad6772011-09-20 21:51:32177#include "ui/base/ui_base_switches.h"
Sadrul Habib Chowdhuryeeb5a942017-11-28 21:17:23178#include "ui/base/ui_base_switches_util.h"
mlamouri7c149652017-03-24 00:00:09179#include "ui/display/display_switches.h"
ennee292bdc2016-09-15 19:57:15180#include "ui/gl/gl_switches.h"
[email protected]2c62b562009-01-27 19:04:50181
Ramin Halavati4aaa3f52018-02-07 07:41:50182#if BUILDFLAG(ENABLE_WEBRTC)
183#include "content/renderer/p2p/socket_dispatcher.h"
184#endif
185
[email protected]33b02992014-03-01 01:06:29186#if defined(OS_ANDROID)
187#include <cpu-features.h>
boliubee541f42015-11-05 00:52:53188#include "content/renderer/android/synchronous_compositor_filter.h"
danakjc7afae52017-06-20 21:12:41189#include "content/renderer/android/synchronous_layer_tree_frame_sink.h"
boliue81d16132016-04-26 00:54:41190#include "content/renderer/media/android/stream_texture_factory.h"
dalecurtis88af3932016-02-20 00:12:20191#include "media/base/android/media_codec_util.h"
[email protected]33b02992014-03-01 01:06:29192#endif
193
194#if defined(OS_MACOSX)
ccamerona7644752014-12-30 01:16:31195#include "base/mac/mac_util.h"
rsesek1efb3c32015-09-29 15:39:50196#include "content/renderer/theme_helper_mac.h"
[email protected]33b02992014-03-01 01:06:29197#include "content/renderer/webscrollbarbehavior_impl_mac.h"
198#endif
199
[email protected]da00a2882009-03-09 17:51:19200#if defined(OS_WIN)
201#include <windows.h>
202#include <objbase.h>
203#endif
204
Brett Wilson0748bf412016-11-22 17:55:46205#if BUILDFLAG(ENABLE_WEBRTC)
Miguel Casasa8c2c5a2018-02-12 18:51:03206#include "content/renderer/media/stream/aec_dump_message_filter.h"
[email protected]22fe91d2014-08-12 17:07:12207#include "content/renderer/media/webrtc/peer_connection_dependency_factory.h"
Miguel Casasee42e702018-02-09 19:07:03208#include "content/renderer/media/webrtc/peer_connection_tracker.h"
209#include "content/renderer/media/webrtc/rtc_peer_connection_handler.h"
[email protected]22fe91d2014-08-12 17:07:12210#endif
211
chunyang.daibe874c52014-11-14 06:45:05212#ifdef ENABLE_VTUNE_JIT_INTERFACE
213#include "v8/src/third_party/vtune/v8-vtune.h"
214#endif
215
ochangdd89a1e2016-06-08 16:39:01216#if defined(ENABLE_IPC_FUZZER)
217#include "content/common/external_ipc_dumper.h"
218#endif
219
tasakb46626a2016-10-18 05:54:44220#if defined(OS_MACOSX)
221#include <malloc/malloc.h>
222#else
223#include <malloc.h>
224#endif
225
[email protected]d293572a2013-05-23 18:50:45226using base::ThreadRestrictions;
[email protected]180ef242013-11-07 06:50:46227using blink::WebDocument;
228using blink::WebFrame;
229using blink::WebNetworkStateNotifier;
230using blink::WebRuntimeFeatures;
231using blink::WebScriptController;
232using blink::WebSecurityPolicy;
233using blink::WebString;
234using blink::WebView;
[email protected]e9ff79c2012-10-19 21:31:26235
236namespace content {
initial.commit09911bf2008-07-26 23:55:29237
[email protected]42f1d7822009-07-23 18:17:55238namespace {
[email protected]da9ccfb2012-01-28 00:34:40239
avi1023d012015-12-25 02:39:14240const int64_t kInitialIdleHandlerDelayMs = 1000;
241const int64_t kLongIdleHandlerDelayMs = 30 * 1000;
[email protected]bee16aab2009-08-26 15:55:03242
[email protected]dd2c1022014-07-22 23:13:57243// Maximum allocation size allowed for image scaling filters that
244// require pre-scaling. Skia will fallback to a filter that doesn't
245// require pre-scaling if the default filter would require an
246// allocation that exceeds this limit.
247const size_t kImageCacheSingleAllocationByteLimit = 64 * 1024 * 1024;
248
samans2040988b2017-04-11 23:58:35249#if defined(OS_ANDROID)
danakj83066a32016-06-21 02:34:49250// Unique identifier for each output surface created.
danakjc7afae52017-06-20 21:12:41251uint32_t g_next_layer_tree_frame_sink_id = 1;
samans2040988b2017-04-11 23:58:35252#endif
danakj83066a32016-06-21 02:34:49253
rockot5c478a72016-09-28 23:14:18254// An implementation of mojom::RenderMessageFilter which can be mocked out
255// for tests which may indirectly send messages over this interface.
256mojom::RenderMessageFilter* g_render_message_filter_for_testing;
257
olegmax045f7fb12017-05-19 07:58:55258// An implementation of RendererBlinkPlatformImpl which can be mocked out
259// for tests.
260RendererBlinkPlatformImpl* g_current_blink_platform_impl_for_testing;
261
[email protected]f1a29a02011-10-06 23:08:44262// Keep the global RenderThreadImpl in a TLS slot so it is impossible to access
[email protected]f3ede412010-06-21 22:52:16263// incorrectly from the wrong thread.
scottmg5e65e3a2017-03-08 08:48:46264base::LazyInstance<base::ThreadLocalPointer<RenderThreadImpl>>::DestructorAtExit
[email protected]6de0fd1d2011-11-15 13:31:49265 lazy_tls = LAZY_INSTANCE_INITIALIZER;
[email protected]1edc16b82009-04-07 17:45:54266
John Abd-El-Malekd4882642017-12-04 21:45:19267base::LazyInstance<scoped_refptr<base::SingleThreadTaskRunner>>::
268 DestructorAtExit g_main_task_runner = LAZY_INSTANCE_INITIALIZER;
269
hong.zhengb28b5332016-05-11 02:33:39270// v8::MemoryPressureLevel should correspond to base::MemoryPressureListener.
271static_assert(static_cast<v8::MemoryPressureLevel>(
272 base::MemoryPressureListener::MEMORY_PRESSURE_LEVEL_NONE) ==
273 v8::MemoryPressureLevel::kNone, "none level not align");
274static_assert(static_cast<v8::MemoryPressureLevel>(
275 base::MemoryPressureListener::MEMORY_PRESSURE_LEVEL_MODERATE) ==
276 v8::MemoryPressureLevel::kModerate, "moderate level not align");
277static_assert(static_cast<v8::MemoryPressureLevel>(
278 base::MemoryPressureListener::MEMORY_PRESSURE_LEVEL_CRITICAL) ==
279 v8::MemoryPressureLevel::kCritical, "critical level not align");
280
hong.zheng2e296f822016-06-29 02:47:44281// WebMemoryPressureLevel should correspond to base::MemoryPressureListener.
282static_assert(static_cast<blink::WebMemoryPressureLevel>(
Blink Reformat1c4d759e2017-04-09 16:34:54283 base::MemoryPressureListener::MEMORY_PRESSURE_LEVEL_NONE) ==
284 blink::kWebMemoryPressureLevelNone,
285 "blink::WebMemoryPressureLevelNone not align");
286static_assert(
287 static_cast<blink::WebMemoryPressureLevel>(
288 base::MemoryPressureListener::MEMORY_PRESSURE_LEVEL_MODERATE) ==
289 blink::kWebMemoryPressureLevelModerate,
290 "blink::WebMemoryPressureLevelModerate not align");
291static_assert(
292 static_cast<blink::WebMemoryPressureLevel>(
293 base::MemoryPressureListener::MEMORY_PRESSURE_LEVEL_CRITICAL) ==
294 blink::kWebMemoryPressureLevelCritical,
295 "blink::WebMemoryPressureLevelCritical not align");
hong.zheng2e296f822016-06-29 02:47:44296
[email protected]b2d98762012-09-03 17:04:06297void* CreateHistogram(
[email protected]d1b8fccc2011-08-03 01:20:13298 const char *name, int min, int max, size_t buckets) {
299 if (min <= 0)
300 min = 1;
[email protected]b2d98762012-09-03 17:04:06301 std::string histogram_name;
302 RenderThreadImpl* render_thread_impl = RenderThreadImpl::current();
303 if (render_thread_impl) { // Can be null in tests.
304 histogram_name = render_thread_impl->
305 histogram_customizer()->ConvertToCustomHistogramName(name);
306 } else {
307 histogram_name = std::string(name);
308 }
[email protected]de415552013-01-23 04:12:17309 base::HistogramBase* histogram = base::Histogram::FactoryGet(
[email protected]b2d98762012-09-03 17:04:06310 histogram_name, min, max, buckets,
311 base::Histogram::kUmaTargetedHistogramFlag);
[email protected]d1b8fccc2011-08-03 01:20:13312 return histogram;
313}
314
[email protected]b2d98762012-09-03 17:04:06315void AddHistogramSample(void* hist, int sample) {
[email protected]d1b8fccc2011-08-03 01:20:13316 base::Histogram* histogram = static_cast<base::Histogram*>(hist);
317 histogram->Add(sample);
318}
319
ben76f52b242016-06-18 05:42:48320class FrameFactoryImpl : public mojom::FrameFactory {
rockotf8fdd9b2015-12-16 22:22:35321 public:
benf28ce882017-05-02 16:15:49322 explicit FrameFactoryImpl(const service_manager::BindSourceInfo& source_info)
323 : source_info_(source_info), routing_id_highmark_(-1) {}
rockotf8fdd9b2015-12-16 22:22:35324
ben76f52b242016-06-18 05:42:48325 private:
326 // mojom::FrameFactory:
Balazs Engedyba034e72017-10-27 22:26:28327 void CreateFrame(int32_t frame_routing_id,
328 mojom::FrameRequest frame_request) override {
rockotf8fdd9b2015-12-16 22:22:35329 // TODO(morrita): This is for investigating http://crbug.com/415059 and
330 // should be removed once it is fixed.
331 CHECK_LT(routing_id_highmark_, frame_routing_id);
332 routing_id_highmark_ = frame_routing_id;
333
334 RenderFrameImpl* frame = RenderFrameImpl::FromRoutingID(frame_routing_id);
335 // We can receive a GetServiceProviderForFrame message for a frame not yet
rockot067ca55f2016-09-30 22:00:15336 // created due to a race between the message and a
337 // mojom::Renderer::CreateView IPC that triggers creation of the RenderFrame
338 // we want.
rockotf8fdd9b2015-12-16 22:22:35339 if (!frame) {
ben76f52b242016-06-18 05:42:48340 RenderThreadImpl::current()->RegisterPendingFrameCreate(
Balazs Engedyba034e72017-10-27 22:26:28341 source_info_, frame_routing_id, std::move(frame_request));
rockotf8fdd9b2015-12-16 22:22:35342 return;
343 }
344
Balazs Engedyba034e72017-10-27 22:26:28345 frame->BindFrame(source_info_, std::move(frame_request));
rockotf8fdd9b2015-12-16 22:22:35346 }
347
348 private:
benf28ce882017-05-02 16:15:49349 service_manager::BindSourceInfo source_info_;
rockotf8fdd9b2015-12-16 22:22:35350 int32_t routing_id_highmark_;
rockotf8fdd9b2015-12-16 22:22:35351};
352
Ben Goodger21ada1e2017-07-19 14:53:01353void CreateFrameFactory(mojom::FrameFactoryRequest request,
354 const service_manager::BindSourceInfo& source_info) {
Jeremy Roman04f27c372017-10-27 15:20:55355 mojo::MakeStrongBinding(std::make_unique<FrameFactoryImpl>(source_info),
rockot8e66a08d2016-09-13 00:48:21356 std::move(request));
rockotf8fdd9b2015-12-16 22:22:35357}
358
sadrul85cc5d82016-12-20 03:37:41359scoped_refptr<ui::ContextProviderCommandBuffer> CreateOffscreenContext(
danakjc3983552016-05-03 00:04:35360 scoped_refptr<gpu::GpuChannelHost> gpu_channel_host,
Antoine Labour5ac65db2017-12-19 18:02:58361 gpu::GpuMemoryBufferManager* gpu_memory_buffer_manager,
danakj0dd9e1e2016-05-11 22:15:09362 const gpu::SharedMemoryLimits& limits,
danakj9a04adc2016-05-16 22:45:07363 bool support_locking,
Victor Miura3a4ad4f82017-12-13 06:03:45364 bool support_gles2_interface,
365 bool support_raster_interface,
Adrienne Walker436a7752017-08-28 23:33:09366 bool support_oop_rasterization,
sadrul85cc5d82016-12-20 03:37:41367 ui::command_buffer_metrics::ContextType type,
sunnypsd8ce1c22016-05-10 18:02:40368 int32_t stream_id,
sunnyps8f9139e2017-05-12 17:53:25369 gpu::SchedulingPriority stream_priority) {
danakje8ec797e2016-04-19 04:08:43370 DCHECK(gpu_channel_host);
371 // This is used to create a few different offscreen contexts:
Victor Miura3a4ad4f82017-12-13 06:03:45372 // - The shared main thread context, used by blink for 2D Canvas.
373 // - The compositor worker context, used for GPU raster.
374 // - The media context, used for accelerated video decoding.
danakje8ec797e2016-04-19 04:08:43375 // This is for an offscreen context, so the default framebuffer doesn't need
376 // alpha, depth, stencil, antialiasing.
Antoine Labourfeab2392017-12-21 20:28:39377 gpu::ContextCreationAttribs attributes;
danakje8ec797e2016-04-19 04:08:43378 attributes.alpha_size = -1;
379 attributes.depth_size = 0;
380 attributes.stencil_size = 0;
381 attributes.samples = 0;
382 attributes.sample_buffers = 0;
383 attributes.bind_generates_resource = false;
384 attributes.lose_context_when_out_of_memory = true;
Victor Miura3a4ad4f82017-12-13 06:03:45385 attributes.enable_gles2_interface = support_gles2_interface;
386 attributes.enable_raster_interface = support_raster_interface;
Adrienne Walker436a7752017-08-28 23:33:09387 attributes.enable_oop_rasterization = support_oop_rasterization;
388
sunnypsd8ce1c22016-05-10 18:02:40389 const bool automatic_flushes = false;
kylechar96f3eba2017-09-25 20:23:56390 return base::MakeRefCounted<ui::ContextProviderCommandBuffer>(
Antoine Labour5ac65db2017-12-19 18:02:58391 std::move(gpu_channel_host), gpu_memory_buffer_manager, stream_id,
392 stream_priority, gpu::kNullSurfaceHandle,
zmo09ea813b2017-01-20 23:38:36393 GURL("chrome://gpu/RenderThreadImpl::CreateOffscreenContext/" +
394 ui::command_buffer_metrics::ContextTypeToString(type)),
Victor Miuraff6488612017-12-21 04:16:15395 automatic_flushes, support_locking, limits, attributes,
396 nullptr /* share_context */, type);
danakje8ec797e2016-04-19 04:08:43397}
398
dalecurtis4a9839a2017-05-04 23:40:47399// Hook that allows single-sample metric code from //components/metrics to
400// connect from the renderer process to the browser process.
401void CreateSingleSampleMetricsProvider(
402 scoped_refptr<base::SingleThreadTaskRunner> task_runner,
403 service_manager::Connector* connector,
404 metrics::mojom::SingleSampleMetricsProviderRequest request) {
405 if (task_runner->BelongsToCurrentThread()) {
406 connector->BindInterface(mojom::kBrowserServiceName, std::move(request));
407 return;
408 }
409
410 task_runner->PostTask(
411 FROM_HERE,
tzikff2a81a2017-09-15 05:10:06412 base::BindOnce(&CreateSingleSampleMetricsProvider, std::move(task_runner),
413 connector, base::Passed(&request)));
dalecurtis4a9839a2017-05-04 23:40:47414}
415
samans7e6675cc2017-06-05 20:16:08416class RendererLocalSurfaceIdProvider : public viz::LocalSurfaceIdProvider {
417 public:
Fady Samueld5c26182017-07-12 02:43:33418 const viz::LocalSurfaceId& GetLocalSurfaceIdForFrame(
danakj5e0a12b2017-09-25 17:26:49419 const viz::CompositorFrame& frame) override {
samans7e6675cc2017-06-05 20:16:08420 auto new_surface_properties =
421 RenderWidgetSurfaceProperties::FromCompositorFrame(frame);
422 if (!local_surface_id_.is_valid() ||
423 new_surface_properties != surface_properties_) {
Chris Blumeefd8f242017-12-08 00:24:27424 local_surface_id_ = parent_local_surface_id_allocator_.GenerateId();
samans7e6675cc2017-06-05 20:16:08425 surface_properties_ = new_surface_properties;
426 }
427 return local_surface_id_;
428 }
429
430 private:
Chris Blumeefd8f242017-12-08 00:24:27431 viz::ParentLocalSurfaceIdAllocator parent_local_surface_id_allocator_;
Fady Samueld5c26182017-07-12 02:43:33432 viz::LocalSurfaceId local_surface_id_;
samans7e6675cc2017-06-05 20:16:08433 RenderWidgetSurfaceProperties surface_properties_;
434};
435
Khushal3e96e662017-10-30 23:16:50436// This factory is used to defer binding of the InterfacePtr to the compositor
437// thread.
438class UkmRecorderFactoryImpl : public cc::UkmRecorderFactory {
439 public:
Lukasz Anforowiczbb0cfd5e2017-12-14 22:39:46440 explicit UkmRecorderFactoryImpl(
441 std::unique_ptr<service_manager::Connector> connector)
Khushalda50f8152017-12-01 09:04:40442 : connector_(std::move(connector)) {
443 DCHECK(connector_);
Khushal3e96e662017-10-30 23:16:50444 }
445 ~UkmRecorderFactoryImpl() override = default;
446
447 std::unique_ptr<ukm::UkmRecorder> CreateRecorder() override {
Khushalda50f8152017-12-01 09:04:40448 return ukm::MojoUkmRecorder::Create(connector_.get());
Khushal3e96e662017-10-30 23:16:50449 }
450
451 private:
Khushalda50f8152017-12-01 09:04:40452 std::unique_ptr<service_manager::Connector> connector_;
Khushal3e96e662017-10-30 23:16:50453};
454
Ben Goodgerf180ce12018-02-09 22:54:01455static const int kWaitForWorkersStatsTimeoutMS = 20;
456
457class ResourceUsageReporterImpl : public content::mojom::ResourceUsageReporter {
458 public:
459 explicit ResourceUsageReporterImpl(base::WeakPtr<RenderThread> thread)
460 : workers_to_go_(0), thread_(thread), weak_factory_(this) {}
461 ~ResourceUsageReporterImpl() override {}
462
463 private:
464 static void CollectOnWorkerThread(
465 const scoped_refptr<base::TaskRunner>& master,
466 base::WeakPtr<ResourceUsageReporterImpl> impl) {
467 size_t total_bytes = 0;
468 size_t used_bytes = 0;
469 v8::Isolate* isolate = v8::Isolate::GetCurrent();
470 if (isolate) {
471 v8::HeapStatistics heap_stats;
472 isolate->GetHeapStatistics(&heap_stats);
473 total_bytes = heap_stats.total_heap_size();
474 used_bytes = heap_stats.used_heap_size();
475 }
476 master->PostTask(FROM_HERE,
477 base::BindOnce(&ResourceUsageReporterImpl::ReceiveStats,
478 impl, total_bytes, used_bytes));
479 }
480
481 void ReceiveStats(size_t total_bytes, size_t used_bytes) {
482 usage_data_->v8_bytes_allocated += total_bytes;
483 usage_data_->v8_bytes_used += used_bytes;
484 workers_to_go_--;
485 if (!workers_to_go_)
486 SendResults();
487 }
488
489 void SendResults() {
490 if (!callback_.is_null())
491 std::move(callback_).Run(std::move(usage_data_));
492 callback_.Reset();
493 weak_factory_.InvalidateWeakPtrs();
494 workers_to_go_ = 0;
495 }
496
497 void GetUsageData(GetUsageDataCallback callback) override {
498 DCHECK(callback_.is_null());
499 weak_factory_.InvalidateWeakPtrs();
500 usage_data_ = mojom::ResourceUsageData::New();
501 usage_data_->reports_v8_stats = true;
502 callback_ = std::move(callback);
503
504 // Since it is not safe to call any Blink or V8 functions until Blink has
505 // been initialized (which also initializes V8), early out and send 0 back
506 // for all resources.
507 if (!thread_) {
508 SendResults();
509 return;
510 }
511
512 blink::WebCache::ResourceTypeStats stats;
513 blink::WebCache::GetResourceTypeStats(&stats);
514 usage_data_->web_cache_stats = mojom::ResourceTypeStats::From(stats);
515
516 v8::Isolate* isolate = v8::Isolate::GetCurrent();
517 if (isolate) {
518 v8::HeapStatistics heap_stats;
519 isolate->GetHeapStatistics(&heap_stats);
520 usage_data_->v8_bytes_allocated = heap_stats.total_heap_size();
521 usage_data_->v8_bytes_used = heap_stats.used_heap_size();
522 }
523 base::RepeatingClosure collect = base::BindRepeating(
524 &ResourceUsageReporterImpl::CollectOnWorkerThread,
525 base::ThreadTaskRunnerHandle::Get(), weak_factory_.GetWeakPtr());
526 workers_to_go_ = RenderThread::Get()->PostTaskToAllWebWorkers(collect);
527 if (workers_to_go_) {
528 // The guard task to send out partial stats
529 // in case some workers are not responsive.
530 base::ThreadTaskRunnerHandle::Get()->PostDelayedTask(
531 FROM_HERE,
532 base::BindOnce(&ResourceUsageReporterImpl::SendResults,
533 weak_factory_.GetWeakPtr()),
534 base::TimeDelta::FromMilliseconds(kWaitForWorkersStatsTimeoutMS));
535 } else {
536 // No worker threads so just send out the main thread data right away.
537 SendResults();
538 }
539 }
540
541 mojom::ResourceUsageDataPtr usage_data_;
542 GetUsageDataCallback callback_;
543 int workers_to_go_;
544 base::WeakPtr<RenderThread> thread_;
545
546 base::WeakPtrFactory<ResourceUsageReporterImpl> weak_factory_;
547
548 DISALLOW_COPY_AND_ASSIGN(ResourceUsageReporterImpl);
549};
550
551void CreateResourceUsageReporter(base::WeakPtr<RenderThread> thread,
552 mojom::ResourceUsageReporterRequest request) {
553 mojo::MakeStrongBinding(base::MakeUnique<ResourceUsageReporterImpl>(thread),
554 std::move(request));
555}
556
[email protected]b2d98762012-09-03 17:04:06557} // namespace
558
[email protected]b2d98762012-09-03 17:04:06559RenderThreadImpl::HistogramCustomizer::HistogramCustomizer() {
560 custom_histograms_.insert("V8.MemoryExternalFragmentationTotal");
561 custom_histograms_.insert("V8.MemoryHeapSampleTotalCommitted");
562 custom_histograms_.insert("V8.MemoryHeapSampleTotalUsed");
hablich4598ddc2015-11-07 18:37:28563 custom_histograms_.insert("V8.MemoryHeapUsed");
564 custom_histograms_.insert("V8.MemoryHeapCommitted");
[email protected]b2d98762012-09-03 17:04:06565}
566
567RenderThreadImpl::HistogramCustomizer::~HistogramCustomizer() {}
568
569void RenderThreadImpl::HistogramCustomizer::RenderViewNavigatedToHost(
570 const std::string& host, size_t view_count) {
avi83883c82014-12-23 00:08:49571 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
572 switches::kDisableHistogramCustomizer)) {
[email protected]9baee832012-12-10 11:07:15573 return;
574 }
[email protected]b2d98762012-09-03 17:04:06575 // Check if all RenderViews are displaying a page from the same host. If there
576 // is only one RenderView, the common host is this view's host. If there are
577 // many, check if this one shares the common host of the other
578 // RenderViews. It's ok to not detect some cases where the RenderViews share a
579 // common host. This information is only used for producing custom histograms.
580 if (view_count == 1)
581 SetCommonHost(host);
582 else if (host != common_host_)
583 SetCommonHost(std::string());
584}
585
586std::string RenderThreadImpl::HistogramCustomizer::ConvertToCustomHistogramName(
587 const char* histogram_name) const {
588 std::string name(histogram_name);
589 if (!common_host_histogram_suffix_.empty() &&
590 custom_histograms_.find(name) != custom_histograms_.end())
591 name += common_host_histogram_suffix_;
592 return name;
593}
594
595void RenderThreadImpl::HistogramCustomizer::SetCommonHost(
596 const std::string& host) {
597 if (host != common_host_) {
598 common_host_ = host;
599 common_host_histogram_suffix_ = HostToCustomHistogramSuffix(host);
Blink Reformat1c4d759e2017-04-09 16:34:54600 blink::MainThreadIsolate()->SetCreateHistogramFunction(CreateHistogram);
[email protected]b2d98762012-09-03 17:04:06601 }
602}
603
hablichd6a4f122015-10-28 11:34:49604std::string RenderThreadImpl::HistogramCustomizer::HostToCustomHistogramSuffix(
605 const std::string& host) {
606 if (host == "mail.google.com")
607 return ".gmail";
608 if (host == "docs.google.com" || host == "drive.google.com")
609 return ".docs";
610 if (host == "plus.google.com")
611 return ".plus";
612 if (host == "inbox.google.com")
613 return ".inbox";
hpayerdd4def052016-02-06 19:06:10614 if (host == "calendar.google.com")
615 return ".calendar";
hablichd6a4f122015-10-28 11:34:49616 if (host == "www.youtube.com")
617 return ".youtube";
618 if (IsAlexaTop10NonGoogleSite(host))
619 return ".top10";
620
621 return std::string();
622}
623
624bool RenderThreadImpl::HistogramCustomizer::IsAlexaTop10NonGoogleSite(
625 const std::string& host) {
626 // The Top10 sites have different TLD and/or subdomains depending on the
627 // localization.
628 if (host == "sina.com.cn")
629 return true;
630
631 std::string sanitized_host =
632 net::registry_controlled_domains::GetDomainAndRegistry(
633 host, net::registry_controlled_domains::INCLUDE_PRIVATE_REGISTRIES);
634
635 if (sanitized_host == "facebook.com")
636 return true;
637 if (sanitized_host == "baidu.com")
638 return true;
639 if (sanitized_host == "qq.com")
640 return true;
641 if (sanitized_host == "twitter.com")
642 return true;
643 if (sanitized_host == "taobao.com")
644 return true;
645 if (sanitized_host == "live.com")
646 return true;
647
648 if (!sanitized_host.empty()) {
649 std::vector<base::StringPiece> host_tokens = base::SplitStringPiece(
650 sanitized_host, ".", base::TRIM_WHITESPACE, base::SPLIT_WANT_NONEMPTY);
651
652 if (host_tokens.size() >= 2) {
653 if ((host_tokens[0] == "yahoo") || (host_tokens[0] == "amazon") ||
654 (host_tokens[0] == "wikipedia")) {
655 return true;
656 }
657 }
658 }
659 return false;
660}
661
leon.han2c0f9f12015-07-11 02:01:19662// static
663RenderThreadImpl* RenderThreadImpl::Create(
664 const InProcessChildThreadParams& params) {
Dmitry Skibaa2476cb92017-12-15 23:44:39665 TRACE_EVENT0("startup", "RenderThreadImpl::Create");
skyostil529caa292016-08-10 17:44:51666 std::unique_ptr<blink::scheduler::RendererScheduler> renderer_scheduler =
667 blink::scheduler::RendererScheduler::Create();
jam75c44222016-03-23 05:34:24668 scoped_refptr<base::SingleThreadTaskRunner> test_task_counter;
669 return new RenderThreadImpl(
670 params, std::move(renderer_scheduler), test_task_counter);
leon.han2c0f9f12015-07-11 02:01:19671}
672
673// static
674RenderThreadImpl* RenderThreadImpl::Create(
dchengcedca5612016-04-09 01:40:15675 std::unique_ptr<base::MessageLoop> main_message_loop,
skyostil529caa292016-08-10 17:44:51676 std::unique_ptr<blink::scheduler::RendererScheduler> renderer_scheduler) {
Dmitry Skibaa2476cb92017-12-15 23:44:39677 TRACE_EVENT0("startup", "RenderThreadImpl::Create");
dcheng07945f632015-12-26 07:59:32678 return new RenderThreadImpl(std::move(main_message_loop),
679 std::move(renderer_scheduler));
leon.han2c0f9f12015-07-11 02:01:19680}
681
rockot5c478a72016-09-28 23:14:18682// static
[email protected]f1a29a02011-10-06 23:08:44683RenderThreadImpl* RenderThreadImpl::current() {
[email protected]526476902011-10-06 20:34:06684 return lazy_tls.Pointer()->Get();
685}
686
rockot5c478a72016-09-28 23:14:18687// static
688mojom::RenderMessageFilter* RenderThreadImpl::current_render_message_filter() {
689 if (g_render_message_filter_for_testing)
690 return g_render_message_filter_for_testing;
691 DCHECK(current());
692 return current()->render_message_filter();
693}
694
695// static
olegmax045f7fb12017-05-19 07:58:55696RendererBlinkPlatformImpl* RenderThreadImpl::current_blink_platform_impl() {
697 if (g_current_blink_platform_impl_for_testing)
698 return g_current_blink_platform_impl_for_testing;
699 DCHECK(current());
700 return current()->blink_platform_impl();
701}
702
703// static
rockot5c478a72016-09-28 23:14:18704void RenderThreadImpl::SetRenderMessageFilterForTesting(
705 mojom::RenderMessageFilter* render_message_filter) {
706 g_render_message_filter_for_testing = render_message_filter;
707}
708
olegmax045f7fb12017-05-19 07:58:55709// static
710void RenderThreadImpl::SetRendererBlinkPlatformImplForTesting(
711 RendererBlinkPlatformImpl* blink_platform_impl) {
712 g_current_blink_platform_impl_for_testing = blink_platform_impl;
713}
714
John Abd-El-Malekd4882642017-12-04 21:45:19715// static
716scoped_refptr<base::SingleThreadTaskRunner>
Hajime Hoshi20578c62018-01-12 09:43:26717RenderThreadImpl::DeprecatedGetMainTaskRunner() {
John Abd-El-Malekd4882642017-12-04 21:45:19718 return g_main_task_runner.Get();
719}
720
staraz067f58242016-11-07 21:06:41721// In single-process mode used for debugging, we don't pass a renderer client
722// ID via command line because RenderThreadImpl lives in the same process as
723// the browser
leon.han2c0f9f12015-07-11 02:01:19724RenderThreadImpl::RenderThreadImpl(
725 const InProcessChildThreadParams& params,
skyostil529caa292016-08-10 17:44:51726 std::unique_ptr<blink::scheduler::RendererScheduler> scheduler,
rockot97a86832016-12-10 04:53:06727 const scoped_refptr<base::SingleThreadTaskRunner>& resource_task_queue)
Hajime Hoshife11b132017-11-13 10:16:07728 : ChildThreadImpl(
729 Options::Builder()
730 .InBrowserProcess(params)
731 .AutoStartServiceManagerConnection(false)
732 .ConnectToBrowser(true)
733 .IPCTaskRunner(scheduler ? scheduler->IPCTaskRunner() : nullptr)
734 .Build()),
dcheng07945f632015-12-26 07:59:32735 renderer_scheduler_(std::move(scheduler)),
rockot067ca55f2016-09-30 22:00:15736 categorized_worker_pool_(new CategorizedWorkerPool()),
staraz067f58242016-11-07 21:06:41737 renderer_binding_(this),
danakjab9ef4d2017-10-31 23:38:33738 client_id_(1),
Ben Goodgerf180ce12018-02-09 22:54:01739 compositing_mode_watcher_binding_(this),
740 weak_factory_(this) {
jam75c44222016-03-23 05:34:24741 Init(resource_task_queue);
morritac6238ab2015-03-18 01:48:29742}
743
[email protected]42f1d7822009-07-23 18:17:55744// When we run plugins in process, we actually run them on the render thread,
745// which means that we need to make the render thread pump UI events.
haraken53f081d2014-11-11 01:03:40746RenderThreadImpl::RenderThreadImpl(
dchengcedca5612016-04-09 01:40:15747 std::unique_ptr<base::MessageLoop> main_message_loop,
skyostil529caa292016-08-10 17:44:51748 std::unique_ptr<blink::scheduler::RendererScheduler> scheduler)
Hajime Hoshia1626932017-11-30 09:50:59749 : ChildThreadImpl(
750 Options::Builder()
751 .AutoStartServiceManagerConnection(false)
752 .ConnectToBrowser(true)
753 .IPCTaskRunner(scheduler ? scheduler->IPCTaskRunner() : nullptr)
754 .Build()),
dcheng07945f632015-12-26 07:59:32755 renderer_scheduler_(std::move(scheduler)),
756 main_message_loop_(std::move(main_message_loop)),
rockot067ca55f2016-09-30 22:00:15757 categorized_worker_pool_(new CategorizedWorkerPool()),
wjmaclean1d970622017-01-21 22:28:24758 is_scroll_animator_enabled_(false),
danakjab9ef4d2017-10-31 23:38:33759 renderer_binding_(this),
Ben Goodgerf180ce12018-02-09 22:54:01760 compositing_mode_watcher_binding_(this),
761 weak_factory_(this) {
jam75c44222016-03-23 05:34:24762 scoped_refptr<base::SingleThreadTaskRunner> test_task_counter;
staraz067f58242016-11-07 21:06:41763 DCHECK(base::CommandLine::ForCurrentProcess()->HasSwitch(
764 switches::kRendererClientId));
765 base::StringToInt(base::CommandLine::ForCurrentProcess()->GetSwitchValueASCII(
766 switches::kRendererClientId),
767 &client_id_);
jam75c44222016-03-23 05:34:24768 Init(test_task_counter);
haraken53f081d2014-11-11 01:03:40769}
770
jam75c44222016-03-23 05:34:24771void RenderThreadImpl::Init(
rockot97a86832016-12-10 04:53:06772 const scoped_refptr<base::SingleThreadTaskRunner>& resource_task_queue) {
fdorayf6d86242015-10-08 16:49:53773 TRACE_EVENT0("startup", "RenderThreadImpl::Init");
[email protected]a872ea1f2010-08-11 04:45:33774
ssidb2e3ece2015-02-09 16:02:20775 base::trace_event::TraceLog::GetInstance()->SetThreadSortIndex(
[email protected]91a2aea2013-07-08 23:14:39776 base::PlatformThread::CurrentId(),
777 kTraceEventRendererMainThreadSortIndex);
778
thakis18e426412017-03-15 12:06:37779#if BUILDFLAG(USE_EXTERNAL_POPUP_MENU)
sievers9dff72052015-11-16 18:35:57780 // On Mac and Android Java UI, the select popups are rendered by the browser.
Blink Reformat1c4d759e2017-04-09 16:34:54781 blink::WebView::SetUseExternalPopupMenus(true);
[email protected]53c607c2011-03-21 23:19:04782#endif
783
[email protected]94f9a0f682009-06-15 18:30:30784 lazy_tls.Pointer()->Set(this);
John Abd-El-Malekd4882642017-12-04 21:45:19785 g_main_task_runner.Get() = base::MessageLoop::current()->task_runner();
[email protected]b3e83de2012-02-07 03:33:28786
[email protected]06c694d2012-02-01 22:26:16787 // Register this object as the main thread.
788 ChildProcess::current()->set_main_thread(this);
789
dalecurtis4a9839a2017-05-04 23:40:47790 metrics::InitializeSingleSampleMetricsFactory(
791 base::BindRepeating(&CreateSingleSampleMetricsProvider,
792 message_loop()->task_runner(), GetConnector()));
793
Sadrul Habib Chowdhuryeeb5a942017-11-28 21:17:23794 gpu_ =
795 ui::Gpu::Create(GetConnector(),
796 switches::IsMusHostingViz() ? ui::mojom::kServiceName
797 : mojom::kBrowserServiceName,
798 GetIOTaskRunner());
penghuange1d86512016-07-08 18:15:00799
Gary Klassenb78686272017-08-11 22:38:13800 viz::mojom::SharedBitmapAllocationNotifierPtr
danakj92429852017-06-29 00:19:03801 shared_bitmap_allocation_notifier_ptr;
Saman Sami9b768542017-07-14 20:42:34802 GetConnector()->BindInterface(
803 mojom::kBrowserServiceName,
danakj92429852017-06-29 00:19:03804 mojo::MakeRequest(&shared_bitmap_allocation_notifier_ptr));
Jeremy Roman04f27c372017-10-27 15:20:55805 shared_bitmap_manager_ = std::make_unique<viz::ClientSharedBitmapManager>(
Gary Klassenb78686272017-08-11 22:38:13806 viz::mojom::ThreadSafeSharedBitmapAllocationNotifierPtr::Create(
danakj92429852017-06-29 00:19:03807 shared_bitmap_allocation_notifier_ptr.PassInterface(),
808 GetChannel()->ipc_task_runner_refptr()));
jcivelli0f21bd52016-12-07 21:21:33809
John Abd-El-Malekf9f86c12017-10-21 07:22:23810 notification_dispatcher_ =
811 new NotificationDispatcher(thread_safe_sender());
812 AddFilter(notification_dispatcher_->GetFilter());
813
Hajime Hoshi1711b522018-01-19 10:29:20814 resource_dispatcher_.reset(new ResourceDispatcher());
Yuzhu Shenfe5f3a52018-01-11 21:24:13815 url_loader_throttle_provider_ =
816 GetContentClient()->renderer()->CreateURLLoaderThrottleProvider(
817 URLLoaderThrottleProviderType::kFrame);
John Abd-El-Malek6b56ef712017-10-21 22:52:46818
Stuart Langley7b8dc772017-10-31 03:55:20819 auto registry = std::make_unique<service_manager::BinderRegistry>();
Ken Rockot510c5972017-12-05 16:37:04820 InitializeWebKit(resource_task_queue, registry.get());
Makoto Shimazu7af43ee2017-08-25 10:20:40821 blink_initialized_time_ = base::TimeTicks::Now();
jam75c44222016-03-23 05:34:24822
[email protected]31f87132010-04-21 23:36:21823 // In single process the single process is all there is.
Alexander Timin4b6152232017-10-17 20:34:06824 webkit_shared_timer_suspended_ = false;
[email protected]bee16aab2009-08-26 15:55:03825 widget_count_ = 0;
826 hidden_widget_count_ = 0;
[email protected]6593ae12011-11-14 12:09:44827 idle_notification_delay_in_ms_ = kInitialIdleHandlerDelayMs;
[email protected]1784b2f2011-11-24 10:53:48828 idle_notifications_to_skip_ = 0;
[email protected]8d86fce2009-02-26 23:37:55829
[email protected]d5b2fdf2013-06-05 09:36:55830 appcache_dispatcher_.reset(
Nicholas Verne07e9c6452017-12-13 04:12:55831 new AppCacheDispatcher(new AppCacheFrontendImpl()));
832 registry->AddInterface(
833 base::BindRepeating(&AppCacheDispatcher::Bind,
834 base::Unretained(appcache_dispatcher())),
Hajime Hoshi20578c62018-01-12 09:43:26835 GetRendererScheduler()->IPCTaskRunner());
[email protected]1910fe82012-05-10 00:04:10836 dom_storage_dispatcher_.reset(new DomStorageDispatcher());
reillyg39fb4662016-11-22 20:27:17837 main_thread_indexed_db_dispatcher_.reset(new IndexedDBDispatcher());
jsbellabadb9b2015-03-23 21:03:44838 main_thread_cache_storage_dispatcher_.reset(
jsbell279efb42015-03-31 17:02:46839 new CacheStorageDispatcher(thread_safe_sender()));
John Abd-El-Malekdcf1d1372017-10-22 06:39:41840 file_system_dispatcher_.reset(new FileSystemDispatcher());
[email protected]dd9241932010-02-24 19:23:13841
[email protected]45048072014-01-14 13:51:29842 vc_manager_.reset(new VideoCaptureImplManager());
[email protected]c9c43a02013-12-17 08:59:54843
fsamuel6c1dfeb2014-12-18 19:21:33844 browser_plugin_manager_.reset(new BrowserPluginManager());
845 AddObserver(browser_plugin_manager_.get());
846
Brett Wilson0748bf412016-11-22 17:55:46847#if BUILDFLAG(ENABLE_WEBRTC)
[email protected]af089972013-01-10 04:04:40848 peer_connection_tracker_.reset(new PeerConnectionTracker());
849 AddObserver(peer_connection_tracker_.get());
850
thestig529ad8a2016-07-08 20:30:12851 p2p_socket_dispatcher_ = new P2PSocketDispatcher(GetIOTaskRunner().get());
[email protected]fc72bb12013-06-02 21:13:46852 AddFilter(p2p_socket_dispatcher_.get());
[email protected]921480f62013-07-20 03:42:57853
ivocadd54f0d2015-12-18 23:17:05854 peer_connection_factory_.reset(
855 new PeerConnectionDependencyFactory(p2p_socket_dispatcher_.get()));
856
skyostil2d3b5bd2015-05-27 15:40:59857 aec_dump_message_filter_ = new AecDumpMessageFilter(
thestig529ad8a2016-07-08 20:30:12858 GetIOTaskRunner(), message_loop()->task_runner());
ivocadd54f0d2015-12-18 23:17:05859
[email protected]da9f30a2014-06-18 19:39:04860 AddFilter(aec_dump_message_filter_.get());
861
Brett Wilson0748bf412016-11-22 17:55:46862#endif // BUILDFLAG(ENABLE_WEBRTC)
Max Morin3d464a42018-01-15 11:17:00863 {
864 scoped_refptr<AudioInputMessageFilter> audio_input_message_filter;
865 if (!base::FeatureList::IsEnabled(
866 features::kUseMojoAudioInputStreamFactory)) {
867 // In case we shouldn't use mojo factories, we need to create an
868 // AudioInputMessageFilter which |audio_input_ipc_factory_| can use for
869 // IPC.
870 audio_input_message_filter =
871 base::MakeRefCounted<AudioInputMessageFilter>(GetIOTaskRunner());
872 AddFilter(audio_input_message_filter.get());
873 }
[email protected]e25f4d72011-06-08 20:58:46874
Max Morin3d464a42018-01-15 11:17:00875 audio_input_ipc_factory_.emplace(std::move(audio_input_message_filter),
876 message_loop()->task_runner(),
877 GetIOTaskRunner());
Max Morind4c4887d2017-06-08 07:41:34878 }
879
Max Morin3d464a42018-01-15 11:17:00880 {
881 scoped_refptr<AudioMessageFilter> audio_output_message_filter;
882 if (!base::FeatureList::IsEnabled(
883 features::kUseMojoAudioOutputStreamFactory)) {
884 // In case we shouldn't use mojo factories, we need to create an
885 // AudioMessageFilter which |audio_output_ipc_factory_| can use for IPC.
886 audio_output_message_filter =
887 base::MakeRefCounted<AudioMessageFilter>(GetIOTaskRunner());
888 AddFilter(audio_output_message_filter.get());
889 }
890
891 audio_output_ipc_factory_.emplace(std::move(audio_output_message_filter),
892 GetIOTaskRunner());
893 }
[email protected]f7eb0a392011-07-12 10:19:51894
thestig529ad8a2016-07-08 20:30:12895 midi_message_filter_ = new MidiMessageFilter(GetIOTaskRunner());
[email protected]a9875152013-06-22 04:03:03896 AddFilter(midi_message_filter_.get());
897
jsbellabadb9b2015-03-23 21:03:44898 AddFilter((new CacheStorageMessageFilter(thread_safe_sender()))->GetFilter());
899
sadrul943e3b32016-08-04 18:22:59900#if defined(USE_AURA)
Scott Violet30daff62017-12-01 07:04:52901 if (IsRunningWithMus())
bend32292b2016-10-07 00:21:58902 CreateRenderWidgetWindowTreeClientFactory(GetServiceManagerConnection());
rockotcef38272016-07-15 22:47:47903#endif
904
Stuart Langley7b8dc772017-10-31 03:55:20905 registry->AddInterface(base::Bind(&SharedWorkerFactoryImpl::Create),
906 base::ThreadTaskRunnerHandle::Get());
Ben Goodgerf180ce12018-02-09 22:54:01907 registry->AddInterface(base::BindRepeating(CreateResourceUsageReporter,
908 weak_factory_.GetWeakPtr()),
909 base::ThreadTaskRunnerHandle::Get());
910
Stuart Langley7b8dc772017-10-31 03:55:20911 GetServiceManagerConnection()->AddConnectionFilter(
912 std::make_unique<SimpleConnectionFilter>(std::move(registry)));
Stuart Langley6771c902017-09-01 11:23:30913
Darin Fisherbcc33632017-09-26 00:57:16914 {
915 auto registry_with_source_info =
Jeremy Roman04f27c372017-10-27 15:20:55916 std::make_unique<service_manager::BinderRegistryWithArgs<
Darin Fisherbcc33632017-09-26 00:57:16917 const service_manager::BindSourceInfo&>>();
918 registry_with_source_info->AddInterface(
919 base::Bind(&CreateFrameFactory), base::ThreadTaskRunnerHandle::Get());
920 GetServiceManagerConnection()->AddConnectionFilter(
Jeremy Roman04f27c372017-10-27 15:20:55921 std::make_unique<SimpleConnectionFilterWithSourceInfo>(
Darin Fisherbcc33632017-09-26 00:57:16922 std::move(registry_with_source_info)));
923 }
rockotcef38272016-07-15 22:47:47924
[email protected]e9ff79c2012-10-19 21:31:26925 GetContentClient()->renderer()->RenderThreadStarted();
[email protected]6779aa12011-03-29 17:32:24926
benbd9dc802017-04-19 01:37:43927 StartServiceManagerConnection();
928
rockot067ca55f2016-09-30 22:00:15929 GetAssociatedInterfaceRegistry()->AddInterface(
930 base::Bind(&RenderThreadImpl::OnRendererInterfaceRequest,
931 base::Unretained(this)));
932
[email protected]b48c53ad2014-02-05 21:59:18933 InitSkiaEventTracer();
ssid59c969162015-07-28 13:02:58934 base::trace_event::MemoryDumpManager::GetInstance()->RegisterDumpProvider(
primiano186d6bfe2015-10-30 13:21:40935 skia::SkiaMemoryDumpProvider::GetInstance(), "Skia", nullptr);
[email protected]b48c53ad2014-02-05 21:59:18936
avi83883c82014-12-23 00:08:49937 const base::CommandLine& command_line =
938 *base::CommandLine::ForCurrentProcess();
[email protected]e54ab492012-06-12 19:40:01939
ochangdd89a1e2016-06-08 16:39:01940#if defined(ENABLE_IPC_FUZZER)
941 if (command_line.HasSwitch(switches::kIpcDumpDirectory)) {
942 base::FilePath dump_directory =
943 command_line.GetSwitchValuePath(switches::kIpcDumpDirectory);
944 IPC::ChannelProxy::OutgoingMessageFilter* filter =
945 LoadExternalIPCDumper(dump_directory);
946 GetChannel()->set_outgoing_message_filter(filter);
947 }
948#endif
949
jbroman0d302162015-09-05 05:46:23950 cc::SetClientNameForMetrics("Renderer");
loysoa6edaaff2015-05-25 03:26:44951
loyso65c93c602015-08-11 05:15:57952 is_threaded_animation_enabled_ =
953 !command_line.HasSwitch(cc::switches::kDisableThreadedAnimation);
954
reveman91a0a872014-11-04 03:40:32955 is_zero_copy_enabled_ = command_line.HasSwitch(switches::kEnableZeroCopy);
ericrk1d17f752015-10-20 03:03:07956 is_partial_raster_enabled_ =
dongseong.hwang23db47f2016-03-08 07:50:02957 !command_line.HasSwitch(switches::kDisablePartialRaster);
ccameronc7fcd132015-11-03 20:14:31958 is_gpu_memory_buffer_compositor_resources_enabled_ = command_line.HasSwitch(
959 switches::kEnableGpuMemoryBufferCompositorResources);
[email protected]a23530d2014-03-11 06:04:14960
Greg Kerra7b943b2017-07-24 23:17:17961// On macOS this value is adjusted in `UpdateScrollbarTheme()`,
962// but the system default is true.
963#if defined(OS_MACOSX)
964 is_elastic_overscroll_enabled_ = true;
ccamerona7644752014-12-30 01:16:31965#else
966 is_elastic_overscroll_enabled_ = false;
967#endif
968
[email protected]a23530d2014-03-11 06:04:14969 if (command_line.HasSwitch(switches::kDisableLCDText)) {
970 is_lcd_text_enabled_ = false;
971 } else if (command_line.HasSwitch(switches::kEnableLCDText)) {
972 is_lcd_text_enabled_ = true;
973 } else {
974#if defined(OS_ANDROID)
975 is_lcd_text_enabled_ = false;
976#else
977 is_lcd_text_enabled_ = true;
978#endif
979 }
980
danakjab9ef4d2017-10-31 23:38:33981 if (command_line.HasSwitch(switches::kDisableGpuCompositing))
982 is_gpu_compositing_disabled_ = true;
983
[email protected]b8d82c22014-03-31 20:12:46984 is_gpu_rasterization_forced_ =
985 command_line.HasSwitch(switches::kForceGpuRasterization);
[email protected]a23530d2014-03-11 06:04:14986
senorblancob60ba952015-01-27 19:12:36987 if (command_line.HasSwitch(switches::kGpuRasterizationMSAASampleCount)) {
988 std::string string_value = command_line.GetSwitchValueASCII(
989 switches::kGpuRasterizationMSAASampleCount);
990 bool parsed_msaa_sample_count =
991 base::StringToInt(string_value, &gpu_rasterization_msaa_sample_count_);
992 DCHECK(parsed_msaa_sample_count) << string_value;
993 DCHECK_GE(gpu_rasterization_msaa_sample_count_, 0);
994 } else {
senorblanco2a5b0e12015-08-14 21:55:37995 gpu_rasterization_msaa_sample_count_ = -1;
senorblancob60ba952015-01-27 19:12:36996 }
997
[email protected]b242b142014-05-07 14:48:49998 if (command_line.HasSwitch(switches::kDisableDistanceFieldText)) {
999 is_distance_field_text_enabled_ = false;
1000 } else if (command_line.HasSwitch(switches::kEnableDistanceFieldText)) {
1001 is_distance_field_text_enabled_ = true;
1002 } else {
1003 is_distance_field_text_enabled_ = false;
1004 }
1005
Khushalfdacdc92017-09-22 22:40:521006 WebRuntimeFeatures::EnableCompositorImageAnimations(
1007 command_line.HasSwitch(switches::kEnableCompositorImageAnimations));
1008
[email protected]433df472012-03-07 20:33:391009 // Note that under Linux, the media library will normally already have
1010 // been initialized by the Zygote before this instance became a Renderer.
chcunninghamfd11b3c2015-06-09 02:09:421011 media::InitializeMediaLibrary();
[email protected]433df472012-03-07 20:33:391012
dalecurtis88af3932016-02-20 00:12:201013#if defined(OS_ANDROID)
1014 if (!command_line.HasSwitch(switches::kDisableAcceleratedVideoDecode) &&
1015 media::MediaCodecUtil::IsMediaCodecAvailable()) {
Zhenyao Mocdae4522018-02-09 20:10:261016 bool accelerated_video_decode_blacklisted = false;
1017 if (!command_line.HasSwitch(switches::kIgnoreGpuBlacklist)) {
1018 int32_t major_version = 0, minor_version = 0, bugfix_version = 0;
1019 base::SysInfo::OperatingSystemVersionNumbers(
1020 &major_version, &minor_version, &bugfix_version);
1021 if (major_version < 5) {
1022 // Currently accelerated video decode is only blacklisted on
1023 // Android older than Lollipop.
1024 scoped_refptr<gpu::GpuChannelHost> gpu_channel_host =
1025 EstablishGpuChannelSync();
1026 if (!gpu_channel_host ||
1027 gpu_channel_host->gpu_feature_info().status_values
1028 [gpu::GPU_FEATURE_TYPE_ACCELERATED_VIDEO_DECODE] !=
1029 gpu::kGpuFeatureStatusEnabled) {
1030 accelerated_video_decode_blacklisted = true;
1031 }
1032 }
1033 }
1034 if (!accelerated_video_decode_blacklisted)
1035 media::EnablePlatformDecoderSupport();
dalecurtis88af3932016-02-20 00:12:201036 }
1037#endif
1038
bashi296ebda2017-03-28 03:27:091039 memory_pressure_listener_.reset(new base::MemoryPressureListener(
1040 base::Bind(&RenderThreadImpl::OnMemoryPressure, base::Unretained(this)),
1041 base::Bind(&RenderThreadImpl::OnSyncMemoryPressure,
1042 base::Unretained(this))));
1043
1044 if (base::FeatureList::IsEnabled(features::kMemoryCoordinator)) {
1045 // Disable MemoryPressureListener when memory coordinator is enabled.
1046 base::MemoryPressureListener::SetNotificationsSuppressed(true);
1047
1048 // TODO(bashi): Revisit how to manage the lifetime of
1049 // ChildMemoryCoordinatorImpl.
1050 // https://codereview.chromium.org/2094583002/#msg52
1051 mojom::MemoryCoordinatorHandlePtr parent_coordinator;
1052 GetConnector()->BindInterface(mojom::kBrowserServiceName,
1053 mojo::MakeRequest(&parent_coordinator));
1054 memory_coordinator_ = CreateChildMemoryCoordinator(
1055 std::move(parent_coordinator), this);
1056 }
1057
danakj16275d4c2015-06-11 19:23:511058 int num_raster_threads = 0;
1059 std::string string_value =
1060 command_line.GetSwitchValueASCII(switches::kNumRasterThreads);
1061 bool parsed_num_raster_threads =
1062 base::StringToInt(string_value, &num_raster_threads);
1063 DCHECK(parsed_num_raster_threads) << string_value;
1064 DCHECK_GT(num_raster_threads, 0);
vmiura78b69282015-02-14 00:01:171065
prashant.nfad657e2016-06-01 07:52:171066 categorized_worker_pool_->Start(num_raster_threads);
[email protected]1e1d1e12014-01-17 16:14:291067
penghuang342762b2016-12-02 21:04:581068 discardable_memory::mojom::DiscardableSharedMemoryManagerPtr manager_ptr;
Sadrul Habib Chowdhury1dbe3b42017-11-18 02:27:431069 if (IsRunningWithMus()) {
penghuangd6843e42016-12-17 13:57:201070#if defined(USE_AURA)
benbd3c2482017-01-07 05:48:211071 GetServiceManagerConnection()->GetConnector()->BindInterface(
penghuangd6843e42016-12-17 13:57:201072 ui::mojom::kServiceName, &manager_ptr);
1073#else
1074 NOTREACHED();
1075#endif
1076 } else {
ben649b3edd2017-03-23 00:32:021077 ChildThread::Get()->GetConnector()->BindInterface(
1078 mojom::kBrowserServiceName, mojo::MakeRequest(&manager_ptr));
penghuangd6843e42016-12-17 13:57:201079 }
1080
Jeremy Roman04f27c372017-10-27 15:20:551081 discardable_shared_memory_manager_ = std::make_unique<
penghuang342762b2016-12-02 21:04:581082 discardable_memory::ClientDiscardableSharedMemoryManager>(
1083 std::move(manager_ptr), GetIOTaskRunner());
1084
boliu9760e212015-06-23 22:49:061085 // TODO(boliu): In single process, browser main loop should set up the
1086 // discardable memory manager, and should skip this if kSingleProcess.
1087 // See crbug.com/503724.
1088 base::DiscardableMemoryAllocator::SetInstance(
penghuang342762b2016-12-02 21:04:581089 discardable_shared_memory_manager_.get());
revemancb5a66af2014-10-25 00:34:391090
ben649b3edd2017-03-23 00:32:021091 GetConnector()->BindInterface(mojom::kBrowserServiceName,
1092 mojo::MakeRequest(&storage_partition_service_));
hajimehoshi69093272016-05-13 08:30:581093
reveman7b97c322016-09-20 02:10:581094#if defined(OS_LINUX)
Nicholas Verne84dc55e2017-11-23 01:02:381095 render_message_filter()->SetThreadPriority(
1096 ChildProcess::current()->io_thread_id(), base::ThreadPriority::DISPLAY);
1097 render_message_filter()->SetThreadPriority(
lukasza6710dbd2017-04-07 20:58:031098 categorized_worker_pool_->background_worker_thread_id(),
reveman7b97c322016-09-20 02:10:581099 base::ThreadPriority::BACKGROUND);
1100#endif
1101
tasakbb0640b2017-05-15 09:02:261102 process_foregrounded_count_ = 0;
tasakb95dbb50c2017-02-08 18:07:501103 needs_to_record_first_active_paint_ = false;
Takashi SAKAMOTO870f6262017-08-22 04:08:271104 was_backgrounded_time_ = base::TimeTicks::Min();
hajimehoshi7bb39582016-10-12 04:30:571105
1106 base::MemoryCoordinatorClientRegistry::GetInstance()->Register(this);
fdoray50a38342016-11-21 20:46:041107
1108 // If this renderer doesn't run inside the browser process, enable
1109 // SequencedWorkerPool. Otherwise, it should already have been enabled.
1110 // TODO(fdoray): Remove this once the SequencedWorkerPool to TaskScheduler
1111 // redirection experiment concludes https://crbug.com/622400.
1112 if (!command_line.HasSwitch(switches::kSingleProcess))
1113 base::SequencedWorkerPool::EnableForProcess();
samans2040988b2017-04-11 23:58:351114
1115 GetConnector()->BindInterface(mojom::kBrowserServiceName,
1116 mojo::MakeRequest(&frame_sink_provider_));
danakjab9ef4d2017-10-31 23:38:331117
1118 if (!is_gpu_compositing_disabled_) {
1119 GetConnector()->BindInterface(
1120 mojom::kBrowserServiceName,
1121 mojo::MakeRequest(&compositing_mode_reporter_));
1122
1123 // Make |this| a CompositingModeWatcher for the
1124 // |compositing_mode_reporter_|.
1125 viz::mojom::CompositingModeWatcherPtr watcher_ptr;
1126 compositing_mode_watcher_binding_.Bind(mojo::MakeRequest(&watcher_ptr));
1127 compositing_mode_reporter_->AddCompositingModeWatcher(
1128 std::move(watcher_ptr));
1129 }
initial.commit09911bf2008-07-26 23:55:291130}
1131
John Abd-El-Malekd4882642017-12-04 21:45:191132RenderThreadImpl::~RenderThreadImpl() {
1133 g_main_task_runner.Get() = nullptr;
1134}
[email protected]ce79d8512013-04-22 22:44:411135
Nicholas Verne5420564d2017-10-27 07:37:541136void RenderThreadImpl::Shutdown() {
John Abd-El-Malekdcf1d1372017-10-22 06:39:411137 ChildThreadImpl::Shutdown();
1138 file_system_dispatcher_.reset();
1139 WebFileSystemImpl::DeleteThreadSpecificInstance();
harakenbbfdd9f02017-01-12 07:14:041140 // In a multi-process mode, we immediately exit the renderer.
1141 // Historically we had a graceful shutdown sequence here but it was
1142 // 1) a waste of performance and 2) a source of lots of complicated
1143 // crashes caused by shutdown ordering. Immediate exit eliminates
1144 // those problems.
cbrunia3f655b2017-03-20 11:36:411145
1146 // Give the V8 isolate a chance to dump internal stats useful for performance
1147 // evaluation and debugging.
Blink Reformat1c4d759e2017-04-09 16:34:541148 blink::MainThreadIsolate()->DumpAndResetStats();
cbrunia3f655b2017-03-20 11:36:411149
Adithya Srinivasandf421e82017-06-01 14:36:111150 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
1151 switches::kDumpBlinkRuntimeCallStats))
1152 blink::LogRuntimeCallStats();
1153
harakenbbfdd9f02017-01-12 07:14:041154 // In a single-process mode, we cannot call _exit(0) in Shutdown() because
1155 // it will exit the process before the browser side is ready to exit.
1156 if (!base::CommandLine::ForCurrentProcess()->HasSwitch(
1157 switches::kSingleProcess))
haraken940efb92017-02-08 05:58:151158 base::Process::TerminateCurrentProcessImmediately(0);
harakenbbfdd9f02017-01-12 07:14:041159}
[email protected]1223d6ef2011-03-28 16:47:501160
harakenbbfdd9f02017-01-12 07:14:041161bool RenderThreadImpl::ShouldBeDestroyed() {
1162 DCHECK(base::CommandLine::ForCurrentProcess()->HasSwitch(
1163 switches::kSingleProcess));
1164 // In a single-process mode, it is unsafe to destruct this renderer thread
1165 // because we haven't run the shutdown sequence. Hence we leak the render
1166 // thread.
1167 //
1168 // In this case, we also need to disable at-exit callbacks because some of
1169 // the at-exit callbacks are expected to run after the renderer thread
1170 // has been destructed.
1171 base::AtExitManager::DisableAllAtExitManagers();
1172 return false;
initial.commit09911bf2008-07-26 23:55:291173}
1174
[email protected]f1a29a02011-10-06 23:08:441175bool RenderThreadImpl::Send(IPC::Message* msg) {
changwan6ed4d432016-05-19 22:03:541176 // There are cases where we want to pump asynchronous messages while waiting
1177 // synchronously for the replies to the message to be sent here. However, this
1178 // may create an opportunity for re-entrancy into WebKit and other subsystems,
1179 // so we need to take care to disable callbacks, timers, and pending network
1180 // loads that could trigger such callbacks.
[email protected]38b592902011-04-16 02:08:421181 bool pumping_events = false;
[email protected]80fc08c52010-03-09 07:43:501182 if (msg->is_sync()) {
1183 if (msg->is_caller_pumping_messages()) {
1184 pumping_events = true;
[email protected]80fc08c52010-03-09 07:43:501185 }
[email protected]c1f50aa2010-02-18 03:46:571186 }
1187
Yoland Yan25439ba2017-10-11 19:45:551188 std::unique_ptr<blink::scheduler::RendererScheduler::RendererPauseHandle>
1189 renderer_paused_handle;
1190
[email protected]c1f50aa2010-02-18 03:46:571191 if (pumping_events) {
Yoland Yan25439ba2017-10-11 19:45:551192 renderer_paused_handle = renderer_scheduler_->PauseRenderer();
Blink Reformat1c4d759e2017-04-09 16:34:541193 WebView::WillEnterModalLoop();
[email protected]c1f50aa2010-02-18 03:46:571194 }
1195
jam8a021512a2015-02-03 18:16:081196 bool rv = ChildThreadImpl::Send(msg);
[email protected]c1f50aa2010-02-18 03:46:571197
Yoland Yan25439ba2017-10-11 19:45:551198 if (pumping_events)
Blink Reformat1c4d759e2017-04-09 16:34:541199 WebView::DidExitModalLoop();
[email protected]c1f50aa2010-02-18 03:46:571200
1201 return rv;
1202}
1203
[email protected]f1a29a02011-10-06 23:08:441204IPC::SyncChannel* RenderThreadImpl::GetChannel() {
[email protected]526476902011-10-06 20:34:061205 return channel();
1206}
1207
[email protected]f1a29a02011-10-06 23:08:441208std::string RenderThreadImpl::GetLocale() {
[email protected]526476902011-10-06 20:34:061209 // The browser process should have passed the locale to the renderer via the
[email protected]dfd53652012-10-25 00:20:021210 // --lang command line flag.
avi83883c82014-12-23 00:08:491211 const base::CommandLine& parsed_command_line =
1212 *base::CommandLine::ForCurrentProcess();
[email protected]526476902011-10-06 20:34:061213 const std::string& lang =
1214 parsed_command_line.GetSwitchValueASCII(switches::kLang);
[email protected]dfd53652012-10-25 00:20:021215 DCHECK(!lang.empty());
[email protected]526476902011-10-06 20:34:061216 return lang;
1217}
1218
[email protected]07bb6332012-01-21 01:07:571219IPC::SyncMessageFilter* RenderThreadImpl::GetSyncMessageFilter() {
1220 return sync_message_filter();
1221}
1222
avi1023d012015-12-25 02:39:141223void RenderThreadImpl::AddRoute(int32_t routing_id, IPC::Listener* listener) {
jam8a021512a2015-02-03 18:16:081224 ChildThreadImpl::GetRouter()->AddRoute(routing_id, listener);
ben76f52b242016-06-18 05:42:481225 auto it = pending_frame_creates_.find(routing_id);
1226 if (it == pending_frame_creates_.end())
rockotf8fdd9b2015-12-16 22:22:351227 return;
1228
1229 RenderFrameImpl* frame = RenderFrameImpl::FromRoutingID(routing_id);
1230 if (!frame)
1231 return;
1232
ben76f52b242016-06-18 05:42:481233 scoped_refptr<PendingFrameCreate> create(it->second);
Balazs Engedyba034e72017-10-27 22:26:281234 frame->BindFrame(it->second->browser_info(), it->second->TakeFrameRequest());
ben76f52b242016-06-18 05:42:481235 pending_frame_creates_.erase(it);
[email protected]c1f50aa2010-02-18 03:46:571236}
1237
avi1023d012015-12-25 02:39:141238void RenderThreadImpl::RemoveRoute(int32_t routing_id) {
jam8a021512a2015-02-03 18:16:081239 ChildThreadImpl::GetRouter()->RemoveRoute(routing_id);
[email protected]c1f50aa2010-02-18 03:46:571240}
[email protected]0ec90d522014-03-12 16:28:191241
ben76f52b242016-06-18 05:42:481242void RenderThreadImpl::RegisterPendingFrameCreate(
benf28ce882017-05-02 16:15:491243 const service_manager::BindSourceInfo& browser_info,
rockotf8fdd9b2015-12-16 22:22:351244 int routing_id,
Balazs Engedyba034e72017-10-27 22:26:281245 mojom::FrameRequest frame_request) {
ben76f52b242016-06-18 05:42:481246 std::pair<PendingFrameCreateMap::iterator, bool> result =
1247 pending_frame_creates_.insert(std::make_pair(
kylechar96f3eba2017-09-25 20:23:561248 routing_id, base::MakeRefCounted<PendingFrameCreate>(
Balazs Engedyba034e72017-10-27 22:26:281249 browser_info, routing_id, std::move(frame_request))));
rockotf8fdd9b2015-12-16 22:22:351250 CHECK(result.second) << "Inserting a duplicate item.";
1251}
1252
leon.han06e55662016-03-26 17:19:421253mojom::StoragePartitionService* RenderThreadImpl::GetStoragePartitionService() {
jamc912ca32016-02-24 20:17:311254 return storage_partition_service_.get();
1255}
1256
jam188f19f2017-06-07 03:56:241257mojom::RendererHost* RenderThreadImpl::GetRendererHost() {
Nicholas Verne06de8122017-11-16 04:47:381258 if (!renderer_host_) {
Joel Hockey3146d142017-11-15 22:27:401259 GetChannel()->GetRemoteAssociatedInterface(&renderer_host_);
Nicholas Verne06de8122017-11-16 04:47:381260 }
jam188f19f2017-06-07 03:56:241261 return renderer_host_.get();
1262}
1263
[email protected]77fc9b92011-10-15 16:20:371264int RenderThreadImpl::GenerateRoutingID() {
rockote261d2112016-09-21 22:22:231265 int32_t routing_id = MSG_ROUTING_NONE;
1266 render_message_filter()->GenerateRoutingID(&routing_id);
[email protected]77fc9b92011-10-15 16:20:371267 return routing_id;
1268}
1269
[email protected]74122042014-04-25 00:07:301270void RenderThreadImpl::AddFilter(IPC::MessageFilter* filter) {
[email protected]42f1d7822009-07-23 18:17:551271 channel()->AddFilter(filter);
1272}
1273
[email protected]74122042014-04-25 00:07:301274void RenderThreadImpl::RemoveFilter(IPC::MessageFilter* filter) {
[email protected]42f1d7822009-07-23 18:17:551275 channel()->RemoveFilter(filter);
1276}
1277
tyoshino832a58a2016-04-18 08:14:081278void RenderThreadImpl::AddObserver(RenderThreadObserver* observer) {
[email protected]526476902011-10-06 20:34:061279 observers_.AddObserver(observer);
nigeltao7cd8d5582016-12-12 06:05:281280 observer->RegisterMojoInterfaces(&associated_interfaces_);
[email protected]526476902011-10-06 20:34:061281}
1282
tyoshino832a58a2016-04-18 08:14:081283void RenderThreadImpl::RemoveObserver(RenderThreadObserver* observer) {
nigeltao7cd8d5582016-12-12 06:05:281284 observer->UnregisterMojoInterfaces(&associated_interfaces_);
[email protected]526476902011-10-06 20:34:061285 observers_.RemoveObserver(observer);
1286}
1287
[email protected]359dfa32011-10-12 01:10:151288void RenderThreadImpl::SetResourceDispatcherDelegate(
[email protected]e9ff79c2012-10-19 21:31:261289 ResourceDispatcherDelegate* delegate) {
John Abd-El-Malek6b56ef712017-10-21 22:52:461290 resource_dispatcher_->set_delegate(delegate);
[email protected]359dfa32011-10-12 01:10:151291}
1292
vollick1050cc62015-12-03 07:04:541293void RenderThreadImpl::InitializeCompositorThread() {
boliu66024c62016-04-20 04:00:411294 base::Thread::Options options;
vollick1050cc62015-12-03 07:04:541295#if defined(OS_ANDROID)
boliu66024c62016-04-20 04:00:411296 options.priority = base::ThreadPriority::DISPLAY;
vollick1050cc62015-12-03 07:04:541297#endif
altiminc7369bf2017-04-11 14:29:151298 compositor_thread_ =
1299 blink::scheduler::WebThreadBase::CreateCompositorThread(options);
boliu66024c62016-04-20 04:00:411300 blink_platform_impl_->SetCompositorThread(compositor_thread_.get());
Yuta Kitamura5ee2b9b2018-02-14 09:00:311301 compositor_task_runner_ = compositor_thread_->GetTaskRunner();
boliu66024c62016-04-20 04:00:411302 compositor_task_runner_->PostTask(
1303 FROM_HERE,
tzikff2a81a2017-09-15 05:10:061304 base::BindOnce(base::IgnoreResult(&ThreadRestrictions::SetIOAllowed),
1305 false));
Sadrul Habib Chowdhury16b3a162018-02-03 01:43:181306 GetContentClient()->renderer()->PostCompositorThreadCreated(
1307 compositor_task_runner_.get());
reveman7b97c322016-09-20 02:10:581308#if defined(OS_LINUX)
Nicholas Verne84dc55e2017-11-23 01:02:381309 render_message_filter()->SetThreadPriority(compositor_thread_->ThreadId(),
1310 base::ThreadPriority::DISPLAY);
reveman7b97c322016-09-20 02:10:581311#endif
vollick1050cc62015-12-03 07:04:541312
Dave Tapuska525eb15e2017-08-17 21:05:501313 if (!base::FeatureList::IsEnabled(features::kMojoInputMessages)) {
1314 SynchronousInputHandlerProxyClient* synchronous_input_handler_proxy_client =
1315 nullptr;
vollick1050cc62015-12-03 07:04:541316#if defined(OS_ANDROID)
Dave Tapuska525eb15e2017-08-17 21:05:501317 if (GetContentClient()->UsingSynchronousCompositing()) {
1318 sync_compositor_message_filter_ =
1319 new SynchronousCompositorFilter(compositor_task_runner_);
1320 AddFilter(sync_compositor_message_filter_.get());
1321 synchronous_input_handler_proxy_client =
1322 sync_compositor_message_filter_.get();
1323 }
vollick1050cc62015-12-03 07:04:541324#endif
Dave Tapuska525eb15e2017-08-17 21:05:501325 scoped_refptr<InputEventFilter> compositor_input_event_filter(
1326 new InputEventFilter(main_input_callback_.callback(),
1327 main_thread_compositor_task_runner_,
1328 compositor_task_runner_));
1329 InputHandlerManagerClient* input_handler_manager_client =
1330 compositor_input_event_filter.get();
1331 input_event_filter_ = compositor_input_event_filter;
1332 input_handler_manager_.reset(new InputHandlerManager(
1333 compositor_task_runner_, input_handler_manager_client,
1334 synchronous_input_handler_proxy_client, renderer_scheduler_.get()));
1335 } else {
1336#if defined(OS_ANDROID)
1337 // TODO(dtapuska): Implement a mojo channel for the synchronous
1338 // compositor android webview uses.
1339 DCHECK(!GetContentClient()->UsingSynchronousCompositing());
1340#endif
1341 }
vollick1050cc62015-12-03 07:04:541342}
1343
jam75c44222016-03-23 05:34:241344void RenderThreadImpl::InitializeWebKit(
Stuart Langley7b8dc772017-10-31 03:55:201345 const scoped_refptr<base::SingleThreadTaskRunner>& resource_task_queue,
Ken Rockot510c5972017-12-05 16:37:041346 service_manager::BinderRegistry* registry) {
jam75c44222016-03-23 05:34:241347 DCHECK(!blink_platform_impl_);
[email protected]d1b8fccc2011-08-03 01:20:131348
avi83883c82014-12-23 00:08:491349 const base::CommandLine& command_line =
1350 *base::CommandLine::ForCurrentProcess();
chunyang.daibe874c52014-11-14 06:45:051351
1352#ifdef ENABLE_VTUNE_JIT_INTERFACE
1353 if (command_line.HasSwitch(switches::kEnableVtune))
1354 gin::Debug::SetJitCodeEventHandler(vTune::GetVtuneCodeEventHandler());
1355#endif
1356
Reilly Grant9944f162017-08-29 01:22:411357 blink_platform_impl_.reset(
1358 new RendererBlinkPlatformImpl(renderer_scheduler_.get()));
rmcilroy4073ae12015-01-08 13:08:101359 SetRuntimeFeaturesDefaultsAndUpdateFromArgs(command_line);
hlopko852ffcf2016-09-16 16:50:591360 GetContentClient()
1361 ->renderer()
1362 ->SetRuntimeFeaturesDefaultsBeforeBlinkInitialization();
Ken Rockot510c5972017-12-05 16:37:041363 blink::Initialize(blink_platform_impl_.get(), registry);
[email protected]d1b8fccc2011-08-03 01:20:131364
Blink Reformat1c4d759e2017-04-09 16:34:541365 v8::Isolate* isolate = blink::MainThreadIsolate();
[email protected]4b5340282014-07-08 11:37:341366 isolate->SetCreateHistogramFunction(CreateHistogram);
1367 isolate->SetAddHistogramSampleFunction(AddHistogramSample);
skyostila37c2a72016-06-29 17:30:071368 renderer_scheduler_->SetRAILModeObserver(this);
[email protected]4b5340282014-07-08 11:37:341369
rmcilroy321f924d2014-11-06 00:56:001370 main_thread_compositor_task_runner_ =
danakj6e3bf8012014-12-16 18:27:531371 renderer_scheduler_->CompositorTaskRunner();
skyostilc30aa402014-10-10 13:49:091372
jdduke691dd572014-12-02 20:47:521373 main_input_callback_.Reset(
1374 base::Bind(base::IgnoreResult(&RenderThreadImpl::OnMessageReceived),
1375 base::Unretained(this)));
1376
khushalsagard7178e42017-01-20 01:31:491377 if (!command_line.HasSwitch(switches::kDisableThreadedCompositing))
vollick1050cc62015-12-03 07:04:541378 InitializeCompositorThread();
[email protected]a9fb30aa2011-10-06 06:58:461379
jdduke691dd572014-12-02 20:47:521380 if (!input_event_filter_.get()) {
1381 // Always provide an input event filter implementation to ensure consistent
1382 // input event scheduling and prioritization.
1383 // TODO(jdduke): Merge InputEventFilter, InputHandlerManager and
1384 // MainThreadInputEventFilter, crbug.com/436057.
1385 input_event_filter_ = new MainThreadInputEventFilter(
1386 main_input_callback_.callback(), main_thread_compositor_task_runner_);
1387 }
1388 AddFilter(input_event_filter_.get());
1389
skyostil2d3b5bd2015-05-27 15:40:591390 scoped_refptr<base::SingleThreadTaskRunner> compositor_impl_side_task_runner;
vollick1050cc62015-12-03 07:04:541391 if (compositor_task_runner_)
skyostil2d3b5bd2015-05-27 15:40:591392 compositor_impl_side_task_runner = compositor_task_runner_;
[email protected]7f1f63f2013-03-07 06:07:291393 else
skyostil2d3b5bd2015-05-27 15:40:591394 compositor_impl_side_task_runner = base::ThreadTaskRunnerHandle::Get();
[email protected]1842fe22012-08-13 23:24:351395
[email protected]58436a12012-03-21 17:10:261396 RenderThreadImpl::RegisterSchemes();
1397
xhwang194acae2014-11-12 22:46:331398 RenderMediaClient::Initialize();
1399
ulan4a385192015-11-11 10:59:181400 if (GetContentClient()->renderer()->RunIdleHandlerWhenWidgetsHidden()) {
[email protected]1784b2f2011-11-24 10:53:481401 ScheduleIdleHandler(kLongIdleHandlerDelayMs);
ulan4a385192015-11-11 10:59:181402 } else {
1403 // If we do not track widget visibility, then assume conservatively that
1404 // the isolate is in background. This reduces memory usage.
1405 isolate->IsolateInBackgroundNotification();
1406 }
[email protected]2541d1a2013-07-10 07:33:271407
John Abd-El-Maleke1d4de32017-10-21 16:14:291408 service_worker_message_filter_ =
1409 new ServiceWorkerMessageFilter(thread_safe_sender());
1410 AddFilter(service_worker_message_filter_->GetFilter());
1411
Shubhie Panicker11a8e6a2017-09-19 09:29:231412 renderer_scheduler_->SetStoppingWhenBackgroundedEnabled(
1413 GetContentClient()->renderer()->AllowStoppingWhenProcessBackgrounded());
jdduke73220f02015-09-04 17:03:511414
reedccf98c52014-10-03 16:40:381415 SkGraphics::SetResourceCacheSingleAllocationByteLimit(
[email protected]dd2c1022014-07-22 23:13:571416 kImageCacheSingleAllocationByteLimit);
1417
reed6e5a72222015-08-06 20:37:161418 // Hook up blink's codecs so skia can call them
reed08cd16372017-02-21 22:11:411419 SkGraphics::SetImageGeneratorFromEncodedDataFactory(
Vladimir Levin325831d2017-08-30 15:03:221420 blink::WebImageGenerator::CreateAsSkImageGenerator);
reed6e5a72222015-08-06 20:37:161421
paritosh.in7e30c902015-04-15 17:04:071422 if (command_line.HasSwitch(switches::kExplicitlyAllowedPorts)) {
1423 std::string allowed_ports =
1424 command_line.GetSwitchValueASCII(switches::kExplicitlyAllowedPorts);
1425 net::SetExplicitlyAllowedPorts(allowed_ports);
1426 }
[email protected]d1b8fccc2011-08-03 01:20:131427}
1428
[email protected]58436a12012-03-21 17:10:261429void RenderThreadImpl::RegisterSchemes() {
mkwst8e94fb32015-05-20 05:05:141430 // chrome:
Blink Reformat1c4d759e2017-04-09 16:34:541431 WebString chrome_scheme(WebString::FromASCII(kChromeUIScheme));
1432 WebSecurityPolicy::RegisterURLSchemeAsDisplayIsolated(chrome_scheme);
1433 WebSecurityPolicy::RegisterURLSchemeAsNotAllowingJavascriptURLs(
mkwst8e94fb32015-05-20 05:05:141434 chrome_scheme);
mkwst8e94fb32015-05-20 05:05:141435
1436 // chrome-devtools:
Blink Reformat1c4d759e2017-04-09 16:34:541437 WebString devtools_scheme(WebString::FromASCII(kChromeDevToolsScheme));
1438 WebSecurityPolicy::RegisterURLSchemeAsDisplayIsolated(devtools_scheme);
meacerce6b66032016-06-02 20:56:051439
1440 // view-source:
Blink Reformat1c4d759e2017-04-09 16:34:541441 WebString view_source_scheme(WebString::FromASCII(kViewSourceScheme));
1442 WebSecurityPolicy::RegisterURLSchemeAsDisplayIsolated(view_source_scheme);
Alex Moshchuk71f485592017-08-16 16:20:001443
1444 // chrome-error:
1445 WebString error_scheme(WebString::FromASCII(kChromeErrorScheme));
1446 WebSecurityPolicy::RegisterURLSchemeAsDisplayIsolated(error_scheme);
1447 WebSecurityPolicy::RegisterURLSchemeAsNotAllowingJavascriptURLs(error_scheme);
[email protected]58436a12012-03-21 17:10:261448}
1449
[email protected]e6e30ac2014-01-13 21:24:391450void RenderThreadImpl::RecordAction(const base::UserMetricsAction& action) {
[email protected]97880c82013-12-04 07:09:211451 Send(new ViewHostMsg_UserMetricsRecordAction(action.str_));
1452}
1453
1454void RenderThreadImpl::RecordComputedAction(const std::string& action) {
[email protected]526476902011-10-06 20:34:061455 Send(new ViewHostMsg_UserMetricsRecordAction(action));
1456}
1457
dchengcedca5612016-04-09 01:40:151458std::unique_ptr<base::SharedMemory>
1459RenderThreadImpl::HostAllocateSharedMemoryBuffer(size_t size) {
sadrulee3ff1f2016-12-09 04:22:011460 return ChildThreadImpl::AllocateSharedMemory(size);
[email protected]00614a82011-10-07 22:39:311461}
1462
Fady Samuel4b5f9862017-07-11 05:27:201463viz::SharedBitmapManager* RenderThreadImpl::GetSharedBitmapManager() {
jbauman2f5c1942014-12-06 03:28:241464 return shared_bitmap_manager();
1465}
1466
[email protected]f1a29a02011-10-06 23:08:441467void RenderThreadImpl::RegisterExtension(v8::Extension* extension) {
Blink Reformat1c4d759e2017-04-09 16:34:541468 WebScriptController::RegisterExtension(extension);
[email protected]526476902011-10-06 20:34:061469}
1470
avi1023d012015-12-25 02:39:141471void RenderThreadImpl::ScheduleIdleHandler(int64_t initial_delay_ms) {
[email protected]6593ae12011-11-14 12:09:441472 idle_notification_delay_in_ms_ = initial_delay_ms;
[email protected]526476902011-10-06 20:34:061473 idle_timer_.Stop();
1474 idle_timer_.Start(FROM_HERE,
[email protected]6593ae12011-11-14 12:09:441475 base::TimeDelta::FromMilliseconds(initial_delay_ms),
[email protected]f1a29a02011-10-06 23:08:441476 this, &RenderThreadImpl::IdleHandler);
[email protected]526476902011-10-06 20:34:061477}
1478
[email protected]f1a29a02011-10-06 23:08:441479void RenderThreadImpl::IdleHandler() {
[email protected]1784b2f2011-11-24 10:53:481480 bool run_in_foreground_tab = (widget_count_ > hidden_widget_count_) &&
[email protected]e9ff79c2012-10-19 21:31:261481 GetContentClient()->renderer()->
[email protected]1784b2f2011-11-24 10:53:481482 RunIdleHandlerWhenWidgetsHidden();
1483 if (run_in_foreground_tab) {
jochen5a32aaf2014-09-26 20:37:431484 if (idle_notifications_to_skip_ > 0) {
1485 --idle_notifications_to_skip_;
1486 } else {
ssid0603ca9f2015-06-09 16:48:081487 ReleaseFreeMemory();
jochen5a32aaf2014-09-26 20:37:431488 }
1489 ScheduleIdleHandler(kLongIdleHandlerDelayMs);
[email protected]1784b2f2011-11-24 10:53:481490 return;
1491 }
[email protected]237a14852012-04-28 02:56:381492
ssid0603ca9f2015-06-09 16:48:081493 ReleaseFreeMemory();
[email protected]526476902011-10-06 20:34:061494
[email protected]26e82322014-01-20 14:18:221495 // Continue the idle timer if the webkit shared timer is not suspended or
1496 // something is left to do.
Alexander Timin4b6152232017-10-17 20:34:061497 bool continue_timer = !webkit_shared_timer_suspended_;
[email protected]26e82322014-01-20 14:18:221498
sullivancd45a3e2014-09-19 14:39:181499 // Schedule next invocation. When the tab is originally hidden, an invocation
1500 // is scheduled for kInitialIdleHandlerDelayMs in
1501 // RenderThreadImpl::WidgetHidden in order to race to a minimal heap.
1502 // After that, idle calls can be much less frequent, so run at a maximum of
1503 // once every kLongIdleHandlerDelayMs.
[email protected]6593ae12011-11-14 12:09:441504 // Dampen the delay using the algorithm (if delay is in seconds):
[email protected]526476902011-10-06 20:34:061505 // delay = delay + 1 / (delay + 2)
1506 // Using floor(delay) has a dampening effect such as:
sullivancd45a3e2014-09-19 14:39:181507 // 30s, 30, 30, 31, 31, 31, 31, 32, 32, ...
[email protected]6593ae12011-11-14 12:09:441508 // If the delay is in milliseconds, the above formula is equivalent to:
1509 // delay_ms / 1000 = delay_ms / 1000 + 1 / (delay_ms / 1000 + 2)
1510 // which is equivalent to
1511 // delay_ms = delay_ms + 1000*1000 / (delay_ms + 2000).
[email protected]26e82322014-01-20 14:18:221512 if (continue_timer) {
sullivancd45a3e2014-09-19 14:39:181513 ScheduleIdleHandler(
1514 std::max(kLongIdleHandlerDelayMs,
1515 idle_notification_delay_in_ms_ +
1516 1000000 / (idle_notification_delay_in_ms_ + 2000)));
[email protected]26e82322014-01-20 14:18:221517
1518 } else {
1519 idle_timer_.Stop();
1520 }
[email protected]526476902011-10-06 20:34:061521
ericwilligers88e69742016-10-17 19:29:551522 for (auto& observer : observers_)
1523 observer.IdleNotification();
[email protected]526476902011-10-06 20:34:061524}
1525
avi1023d012015-12-25 02:39:141526int64_t RenderThreadImpl::GetIdleNotificationDelayInMs() const {
[email protected]6593ae12011-11-14 12:09:441527 return idle_notification_delay_in_ms_;
[email protected]526476902011-10-06 20:34:061528}
1529
[email protected]6593ae12011-11-14 12:09:441530void RenderThreadImpl::SetIdleNotificationDelayInMs(
avi1023d012015-12-25 02:39:141531 int64_t idle_notification_delay_in_ms) {
[email protected]6593ae12011-11-14 12:09:441532 idle_notification_delay_in_ms_ = idle_notification_delay_in_ms;
[email protected]4a7d6392011-09-19 20:55:081533}
1534
[email protected]5b18406362013-06-18 18:46:431535int RenderThreadImpl::PostTaskToAllWebWorkers(const base::Closure& closure) {
kinukoef647412015-12-23 06:10:431536 return WorkerThreadRegistry::Instance()->PostTaskToAllThreads(closure);
[email protected]a9bd323d2013-06-17 20:27:561537}
1538
[email protected]b02f5902012-12-19 07:33:001539bool RenderThreadImpl::ResolveProxy(const GURL& url, std::string* proxy_list) {
1540 bool result = false;
1541 Send(new ViewHostMsg_ResolveProxy(url, &result, proxy_list));
1542 return result;
1543}
1544
[email protected]1784b2f2011-11-24 10:53:481545void RenderThreadImpl::PostponeIdleNotification() {
1546 idle_notifications_to_skip_ = 2;
1547}
1548
dcastagna7f45dada2015-10-19 20:17:351549media::GpuVideoAcceleratorFactories* RenderThreadImpl::GetGpuFactories() {
[email protected]3bb8bb32013-07-11 13:13:031550 DCHECK(IsMainThread());
1551
dcastagna09bd6b32016-02-01 21:54:281552 if (!gpu_factories_.empty()) {
sadrul85cc5d82016-12-20 03:37:411553 scoped_refptr<ui::ContextProviderCommandBuffer> shared_context_provider =
dcastagna09bd6b32016-02-01 21:54:281554 gpu_factories_.back()->ContextProviderMainThread();
1555 if (shared_context_provider) {
Xu Xing32549162017-07-17 22:25:431556 viz::ContextProvider::ScopedContextLock lock(
dcastagna09bd6b32016-02-01 21:54:281557 shared_context_provider.get());
Miguel Casas5e1018052018-01-09 19:17:361558 if (lock.ContextGL()->GetGraphicsResetStatusKHR() == GL_NO_ERROR)
leon.han21e0e482017-02-23 04:13:321559 return gpu_factories_.back().get();
Miguel Casas5e1018052018-01-09 19:17:361560
1561 scoped_refptr<base::SingleThreadTaskRunner> media_task_runner =
1562 GetMediaThreadTaskRunner();
1563 media_task_runner->PostTask(
1564 FROM_HERE,
1565 base::BindOnce(
1566 base::IgnoreResult(
1567 &GpuVideoAcceleratorFactoriesImpl::CheckContextLost),
1568 base::Unretained(gpu_factories_.back().get())));
dcastagna09bd6b32016-02-01 21:54:281569 }
1570 }
dcastagna7f45dada2015-10-19 20:17:351571
tobiasjsca238b3b2015-06-24 22:53:541572 const base::CommandLine* cmd_line = base::CommandLine::ForCurrentProcess();
1573
danakj0b4b94e32016-05-10 22:33:011574 scoped_refptr<gpu::GpuChannelHost> gpu_channel_host =
sadrul6d310fa2016-08-04 02:12:161575 EstablishGpuChannelSync();
danakj0b4b94e32016-05-10 22:33:011576 if (!gpu_channel_host)
1577 return nullptr;
danakj0dd9e1e2016-05-11 22:15:091578 // This context is only used to create textures and mailbox them, so
1579 // use lower limits than the default.
1580 gpu::SharedMemoryLimits limits = gpu::SharedMemoryLimits::ForMailboxContext();
danakj9a04adc2016-05-16 22:45:071581 bool support_locking = true;
Victor Miura3a4ad4f82017-12-13 06:03:451582 bool support_gles2_interface = true;
1583 bool support_raster_interface = false;
Adrienne Walker436a7752017-08-28 23:33:091584 bool support_oop_rasterization = false;
sadrul85cc5d82016-12-20 03:37:411585 scoped_refptr<ui::ContextProviderCommandBuffer> media_context_provider =
Antoine Labour5ac65db2017-12-19 18:02:581586 CreateOffscreenContext(
1587 gpu_channel_host, GetGpuMemoryBufferManager(), limits,
1588 support_locking, support_gles2_interface, support_raster_interface,
1589 support_oop_rasterization, ui::command_buffer_metrics::MEDIA_CONTEXT,
Sunny Sachanandaniaf5912a2018-01-22 23:49:521590 kGpuStreamIdMedia, kGpuStreamPriorityMedia);
danakj45cfd232017-10-18 19:31:311591 auto result = media_context_provider->BindToCurrentThread();
1592 if (result != gpu::ContextResult::kSuccess)
danakj0b4b94e32016-05-10 22:33:011593 return nullptr;
danakj0b4b94e32016-05-10 22:33:011594
acolwellb4034942014-08-28 15:42:431595 scoped_refptr<base::SingleThreadTaskRunner> media_task_runner =
1596 GetMediaThreadTaskRunner();
danakj0b4b94e32016-05-10 22:33:011597 const bool enable_video_accelerator =
Zhenyao Mo16d39b82017-12-15 22:48:041598 !cmd_line->HasSwitch(switches::kDisableAcceleratedVideoDecode) &&
1599 (gpu_channel_host->gpu_feature_info()
1600 .status_values[gpu::GPU_FEATURE_TYPE_ACCELERATED_VIDEO_DECODE] ==
1601 gpu::kGpuFeatureStatusEnabled);
danakj0b4b94e32016-05-10 22:33:011602 const bool enable_gpu_memory_buffer_video_frames =
danakjab9ef4d2017-10-31 23:38:331603 !is_gpu_compositing_disabled_ &&
dcastagna43c3a86a2016-02-02 21:16:381604#if defined(OS_MACOSX) || defined(OS_LINUX)
danakjab9ef4d2017-10-31 23:38:331605 !cmd_line->HasSwitch(switches::kDisableGpuMemoryBufferVideoFrames);
jbaumana0bb8982017-05-05 19:50:531606#elif defined(OS_WIN)
1607 !cmd_line->HasSwitch(switches::kDisableGpuMemoryBufferVideoFrames) &&
jbaumana0bb8982017-05-05 19:50:531608 (cmd_line->HasSwitch(switches::kEnableGpuMemoryBufferVideoFrames) ||
1609 gpu_channel_host->gpu_info().supports_overlays);
dcastagnab65e6072015-09-05 07:18:421610#else
danakj0b4b94e32016-05-10 22:33:011611 cmd_line->HasSwitch(switches::kEnableGpuMemoryBufferVideoFrames);
dcastagnab65e6072015-09-05 07:18:421612#endif
dcastagna5077d6d2016-01-27 00:07:051613
Miguel Casas-Sanchez7d464702017-07-29 14:19:211614 media::mojom::VideoEncodeAcceleratorProviderPtr vea_provider;
1615 gpu_->CreateVideoEncodeAcceleratorProvider(mojo::MakeRequest(&vea_provider));
Miguel Casas-Sanchezdaca32562017-07-11 08:05:451616
Miguel Casas-Sanchezcfcca5d52017-07-07 02:32:591617 gpu_factories_.push_back(GpuVideoAcceleratorFactoriesImpl::Create(
danakj0b4b94e32016-05-10 22:33:011618 std::move(gpu_channel_host), base::ThreadTaskRunnerHandle::Get(),
1619 media_task_runner, std::move(media_context_provider),
Victor Miuracabdfac2018-01-05 02:18:181620 enable_gpu_memory_buffer_video_frames, enable_video_accelerator,
1621 vea_provider.PassInterface()));
Miguel Casas5e1018052018-01-09 19:17:361622 gpu_factories_.back()->SetRenderingColorSpace(rendering_color_space_);
leon.han21e0e482017-02-23 04:13:321623 return gpu_factories_.back().get();
[email protected]3bb8bb32013-07-11 13:13:031624}
1625
sadrul85cc5d82016-12-20 03:37:411626scoped_refptr<ui::ContextProviderCommandBuffer>
[email protected]f10dc472013-09-27 03:31:591627RenderThreadImpl::SharedMainThreadContextProvider() {
[email protected]e06e1122013-03-15 17:12:381628 DCHECK(IsMainThread());
danakje8ec797e2016-04-19 04:08:431629 if (shared_main_thread_contexts_ &&
1630 shared_main_thread_contexts_->ContextGL()->GetGraphicsResetStatusKHR() ==
1631 GL_NO_ERROR)
1632 return shared_main_thread_contexts_;
1633
sadrul6d310fa2016-08-04 02:12:161634 scoped_refptr<gpu::GpuChannelHost> gpu_channel_host(
1635 EstablishGpuChannelSync());
danakje8ec797e2016-04-19 04:08:431636 if (!gpu_channel_host) {
1637 shared_main_thread_contexts_ = nullptr;
1638 return nullptr;
[email protected]c29b7ff2013-03-06 03:51:041639 }
danakje8ec797e2016-04-19 04:08:431640
danakj9a04adc2016-05-16 22:45:071641 bool support_locking = false;
Victor Miura3a4ad4f82017-12-13 06:03:451642 bool support_gles2_interface = true;
Khushal60916ba2018-01-19 19:47:471643 bool support_raster_interface = true;
Adrienne Walker436a7752017-08-28 23:33:091644 bool support_oop_rasterization = false;
danakjc3983552016-05-03 00:04:351645 shared_main_thread_contexts_ = CreateOffscreenContext(
Antoine Labour5ac65db2017-12-19 18:02:581646 std::move(gpu_channel_host), GetGpuMemoryBufferManager(),
1647 gpu::SharedMemoryLimits(), support_locking, support_gles2_interface,
1648 support_raster_interface, support_oop_rasterization,
sadrul85cc5d82016-12-20 03:37:411649 ui::command_buffer_metrics::RENDERER_MAINTHREAD_CONTEXT,
sunnyps8f9139e2017-05-12 17:53:251650 kGpuStreamIdDefault, kGpuStreamPriorityDefault);
danakj45cfd232017-10-18 19:31:311651 auto result = shared_main_thread_contexts_->BindToCurrentThread();
1652 if (result != gpu::ContextResult::kSuccess)
danakje8ec797e2016-04-19 04:08:431653 shared_main_thread_contexts_ = nullptr;
[email protected]f10dc472013-09-27 03:31:591654 return shared_main_thread_contexts_;
[email protected]c29b7ff2013-03-06 03:51:041655}
1656
siva.gunturi5d4feb052015-11-15 16:15:311657#if defined(OS_ANDROID)
boliuf8753bf62016-02-11 20:09:421658
siva.gunturi5d4feb052015-11-15 16:15:311659scoped_refptr<StreamTextureFactory> RenderThreadImpl::GetStreamTexureFactory() {
1660 DCHECK(IsMainThread());
boliu30f1b262016-04-19 00:12:331661 if (!stream_texture_factory_.get() ||
1662 stream_texture_factory_->ContextGL()->GetGraphicsResetStatusKHR() !=
1663 GL_NO_ERROR) {
sadrul85cc5d82016-12-20 03:37:411664 scoped_refptr<ui::ContextProviderCommandBuffer> shared_context_provider =
piman9fc22f32016-05-02 22:21:221665 SharedMainThreadContextProvider();
1666 if (!shared_context_provider) {
penghuange1d86512016-07-08 18:15:001667 stream_texture_factory_ = nullptr;
1668 return nullptr;
siva.gunturi5d4feb052015-11-15 16:15:311669 }
piman9fc22f32016-05-02 22:21:221670 DCHECK(shared_context_provider->GetCommandBufferProxy());
1671 DCHECK(shared_context_provider->GetCommandBufferProxy()->channel());
1672 stream_texture_factory_ =
1673 StreamTextureFactory::Create(std::move(shared_context_provider));
siva.gunturi5d4feb052015-11-15 16:15:311674 }
1675 return stream_texture_factory_;
1676}
boliuf8753bf62016-02-11 20:09:421677
1678bool RenderThreadImpl::EnableStreamTextureCopy() {
boliu30f1b262016-04-19 00:12:331679 return sync_compositor_message_filter_.get();
boliuf8753bf62016-02-11 20:09:421680}
1681
siva.gunturi5d4feb052015-11-15 16:15:311682#endif
1683
[email protected]e9ff79c2012-10-19 21:31:261684AudioRendererMixerManager* RenderThreadImpl::GetAudioRendererMixerManager() {
[email protected]59383c782013-04-17 16:43:271685 if (!audio_renderer_mixer_manager_) {
olka7a4679392016-05-27 15:32:581686 audio_renderer_mixer_manager_ = AudioRendererMixerManager::Create();
[email protected]3958e972012-07-17 00:25:411687 }
1688
1689 return audio_renderer_mixer_manager_.get();
1690}
1691
[email protected]73429ca2014-03-06 06:07:471692base::WaitableEvent* RenderThreadImpl::GetShutdownEvent() {
1693 return ChildProcess::current()->GetShutDownEvent();
1694}
1695
staraz067f58242016-11-07 21:06:411696int32_t RenderThreadImpl::GetClientId() {
1697 return client_id_;
1698}
1699
Karan Bhatiac89897f2017-08-10 01:06:401700void RenderThreadImpl::SetRendererProcessType(
1701 blink::scheduler::RendererProcessType type) {
1702 renderer_scheduler_->SetRendererProcessType(type);
1703}
1704
John Abd-El-Malek6b56ef712017-10-21 22:52:461705bool RenderThreadImpl::OnMessageReceived(const IPC::Message& msg) {
John Abd-El-Malekdcf1d1372017-10-22 06:39:411706 if (file_system_dispatcher_->OnMessageReceived(msg))
1707 return true;
John Abd-El-Malek6b56ef712017-10-21 22:52:461708 return ChildThreadImpl::OnMessageReceived(msg);
1709}
1710
rockot067ca55f2016-09-30 22:00:151711void RenderThreadImpl::OnAssociatedInterfaceRequest(
1712 const std::string& name,
1713 mojo::ScopedInterfaceEndpointHandle handle) {
rockot70bbb59492017-01-25 00:56:511714 if (associated_interfaces_.CanBindRequest(name))
1715 associated_interfaces_.BindRequest(name, std::move(handle));
1716 else
1717 ChildThreadImpl::OnAssociatedInterfaceRequest(name, std::move(handle));
rockot067ca55f2016-09-30 22:00:151718}
1719
weilifabbf7572017-05-22 19:05:161720scoped_refptr<base::SingleThreadTaskRunner>
1721RenderThreadImpl::GetIOTaskRunner() {
1722 return ChildProcess::current()->io_task_runner();
1723}
1724
danakj6e3bf8012014-12-16 18:27:531725bool RenderThreadImpl::IsGpuRasterizationForced() {
1726 return is_gpu_rasterization_forced_;
1727}
1728
senorblancob60ba952015-01-27 19:12:361729int RenderThreadImpl::GetGpuRasterizationMSAASampleCount() {
1730 return gpu_rasterization_msaa_sample_count_;
1731}
1732
danakj6e3bf8012014-12-16 18:27:531733bool RenderThreadImpl::IsLcdTextEnabled() {
1734 return is_lcd_text_enabled_;
1735}
1736
1737bool RenderThreadImpl::IsDistanceFieldTextEnabled() {
1738 return is_distance_field_text_enabled_;
1739}
1740
1741bool RenderThreadImpl::IsZeroCopyEnabled() {
1742 return is_zero_copy_enabled_;
1743}
1744
ericrk1d17f752015-10-20 03:03:071745bool RenderThreadImpl::IsPartialRasterEnabled() {
1746 return is_partial_raster_enabled_;
jbroman5f7f71932015-08-18 16:24:461747}
1748
ccameronc7fcd132015-11-03 20:14:311749bool RenderThreadImpl::IsGpuMemoryBufferCompositorResourcesEnabled() {
1750 return is_gpu_memory_buffer_compositor_resources_enabled_;
1751}
1752
ccamerona7644752014-12-30 01:16:311753bool RenderThreadImpl::IsElasticOverscrollEnabled() {
1754 return is_elastic_overscroll_enabled_;
1755}
1756
danakj6e3bf8012014-12-16 18:27:531757scoped_refptr<base::SingleThreadTaskRunner>
1758RenderThreadImpl::GetCompositorMainThreadTaskRunner() {
1759 return main_thread_compositor_task_runner_;
1760}
1761
1762scoped_refptr<base::SingleThreadTaskRunner>
1763RenderThreadImpl::GetCompositorImplThreadTaskRunner() {
skyostil2d3b5bd2015-05-27 15:40:591764 return compositor_task_runner_;
danakj6e3bf8012014-12-16 18:27:531765}
1766
1767gpu::GpuMemoryBufferManager* RenderThreadImpl::GetGpuMemoryBufferManager() {
sadrul53546592016-12-17 01:44:211768 return gpu_->gpu_memory_buffer_manager();
danakj6e3bf8012014-12-16 18:27:531769}
1770
skyostil529caa292016-08-10 17:44:511771blink::scheduler::RendererScheduler* RenderThreadImpl::GetRendererScheduler() {
danakj6e3bf8012014-12-16 18:27:531772 return renderer_scheduler_.get();
1773}
1774
Fady Samuelc645ffe2017-07-24 17:28:201775std::unique_ptr<viz::SyntheticBeginFrameSource>
samans09812d32017-03-27 19:51:501776RenderThreadImpl::CreateSyntheticBeginFrameSource() {
1777 base::SingleThreadTaskRunner* compositor_impl_side_task_runner =
1778 compositor_task_runner_ ? compositor_task_runner_.get()
1779 : base::ThreadTaskRunnerHandle::Get().get();
Jeremy Roman04f27c372017-10-27 15:20:551780 return std::make_unique<viz::BackToBackBeginFrameSource>(
1781 std::make_unique<viz::DelayBasedTimeSource>(
samans09812d32017-03-27 19:51:501782 compositor_impl_side_task_runner));
1783}
1784
reveman34b7a1522015-03-23 20:27:471785cc::TaskGraphRunner* RenderThreadImpl::GetTaskGraphRunner() {
prashant.nfad657e2016-06-01 07:52:171786 return categorized_worker_pool_->GetTaskGraphRunner();
reveman34b7a1522015-03-23 20:27:471787}
1788
loyso65c93c602015-08-11 05:15:571789bool RenderThreadImpl::IsThreadedAnimationEnabled() {
1790 return is_threaded_animation_enabled_;
1791}
1792
wjmaclean1d970622017-01-21 22:28:241793bool RenderThreadImpl::IsScrollAnimatorEnabled() {
1794 return is_scroll_animator_enabled_;
1795}
1796
Khushal3e96e662017-10-30 23:16:501797std::unique_ptr<cc::UkmRecorderFactory>
1798RenderThreadImpl::CreateUkmRecorderFactory() {
Khushalda50f8152017-12-01 09:04:401799 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
1800 switches::kDisableCompositorUkmForTests)) {
1801 return nullptr;
1802 }
1803
1804 return std::make_unique<UkmRecorderFactoryImpl>(GetConnector()->Clone());
Khushal3e96e662017-10-30 23:16:501805}
1806
skyostila37c2a72016-06-29 17:30:071807void RenderThreadImpl::OnRAILModeChanged(v8::RAILMode rail_mode) {
Blink Reformat1c4d759e2017-04-09 16:34:541808 blink::MainThreadIsolate()->SetRAILMode(rail_mode);
1809 blink::SetRAILModeOnWorkerThreadIsolates(rail_mode);
skyostila37c2a72016-06-29 17:30:071810}
1811
[email protected]b3e83de2012-02-07 03:33:281812bool RenderThreadImpl::IsMainThread() {
1813 return !!current();
1814}
1815
torne88b66452016-05-03 13:22:141816void RenderThreadImpl::OnChannelError() {
1817 // In single-process mode, the renderer can't be restarted after shutdown.
1818 // So, if we get a channel error, crash the whole process right now to get a
1819 // more informative stack, since we will otherwise just crash later when we
1820 // try to restart it.
1821 CHECK(!base::CommandLine::ForCurrentProcess()->HasSwitch(
1822 switches::kSingleProcess));
1823 ChildThreadImpl::OnChannelError();
1824}
1825
Nicholas Verne06de8122017-11-16 04:47:381826void RenderThreadImpl::OnProcessFinalRelease() {
1827 if (on_channel_error_called())
1828 return;
1829 // The child process shutdown sequence is a request response based mechanism,
1830 // where we send out an initial feeler request to the child process host
1831 // instance in the browser to verify if it's ok to shutdown the child process.
1832 // The browser then sends back a response if it's ok to shutdown. This avoids
1833 // race conditions if the process refcount is 0 but there's an IPC message
1834 // inflight that would addref it.
1835 GetRendererHost()->ShutdownRequest();
1836}
1837
[email protected]f1a29a02011-10-06 23:08:441838bool RenderThreadImpl::OnControlMessageReceived(const IPC::Message& msg) {
dchenga2d442c22016-10-13 15:39:211839 for (auto& observer : observers_) {
1840 if (observer.OnControlMessageReceived(msg))
[email protected]1223d6ef2011-03-28 16:47:501841 return true;
1842 }
1843
[email protected]70c19a932010-05-14 12:59:111844 // Some messages are handled by delegates.
Nicholas Verne07e9c6452017-12-13 04:12:551845 if (dom_storage_dispatcher_->OnMessageReceived(msg)) {
[email protected]a95986a82010-12-24 06:19:281846 return true;
[email protected]1910fe82012-05-10 00:04:101847 }
Darin Fisherbcc33632017-09-26 00:57:161848 return false;
initial.commit09911bf2008-07-26 23:55:291849}
1850
Shubhie Panicker45ce80a82018-02-01 01:40:191851void RenderThreadImpl::SetSchedulerKeepActive(bool keep_active) {
1852 renderer_scheduler_->SetSchedulerKeepActive(keep_active);
1853}
1854
Nicholas Verne5420564d2017-10-27 07:37:541855void RenderThreadImpl::SetProcessBackgrounded(bool backgrounded) {
1856 // Set timer slack to maximum on main thread when in background.
1857 base::TimerSlack timer_slack = base::TIMER_SLACK_NONE;
1858 if (backgrounded)
1859 timer_slack = base::TIMER_SLACK_MAXIMUM;
1860 base::MessageLoop::current()->SetTimerSlack(timer_slack);
jdduke73220f02015-09-04 17:03:511861
Alexander Timin771b3372017-06-15 13:26:471862 renderer_scheduler_->SetRendererBackgrounded(backgrounded);
hajimehoshi69093272016-05-13 08:30:581863 if (backgrounded) {
tasakb95dbb50c2017-02-08 18:07:501864 needs_to_record_first_active_paint_ = false;
tasak335a1872017-06-14 09:50:231865 GetRendererScheduler()->DefaultTaskRunner()->PostDelayedTask(
1866 FROM_HERE,
tzikff2a81a2017-09-15 05:10:061867 base::BindOnce(&RenderThreadImpl::RecordMemoryUsageAfterBackgrounded,
1868 base::Unretained(this), "5min",
1869 process_foregrounded_count_),
tasak335a1872017-06-14 09:50:231870 base::TimeDelta::FromMinutes(5));
1871 GetRendererScheduler()->DefaultTaskRunner()->PostDelayedTask(
1872 FROM_HERE,
tzikff2a81a2017-09-15 05:10:061873 base::BindOnce(&RenderThreadImpl::RecordMemoryUsageAfterBackgrounded,
1874 base::Unretained(this), "10min",
1875 process_foregrounded_count_),
tasak335a1872017-06-14 09:50:231876 base::TimeDelta::FromMinutes(10));
1877 GetRendererScheduler()->DefaultTaskRunner()->PostDelayedTask(
1878 FROM_HERE,
tzikff2a81a2017-09-15 05:10:061879 base::BindOnce(&RenderThreadImpl::RecordMemoryUsageAfterBackgrounded,
1880 base::Unretained(this), "15min",
1881 process_foregrounded_count_),
tasak335a1872017-06-14 09:50:231882 base::TimeDelta::FromMinutes(15));
Takashi SAKAMOTO870f6262017-08-22 04:08:271883 was_backgrounded_time_ = base::TimeTicks::Now();
hajimehoshi69093272016-05-13 08:30:581884 } else {
tasakbb0640b2017-05-15 09:02:261885 process_foregrounded_count_++;
hajimehoshi69093272016-05-13 08:30:581886 }
1887}
1888
Nicholas Verne5420564d2017-10-27 07:37:541889void RenderThreadImpl::ProcessPurgeAndSuspend() {
tasak6ff44032016-11-07 06:45:251890 if (!RendererIsHidden())
hajimehoshi69093272016-05-13 08:30:581891 return;
tasakff1e62422016-12-22 04:53:551892
tasakc4de4672017-04-26 02:37:361893 if (!base::FeatureList::IsEnabled(features::kPurgeAndSuspend))
1894 return;
1895
1896 base::MemoryCoordinatorClientRegistry::GetInstance()->PurgeMemory();
tasakb95dbb50c2017-02-08 18:07:501897 needs_to_record_first_active_paint_ = true;
tasakc4de4672017-04-26 02:37:361898
1899 RendererMemoryMetrics memory_metrics;
1900 if (!GetRendererMemoryMetrics(&memory_metrics))
1901 return;
1902
1903 purge_and_suspend_memory_metrics_ = memory_metrics;
tasaka27961a2017-05-24 07:33:251904 GetRendererScheduler()->DefaultTaskRunner()->PostDelayedTask(
1905 FROM_HERE,
tzikff2a81a2017-09-15 05:10:061906 base::BindOnce(
1907 &RenderThreadImpl::RecordPurgeAndSuspendMemoryGrowthMetrics,
1908 base::Unretained(this), "30min", process_foregrounded_count_),
tasaka27961a2017-05-24 07:33:251909 base::TimeDelta::FromMinutes(30));
1910 GetRendererScheduler()->DefaultTaskRunner()->PostDelayedTask(
1911 FROM_HERE,
tzikff2a81a2017-09-15 05:10:061912 base::BindOnce(
1913 &RenderThreadImpl::RecordPurgeAndSuspendMemoryGrowthMetrics,
1914 base::Unretained(this), "60min", process_foregrounded_count_),
tasaka27961a2017-05-24 07:33:251915 base::TimeDelta::FromMinutes(60));
1916 GetRendererScheduler()->DefaultTaskRunner()->PostDelayedTask(
1917 FROM_HERE,
tzikff2a81a2017-09-15 05:10:061918 base::BindOnce(
1919 &RenderThreadImpl::RecordPurgeAndSuspendMemoryGrowthMetrics,
1920 base::Unretained(this), "90min", process_foregrounded_count_),
tasaka27961a2017-05-24 07:33:251921 base::TimeDelta::FromMinutes(90));
tasakb46626a2016-10-18 05:54:441922}
1923
bashia0ba0d42017-04-03 08:11:061924bool RenderThreadImpl::GetRendererMemoryMetrics(
keishi51ed0d52017-01-12 10:04:461925 RendererMemoryMetrics* memory_metrics) const {
1926 DCHECK(memory_metrics);
1927
chrisha05e94f22017-04-05 22:06:041928 // Cache this result, as it can change while this code is running, and is used
1929 // as a divisor below.
1930 size_t render_view_count = RenderView::GetRenderViewCount();
1931
1932 // If there are no render views it doesn't make sense to calculate metrics
1933 // right now.
1934 if (render_view_count == 0)
bashia0ba0d42017-04-03 08:11:061935 return false;
1936
keishi51ed0d52017-01-12 10:04:461937 blink::WebMemoryStatistics blink_stats = blink::WebMemoryStatistics::Get();
1938 memory_metrics->partition_alloc_kb =
Blink Reformat1c4d759e2017-04-09 16:34:541939 blink_stats.partition_alloc_total_allocated_bytes / 1024;
1940 memory_metrics->blink_gc_kb =
1941 blink_stats.blink_gc_total_allocated_bytes / 1024;
keishi12b598b92017-06-20 10:25:261942 std::unique_ptr<base::ProcessMetrics> metric(
1943 base::ProcessMetrics::CreateCurrentProcessMetrics());
1944 size_t malloc_usage = metric->GetMallocUsage();
keishi51ed0d52017-01-12 10:04:461945 memory_metrics->malloc_mb = malloc_usage / 1024 / 1024;
1946
1947 discardable_memory::ClientDiscardableSharedMemoryManager::Statistics
1948 discardable_stats = discardable_shared_memory_manager_->GetStatistics();
1949 size_t discardable_usage =
1950 discardable_stats.total_size - discardable_stats.freelist_size;
1951 memory_metrics->discardable_kb = discardable_usage / 1024;
1952
1953 size_t v8_usage = 0;
Blink Reformat1c4d759e2017-04-09 16:34:541954 if (v8::Isolate* isolate = blink::MainThreadIsolate()) {
keishi51ed0d52017-01-12 10:04:461955 v8::HeapStatistics v8_heap_statistics;
1956 isolate->GetHeapStatistics(&v8_heap_statistics);
1957 v8_usage = v8_heap_statistics.total_heap_size();
1958 }
1959 // TODO(tasak): Currently only memory usage of mainThreadIsolate() is
1960 // reported. We should collect memory usages of all isolates using
1961 // memory-infra.
1962 memory_metrics->v8_main_thread_isolate_mb = v8_usage / 1024 / 1024;
Blink Reformat1c4d759e2017-04-09 16:34:541963 size_t total_allocated = blink_stats.partition_alloc_total_allocated_bytes +
1964 blink_stats.blink_gc_total_allocated_bytes +
keishi51ed0d52017-01-12 10:04:461965 malloc_usage + v8_usage + discardable_usage;
1966 memory_metrics->total_allocated_mb = total_allocated / 1024 / 1024;
1967 memory_metrics->non_discardable_total_allocated_mb =
1968 (total_allocated - discardable_usage) / 1024 / 1024;
1969 memory_metrics->total_allocated_per_render_view_mb =
chrisha05e94f22017-04-05 22:06:041970 total_allocated / render_view_count / 1024 / 1024;
bashia0ba0d42017-04-03 08:11:061971
1972 return true;
keishi51ed0d52017-01-12 10:04:461973}
1974
tasak335a1872017-06-14 09:50:231975static void RecordMemoryUsageAfterBackgroundedMB(const char* basename,
1976 const char* suffix,
1977 int memory_usage) {
1978 std::string histogram_name = base::StringPrintf("%s.%s", basename, suffix);
1979 base::UmaHistogramMemoryLargeMB(histogram_name, memory_usage);
1980}
1981
1982void RenderThreadImpl::RecordMemoryUsageAfterBackgrounded(
1983 const char* suffix,
1984 int foregrounded_count) {
1985 // If this renderer is resumed, we should not update UMA.
1986 if (!RendererIsHidden())
1987 return;
1988 // If this renderer was not kept backgrounded for 5/10/15 minutes,
1989 // we should not record current memory usage.
1990 if (foregrounded_count != process_foregrounded_count_)
1991 return;
1992
1993 RendererMemoryMetrics memory_metrics;
1994 if (!GetRendererMemoryMetrics(&memory_metrics))
1995 return;
1996 RecordMemoryUsageAfterBackgroundedMB(
1997 "Memory.Experimental.Renderer.PartitionAlloc.AfterBackgrounded", suffix,
1998 memory_metrics.partition_alloc_kb / 1024);
1999 RecordMemoryUsageAfterBackgroundedMB(
2000 "Memory.Experimental.Renderer.BlinkGC.AfterBackgrounded", suffix,
2001 memory_metrics.blink_gc_kb / 1024);
2002 RecordMemoryUsageAfterBackgroundedMB(
2003 "Memory.Experimental.Renderer.Malloc.AfterBackgrounded", suffix,
2004 memory_metrics.malloc_mb);
2005 RecordMemoryUsageAfterBackgroundedMB(
2006 "Memory.Experimental.Renderer.Discardable.AfterBackgrounded", suffix,
2007 memory_metrics.discardable_kb / 1024);
2008 RecordMemoryUsageAfterBackgroundedMB(
2009 "Memory.Experimental.Renderer.V8MainThreaIsolate.AfterBackgrounded",
2010 suffix, memory_metrics.v8_main_thread_isolate_mb);
2011 RecordMemoryUsageAfterBackgroundedMB(
2012 "Memory.Experimental.Renderer.TotalAllocated.AfterBackgrounded", suffix,
2013 memory_metrics.total_allocated_mb);
2014}
2015
tasak72f64042017-01-19 14:02:532016#define GET_MEMORY_GROWTH(current, previous, allocator) \
2017 (current.allocator > previous.allocator \
2018 ? current.allocator - previous.allocator \
2019 : 0)
2020
tasaka27961a2017-05-24 07:33:252021static void RecordPurgeAndSuspendMemoryGrowthKB(const char* basename,
2022 const char* suffix,
2023 int memory_usage) {
2024 std::string histogram_name = base::StringPrintf("%s.%s", basename, suffix);
2025 base::UmaHistogramMemoryKB(histogram_name, memory_usage);
2026}
tasakbb0640b2017-05-15 09:02:262027
2028void RenderThreadImpl::RecordPurgeAndSuspendMemoryGrowthMetrics(
2029 const char* suffix,
2030 int foregrounded_count_when_purged) {
tasak72f64042017-01-19 14:02:532031 // If this renderer is resumed, we should not update UMA.
2032 if (!RendererIsHidden())
2033 return;
tasakbb0640b2017-05-15 09:02:262034 if (foregrounded_count_when_purged != process_foregrounded_count_)
2035 return;
tasak72f64042017-01-19 14:02:532036
2037 RendererMemoryMetrics memory_metrics;
bashia0ba0d42017-04-03 08:11:062038 if (!GetRendererMemoryMetrics(&memory_metrics))
2039 return;
2040
tasaka27961a2017-05-24 07:33:252041 RecordPurgeAndSuspendMemoryGrowthKB(
tasakbb0640b2017-05-15 09:02:262042 "PurgeAndSuspend.Experimental.MemoryGrowth.PartitionAllocKB", suffix,
tasak72f64042017-01-19 14:02:532043 GET_MEMORY_GROWTH(memory_metrics, purge_and_suspend_memory_metrics_,
2044 partition_alloc_kb));
tasaka27961a2017-05-24 07:33:252045 RecordPurgeAndSuspendMemoryGrowthKB(
tasakbb0640b2017-05-15 09:02:262046 "PurgeAndSuspend.Experimental.MemoryGrowth.BlinkGCKB", suffix,
tasak72f64042017-01-19 14:02:532047 GET_MEMORY_GROWTH(memory_metrics, purge_and_suspend_memory_metrics_,
2048 blink_gc_kb));
tasaka27961a2017-05-24 07:33:252049 RecordPurgeAndSuspendMemoryGrowthKB(
tasakbb0640b2017-05-15 09:02:262050 "PurgeAndSuspend.Experimental.MemoryGrowth.MallocKB", suffix,
tasak72f64042017-01-19 14:02:532051 GET_MEMORY_GROWTH(memory_metrics, purge_and_suspend_memory_metrics_,
tasakbb0640b2017-05-15 09:02:262052 malloc_mb) *
2053 1024);
tasaka27961a2017-05-24 07:33:252054 RecordPurgeAndSuspendMemoryGrowthKB(
tasakbb0640b2017-05-15 09:02:262055 "PurgeAndSuspend.Experimental.MemoryGrowth.DiscardableKB", suffix,
tasak72f64042017-01-19 14:02:532056 GET_MEMORY_GROWTH(memory_metrics, purge_and_suspend_memory_metrics_,
2057 discardable_kb));
tasaka27961a2017-05-24 07:33:252058 RecordPurgeAndSuspendMemoryGrowthKB(
tasakbb0640b2017-05-15 09:02:262059 "PurgeAndSuspend.Experimental.MemoryGrowth.V8MainThreadIsolateKB", suffix,
tasak72f64042017-01-19 14:02:532060 GET_MEMORY_GROWTH(memory_metrics, purge_and_suspend_memory_metrics_,
tasakbb0640b2017-05-15 09:02:262061 v8_main_thread_isolate_mb) *
2062 1024);
tasaka27961a2017-05-24 07:33:252063 RecordPurgeAndSuspendMemoryGrowthKB(
tasakbb0640b2017-05-15 09:02:262064 "PurgeAndSuspend.Experimental.MemoryGrowth.TotalAllocatedKB", suffix,
tasak72f64042017-01-19 14:02:532065 GET_MEMORY_GROWTH(memory_metrics, purge_and_suspend_memory_metrics_,
tasakbb0640b2017-05-15 09:02:262066 total_allocated_mb) *
2067 1024);
jdduke73220f02015-09-04 17:03:512068}
2069
danakjab9ef4d2017-10-31 23:38:332070void RenderThreadImpl::CompositingModeFallbackToSoftware() {
Antoine Labour7fcbc782017-11-14 16:59:582071 gpu_->LoseChannel();
danakjab9ef4d2017-10-31 23:38:332072 is_gpu_compositing_disabled_ = true;
2073}
2074
Bo Liud1ef1c32017-12-08 06:15:502075scoped_refptr<gpu::GpuChannelHost> RenderThreadImpl::EstablishGpuChannelSync() {
[email protected]d13f35d2012-05-18 02:28:152076 TRACE_EVENT0("gpu", "RenderThreadImpl::EstablishGpuChannelSync");
2077
Antoine Labour7fcbc782017-11-14 16:59:582078 scoped_refptr<gpu::GpuChannelHost> gpu_channel =
Bo Liud1ef1c32017-12-08 06:15:502079 gpu_->EstablishGpuChannelSync();
Antoine Labour7fcbc782017-11-14 16:59:582080 if (gpu_channel)
2081 GetContentClient()->SetGpuInfo(gpu_channel->gpu_info());
2082 return gpu_channel;
[email protected]3bf4d532010-03-27 00:23:342083}
2084
danakjc7afae52017-06-20 21:12:412085void RenderThreadImpl::RequestNewLayerTreeFrameSink(
danakj83066a32016-06-21 02:34:492086 int routing_id,
2087 scoped_refptr<FrameSwapMessageQueue> frame_swap_message_queue,
fsamuelcf3002e2017-03-20 23:13:472088 const GURL& url,
danakjc7afae52017-06-20 21:12:412089 const LayerTreeFrameSinkCallback& callback) {
danakj946e3172017-11-06 23:46:512090 // Misconfigured bots (eg. crbug.com/780757) could run layout tests on a
2091 // machine where gpu compositing doesn't work. Don't crash in that case.
2092 if (layout_test_mode() && is_gpu_compositing_disabled_) {
2093 LOG(FATAL) << "Layout tests require gpu compositing, but it is disabled.";
2094 return;
2095 }
2096
danakj83066a32016-06-21 02:34:492097 const base::CommandLine& command_line =
2098 *base::CommandLine::ForCurrentProcess();
Xu Xing48e1b322017-09-25 10:48:012099 viz::ClientLayerTreeFrameSink::InitParams params;
Sunny Sachanandani158d26d2017-12-12 19:44:102100 params.compositor_task_runner = compositor_task_runner_;
Xu Xing48e1b322017-09-25 10:48:012101 params.enable_surface_synchronization =
Fady Samuel343a74952017-11-30 14:19:202102 features::IsSurfaceSynchronizationEnabled();
Xu Xing48e1b322017-09-25 10:48:012103 params.local_surface_id_provider =
Jeremy Roman04f27c372017-10-27 15:20:552104 std::make_unique<RendererLocalSurfaceIdProvider>();
Ria Jiang4bbc6182018-02-12 19:02:192105 if (features::IsVizHitTestingDrawQuadEnabled()) {
Gary Klassen2c346fb2018-02-07 18:08:402106 params.hit_test_data_provider =
Ria Jiang28051112018-02-13 16:38:522107 std::make_unique<viz::HitTestDataProviderDrawQuad>(
2108 true /* should_ask_for_child_region */);
Gary Klassen2c346fb2018-02-07 18:08:402109 }
Fady Samuel0c4b4bf2017-08-22 00:06:462110
Eric Seckler8af8c0e52018-01-17 23:45:532111 // The renderer runs animations and layout for animate_only BeginFrames.
2112 params.wants_animate_only_begin_frames = true;
2113
samans09812d32017-03-27 19:51:502114 // In disable gpu vsync mode, also let the renderer tick as fast as it
2115 // can. The top level begin frame source will also be running as a back
2116 // to back begin frame source, but using a synthetic begin frame source
2117 // here reduces latency when in this mode (at least for frames
2118 // starting--it potentially increases it for input on the other hand.)
samans09812d32017-03-27 19:51:502119 if (command_line.HasSwitch(switches::kDisableGpuVsync) &&
2120 command_line.GetSwitchValueASCII(switches::kDisableGpuVsync) != "gpu") {
Xu Xing48e1b322017-09-25 10:48:012121 params.synthetic_begin_frame_source = CreateSyntheticBeginFrameSource();
samans09812d32017-03-27 19:51:502122 }
2123
sadrul943e3b32016-08-04 18:22:592124#if defined(USE_AURA)
Sadrul Habib Chowdhuryeeb5a942017-11-28 21:17:232125 if (switches::IsMusHostingViz()) {
Scott Violet986ac472017-08-10 16:38:342126 if (!RendererWindowTreeClient::Get(routing_id)) {
2127 callback.Run(nullptr);
2128 return;
2129 }
Bo Liud1ef1c32017-12-08 06:15:502130 scoped_refptr<gpu::GpuChannelHost> channel = EstablishGpuChannelSync();
sadrulbe22c4f2017-03-14 06:59:252131 // If the channel could not be established correctly, then return null. This
2132 // would cause the compositor to wait and try again at a later time.
fsamuelcf3002e2017-03-20 23:13:472133 if (!channel) {
2134 callback.Run(nullptr);
2135 return;
2136 }
fsamuel95c974eb2017-03-22 10:00:252137 RendererWindowTreeClient::Get(routing_id)
danakjc7afae52017-06-20 21:12:412138 ->RequestLayerTreeFrameSink(
fsamuel95c974eb2017-03-22 10:00:252139 gpu_->CreateContextProvider(std::move(channel)),
2140 GetGpuMemoryBufferManager(), callback);
fsamuelcf3002e2017-03-20 23:13:472141 return;
danakj83066a32016-06-21 02:34:492142 }
2143#endif
2144
Gary Klassen4d0f0232017-07-27 23:23:122145 viz::mojom::CompositorFrameSinkRequest sink_request =
kylecharb82991b2017-10-04 22:40:082146 mojo::MakeRequest(&params.pipes.compositor_frame_sink_info);
Gary Klassen4d0f0232017-07-27 23:23:122147 viz::mojom::CompositorFrameSinkClientPtr client;
kylecharb82991b2017-10-04 22:40:082148 params.pipes.client_request = mojo::MakeRequest(&client);
samansa61ab212017-05-24 12:11:432149
danakj83066a32016-06-21 02:34:492150 if (command_line.HasSwitch(switches::kEnableVulkan)) {
Alex Zhang1f159572017-08-23 20:14:202151 scoped_refptr<viz::VulkanContextProvider> vulkan_context_provider =
2152 viz::VulkanInProcessContextProvider::Create();
danakj83066a32016-06-21 02:34:492153 if (vulkan_context_provider) {
2154 DCHECK(!layout_test_mode());
samansa61ab212017-05-24 12:11:432155 frame_sink_provider_->CreateForWidget(routing_id, std::move(sink_request),
2156 std::move(client));
Jeremy Roman04f27c372017-10-27 15:20:552157 callback.Run(std::make_unique<viz::ClientLayerTreeFrameSink>(
Xu Xing48e1b322017-09-25 10:48:012158 std::move(vulkan_context_provider), &params));
fsamuelcf3002e2017-03-20 23:13:472159 return;
danakj83066a32016-06-21 02:34:492160 }
2161 }
2162
danakjab9ef4d2017-10-31 23:38:332163 if (is_gpu_compositing_disabled_) {
danakj83066a32016-06-21 02:34:492164 DCHECK(!layout_test_mode());
samansa61ab212017-05-24 12:11:432165 frame_sink_provider_->CreateForWidget(routing_id, std::move(sink_request),
2166 std::move(client));
Xu Xing48e1b322017-09-25 10:48:012167 params.shared_bitmap_manager = shared_bitmap_manager();
Jeremy Roman04f27c372017-10-27 15:20:552168 callback.Run(std::make_unique<viz::ClientLayerTreeFrameSink>(
Xu Xing48e1b322017-09-25 10:48:012169 nullptr, nullptr, &params));
fsamuelcf3002e2017-03-20 23:13:472170 return;
danakj83066a32016-06-21 02:34:492171 }
2172
danakjab9ef4d2017-10-31 23:38:332173 scoped_refptr<gpu::GpuChannelHost> gpu_channel_host =
Bo Liud1ef1c32017-12-08 06:15:502174 EstablishGpuChannelSync();
danakjab9ef4d2017-10-31 23:38:332175 if (!gpu_channel_host) {
2176 // Wait and try again. We may hear that the compositing mode has switched
2177 // to software in the meantime.
2178 callback.Run(nullptr);
2179 return;
2180 }
2181
Victor Miuraff6488612017-12-21 04:16:152182 scoped_refptr<viz::RasterContextProvider> worker_context_provider =
danakj83066a32016-06-21 02:34:492183 SharedCompositorWorkerContextProvider();
2184 if (!worker_context_provider) {
2185 // Cause the compositor to wait and try again.
fsamuelcf3002e2017-03-20 23:13:472186 callback.Run(nullptr);
2187 return;
danakj83066a32016-06-21 02:34:492188 }
2189
2190 // The renderer compositor context doesn't do a lot of stuff, so we don't
2191 // expect it to need a lot of space for commands or transfer. Raster and
2192 // uploads happen on the worker context instead.
2193 gpu::SharedMemoryLimits limits = gpu::SharedMemoryLimits::ForMailboxContext();
2194
2195 // This is for an offscreen context for the compositor. So the default
2196 // framebuffer doesn't need alpha, depth, stencil, antialiasing.
Antoine Labourfeab2392017-12-21 20:28:392197 gpu::ContextCreationAttribs attributes;
danakj83066a32016-06-21 02:34:492198 attributes.alpha_size = -1;
2199 attributes.depth_size = 0;
2200 attributes.stencil_size = 0;
2201 attributes.samples = 0;
2202 attributes.sample_buffers = 0;
2203 attributes.bind_generates_resource = false;
2204 attributes.lose_context_when_out_of_memory = true;
Victor Miura3a4ad4f82017-12-13 06:03:452205 attributes.enable_gles2_interface = true;
2206 attributes.enable_raster_interface = false;
2207 attributes.enable_oop_rasterization = false;
danakj83066a32016-06-21 02:34:492208
2209 constexpr bool automatic_flushes = false;
2210 constexpr bool support_locking = false;
2211
sadrul85cc5d82016-12-20 03:37:412212 scoped_refptr<ui::ContextProviderCommandBuffer> context_provider(
2213 new ui::ContextProviderCommandBuffer(
Antoine Labour5ac65db2017-12-19 18:02:582214 gpu_channel_host, GetGpuMemoryBufferManager(), kGpuStreamIdDefault,
2215 kGpuStreamPriorityDefault, gpu::kNullSurfaceHandle, url,
Victor Miuraff6488612017-12-21 04:16:152216 automatic_flushes, support_locking, limits, attributes,
2217 nullptr /* share_context */,
sadrul85cc5d82016-12-20 03:37:412218 ui::command_buffer_metrics::RENDER_COMPOSITOR_CONTEXT));
danakj83066a32016-06-21 02:34:492219
danakj83066a32016-06-21 02:34:492220 if (layout_test_deps_) {
danakjc7afae52017-06-20 21:12:412221 callback.Run(layout_test_deps_->CreateLayerTreeFrameSink(
jbroman6ccbc7d472016-07-27 04:45:412222 routing_id, std::move(gpu_channel_host), std::move(context_provider),
fsamuelcf3002e2017-03-20 23:13:472223 std::move(worker_context_provider), GetGpuMemoryBufferManager(), this));
2224 return;
danakj83066a32016-06-21 02:34:492225 }
2226
2227#if defined(OS_ANDROID)
2228 if (sync_compositor_message_filter_) {
Jeremy Roman04f27c372017-10-27 15:20:552229 callback.Run(std::make_unique<SynchronousLayerTreeFrameSink>(
danakja40dd4482016-06-28 01:14:102230 std::move(context_provider), std::move(worker_context_provider),
danakja2b002952017-12-14 22:36:222231 compositor_task_runner_, GetGpuMemoryBufferManager(), routing_id,
Dave Tapuska9732f002018-01-20 01:35:462232 g_next_layer_tree_frame_sink_id++,
2233 std::move(params.synthetic_begin_frame_source),
danakja2b002952017-12-14 22:36:222234 sync_compositor_message_filter_.get(),
fsamuelcf3002e2017-03-20 23:13:472235 std::move(frame_swap_message_queue)));
2236 return;
danakj83066a32016-06-21 02:34:492237 }
2238#endif
samansa61ab212017-05-24 12:11:432239 frame_sink_provider_->CreateForWidget(routing_id, std::move(sink_request),
2240 std::move(client));
Xu Xing48e1b322017-09-25 10:48:012241 params.gpu_memory_buffer_manager = GetGpuMemoryBufferManager();
Jeremy Roman04f27c372017-10-27 15:20:552242 callback.Run(std::make_unique<viz::ClientLayerTreeFrameSink>(
samans2040988b2017-04-11 23:58:352243 std::move(context_provider), std::move(worker_context_provider),
Xu Xing48e1b322017-09-25 10:48:012244 &params));
danakj83066a32016-06-21 02:34:492245}
2246
Sam McNally52e50282017-11-29 00:54:022247blink::AssociatedInterfaceRegistry*
rockot067ca55f2016-09-30 22:00:152248RenderThreadImpl::GetAssociatedInterfaceRegistry() {
2249 return &associated_interfaces_;
2250}
2251
jbroman6ccbc7d472016-07-27 04:45:412252std::unique_ptr<cc::SwapPromise>
2253RenderThreadImpl::RequestCopyOfOutputForLayoutTest(
2254 int32_t routing_id,
Fady Samueldfecb7d2017-07-26 11:41:042255 std::unique_ptr<viz::CopyOutputRequest> request) {
jbroman6ccbc7d472016-07-27 04:45:412256 DCHECK(layout_test_deps_);
2257 return layout_test_deps_->RequestCopyOfOutput(routing_id, std::move(request));
2258}
2259
altimineb6bd1962017-05-03 14:52:382260std::unique_ptr<blink::WebMediaStreamCenter>
2261RenderThreadImpl::CreateMediaStreamCenter(
[email protected]180ef242013-11-07 06:50:462262 blink::WebMediaStreamCenterClient* client) {
altimineb6bd1962017-05-03 14:52:382263 std::unique_ptr<blink::WebMediaStreamCenter> media_stream_center;
Brett Wilson0748bf412016-11-22 17:55:462264#if BUILDFLAG(ENABLE_WEBRTC)
altimineb6bd1962017-05-03 14:52:382265 if (!media_stream_center) {
Harald Alvestrand4931caa2017-11-08 16:53:352266 media_stream_center = std::make_unique<MediaStreamCenter>(
2267 client, GetPeerConnectionDependencyFactory());
[email protected]68e5fee2013-02-18 10:04:222268 }
[email protected]d8cd8372012-03-09 10:49:512269#endif
altimineb6bd1962017-05-03 14:52:382270 return media_stream_center;
[email protected]d8cd8372012-03-09 10:49:512271}
2272
Brett Wilson0748bf412016-11-22 17:55:462273#if BUILDFLAG(ENABLE_WEBRTC)
[email protected]0107d8a2014-05-16 10:20:342274PeerConnectionDependencyFactory*
2275RenderThreadImpl::GetPeerConnectionDependencyFactory() {
[email protected]83e0a482014-05-22 18:07:182276 return peer_connection_factory_.get();
[email protected]6ee10bd2012-09-13 09:01:532277}
[email protected]22fe91d2014-08-12 17:07:122278#endif
[email protected]6ee10bd2012-09-13 09:01:532279
rockot1587e332016-07-27 17:44:142280mojom::RenderFrameMessageFilter*
2281RenderThreadImpl::render_frame_message_filter() {
2282 if (!render_frame_message_filter_)
2283 GetChannel()->GetRemoteAssociatedInterface(&render_frame_message_filter_);
2284 return render_frame_message_filter_.get();
2285}
2286
rockote261d2112016-09-21 22:22:232287mojom::RenderMessageFilter* RenderThreadImpl::render_message_filter() {
2288 if (!render_message_filter_)
2289 GetChannel()->GetRemoteAssociatedInterface(&render_message_filter_);
2290 return render_message_filter_.get();
2291}
2292
penghuang346a46f92016-03-31 21:37:522293gpu::GpuChannelHost* RenderThreadImpl::GetGpuChannel() {
Antoine Labour7fcbc782017-11-14 16:59:582294 return gpu_->GetGpuChannel().get();
[email protected]6217d392010-03-25 22:08:352295}
2296
Ben Goodger16331302018-01-23 00:43:212297void RenderThreadImpl::CreateEmbedderRendererService(
2298 service_manager::mojom::ServiceRequest service_request) {
2299 GetContentClient()->renderer()->CreateRendererService(
2300 std::move(service_request));
2301}
2302
rockot067ca55f2016-09-30 22:00:152303void RenderThreadImpl::CreateView(mojom::CreateViewParamsPtr params) {
2304 CompositorDependencies* compositor_deps = this;
wjmaclean1d970622017-01-21 22:28:242305 is_scroll_animator_enabled_ = params->web_preferences.enable_scroll_animator;
rockot067ca55f2016-09-30 22:00:152306 // When bringing in render_view, also bring in webkit's glue and jsbindings.
Balazs Engedyba034e72017-10-27 22:26:282307 RenderViewImpl::Create(compositor_deps, std::move(params),
Hajime Hoshiabb3c8f2017-12-04 18:41:392308 RenderWidget::ShowCallback(),
2309 GetRendererScheduler()->DefaultTaskRunner());
rockot067ca55f2016-09-30 22:00:152310}
2311
rockot53be7caf2016-10-04 20:17:082312void RenderThreadImpl::CreateFrame(mojom::CreateFrameParamsPtr params) {
rockot53be7caf2016-10-04 20:17:082313 CompositorDependencies* compositor_deps = this;
Ken Rockot26efbd62017-11-16 04:39:492314 service_manager::mojom::InterfaceProviderPtr interface_provider(
2315 std::move(params->interface_provider));
rockot53be7caf2016-10-04 20:17:082316 RenderFrameImpl::CreateFrame(
Ken Rockot26efbd62017-11-16 04:39:492317 params->routing_id, std::move(interface_provider),
Balazs Engedyba034e72017-10-27 22:26:282318 params->proxy_routing_id, params->opener_routing_id,
rockot53be7caf2016-10-04 20:17:082319 params->parent_routing_id, params->previous_sibling_routing_id,
Pavel Feldman25234722017-10-11 02:49:062320 params->devtools_frame_token, params->replication_state, compositor_deps,
Daniel Chenge0555e192018-01-18 20:00:052321 *params->widget_params, params->frame_owner_properties,
2322 params->has_committed_real_load);
rockot53be7caf2016-10-04 20:17:082323}
2324
Makoto Shimazu7af43ee2017-08-25 10:20:402325void RenderThreadImpl::SetUpEmbeddedWorkerChannelForServiceWorker(
2326 mojom::EmbeddedWorkerInstanceClientAssociatedRequest client_request) {
2327 EmbeddedWorkerInstanceClientImpl::Create(
2328 blink_initialized_time_, GetIOTaskRunner(), std::move(client_request));
2329}
2330
rockot53be7caf2016-10-04 20:17:082331void RenderThreadImpl::CreateFrameProxy(
2332 int32_t routing_id,
2333 int32_t render_view_routing_id,
2334 int32_t opener_routing_id,
2335 int32_t parent_routing_id,
Dmitry Gozman89361212018-02-13 16:10:442336 const FrameReplicationState& replicated_state,
2337 const base::UnguessableToken& devtools_frame_token) {
nick3b5a21f2016-11-22 23:07:112338 RenderFrameProxy::CreateFrameProxy(
2339 routing_id, render_view_routing_id,
2340 RenderFrameImpl::ResolveOpener(opener_routing_id), parent_routing_id,
Dmitry Gozman89361212018-02-13 16:10:442341 replicated_state, devtools_frame_token);
rockot53be7caf2016-10-04 20:17:082342}
2343
rockota2db0da2016-10-18 17:39:112344void RenderThreadImpl::OnNetworkConnectionChanged(
2345 net::NetworkChangeNotifier::ConnectionType type,
2346 double max_bandwidth_mbps) {
2347 bool online = type != net::NetworkChangeNotifier::CONNECTION_NONE;
Blink Reformat1c4d759e2017-04-09 16:34:542348 WebNetworkStateNotifier::SetOnLine(online);
rockota2db0da2016-10-18 17:39:112349 for (auto& observer : observers_)
2350 observer.NetworkStateChanged(online);
Blink Reformat1c4d759e2017-04-09 16:34:542351 WebNetworkStateNotifier::SetWebConnection(
rockota2db0da2016-10-18 17:39:112352 NetConnectionTypeToWebConnectionType(type), max_bandwidth_mbps);
2353}
2354
tbansal15973c32017-05-10 18:40:442355void RenderThreadImpl::OnNetworkQualityChanged(
tbansalb612c5d2017-05-25 18:53:062356 net::EffectiveConnectionType type,
tbansal99d8aeb2017-05-22 19:12:582357 base::TimeDelta http_rtt,
2358 base::TimeDelta transport_rtt,
tbansal15973c32017-05-10 18:40:442359 double downlink_throughput_kbps) {
2360 UMA_HISTOGRAM_BOOLEAN("NQE.RenderThreadNotified", true);
tbansalb612c5d2017-05-25 18:53:062361 WebNetworkStateNotifier::SetNetworkQuality(
2362 EffectiveConnectionTypeToWebEffectiveConnectionType(type), http_rtt,
2363 transport_rtt, downlink_throughput_kbps);
tbansal15973c32017-05-10 18:40:442364}
2365
rockota2db0da2016-10-18 17:39:112366void RenderThreadImpl::SetWebKitSharedTimersSuspended(bool suspend) {
2367#if defined(OS_ANDROID)
2368 if (suspend) {
Alexander Timin4b6152232017-10-17 20:34:062369 renderer_scheduler_->PauseTimersForAndroidWebView();
rockota2db0da2016-10-18 17:39:112370 } else {
Alexander Timin4b6152232017-10-17 20:34:062371 renderer_scheduler_->ResumeTimersForAndroidWebView();
rockota2db0da2016-10-18 17:39:112372 }
Alexander Timin4b6152232017-10-17 20:34:062373 webkit_shared_timer_suspended_ = suspend;
rockota2db0da2016-10-18 17:39:112374#else
2375 NOTREACHED();
2376#endif
2377}
2378
2379void RenderThreadImpl::UpdateScrollbarTheme(
2380 mojom::UpdateScrollbarThemeParamsPtr params) {
2381#if defined(OS_MACOSX)
2382 static_cast<WebScrollbarBehaviorImpl*>(
Blink Reformat1c4d759e2017-04-09 16:34:542383 blink_platform_impl_->ScrollbarBehavior())
rockota2db0da2016-10-18 17:39:112384 ->set_jump_on_track_click(params->jump_on_track_click);
2385
Blink Reformat1c4d759e2017-04-09 16:34:542386 blink::WebScrollbarTheme::UpdateScrollbarsWithNSDefaults(
rockota2db0da2016-10-18 17:39:112387 params->initial_button_delay, params->autoscroll_button_delay,
2388 params->preferred_scroller_style, params->redraw,
2389 params->button_placement);
Greg Kerra7b943b2017-07-24 23:17:172390
2391 is_elastic_overscroll_enabled_ = params->scroll_view_rubber_banding;
rockota2db0da2016-10-18 17:39:112392#else
2393 NOTREACHED();
2394#endif
2395}
2396
2397void RenderThreadImpl::OnSystemColorsChanged(
2398 int32_t aqua_color_variant,
2399 const std::string& highlight_text_color,
2400 const std::string& highlight_color) {
2401#if defined(OS_MACOSX)
2402 SystemColorsDidChange(aqua_color_variant, highlight_text_color,
2403 highlight_color);
2404#else
2405 NOTREACHED();
2406#endif
2407}
2408
2409void RenderThreadImpl::PurgePluginListCache(bool reload_pages) {
brettw4b461082016-11-19 18:55:162410#if BUILDFLAG(ENABLE_PLUGINS)
rockota2db0da2016-10-18 17:39:112411 // The call below will cause a GetPlugins call with refresh=true, but at this
2412 // point we already know that the browser has refreshed its list, so disable
2413 // refresh temporarily to prevent each renderer process causing the list to be
2414 // regenerated.
2415 blink_platform_impl_->set_plugin_refresh_allowed(false);
Blink Reformat1c4d759e2017-04-09 16:34:542416 blink::ResetPluginCache(reload_pages);
rockota2db0da2016-10-18 17:39:112417 blink_platform_impl_->set_plugin_refresh_allowed(true);
2418
2419 for (auto& observer : observers_)
2420 observer.PluginListChanged();
2421#else
2422 NOTREACHED();
2423#endif
2424}
2425
[email protected]5071cb22013-07-10 02:19:062426void RenderThreadImpl::OnMemoryPressure(
2427 base::MemoryPressureListener::MemoryPressureLevel memory_pressure_level) {
kylecharb82991b2017-10-04 22:40:082428 TRACE_EVENT0("memory", "RenderThreadImpl::OnMemoryPressure");
rmcilroy7fbb3bd52015-02-17 19:02:142429 if (blink_platform_impl_) {
Blink Reformat1c4d759e2017-04-09 16:34:542430 blink::WebMemoryCoordinator::OnMemoryPressure(
bashic577bfc2016-01-08 03:42:352431 static_cast<blink::WebMemoryPressureLevel>(memory_pressure_level));
hajimehoshi7bb39582016-10-12 04:30:572432 }
2433 if (memory_pressure_level ==
2434 base::MemoryPressureListener::MEMORY_PRESSURE_LEVEL_CRITICAL) {
2435 ReleaseFreeMemory();
2436 ClearMemory();
2437 }
2438}
rmcilroyab967c972015-02-17 23:15:002439
hajimehoshi7bb39582016-10-12 04:30:572440void RenderThreadImpl::OnMemoryStateChange(base::MemoryState state) {
hajimehoshi7bb39582016-10-12 04:30:572441 if (blink_platform_impl_) {
Blink Reformat1c4d759e2017-04-09 16:34:542442 blink::WebMemoryCoordinator::OnMemoryStateChange(
hajimehoshi7bb39582016-10-12 04:30:572443 static_cast<blink::MemoryState>(state));
2444 }
bashi233f65e2017-02-09 08:36:032445}
2446
2447void RenderThreadImpl::OnPurgeMemory() {
bashib9058f282017-03-30 01:55:242448 // Record amount of purged memory after 2 seconds. 2 seconds is arbitrary
2449 // but it works most cases.
2450 RendererMemoryMetrics metrics;
bashia0ba0d42017-04-03 08:11:062451 if (!GetRendererMemoryMetrics(&metrics))
2452 return;
2453
bashib9058f282017-03-30 01:55:242454 GetRendererScheduler()->DefaultTaskRunner()->PostDelayedTask(
2455 FROM_HERE,
tzikff2a81a2017-09-15 05:10:062456 base::BindOnce(&RenderThreadImpl::RecordPurgeMemory,
2457 base::Unretained(this), std::move(metrics)),
bashib9058f282017-03-30 01:55:242458 base::TimeDelta::FromSeconds(2));
2459
bashi233f65e2017-02-09 08:36:032460 OnTrimMemoryImmediately();
2461 ReleaseFreeMemory();
2462 ClearMemory();
2463 if (blink_platform_impl_)
Blink Reformat1c4d759e2017-04-09 16:34:542464 blink::WebMemoryCoordinator::OnPurgeMemory();
hajimehoshi7bb39582016-10-12 04:30:572465}
2466
bashib9058f282017-03-30 01:55:242467void RenderThreadImpl::RecordPurgeMemory(RendererMemoryMetrics before) {
2468 RendererMemoryMetrics after;
bashia0ba0d42017-04-03 08:11:062469 if (!GetRendererMemoryMetrics(&after))
2470 return;
bashib9058f282017-03-30 01:55:242471 int64_t mbytes = static_cast<int64_t>(before.total_allocated_mb) -
2472 static_cast<int64_t>(after.total_allocated_mb);
2473 if (mbytes < 0)
2474 mbytes = 0;
2475 UMA_HISTOGRAM_MEMORY_LARGE_MB("Memory.Experimental.Renderer.PurgedMemory",
2476 mbytes);
2477}
2478
hajimehoshi7bb39582016-10-12 04:30:572479void RenderThreadImpl::ClearMemory() {
2480 // Do not call into blink if it is not initialized.
2481 if (blink_platform_impl_) {
2482 // Purge Skia font cache, by setting it to 0 and then again to the
2483 // previous limit.
2484 size_t font_cache_limit = SkGraphics::SetFontCacheLimit(0);
2485 SkGraphics::SetFontCacheLimit(font_cache_limit);
rmcilroy7fbb3bd52015-02-17 19:02:142486 }
[email protected]5071cb22013-07-10 02:19:062487}
2488
Marijn Kruisselbrink8c276412017-07-29 06:11:212489scoped_refptr<base::TaskRunner> RenderThreadImpl::GetFileThreadTaskRunner() {
2490 return blink_platform_impl_->BaseFileTaskRunner();
[email protected]c6a7b862010-08-20 22:19:382491}
[email protected]e9ff79c2012-10-19 21:31:262492
acolwellb4034942014-08-28 15:42:432493scoped_refptr<base::SingleThreadTaskRunner>
2494RenderThreadImpl::GetMediaThreadTaskRunner() {
fdoraye94d8642016-07-07 19:19:012495 DCHECK(message_loop()->task_runner()->BelongsToCurrentThread());
[email protected]c1330c82013-06-06 02:23:252496 if (!media_thread_) {
2497 media_thread_.reset(new base::Thread("Media"));
2498 media_thread_->Start();
2499 }
skyostil2d3b5bd2015-05-27 15:40:592500 return media_thread_->task_runner();
[email protected]c1330c82013-06-06 02:23:252501}
2502
dcastagna4517a182015-08-05 19:51:032503base::TaskRunner* RenderThreadImpl::GetWorkerTaskRunner() {
prashant.nfad657e2016-06-01 07:52:172504 return categorized_worker_pool_.get();
dcastagnab880e8f2015-06-30 20:16:062505}
2506
Victor Miuraff6488612017-12-21 04:16:152507scoped_refptr<viz::RasterContextProvider>
danakj0b4b94e32016-05-10 22:33:012508RenderThreadImpl::SharedCompositorWorkerContextProvider() {
revemand180dfc32015-09-24 00:19:432509 DCHECK(IsMainThread());
2510 // Try to reuse existing shared worker context provider.
revemand180dfc32015-09-24 00:19:432511 if (shared_worker_context_provider_) {
2512 // Note: If context is lost, delete reference after releasing the lock.
Victor Miura29b7ea3d2017-12-19 20:23:592513 viz::RasterContextProvider::ScopedRasterContextLock lock(
boliu11afa7e2016-04-18 18:04:142514 shared_worker_context_provider_.get());
Victor Miura29b7ea3d2017-12-19 20:23:592515 if (lock.RasterInterface()->GetGraphicsResetStatusKHR() == GL_NO_ERROR)
danakje8ec797e2016-04-19 04:08:432516 return shared_worker_context_provider_;
revemand180dfc32015-09-24 00:19:432517 }
danakje8ec797e2016-04-19 04:08:432518
sadrul6d310fa2016-08-04 02:12:162519 scoped_refptr<gpu::GpuChannelHost> gpu_channel_host(
2520 EstablishGpuChannelSync());
danakje8ec797e2016-04-19 04:08:432521 if (!gpu_channel_host) {
2522 shared_worker_context_provider_ = nullptr;
2523 return shared_worker_context_provider_;
revemand180dfc32015-09-24 00:19:432524 }
danakje8ec797e2016-04-19 04:08:432525
danakj9a04adc2016-05-16 22:45:072526 bool support_locking = true;
Adrienne Walker436a7752017-08-28 23:33:092527 bool support_oop_rasterization =
2528 base::CommandLine::ForCurrentProcess()->HasSwitch(
2529 switches::kEnableOOPRasterization);
Victor Miura589575e2018-02-14 21:37:542530 bool support_gles2_interface = !support_oop_rasterization;
Victor Miura3a4ad4f82017-12-13 06:03:452531 bool support_raster_interface = true;
danakj0dd9e1e2016-05-11 22:15:092532 shared_worker_context_provider_ = CreateOffscreenContext(
Antoine Labour5ac65db2017-12-19 18:02:582533 std::move(gpu_channel_host), GetGpuMemoryBufferManager(),
2534 gpu::SharedMemoryLimits(), support_locking, support_gles2_interface,
2535 support_raster_interface, support_oop_rasterization,
Victor Miuraff6488612017-12-21 04:16:152536 ui::command_buffer_metrics::RENDER_WORKER_CONTEXT, kGpuStreamIdWorker,
2537 kGpuStreamPriorityWorker);
danakj45cfd232017-10-18 19:31:312538 auto result = shared_worker_context_provider_->BindToCurrentThread();
2539 if (result != gpu::ContextResult::kSuccess)
danakje8ec797e2016-04-19 04:08:432540 shared_worker_context_provider_ = nullptr;
revemand180dfc32015-09-24 00:19:432541 return shared_worker_context_provider_;
2542}
2543
juncai2f298a82017-04-18 03:51:392544void RenderThreadImpl::SampleGamepads(device::Gamepads* data) {
Blink Reformat1c4d759e2017-04-09 16:34:542545 blink_platform_impl_->SampleGamepads(*data);
[email protected]0ff736562014-05-09 09:09:472546}
2547
rmcilroyaa296052015-04-14 15:35:272548bool RenderThreadImpl::RendererIsHidden() const {
2549 return widget_count_ > 0 && hidden_widget_count_ == widget_count_;
2550}
2551
[email protected]b2db9272014-01-10 17:42:002552void RenderThreadImpl::WidgetCreated() {
rmcilroyaa296052015-04-14 15:35:272553 bool renderer_was_hidden = RendererIsHidden();
[email protected]b2db9272014-01-10 17:42:002554 widget_count_++;
rmcilroyaa296052015-04-14 15:35:272555 if (renderer_was_hidden)
2556 OnRendererVisible();
[email protected]b2db9272014-01-10 17:42:002557}
2558
2559void RenderThreadImpl::WidgetDestroyed() {
rmcilroyaa296052015-04-14 15:35:272560 // TODO(rmcilroy): Remove the restriction that destroyed widgets must be
2561 // unhidden before WidgetDestroyed is called.
2562 DCHECK_GT(widget_count_, 0);
2563 DCHECK_GT(widget_count_, hidden_widget_count_);
[email protected]b2db9272014-01-10 17:42:002564 widget_count_--;
rmcilroyaa296052015-04-14 15:35:272565 if (RendererIsHidden())
2566 OnRendererHidden();
[email protected]b2db9272014-01-10 17:42:002567}
2568
2569void RenderThreadImpl::WidgetHidden() {
2570 DCHECK_LT(hidden_widget_count_, widget_count_);
2571 hidden_widget_count_++;
rmcilroyaa296052015-04-14 15:35:272572 if (RendererIsHidden())
2573 OnRendererHidden();
[email protected]b2db9272014-01-10 17:42:002574}
2575
2576void RenderThreadImpl::WidgetRestored() {
rmcilroyaa296052015-04-14 15:35:272577 bool renderer_was_hidden = RendererIsHidden();
[email protected]b2db9272014-01-10 17:42:002578 DCHECK_GT(hidden_widget_count_, 0);
2579 hidden_widget_count_--;
rmcilroyaa296052015-04-14 15:35:272580 if (renderer_was_hidden)
2581 OnRendererVisible();
2582}
[email protected]b2db9272014-01-10 17:42:002583
rmcilroyaa296052015-04-14 15:35:272584void RenderThreadImpl::OnRendererHidden() {
Blink Reformat1c4d759e2017-04-09 16:34:542585 blink::MainThreadIsolate()->IsolateInBackgroundNotification();
rmcilroyaa296052015-04-14 15:35:272586 // TODO(rmcilroy): Remove IdleHandler and replace it with an IdleTask
2587 // scheduled by the RendererScheduler - http://crbug.com/469210.
ulan4a385192015-11-11 10:59:182588 if (!GetContentClient()->renderer()->RunIdleHandlerWhenWidgetsHidden())
2589 return;
Alexander Timin771b3372017-06-15 13:26:472590 renderer_scheduler_->SetRendererHidden(true);
ulan4a385192015-11-11 10:59:182591 ScheduleIdleHandler(kInitialIdleHandlerDelayMs);
rmcilroyaa296052015-04-14 15:35:272592}
2593
2594void RenderThreadImpl::OnRendererVisible() {
Blink Reformat1c4d759e2017-04-09 16:34:542595 blink::MainThreadIsolate()->IsolateInForegroundNotification();
rmcilroyaa296052015-04-14 15:35:272596 if (!GetContentClient()->renderer()->RunIdleHandlerWhenWidgetsHidden())
[email protected]b2db9272014-01-10 17:42:002597 return;
Alexander Timin771b3372017-06-15 13:26:472598 renderer_scheduler_->SetRendererHidden(false);
[email protected]b2db9272014-01-10 17:42:002599 ScheduleIdleHandler(kLongIdleHandlerDelayMs);
2600}
2601
ssid0603ca9f2015-06-09 16:48:082602void RenderThreadImpl::ReleaseFreeMemory() {
2603 base::allocator::ReleaseFreeMemory();
penghuang342762b2016-12-02 21:04:582604 discardable_shared_memory_manager_->ReleaseFreeMemory();
ssid0603ca9f2015-06-09 16:48:082605
2606 if (blink_platform_impl_)
Blink Reformat1c4d759e2017-04-09 16:34:542607 blink::DecommitFreeableMemory();
ssid0603ca9f2015-06-09 16:48:082608}
2609
ben76f52b242016-06-18 05:42:482610RenderThreadImpl::PendingFrameCreate::PendingFrameCreate(
benf28ce882017-05-02 16:15:492611 const service_manager::BindSourceInfo& browser_info,
rockotf8fdd9b2015-12-16 22:22:352612 int routing_id,
Balazs Engedyba034e72017-10-27 22:26:282613 mojom::FrameRequest frame_request)
benf28ce882017-05-02 16:15:492614 : browser_info_(browser_info),
2615 routing_id_(routing_id),
Balazs Engedyba034e72017-10-27 22:26:282616 frame_request_(std::move(frame_request)) {}
rockotf8fdd9b2015-12-16 22:22:352617
ben76f52b242016-06-18 05:42:482618RenderThreadImpl::PendingFrameCreate::~PendingFrameCreate() {
rockotf8fdd9b2015-12-16 22:22:352619}
2620
ben76f52b242016-06-18 05:42:482621void RenderThreadImpl::PendingFrameCreate::OnConnectionError() {
rockotf8fdd9b2015-12-16 22:22:352622 size_t erased =
ben76f52b242016-06-18 05:42:482623 RenderThreadImpl::current()->pending_frame_creates_.erase(routing_id_);
rockotf8fdd9b2015-12-16 22:22:352624 DCHECK_EQ(1u, erased);
2625}
2626
hong.zhengb28b5332016-05-11 02:33:392627void RenderThreadImpl::OnSyncMemoryPressure(
2628 base::MemoryPressureListener::MemoryPressureLevel memory_pressure_level) {
Blink Reformat1c4d759e2017-04-09 16:34:542629 if (!blink::MainThreadIsolate())
hong.zhengb28b5332016-05-11 02:33:392630 return;
2631
2632 v8::MemoryPressureLevel v8_memory_pressure_level =
2633 static_cast<v8::MemoryPressureLevel>(memory_pressure_level);
2634
Luke Halliwell16136de2017-07-05 21:15:562635#if !BUILDFLAG(ALLOW_CRITICAL_MEMORY_PRESSURE_HANDLING_IN_FOREGROUND)
hong.zhengb28b5332016-05-11 02:33:392636 // In order to reduce performance impact, translate critical level to
Luke Halliwell16136de2017-07-05 21:15:562637 // moderate level for foreground renderer.
hong.zhengb28b5332016-05-11 02:33:392638 if (!RendererIsHidden() &&
2639 v8_memory_pressure_level == v8::MemoryPressureLevel::kCritical)
2640 v8_memory_pressure_level = v8::MemoryPressureLevel::kModerate;
Luke Halliwell16136de2017-07-05 21:15:562641#endif // !BUILDFLAG(ALLOW_CRITICAL_MEMORY_PRESSURE_HANDLING_IN_FOREGROUND)
hong.zhengb28b5332016-05-11 02:33:392642
Blink Reformat1c4d759e2017-04-09 16:34:542643 blink::MainThreadIsolate()->MemoryPressureNotification(
hong.zhengb28b5332016-05-11 02:33:392644 v8_memory_pressure_level);
2645 blink::MemoryPressureNotificationToWorkerThreadIsolates(
2646 v8_memory_pressure_level);
2647}
2648
bashic4b4afcb2016-08-23 06:37:522649// Note that this would be called only when memory_coordinator is enabled.
2650// OnSyncMemoryPressure() is never called in that case.
2651void RenderThreadImpl::OnTrimMemoryImmediately() {
Blink Reformat1c4d759e2017-04-09 16:34:542652 if (blink::MainThreadIsolate()) {
2653 blink::MainThreadIsolate()->MemoryPressureNotification(
bashic4b4afcb2016-08-23 06:37:522654 v8::MemoryPressureLevel::kCritical);
2655 blink::MemoryPressureNotificationToWorkerThreadIsolates(
2656 v8::MemoryPressureLevel::kCritical);
2657 }
2658}
2659
rockot067ca55f2016-09-30 22:00:152660void RenderThreadImpl::OnRendererInterfaceRequest(
2661 mojom::RendererAssociatedRequest request) {
2662 DCHECK(!renderer_binding_.is_bound());
2663 renderer_binding_.Bind(std::move(request));
2664}
bashic4b4afcb2016-08-23 06:37:522665
Takashi SAKAMOTO870f6262017-08-22 04:08:272666bool RenderThreadImpl::NeedsToRecordFirstActivePaint(
2667 int ttfap_metric_type) const {
2668 if (ttfap_metric_type == RenderWidget::TTFAP_AFTER_PURGED)
2669 return needs_to_record_first_active_paint_;
2670
2671 if (was_backgrounded_time_.is_min())
2672 return false;
2673 base::TimeDelta passed = base::TimeTicks::Now() - was_backgrounded_time_;
2674 return passed.InMinutes() >= 5;
2675}
2676
Miguel Casas5e1018052018-01-09 19:17:362677void RenderThreadImpl::SetRenderingColorSpace(
2678 const gfx::ColorSpace& color_space) {
2679 DCHECK(IsMainThread());
2680 rendering_color_space_ = color_space;
2681
2682 for (const auto& factories : gpu_factories_) {
2683 if (factories)
2684 factories->SetRenderingColorSpace(color_space);
2685 }
2686}
2687
[email protected]e9ff79c2012-10-19 21:31:262688} // namespace content