blob: bd4ef1a6c6400f651419daaff4a67dff50dc3957 [file] [log] [blame]
[email protected]d3d6325d2012-01-03 21:17:361// Copyright (c) 2012 The Chromium Authors. All rights reserved.
license.botbf09a502008-08-24 00:55:552// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
initial.commit09911bf2008-07-26 23:55:294
[email protected]f1a29a02011-10-06 23:08:445#include "content/renderer/render_thread_impl.h"
initial.commit09911bf2008-07-26 23:55:296
[email protected]da00a2882009-03-09 17:51:197#include <algorithm>
[email protected]61a9b2d82010-02-26 00:31:088#include <limits>
[email protected]75e126b932009-09-28 19:38:499#include <map>
dcheng07945f632015-12-26 07:59:3210#include <utility>
[email protected]da00a2882009-03-09 17:51:1911#include <vector>
12
[email protected]237a14852012-04-28 02:56:3813#include "base/allocator/allocator_extension.h"
harakenbbfdd9f02017-01-12 07:14:0414#include "base/at_exit.h"
[email protected]06533c0b2009-03-05 21:39:1115#include "base/command_line.h"
creis9f7248b2016-01-27 20:27:3916#include "base/debug/crash_logging.h"
[email protected]94f9a0f682009-06-15 18:30:3017#include "base/lazy_instance.h"
[email protected]bee16aab2009-08-26 15:55:0318#include "base/logging.h"
avi1023d012015-12-25 02:39:1419#include "base/macros.h"
reveman1af05cb32015-03-17 23:18:1620#include "base/memory/discardable_memory_allocator.h"
hajimehoshi7bb39582016-10-12 04:30:5721#include "base/memory/memory_coordinator_client_registry.h"
dchengcedca5612016-04-09 01:40:1522#include "base/memory/ptr_util.h"
[email protected]8bac37b2013-07-18 19:13:5623#include "base/memory/shared_memory.h"
[email protected]835d7c82010-10-14 04:38:3824#include "base/metrics/field_trial.h"
asvitkine8d51e9d2016-09-02 23:55:4325#include "base/metrics/histogram_macros.h"
[email protected]433df472012-03-07 20:33:3926#include "base/path_service.h"
tasakb46626a2016-10-18 05:54:4427#include "base/process/process_metrics.h"
fdoray2df4a9e2016-07-18 23:47:1628#include "base/run_loop.h"
[email protected]21aa99682013-06-11 07:17:0129#include "base/strings/string16.h"
[email protected]1e1d1e12014-01-17 16:14:2930#include "base/strings/string_number_conversions.h"
hablichd6a4f122015-10-28 11:34:4931#include "base/strings/string_split.h"
ccameron6728bae32015-01-09 20:18:0632#include "base/strings/sys_string_conversions.h"
[email protected]74ebfb12013-06-07 20:48:0033#include "base/strings/utf_string_conversions.h"
fdoray50a38342016-11-21 20:46:0434#include "base/threading/sequenced_worker_pool.h"
reveman34b7a1522015-03-23 20:27:4735#include "base/threading/simple_thread.h"
[email protected]1357c322010-12-30 22:18:5636#include "base/threading/thread_local.h"
[email protected]d293572a2013-05-23 18:50:4537#include "base/threading/thread_restrictions.h"
gab30f26df2016-05-11 19:37:5538#include "base/threading/thread_task_runner_handle.h"
ccameron9c48d1d42016-09-22 01:46:0139#include "base/trace_event/memory_dump_manager.h"
primiano9e38d552015-01-28 04:18:0140#include "base/trace_event/trace_event.h"
[email protected]7a4de7a62010-08-17 18:38:2441#include "base/values.h"
avi1023d012015-12-25 02:39:1442#include "build/build_config.h"
jbroman0d302162015-09-05 05:46:2343#include "cc/base/histograms.h"
[email protected]d72493152014-01-08 17:37:4544#include "cc/base/switches.h"
[email protected]38564622014-08-19 02:47:1845#include "cc/blink/web_layer_impl.h"
ericrk9151705c2016-07-26 19:53:1646#include "cc/output/buffer_to_texture_target_map.h"
danakj1120f4c2016-09-15 02:05:3247#include "cc/output/compositor_frame_sink.h"
jbroman6ccbc7d472016-07-27 04:45:4148#include "cc/output/copy_output_request.h"
danakj83066a32016-06-21 02:34:4949#include "cc/output/vulkan_in_process_context_provider.h"
danakj920156852015-05-18 20:22:2950#include "cc/raster/task_graph_runner.h"
vollick1050cc62015-12-03 07:04:5451#include "cc/trees/layer_tree_host_common.h"
loysoa6edaaff2015-05-25 03:26:4452#include "cc/trees/layer_tree_settings.h"
penghuangd81c1a62016-11-02 20:06:0653#include "components/discardable_memory/client/client_discardable_shared_memory_manager.h"
[email protected]a8cb3b73b2013-08-12 05:50:5054#include "content/child/appcache/appcache_dispatcher.h"
55#include "content/child/appcache/appcache_frontend_impl.h"
dmurph1fb98482016-03-30 21:14:2656#include "content/child/blob_storage/blob_message_filter.h"
[email protected]10208ea2013-06-06 20:08:0357#include "content/child/child_histogram_message_filter.h"
alexclarke0bc36e8d32014-12-17 17:29:2058#include "content/child/child_resource_message_filter.h"
[email protected]fdeac262014-07-10 12:52:5159#include "content/child/content_child_helpers.h"
[email protected]89c36f82013-07-17 06:23:2760#include "content/child/db_message_filter.h"
[email protected]c7199a6e2013-06-04 12:56:0161#include "content/child/indexed_db/indexed_db_dispatcher.h"
bashia6264042016-09-15 04:49:5162#include "content/child/memory/child_memory_coordinator_impl.h"
[email protected]10208ea2013-06-06 20:08:0363#include "content/child/resource_dispatcher.h"
alexclarke0bc36e8d32014-12-17 17:29:2064#include "content/child/resource_scheduling_filter.h"
[email protected]643255da2013-06-12 20:55:1365#include "content/child/runtime_features.h"
[email protected]57cf97882013-06-26 20:39:0166#include "content/child/thread_safe_sender.h"
[email protected]c7199a6e2013-06-04 12:56:0167#include "content/child/web_database_observer_impl.h"
kinukoef647412015-12-23 06:10:4368#include "content/child/worker_thread_registry.h"
[email protected]bdae9812011-10-15 00:33:0369#include "content/common/child_process_messages.h"
[email protected]89c36f82013-07-17 06:23:2770#include "content/common/content_constants_internal.h"
[email protected]5f2aa722013-08-07 16:59:4171#include "content/common/dom_storage/dom_storage_messages.h"
thakis18e426412017-03-15 12:06:3772#include "content/common/features.h"
chiniforooshan614d70a2017-03-17 01:19:3373#include "content/common/field_trial_recorder.mojom.h"
[email protected]82307f6b2014-08-07 03:30:1274#include "content/common/frame_messages.h"
raymesbba82b32016-07-19 00:41:3875#include "content/common/frame_owner_properties.h"
avia7c3f51c2015-09-16 00:30:3176#include "content/common/render_process_messages.h"
[email protected]94dc971d2011-03-05 19:08:3277#include "content/common/resource_messages.h"
alexmos68734212016-08-27 00:06:3178#include "content/common/site_isolation_policy.h"
[email protected]778574e2011-03-21 22:03:5079#include "content/common/view_messages.h"
[email protected]0ec90d522014-03-12 16:28:1980#include "content/common/worker_messages.h"
[email protected]a458504b2012-07-23 19:57:0681#include "content/public/common/content_constants.h"
bashia6264042016-09-15 04:49:5182#include "content/public/common/content_features.h"
[email protected]433df472012-03-07 20:33:3983#include "content/public/common/content_paths.h"
[email protected]c08950d22011-10-13 22:20:2984#include "content/public/common/content_switches.h"
[email protected]daf82f82011-10-31 22:35:3185#include "content/public/common/renderer_preferences.h"
benbd9dc802017-04-19 01:37:4386#include "content/public/common/service_manager_connection.h"
ben649b3edd2017-03-23 00:32:0287#include "content/public/common/service_names.mojom.h"
benbd9dc802017-04-19 01:37:4388#include "content/public/common/simple_connection_filter.h"
[email protected]58436a12012-03-21 17:10:2689#include "content/public/common/url_constants.h"
[email protected]d344114c2011-10-01 01:24:3490#include "content/public/renderer/content_renderer_client.h"
tyoshino832a58a2016-04-18 08:14:0891#include "content/public/renderer/render_thread_observer.h"
[email protected]64ffa0442011-10-03 22:08:3692#include "content/public/renderer/render_view_visitor.h"
fsamuel6c1dfeb2014-12-18 19:21:3393#include "content/renderer/browser_plugin/browser_plugin_manager.h"
jsbell279efb42015-03-31 17:02:4694#include "content/renderer/cache_storage/cache_storage_dispatcher.h"
95#include "content/renderer/cache_storage/cache_storage_message_filter.h"
prashant.nfad657e2016-06-01 07:52:1796#include "content/renderer/categorized_worker_pool.h"
[email protected]70019152012-12-19 11:44:1997#include "content/renderer/devtools/devtools_agent_filter.h"
[email protected]1910fe82012-05-10 00:04:1098#include "content/renderer/dom_storage/dom_storage_dispatcher.h"
99#include "content/renderer/dom_storage/webstoragearea_impl.h"
100#include "content/renderer/dom_storage/webstoragenamespace_impl.h"
simonhonga7e3ac42014-11-11 20:50:22101#include "content/renderer/gpu/compositor_external_begin_frame_source.h"
102#include "content/renderer/gpu/compositor_forwarding_message_filter.h"
danakj83066a32016-06-21 02:34:49103#include "content/renderer/gpu/frame_swap_message_queue.h"
danakj1120f4c2016-09-15 02:05:32104#include "content/renderer/gpu/renderer_compositor_frame_sink.h"
[email protected]7a72d452013-12-13 10:01:13105#include "content/renderer/input/input_event_filter.h"
106#include "content/renderer/input/input_handler_manager.h"
jdduke691dd572014-12-02 20:47:52107#include "content/renderer/input/main_thread_input_event_filter.h"
[email protected]f7eb0a392011-07-12 10:19:51108#include "content/renderer/media/audio_input_message_filter.h"
109#include "content/renderer/media/audio_message_filter.h"
[email protected]3958e972012-07-17 00:25:41110#include "content/renderer/media/audio_renderer_mixer_manager.h"
[email protected]d8cd8372012-03-09 10:49:51111#include "content/renderer/media/media_stream_center.h"
[email protected]a9875152013-06-22 04:03:03112#include "content/renderer/media/midi_message_filter.h"
xhwang194acae2014-11-12 22:46:33113#include "content/renderer/media/render_media_client.h"
[email protected]2329bfc72014-02-28 02:03:21114#include "content/renderer/media/renderer_gpu_video_accelerator_factories.h"
[email protected]80b161a2011-06-27 17:42:11115#include "content/renderer/media/video_capture_impl_manager.h"
[email protected]d7ff5fb2014-05-29 19:50:25116#include "content/renderer/net_info_helper.h"
[email protected]4761cf12012-09-12 10:37:55117#include "content/renderer/p2p/socket_dispatcher.h"
[email protected]82307f6b2014-08-07 03:30:12118#include "content/renderer/render_frame_proxy.h"
[email protected]8704f89b2011-04-15 00:30:05119#include "content/renderer/render_process_impl.h"
[email protected]310ebd6302011-10-10 19:06:28120#include "content/renderer/render_view_impl.h"
tfarina556a7232014-10-05 01:02:09121#include "content/renderer/renderer_blink_platform_impl.h"
jdduke94ae1f32015-02-05 06:27:13122#include "content/renderer/scheduler/resource_dispatch_throttler.h"
shimazu5de409e42016-09-29 08:45:28123#include "content/renderer/service_worker/embedded_worker_instance_client_impl.h"
mek27c9d742015-07-16 18:30:18124#include "content/renderer/service_worker/service_worker_context_client.h"
kinuko5af4ffe2015-06-09 03:38:46125#include "content/renderer/service_worker/service_worker_context_message_filter.h"
[email protected]0ec90d522014-03-12 16:28:19126#include "content/renderer/shared_worker/embedded_shared_worker_stub.h"
juncai2f298a82017-04-18 03:51:39127#include "device/gamepad/public/cpp/gamepads.h"
chunyang.daibe874c52014-11-14 06:45:05128#include "gin/public/debug.h"
dongseong.hwang72183b02014-12-08 10:41:55129#include "gpu/GLES2/gl2extchromium.h"
danakj6f4e1e22016-04-20 03:27:34130#include "gpu/command_buffer/client/shared_memory_limits.h"
danakj870925d42016-05-03 20:07:38131#include "gpu/ipc/client/command_buffer_proxy_impl.h"
penghuang346a46f92016-03-31 21:37:52132#include "gpu/ipc/client/gpu_channel_host.h"
[email protected]46f36a492010-07-28 19:36:41133#include "ipc/ipc_channel_handle.h"
amistryd4aa70d2016-06-23 07:52:37134#include "ipc/ipc_channel_mojo.h"
[email protected]cb6037d2009-11-16 22:55:17135#include "ipc/ipc_platform_file.h"
[email protected]433df472012-03-07 20:33:39136#include "media/base/media.h"
chcunningham9a285ed2017-03-08 21:48:56137#include "media/base/media_switches.h"
Brett Wilson0748bf412016-11-22 17:55:46138#include "media/media_features.h"
servolk8b3b39b2015-03-03 19:08:18139#include "media/renderers/gpu_video_accelerator_factories.h"
rockot85dce0862015-11-13 01:33:59140#include "mojo/public/cpp/bindings/strong_binding.h"
[email protected]620161e2011-03-07 18:05:26141#include "net/base/net_errors.h"
eroman9ab64842015-07-21 05:07:52142#include "net/base/port_util.h"
hablichd6a4f122015-10-28 11:34:49143#include "net/base/registry_controlled_domains/registry_controlled_domain.h"
tfarina7a4a7fd2016-01-20 14:23:44144#include "net/base/url_util.h"
brettw4b461082016-11-19 18:55:16145#include "ppapi/features/features.h"
benbd9dc802017-04-19 01:37:43146#include "services/service_manager/public/cpp/binder_registry.h"
penghuangd6843e42016-12-17 13:57:20147#include "services/service_manager/public/cpp/connector.h"
rockot734fb662016-10-15 16:41:30148#include "services/service_manager/public/cpp/interface_provider.h"
xlai11ac7802017-04-07 20:13:18149#include "services/ui/public/cpp/bitmap/child_shared_bitmap_manager.h"
sadrul85cc5d82016-12-20 03:37:41150#include "services/ui/public/cpp/gpu/context_provider_command_buffer.h"
penghuangd6843e42016-12-17 13:57:20151#include "services/ui/public/interfaces/constants.mojom.h"
[email protected]b48c53ad2014-02-05 21:59:18152#include "skia/ext/event_tracer_impl.h"
ssid59c969162015-07-28 13:02:58153#include "skia/ext/skia_memory_dump_provider.h"
kinukoed1ed1d2017-02-08 09:13:43154#include "third_party/WebKit/public/platform/WebCache.h"
reed6e5a72222015-08-06 20:37:16155#include "third_party/WebKit/public/platform/WebImageGenerator.h"
bashi5f4c78922016-08-18 23:06:08156#include "third_party/WebKit/public/platform/WebMemoryCoordinator.h"
kinukofbfee762017-03-08 04:01:06157#include "third_party/WebKit/public/platform/WebNetworkStateNotifier.h"
[email protected]89c36f82013-07-17 06:23:27158#include "third_party/WebKit/public/platform/WebString.h"
skyostil457b0a12014-09-09 10:12:07159#include "third_party/WebKit/public/platform/WebThread.h"
altiminc7369bf2017-04-11 14:29:15160#include "third_party/WebKit/public/platform/scheduler/child/webthread_base.h"
skyostil529caa292016-08-10 17:44:51161#include "third_party/WebKit/public/platform/scheduler/renderer/renderer_scheduler.h"
[email protected]2255a9332013-06-17 05:12:31162#include "third_party/WebKit/public/web/WebDatabase.h"
163#include "third_party/WebKit/public/web/WebDocument.h"
164#include "third_party/WebKit/public/web/WebFrame.h"
165#include "third_party/WebKit/public/web/WebKit.h"
[email protected]2255a9332013-06-17 05:12:31166#include "third_party/WebKit/public/web/WebRuntimeFeatures.h"
167#include "third_party/WebKit/public/web/WebScriptController.h"
168#include "third_party/WebKit/public/web/WebSecurityPolicy.h"
[email protected]2255a9332013-06-17 05:12:31169#include "third_party/WebKit/public/web/WebView.h"
[email protected]ddbb53342014-01-06 10:59:47170#include "third_party/skia/include/core/SkGraphics.h"
[email protected]c49201a2012-05-24 11:04:57171#include "ui/base/layout.h"
[email protected]18ad6772011-09-20 21:51:32172#include "ui/base/ui_base_switches.h"
mlamouri7c149652017-03-24 00:00:09173#include "ui/display/display_switches.h"
ennee292bdc2016-09-15 19:57:15174#include "ui/gl/gl_switches.h"
[email protected]2c62b562009-01-27 19:04:50175
[email protected]33b02992014-03-01 01:06:29176#if defined(OS_ANDROID)
177#include <cpu-features.h>
boliubee541f42015-11-05 00:52:53178#include "content/renderer/android/synchronous_compositor_filter.h"
danakj1120f4c2016-09-15 02:05:32179#include "content/renderer/android/synchronous_compositor_frame_sink.h"
boliue81d16132016-04-26 00:54:41180#include "content/renderer/media/android/stream_texture_factory.h"
dalecurtis88af3932016-02-20 00:12:20181#include "media/base/android/media_codec_util.h"
[email protected]33b02992014-03-01 01:06:29182#endif
183
184#if defined(OS_MACOSX)
ccamerona7644752014-12-30 01:16:31185#include "base/mac/mac_util.h"
rsesek1efb3c32015-09-29 15:39:50186#include "content/renderer/theme_helper_mac.h"
[email protected]33b02992014-03-01 01:06:29187#include "content/renderer/webscrollbarbehavior_impl_mac.h"
188#endif
189
[email protected]da00a2882009-03-09 17:51:19190#if defined(OS_WIN)
191#include <windows.h>
192#include <objbase.h>
193#endif
194
Brett Wilson0748bf412016-11-22 17:55:46195#if BUILDFLAG(ENABLE_WEBRTC)
liushouqun517b1292016-09-14 05:58:59196#include "content/renderer/media/aec_dump_message_filter.h"
[email protected]22fe91d2014-08-12 17:07:12197#include "content/renderer/media/peer_connection_tracker.h"
198#include "content/renderer/media/rtc_peer_connection_handler.h"
199#include "content/renderer/media/webrtc/peer_connection_dependency_factory.h"
[email protected]22fe91d2014-08-12 17:07:12200#endif
201
chunyang.daibe874c52014-11-14 06:45:05202#ifdef ENABLE_VTUNE_JIT_INTERFACE
203#include "v8/src/third_party/vtune/v8-vtune.h"
204#endif
205
bend32292b2016-10-07 00:21:58206#include "content/public/common/service_manager_connection.h"
fsamuel2545ecc2015-12-05 00:44:46207#include "content/renderer/mus/render_widget_window_tree_client_factory.h"
sadrul602ce1362017-01-26 06:41:10208#include "content/renderer/mus/renderer_window_tree_client.h"
sadrul04cfa892016-12-09 17:53:49209#include "services/ui/public/cpp/gpu/gpu.h"
fsamuel6c6da0232015-11-26 05:13:46210
ochangdd89a1e2016-06-08 16:39:01211#if defined(ENABLE_IPC_FUZZER)
212#include "content/common/external_ipc_dumper.h"
213#endif
214
tasakb46626a2016-10-18 05:54:44215#if defined(OS_MACOSX)
216#include <malloc/malloc.h>
217#else
218#include <malloc.h>
219#endif
220
[email protected]d293572a2013-05-23 18:50:45221using base::ThreadRestrictions;
[email protected]180ef242013-11-07 06:50:46222using blink::WebDocument;
223using blink::WebFrame;
224using blink::WebNetworkStateNotifier;
225using blink::WebRuntimeFeatures;
226using blink::WebScriptController;
227using blink::WebSecurityPolicy;
228using blink::WebString;
229using blink::WebView;
[email protected]e9ff79c2012-10-19 21:31:26230
231namespace content {
initial.commit09911bf2008-07-26 23:55:29232
[email protected]42f1d7822009-07-23 18:17:55233namespace {
[email protected]da9ccfb2012-01-28 00:34:40234
avi1023d012015-12-25 02:39:14235const int64_t kInitialIdleHandlerDelayMs = 1000;
236const int64_t kLongIdleHandlerDelayMs = 30 * 1000;
[email protected]bee16aab2009-08-26 15:55:03237
jdduke94ae1f32015-02-05 06:27:13238#if defined(OS_ANDROID)
239// On Android, resource messages can each take ~1.5ms to dispatch on the browser
240// IO thread. Limiting the message rate to 3/frame at 60hz ensures that the
241// induced work takes but a fraction (~1/4) of the overall frame budget.
242const int kMaxResourceRequestsPerFlushWhenThrottled = 3;
243#else
244const int kMaxResourceRequestsPerFlushWhenThrottled = 8;
245#endif
246const double kThrottledResourceRequestFlushPeriodS = 1. / 60.;
247
[email protected]dd2c1022014-07-22 23:13:57248// Maximum allocation size allowed for image scaling filters that
249// require pre-scaling. Skia will fallback to a filter that doesn't
250// require pre-scaling if the default filter would require an
251// allocation that exceeds this limit.
252const size_t kImageCacheSingleAllocationByteLimit = 64 * 1024 * 1024;
253
samans2040988b2017-04-11 23:58:35254#if defined(OS_ANDROID)
danakj83066a32016-06-21 02:34:49255// Unique identifier for each output surface created.
danakj1120f4c2016-09-15 02:05:32256uint32_t g_next_compositor_frame_sink_id = 1;
samans2040988b2017-04-11 23:58:35257#endif
danakj83066a32016-06-21 02:34:49258
rockot5c478a72016-09-28 23:14:18259// An implementation of mojom::RenderMessageFilter which can be mocked out
260// for tests which may indirectly send messages over this interface.
261mojom::RenderMessageFilter* g_render_message_filter_for_testing;
262
[email protected]f1a29a02011-10-06 23:08:44263// Keep the global RenderThreadImpl in a TLS slot so it is impossible to access
[email protected]f3ede412010-06-21 22:52:16264// incorrectly from the wrong thread.
scottmg5e65e3a2017-03-08 08:48:46265base::LazyInstance<base::ThreadLocalPointer<RenderThreadImpl>>::DestructorAtExit
[email protected]6de0fd1d2011-11-15 13:31:49266 lazy_tls = LAZY_INSTANCE_INITIALIZER;
[email protected]1edc16b82009-04-07 17:45:54267
hong.zhengb28b5332016-05-11 02:33:39268// v8::MemoryPressureLevel should correspond to base::MemoryPressureListener.
269static_assert(static_cast<v8::MemoryPressureLevel>(
270 base::MemoryPressureListener::MEMORY_PRESSURE_LEVEL_NONE) ==
271 v8::MemoryPressureLevel::kNone, "none level not align");
272static_assert(static_cast<v8::MemoryPressureLevel>(
273 base::MemoryPressureListener::MEMORY_PRESSURE_LEVEL_MODERATE) ==
274 v8::MemoryPressureLevel::kModerate, "moderate level not align");
275static_assert(static_cast<v8::MemoryPressureLevel>(
276 base::MemoryPressureListener::MEMORY_PRESSURE_LEVEL_CRITICAL) ==
277 v8::MemoryPressureLevel::kCritical, "critical level not align");
278
hong.zheng2e296f822016-06-29 02:47:44279// WebMemoryPressureLevel should correspond to base::MemoryPressureListener.
280static_assert(static_cast<blink::WebMemoryPressureLevel>(
Blink Reformat1c4d759e2017-04-09 16:34:54281 base::MemoryPressureListener::MEMORY_PRESSURE_LEVEL_NONE) ==
282 blink::kWebMemoryPressureLevelNone,
283 "blink::WebMemoryPressureLevelNone not align");
284static_assert(
285 static_cast<blink::WebMemoryPressureLevel>(
286 base::MemoryPressureListener::MEMORY_PRESSURE_LEVEL_MODERATE) ==
287 blink::kWebMemoryPressureLevelModerate,
288 "blink::WebMemoryPressureLevelModerate not align");
289static_assert(
290 static_cast<blink::WebMemoryPressureLevel>(
291 base::MemoryPressureListener::MEMORY_PRESSURE_LEVEL_CRITICAL) ==
292 blink::kWebMemoryPressureLevelCritical,
293 "blink::WebMemoryPressureLevelCritical not align");
hong.zheng2e296f822016-06-29 02:47:44294
[email protected]b2d98762012-09-03 17:04:06295void* CreateHistogram(
[email protected]d1b8fccc2011-08-03 01:20:13296 const char *name, int min, int max, size_t buckets) {
297 if (min <= 0)
298 min = 1;
[email protected]b2d98762012-09-03 17:04:06299 std::string histogram_name;
300 RenderThreadImpl* render_thread_impl = RenderThreadImpl::current();
301 if (render_thread_impl) { // Can be null in tests.
302 histogram_name = render_thread_impl->
303 histogram_customizer()->ConvertToCustomHistogramName(name);
304 } else {
305 histogram_name = std::string(name);
306 }
[email protected]de415552013-01-23 04:12:17307 base::HistogramBase* histogram = base::Histogram::FactoryGet(
[email protected]b2d98762012-09-03 17:04:06308 histogram_name, min, max, buckets,
309 base::Histogram::kUmaTargetedHistogramFlag);
[email protected]d1b8fccc2011-08-03 01:20:13310 return histogram;
311}
312
[email protected]b2d98762012-09-03 17:04:06313void AddHistogramSample(void* hist, int sample) {
[email protected]d1b8fccc2011-08-03 01:20:13314 base::Histogram* histogram = static_cast<base::Histogram*>(hist);
315 histogram->Add(sample);
316}
317
ben76f52b242016-06-18 05:42:48318class FrameFactoryImpl : public mojom::FrameFactory {
rockotf8fdd9b2015-12-16 22:22:35319 public:
rockot8e66a08d2016-09-13 00:48:21320 FrameFactoryImpl() : routing_id_highmark_(-1) {}
rockotf8fdd9b2015-12-16 22:22:35321
ben76f52b242016-06-18 05:42:48322 private:
323 // mojom::FrameFactory:
324 void CreateFrame(int32_t frame_routing_id,
325 mojom::FrameRequest frame_request,
326 mojom::FrameHostPtr frame_host) override {
rockotf8fdd9b2015-12-16 22:22:35327 // TODO(morrita): This is for investigating http://crbug.com/415059 and
328 // should be removed once it is fixed.
329 CHECK_LT(routing_id_highmark_, frame_routing_id);
330 routing_id_highmark_ = frame_routing_id;
331
332 RenderFrameImpl* frame = RenderFrameImpl::FromRoutingID(frame_routing_id);
333 // We can receive a GetServiceProviderForFrame message for a frame not yet
rockot067ca55f2016-09-30 22:00:15334 // created due to a race between the message and a
335 // mojom::Renderer::CreateView IPC that triggers creation of the RenderFrame
336 // we want.
rockotf8fdd9b2015-12-16 22:22:35337 if (!frame) {
ben76f52b242016-06-18 05:42:48338 RenderThreadImpl::current()->RegisterPendingFrameCreate(
339 frame_routing_id, std::move(frame_request), std::move(frame_host));
rockotf8fdd9b2015-12-16 22:22:35340 return;
341 }
342
dominickn6c1f1cf2016-12-20 06:13:33343 frame->BindFrame(std::move(frame_request), std::move(frame_host));
rockotf8fdd9b2015-12-16 22:22:35344 }
345
346 private:
347 int32_t routing_id_highmark_;
rockotf8fdd9b2015-12-16 22:22:35348};
349
ben76f52b242016-06-18 05:42:48350void CreateFrameFactory(mojom::FrameFactoryRequest request) {
rockot8e66a08d2016-09-13 00:48:21351 mojo::MakeStrongBinding(base::MakeUnique<FrameFactoryImpl>(),
352 std::move(request));
rockotf8fdd9b2015-12-16 22:22:35353}
354
sadrul85cc5d82016-12-20 03:37:41355scoped_refptr<ui::ContextProviderCommandBuffer> CreateOffscreenContext(
danakjc3983552016-05-03 00:04:35356 scoped_refptr<gpu::GpuChannelHost> gpu_channel_host,
danakj0dd9e1e2016-05-11 22:15:09357 const gpu::SharedMemoryLimits& limits,
danakj9a04adc2016-05-16 22:45:07358 bool support_locking,
sadrul85cc5d82016-12-20 03:37:41359 ui::command_buffer_metrics::ContextType type,
sunnypsd8ce1c22016-05-10 18:02:40360 int32_t stream_id,
361 gpu::GpuStreamPriority stream_priority) {
danakje8ec797e2016-04-19 04:08:43362 DCHECK(gpu_channel_host);
363 // This is used to create a few different offscreen contexts:
364 // - The shared main thread context (offscreen) used by blink for canvas.
365 // - The worker context (offscreen) used for GPU raster and video decoding.
366 // This is for an offscreen context, so the default framebuffer doesn't need
367 // alpha, depth, stencil, antialiasing.
368 gpu::gles2::ContextCreationAttribHelper attributes;
369 attributes.alpha_size = -1;
370 attributes.depth_size = 0;
371 attributes.stencil_size = 0;
372 attributes.samples = 0;
373 attributes.sample_buffers = 0;
374 attributes.bind_generates_resource = false;
375 attributes.lose_context_when_out_of_memory = true;
sunnypsd8ce1c22016-05-10 18:02:40376 const bool automatic_flushes = false;
sadrul85cc5d82016-12-20 03:37:41377 return make_scoped_refptr(new ui::ContextProviderCommandBuffer(
sunnypsd8ce1c22016-05-10 18:02:40378 std::move(gpu_channel_host), stream_id, stream_priority,
379 gpu::kNullSurfaceHandle,
zmo09ea813b2017-01-20 23:38:36380 GURL("chrome://gpu/RenderThreadImpl::CreateOffscreenContext/" +
381 ui::command_buffer_metrics::ContextTypeToString(type)),
pimand488e8b42016-06-30 19:06:59382 automatic_flushes, support_locking, limits, attributes, nullptr, type));
danakje8ec797e2016-04-19 04:08:43383}
384
penghuange1d86512016-07-08 18:15:00385bool IsRunningInMash() {
386 const base::CommandLine* cmdline = base::CommandLine::ForCurrentProcess();
387 return cmdline->HasSwitch(switches::kIsRunningInMash);
388}
389
[email protected]b2d98762012-09-03 17:04:06390} // namespace
391
[email protected]fdeac262014-07-10 12:52:51392// For measuring memory usage after each task. Behind a command line flag.
393class MemoryObserver : public base::MessageLoop::TaskObserver {
394 public:
395 MemoryObserver() {}
dcheng6d18e402014-10-21 12:32:52396 ~MemoryObserver() override {}
[email protected]fdeac262014-07-10 12:52:51397
dcheng6d18e402014-10-21 12:32:52398 void WillProcessTask(const base::PendingTask& pending_task) override {}
[email protected]fdeac262014-07-10 12:52:51399
dcheng6d18e402014-10-21 12:32:52400 void DidProcessTask(const base::PendingTask& pending_task) override {
asvitkinec0fb8022014-08-26 04:39:35401 LOCAL_HISTOGRAM_MEMORY_KB("Memory.RendererUsed", GetMemoryUsageKB());
[email protected]fdeac262014-07-10 12:52:51402 }
403
404 private:
405 DISALLOW_COPY_AND_ASSIGN(MemoryObserver);
406};
407
[email protected]b2d98762012-09-03 17:04:06408RenderThreadImpl::HistogramCustomizer::HistogramCustomizer() {
409 custom_histograms_.insert("V8.MemoryExternalFragmentationTotal");
410 custom_histograms_.insert("V8.MemoryHeapSampleTotalCommitted");
411 custom_histograms_.insert("V8.MemoryHeapSampleTotalUsed");
hablich4598ddc2015-11-07 18:37:28412 custom_histograms_.insert("V8.MemoryHeapUsed");
413 custom_histograms_.insert("V8.MemoryHeapCommitted");
[email protected]b2d98762012-09-03 17:04:06414}
415
416RenderThreadImpl::HistogramCustomizer::~HistogramCustomizer() {}
417
418void RenderThreadImpl::HistogramCustomizer::RenderViewNavigatedToHost(
419 const std::string& host, size_t view_count) {
avi83883c82014-12-23 00:08:49420 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
421 switches::kDisableHistogramCustomizer)) {
[email protected]9baee832012-12-10 11:07:15422 return;
423 }
[email protected]b2d98762012-09-03 17:04:06424 // Check if all RenderViews are displaying a page from the same host. If there
425 // is only one RenderView, the common host is this view's host. If there are
426 // many, check if this one shares the common host of the other
427 // RenderViews. It's ok to not detect some cases where the RenderViews share a
428 // common host. This information is only used for producing custom histograms.
429 if (view_count == 1)
430 SetCommonHost(host);
431 else if (host != common_host_)
432 SetCommonHost(std::string());
433}
434
435std::string RenderThreadImpl::HistogramCustomizer::ConvertToCustomHistogramName(
436 const char* histogram_name) const {
437 std::string name(histogram_name);
438 if (!common_host_histogram_suffix_.empty() &&
439 custom_histograms_.find(name) != custom_histograms_.end())
440 name += common_host_histogram_suffix_;
441 return name;
442}
443
444void RenderThreadImpl::HistogramCustomizer::SetCommonHost(
445 const std::string& host) {
446 if (host != common_host_) {
447 common_host_ = host;
448 common_host_histogram_suffix_ = HostToCustomHistogramSuffix(host);
Blink Reformat1c4d759e2017-04-09 16:34:54449 blink::MainThreadIsolate()->SetCreateHistogramFunction(CreateHistogram);
[email protected]b2d98762012-09-03 17:04:06450 }
451}
452
hablichd6a4f122015-10-28 11:34:49453std::string RenderThreadImpl::HistogramCustomizer::HostToCustomHistogramSuffix(
454 const std::string& host) {
455 if (host == "mail.google.com")
456 return ".gmail";
457 if (host == "docs.google.com" || host == "drive.google.com")
458 return ".docs";
459 if (host == "plus.google.com")
460 return ".plus";
461 if (host == "inbox.google.com")
462 return ".inbox";
hpayerdd4def052016-02-06 19:06:10463 if (host == "calendar.google.com")
464 return ".calendar";
hablichd6a4f122015-10-28 11:34:49465 if (host == "www.youtube.com")
466 return ".youtube";
467 if (IsAlexaTop10NonGoogleSite(host))
468 return ".top10";
469
470 return std::string();
471}
472
473bool RenderThreadImpl::HistogramCustomizer::IsAlexaTop10NonGoogleSite(
474 const std::string& host) {
475 // The Top10 sites have different TLD and/or subdomains depending on the
476 // localization.
477 if (host == "sina.com.cn")
478 return true;
479
480 std::string sanitized_host =
481 net::registry_controlled_domains::GetDomainAndRegistry(
482 host, net::registry_controlled_domains::INCLUDE_PRIVATE_REGISTRIES);
483
484 if (sanitized_host == "facebook.com")
485 return true;
486 if (sanitized_host == "baidu.com")
487 return true;
488 if (sanitized_host == "qq.com")
489 return true;
490 if (sanitized_host == "twitter.com")
491 return true;
492 if (sanitized_host == "taobao.com")
493 return true;
494 if (sanitized_host == "live.com")
495 return true;
496
497 if (!sanitized_host.empty()) {
498 std::vector<base::StringPiece> host_tokens = base::SplitStringPiece(
499 sanitized_host, ".", base::TRIM_WHITESPACE, base::SPLIT_WANT_NONEMPTY);
500
501 if (host_tokens.size() >= 2) {
502 if ((host_tokens[0] == "yahoo") || (host_tokens[0] == "amazon") ||
503 (host_tokens[0] == "wikipedia")) {
504 return true;
505 }
506 }
507 }
508 return false;
509}
510
leon.han2c0f9f12015-07-11 02:01:19511// static
512RenderThreadImpl* RenderThreadImpl::Create(
513 const InProcessChildThreadParams& params) {
skyostil529caa292016-08-10 17:44:51514 std::unique_ptr<blink::scheduler::RendererScheduler> renderer_scheduler =
515 blink::scheduler::RendererScheduler::Create();
jam75c44222016-03-23 05:34:24516 scoped_refptr<base::SingleThreadTaskRunner> test_task_counter;
517 return new RenderThreadImpl(
518 params, std::move(renderer_scheduler), test_task_counter);
leon.han2c0f9f12015-07-11 02:01:19519}
520
521// static
522RenderThreadImpl* RenderThreadImpl::Create(
dchengcedca5612016-04-09 01:40:15523 std::unique_ptr<base::MessageLoop> main_message_loop,
skyostil529caa292016-08-10 17:44:51524 std::unique_ptr<blink::scheduler::RendererScheduler> renderer_scheduler) {
dcheng07945f632015-12-26 07:59:32525 return new RenderThreadImpl(std::move(main_message_loop),
526 std::move(renderer_scheduler));
leon.han2c0f9f12015-07-11 02:01:19527}
528
rockot5c478a72016-09-28 23:14:18529// static
[email protected]f1a29a02011-10-06 23:08:44530RenderThreadImpl* RenderThreadImpl::current() {
[email protected]526476902011-10-06 20:34:06531 return lazy_tls.Pointer()->Get();
532}
533
rockot5c478a72016-09-28 23:14:18534// static
535mojom::RenderMessageFilter* RenderThreadImpl::current_render_message_filter() {
536 if (g_render_message_filter_for_testing)
537 return g_render_message_filter_for_testing;
538 DCHECK(current());
539 return current()->render_message_filter();
540}
541
542// static
543void RenderThreadImpl::SetRenderMessageFilterForTesting(
544 mojom::RenderMessageFilter* render_message_filter) {
545 g_render_message_filter_for_testing = render_message_filter;
546}
547
staraz067f58242016-11-07 21:06:41548// In single-process mode used for debugging, we don't pass a renderer client
549// ID via command line because RenderThreadImpl lives in the same process as
550// the browser
leon.han2c0f9f12015-07-11 02:01:19551RenderThreadImpl::RenderThreadImpl(
552 const InProcessChildThreadParams& params,
skyostil529caa292016-08-10 17:44:51553 std::unique_ptr<blink::scheduler::RendererScheduler> scheduler,
rockot97a86832016-12-10 04:53:06554 const scoped_refptr<base::SingleThreadTaskRunner>& resource_task_queue)
morritac6238ab2015-03-18 01:48:29555 : ChildThreadImpl(Options::Builder()
prashant.nfad657e2016-06-01 07:52:17556 .InBrowserProcess(params)
bend32292b2016-10-07 00:21:58557 .AutoStartServiceManagerConnection(false)
ben5be0b9132016-08-03 00:17:18558 .ConnectToBrowser(true)
prashant.nfad657e2016-06-01 07:52:17559 .Build()),
dcheng07945f632015-12-26 07:59:32560 renderer_scheduler_(std::move(scheduler)),
rockot067ca55f2016-09-30 22:00:15561 categorized_worker_pool_(new CategorizedWorkerPool()),
staraz067f58242016-11-07 21:06:41562 renderer_binding_(this),
chiniforooshan614d70a2017-03-17 01:19:33563 client_id_(1),
564 field_trial_syncer_(this) {
jam75c44222016-03-23 05:34:24565 Init(resource_task_queue);
morritac6238ab2015-03-18 01:48:29566}
567
[email protected]42f1d7822009-07-23 18:17:55568// When we run plugins in process, we actually run them on the render thread,
569// which means that we need to make the render thread pump UI events.
haraken53f081d2014-11-11 01:03:40570RenderThreadImpl::RenderThreadImpl(
dchengcedca5612016-04-09 01:40:15571 std::unique_ptr<base::MessageLoop> main_message_loop,
skyostil529caa292016-08-10 17:44:51572 std::unique_ptr<blink::scheduler::RendererScheduler> scheduler)
rockotcef38272016-07-15 22:47:47573 : ChildThreadImpl(Options::Builder()
bend32292b2016-10-07 00:21:58574 .AutoStartServiceManagerConnection(false)
ben5be0b9132016-08-03 00:17:18575 .ConnectToBrowser(true)
rockotcef38272016-07-15 22:47:47576 .Build()),
dcheng07945f632015-12-26 07:59:32577 renderer_scheduler_(std::move(scheduler)),
578 main_message_loop_(std::move(main_message_loop)),
rockot067ca55f2016-09-30 22:00:15579 categorized_worker_pool_(new CategorizedWorkerPool()),
wjmaclean1d970622017-01-21 22:28:24580 is_scroll_animator_enabled_(false),
fsamuel4c5c87142017-03-14 03:14:26581 is_surface_synchronization_enabled_(false),
chiniforooshan614d70a2017-03-17 01:19:33582 renderer_binding_(this),
583 field_trial_syncer_(this) {
jam75c44222016-03-23 05:34:24584 scoped_refptr<base::SingleThreadTaskRunner> test_task_counter;
staraz067f58242016-11-07 21:06:41585 DCHECK(base::CommandLine::ForCurrentProcess()->HasSwitch(
586 switches::kRendererClientId));
587 base::StringToInt(base::CommandLine::ForCurrentProcess()->GetSwitchValueASCII(
588 switches::kRendererClientId),
589 &client_id_);
jam75c44222016-03-23 05:34:24590 Init(test_task_counter);
haraken53f081d2014-11-11 01:03:40591}
592
jam75c44222016-03-23 05:34:24593void RenderThreadImpl::Init(
rockot97a86832016-12-10 04:53:06594 const scoped_refptr<base::SingleThreadTaskRunner>& resource_task_queue) {
fdorayf6d86242015-10-08 16:49:53595 TRACE_EVENT0("startup", "RenderThreadImpl::Init");
[email protected]a872ea1f2010-08-11 04:45:33596
ssidb2e3ece2015-02-09 16:02:20597 base::trace_event::TraceLog::GetInstance()->SetThreadSortIndex(
[email protected]91a2aea2013-07-08 23:14:39598 base::PlatformThread::CurrentId(),
599 kTraceEventRendererMainThreadSortIndex);
600
thakis18e426412017-03-15 12:06:37601#if BUILDFLAG(USE_EXTERNAL_POPUP_MENU)
sievers9dff72052015-11-16 18:35:57602 // On Mac and Android Java UI, the select popups are rendered by the browser.
Blink Reformat1c4d759e2017-04-09 16:34:54603 blink::WebView::SetUseExternalPopupMenus(true);
[email protected]53c607c2011-03-21 23:19:04604#endif
605
[email protected]94f9a0f682009-06-15 18:30:30606 lazy_tls.Pointer()->Set(this);
[email protected]b3e83de2012-02-07 03:33:28607
[email protected]06c694d2012-02-01 22:26:16608 // Register this object as the main thread.
609 ChildProcess::current()->set_main_thread(this);
610
ben649b3edd2017-03-23 00:32:02611 gpu_ = ui::Gpu::Create(
612 GetConnector(),
613 IsRunningInMash() ? ui::mojom::kServiceName : mojom::kBrowserServiceName,
614 GetIOTaskRunner());
penghuange1d86512016-07-08 18:15:00615
xlai11ac7802017-04-07 20:13:18616 cc::mojom::SharedBitmapManagerAssociatedPtr shared_bitmap_manager_ptr;
617 render_message_filter()->GetSharedBitmapManager(
618 mojo::MakeRequest(&shared_bitmap_manager_ptr));
619 shared_bitmap_manager_.reset(new ui::ChildSharedBitmapManager(
620 cc::mojom::ThreadSafeSharedBitmapManagerAssociatedPtr::Create(
621 shared_bitmap_manager_ptr.PassInterface(),
622 GetChannel()->ipc_task_runner_refptr())));
jcivelli0f21bd52016-12-07 21:21:33623
jam75c44222016-03-23 05:34:24624 InitializeWebKit(resource_task_queue);
625
[email protected]31f87132010-04-21 23:36:21626 // In single process the single process is all there is.
[email protected]26e82322014-01-20 14:18:22627 webkit_shared_timer_suspended_ = false;
[email protected]bee16aab2009-08-26 15:55:03628 widget_count_ = 0;
629 hidden_widget_count_ = 0;
[email protected]6593ae12011-11-14 12:09:44630 idle_notification_delay_in_ms_ = kInitialIdleHandlerDelayMs;
[email protected]1784b2f2011-11-24 10:53:48631 idle_notifications_to_skip_ = 0;
[email protected]8d86fce2009-02-26 23:37:55632
[email protected]d5b2fdf2013-06-05 09:36:55633 appcache_dispatcher_.reset(
[email protected]a8cb3b73b2013-08-12 05:50:50634 new AppCacheDispatcher(Get(), new AppCacheFrontendImpl()));
[email protected]1910fe82012-05-10 00:04:10635 dom_storage_dispatcher_.reset(new DomStorageDispatcher());
reillyg39fb4662016-11-22 20:27:17636 main_thread_indexed_db_dispatcher_.reset(new IndexedDBDispatcher());
jsbellabadb9b2015-03-23 21:03:44637 main_thread_cache_storage_dispatcher_.reset(
jsbell279efb42015-03-31 17:02:46638 new CacheStorageDispatcher(thread_safe_sender()));
[email protected]dd9241932010-02-24 19:23:13639
jdduke94ae1f32015-02-05 06:27:13640 // Note: This may reorder messages from the ResourceDispatcher with respect to
641 // other subsystems.
642 resource_dispatch_throttler_.reset(new ResourceDispatchThrottler(
643 static_cast<RenderThread*>(this), renderer_scheduler_.get(),
644 base::TimeDelta::FromSecondsD(kThrottledResourceRequestFlushPeriodS),
645 kMaxResourceRequestsPerFlushWhenThrottled));
646 resource_dispatcher()->set_message_sender(resource_dispatch_throttler_.get());
647
penghuange1d86512016-07-08 18:15:00648 media_stream_center_ = nullptr;
[email protected]d8cd8372012-03-09 10:49:51649
thestig529ad8a2016-07-08 20:30:12650 blob_message_filter_ = new BlobMessageFilter(GetFileThreadTaskRunner());
dmurph1fb98482016-03-30 21:14:26651 AddFilter(blob_message_filter_.get());
[email protected]017022b2009-07-27 23:06:34652 db_message_filter_ = new DBMessageFilter();
653 AddFilter(db_message_filter_.get());
[email protected]dd9241932010-02-24 19:23:13654
[email protected]45048072014-01-14 13:51:29655 vc_manager_.reset(new VideoCaptureImplManager());
[email protected]c9c43a02013-12-17 08:59:54656
fsamuel6c1dfeb2014-12-18 19:21:33657 browser_plugin_manager_.reset(new BrowserPluginManager());
658 AddObserver(browser_plugin_manager_.get());
659
Brett Wilson0748bf412016-11-22 17:55:46660#if BUILDFLAG(ENABLE_WEBRTC)
[email protected]af089972013-01-10 04:04:40661 peer_connection_tracker_.reset(new PeerConnectionTracker());
662 AddObserver(peer_connection_tracker_.get());
663
thestig529ad8a2016-07-08 20:30:12664 p2p_socket_dispatcher_ = new P2PSocketDispatcher(GetIOTaskRunner().get());
[email protected]fc72bb12013-06-02 21:13:46665 AddFilter(p2p_socket_dispatcher_.get());
[email protected]921480f62013-07-20 03:42:57666
ivocadd54f0d2015-12-18 23:17:05667 peer_connection_factory_.reset(
668 new PeerConnectionDependencyFactory(p2p_socket_dispatcher_.get()));
669
skyostil2d3b5bd2015-05-27 15:40:59670 aec_dump_message_filter_ = new AecDumpMessageFilter(
thestig529ad8a2016-07-08 20:30:12671 GetIOTaskRunner(), message_loop()->task_runner());
ivocadd54f0d2015-12-18 23:17:05672
[email protected]da9f30a2014-06-18 19:39:04673 AddFilter(aec_dump_message_filter_.get());
674
Brett Wilson0748bf412016-11-22 17:55:46675#endif // BUILDFLAG(ENABLE_WEBRTC)
[email protected]e25f4d72011-06-08 20:58:46676
thestig529ad8a2016-07-08 20:30:12677 audio_input_message_filter_ = new AudioInputMessageFilter(GetIOTaskRunner());
[email protected]f7eb0a392011-07-12 10:19:51678 AddFilter(audio_input_message_filter_.get());
679
thestig529ad8a2016-07-08 20:30:12680 audio_message_filter_ = new AudioMessageFilter(GetIOTaskRunner());
[email protected]f7eb0a392011-07-12 10:19:51681 AddFilter(audio_message_filter_.get());
682
thestig529ad8a2016-07-08 20:30:12683 midi_message_filter_ = new MidiMessageFilter(GetIOTaskRunner());
[email protected]a9875152013-06-22 04:03:03684 AddFilter(midi_message_filter_.get());
685
jsbellabadb9b2015-03-23 21:03:44686 AddFilter((new CacheStorageMessageFilter(thread_safe_sender()))->GetFilter());
687
kinuko5af4ffe2015-06-09 03:38:46688 AddFilter((new ServiceWorkerContextMessageFilter())->GetFilter());
[email protected]ddbb53342014-01-06 10:59:47689
sadrul943e3b32016-08-04 18:22:59690#if defined(USE_AURA)
fsamuel098eade2017-03-21 18:06:14691 if (IsRunningInMash()) {
bend32292b2016-10-07 00:21:58692 CreateRenderWidgetWindowTreeClientFactory(GetServiceManagerConnection());
rockotcef38272016-07-15 22:47:47693 }
694#endif
695
benbd9dc802017-04-19 01:37:43696 auto registry = base::MakeUnique<service_manager::BinderRegistry>();
697 registry->AddInterface(base::Bind(&CreateFrameFactory),
698 base::ThreadTaskRunnerHandle::Get());
699 registry->AddInterface(base::Bind(&EmbeddedWorkerInstanceClientImpl::Create),
700 base::ThreadTaskRunnerHandle::Get());
701 GetServiceManagerConnection()->AddConnectionFilter(
702 base::MakeUnique<SimpleConnectionFilter>(std::move(registry)));
rockotcef38272016-07-15 22:47:47703
[email protected]e9ff79c2012-10-19 21:31:26704 GetContentClient()->renderer()->RenderThreadStarted();
[email protected]6779aa12011-03-29 17:32:24705
benbd9dc802017-04-19 01:37:43706 StartServiceManagerConnection();
707
chiniforooshan614d70a2017-03-17 01:19:33708 field_trial_syncer_.InitFieldTrialObserving(
709 *base::CommandLine::ForCurrentProcess(), switches::kSingleProcess);
710
rockot067ca55f2016-09-30 22:00:15711 GetAssociatedInterfaceRegistry()->AddInterface(
712 base::Bind(&RenderThreadImpl::OnRendererInterfaceRequest,
713 base::Unretained(this)));
714
[email protected]b48c53ad2014-02-05 21:59:18715 InitSkiaEventTracer();
ssid59c969162015-07-28 13:02:58716 base::trace_event::MemoryDumpManager::GetInstance()->RegisterDumpProvider(
primiano186d6bfe2015-10-30 13:21:40717 skia::SkiaMemoryDumpProvider::GetInstance(), "Skia", nullptr);
[email protected]b48c53ad2014-02-05 21:59:18718
avi83883c82014-12-23 00:08:49719 const base::CommandLine& command_line =
720 *base::CommandLine::ForCurrentProcess();
[email protected]e54ab492012-06-12 19:40:01721
ochangdd89a1e2016-06-08 16:39:01722#if defined(ENABLE_IPC_FUZZER)
723 if (command_line.HasSwitch(switches::kIpcDumpDirectory)) {
724 base::FilePath dump_directory =
725 command_line.GetSwitchValuePath(switches::kIpcDumpDirectory);
726 IPC::ChannelProxy::OutgoingMessageFilter* filter =
727 LoadExternalIPCDumper(dump_directory);
728 GetChannel()->set_outgoing_message_filter(filter);
729 }
730#endif
731
jbroman0d302162015-09-05 05:46:23732 cc::SetClientNameForMetrics("Renderer");
loysoa6edaaff2015-05-25 03:26:44733
loyso65c93c602015-08-11 05:15:57734 is_threaded_animation_enabled_ =
735 !command_line.HasSwitch(cc::switches::kDisableThreadedAnimation);
736
fsamuel4c5c87142017-03-14 03:14:26737 is_surface_synchronization_enabled_ =
738 command_line.HasSwitch(cc::switches::kEnableSurfaceSynchronization);
739
reveman91a0a872014-11-04 03:40:32740 is_zero_copy_enabled_ = command_line.HasSwitch(switches::kEnableZeroCopy);
ericrk1d17f752015-10-20 03:03:07741 is_partial_raster_enabled_ =
dongseong.hwang23db47f2016-03-08 07:50:02742 !command_line.HasSwitch(switches::kDisablePartialRaster);
ccameronc7fcd132015-11-03 20:14:31743 is_gpu_memory_buffer_compositor_resources_enabled_ = command_line.HasSwitch(
744 switches::kEnableGpuMemoryBufferCompositorResources);
[email protected]a23530d2014-03-11 06:04:14745
jame1f453c2016-03-21 15:51:34746#if defined(OS_MACOSX)
thakis114a1ef2016-04-26 16:02:59747 base::ScopedCFTypeRef<CFStringRef> key(
748 base::SysUTF8ToCFStringRef("NSScrollViewRubberbanding"));
749 Boolean key_exists = false;
750 Boolean value = CFPreferencesGetAppBooleanValue(
751 key, kCFPreferencesCurrentApplication, &key_exists);
752 is_elastic_overscroll_enabled_ = !key_exists || value;
ccamerona7644752014-12-30 01:16:31753#else
754 is_elastic_overscroll_enabled_ = false;
755#endif
756
danakje6eb185c2015-02-27 23:52:05757 std::string image_texture_target_string =
dcastagna7f2f7192015-06-16 18:44:35758 command_line.GetSwitchValueASCII(switches::kContentImageTextureTarget);
ericrk9151705c2016-07-26 19:53:16759 buffer_to_texture_target_map_ =
760 cc::StringToBufferToTextureTargetMap(image_texture_target_string);
reveman44b807f12014-11-26 02:44:50761
[email protected]a23530d2014-03-11 06:04:14762 if (command_line.HasSwitch(switches::kDisableLCDText)) {
763 is_lcd_text_enabled_ = false;
764 } else if (command_line.HasSwitch(switches::kEnableLCDText)) {
765 is_lcd_text_enabled_ = true;
766 } else {
767#if defined(OS_ANDROID)
768 is_lcd_text_enabled_ = false;
769#else
770 is_lcd_text_enabled_ = true;
771#endif
772 }
773
[email protected]b8d82c22014-03-31 20:12:46774 is_gpu_rasterization_forced_ =
775 command_line.HasSwitch(switches::kForceGpuRasterization);
sunnypsd8ce1c22016-05-10 18:02:40776 is_async_worker_context_enabled_ =
777 command_line.HasSwitch(switches::kEnableGpuAsyncWorkerContext);
[email protected]a23530d2014-03-11 06:04:14778
senorblancob60ba952015-01-27 19:12:36779 if (command_line.HasSwitch(switches::kGpuRasterizationMSAASampleCount)) {
780 std::string string_value = command_line.GetSwitchValueASCII(
781 switches::kGpuRasterizationMSAASampleCount);
782 bool parsed_msaa_sample_count =
783 base::StringToInt(string_value, &gpu_rasterization_msaa_sample_count_);
784 DCHECK(parsed_msaa_sample_count) << string_value;
785 DCHECK_GE(gpu_rasterization_msaa_sample_count_, 0);
786 } else {
senorblanco2a5b0e12015-08-14 21:55:37787 gpu_rasterization_msaa_sample_count_ = -1;
senorblancob60ba952015-01-27 19:12:36788 }
789
[email protected]b242b142014-05-07 14:48:49790 if (command_line.HasSwitch(switches::kDisableDistanceFieldText)) {
791 is_distance_field_text_enabled_ = false;
792 } else if (command_line.HasSwitch(switches::kEnableDistanceFieldText)) {
793 is_distance_field_text_enabled_ = true;
794 } else {
795 is_distance_field_text_enabled_ = false;
796 }
797
[email protected]433df472012-03-07 20:33:39798 // Note that under Linux, the media library will normally already have
799 // been initialized by the Zygote before this instance became a Renderer.
chcunninghamfd11b3c2015-06-09 02:09:42800 media::InitializeMediaLibrary();
[email protected]433df472012-03-07 20:33:39801
dalecurtis88af3932016-02-20 00:12:20802#if defined(OS_ANDROID)
803 if (!command_line.HasSwitch(switches::kDisableAcceleratedVideoDecode) &&
804 media::MediaCodecUtil::IsMediaCodecAvailable()) {
805 media::EnablePlatformDecoderSupport();
806 }
807#endif
808
hubbee6c6eb342017-03-15 20:34:11809 if (base::CommandLine::ForCurrentProcess()->HasSwitch(switches::kEnableHDR) ||
chcunningham9a285ed2017-03-08 21:48:56810 base::CommandLine::ForCurrentProcess()->HasSwitch(
811 switches::kEnableNewVp9CodecString)) {
812 media::EnableNewVp9CodecStringSupport();
813 }
814
bashi296ebda2017-03-28 03:27:09815 memory_pressure_listener_.reset(new base::MemoryPressureListener(
816 base::Bind(&RenderThreadImpl::OnMemoryPressure, base::Unretained(this)),
817 base::Bind(&RenderThreadImpl::OnSyncMemoryPressure,
818 base::Unretained(this))));
819
820 if (base::FeatureList::IsEnabled(features::kMemoryCoordinator)) {
821 // Disable MemoryPressureListener when memory coordinator is enabled.
822 base::MemoryPressureListener::SetNotificationsSuppressed(true);
823
824 // TODO(bashi): Revisit how to manage the lifetime of
825 // ChildMemoryCoordinatorImpl.
826 // https://codereview.chromium.org/2094583002/#msg52
827 mojom::MemoryCoordinatorHandlePtr parent_coordinator;
828 GetConnector()->BindInterface(mojom::kBrowserServiceName,
829 mojo::MakeRequest(&parent_coordinator));
830 memory_coordinator_ = CreateChildMemoryCoordinator(
831 std::move(parent_coordinator), this);
832 }
833
danakj16275d4c2015-06-11 19:23:51834 int num_raster_threads = 0;
835 std::string string_value =
836 command_line.GetSwitchValueASCII(switches::kNumRasterThreads);
837 bool parsed_num_raster_threads =
838 base::StringToInt(string_value, &num_raster_threads);
839 DCHECK(parsed_num_raster_threads) << string_value;
840 DCHECK_GT(num_raster_threads, 0);
vmiura78b69282015-02-14 00:01:17841
vmpstr6c0b5112016-04-25 22:12:14842 // TODO(vmpstr): If the flag sticks, we should clean it up and always have
843 // image decode tasks.
vmpstr9dd810a2016-01-19 21:16:10844 are_image_decode_tasks_enabled_ = true;
halliwell4b3deee2014-12-19 19:57:49845
prashant.nfad657e2016-06-01 07:52:17846 categorized_worker_pool_->Start(num_raster_threads);
[email protected]1e1d1e12014-01-17 16:14:29847
penghuang342762b2016-12-02 21:04:58848 discardable_memory::mojom::DiscardableSharedMemoryManagerPtr manager_ptr;
penghuangd6843e42016-12-17 13:57:20849 if (IsRunningInMash()) {
850#if defined(USE_AURA)
benbd3c2482017-01-07 05:48:21851 GetServiceManagerConnection()->GetConnector()->BindInterface(
penghuangd6843e42016-12-17 13:57:20852 ui::mojom::kServiceName, &manager_ptr);
853#else
854 NOTREACHED();
855#endif
856 } else {
ben649b3edd2017-03-23 00:32:02857 ChildThread::Get()->GetConnector()->BindInterface(
858 mojom::kBrowserServiceName, mojo::MakeRequest(&manager_ptr));
penghuangd6843e42016-12-17 13:57:20859 }
860
penghuang342762b2016-12-02 21:04:58861 discardable_shared_memory_manager_ = base::MakeUnique<
862 discardable_memory::ClientDiscardableSharedMemoryManager>(
863 std::move(manager_ptr), GetIOTaskRunner());
864
boliu9760e212015-06-23 22:49:06865 // TODO(boliu): In single process, browser main loop should set up the
866 // discardable memory manager, and should skip this if kSingleProcess.
867 // See crbug.com/503724.
868 base::DiscardableMemoryAllocator::SetInstance(
penghuang342762b2016-12-02 21:04:58869 discardable_shared_memory_manager_.get());
revemancb5a66af2014-10-25 00:34:39870
ben649b3edd2017-03-23 00:32:02871 GetConnector()->BindInterface(mojom::kBrowserServiceName,
872 mojo::MakeRequest(&storage_partition_service_));
hajimehoshi69093272016-05-13 08:30:58873
reveman7b97c322016-09-20 02:10:58874#if defined(OS_LINUX)
875 ChildProcess::current()->SetIOThreadPriority(base::ThreadPriority::DISPLAY);
876 ChildThreadImpl::current()->SetThreadPriority(
lukasza6710dbd2017-04-07 20:58:03877 categorized_worker_pool_->background_worker_thread_id(),
reveman7b97c322016-09-20 02:10:58878 base::ThreadPriority::BACKGROUND);
879#endif
880
tasakb46626a2016-10-18 05:54:44881 record_purge_suspend_metric_closure_.Reset(base::Bind(
882 &RenderThreadImpl::RecordPurgeAndSuspendMetrics, base::Unretained(this)));
tasak72f64042017-01-19 14:02:53883 record_purge_suspend_growth_metric_closure_.Reset(
884 base::Bind(&RenderThreadImpl::RecordPurgeAndSuspendMemoryGrowthMetrics,
885 base::Unretained(this)));
tasakb95dbb50c2017-02-08 18:07:50886 needs_to_record_first_active_paint_ = false;
hajimehoshi7bb39582016-10-12 04:30:57887
888 base::MemoryCoordinatorClientRegistry::GetInstance()->Register(this);
fdoray50a38342016-11-21 20:46:04889
890 // If this renderer doesn't run inside the browser process, enable
891 // SequencedWorkerPool. Otherwise, it should already have been enabled.
892 // TODO(fdoray): Remove this once the SequencedWorkerPool to TaskScheduler
893 // redirection experiment concludes https://crbug.com/622400.
894 if (!command_line.HasSwitch(switches::kSingleProcess))
895 base::SequencedWorkerPool::EnableForProcess();
samans2040988b2017-04-11 23:58:35896
897 GetConnector()->BindInterface(mojom::kBrowserServiceName,
898 mojo::MakeRequest(&frame_sink_provider_));
initial.commit09911bf2008-07-26 23:55:29899}
900
[email protected]f1a29a02011-10-06 23:08:44901RenderThreadImpl::~RenderThreadImpl() {
[email protected]ce79d8512013-04-22 22:44:41902}
903
904void RenderThreadImpl::Shutdown() {
harakenbbfdd9f02017-01-12 07:14:04905 // In a multi-process mode, we immediately exit the renderer.
906 // Historically we had a graceful shutdown sequence here but it was
907 // 1) a waste of performance and 2) a source of lots of complicated
908 // crashes caused by shutdown ordering. Immediate exit eliminates
909 // those problems.
cbrunia3f655b2017-03-20 11:36:41910
911 // Give the V8 isolate a chance to dump internal stats useful for performance
912 // evaluation and debugging.
Blink Reformat1c4d759e2017-04-09 16:34:54913 blink::MainThreadIsolate()->DumpAndResetStats();
cbrunia3f655b2017-03-20 11:36:41914
harakenbbfdd9f02017-01-12 07:14:04915 // In a single-process mode, we cannot call _exit(0) in Shutdown() because
916 // it will exit the process before the browser side is ready to exit.
917 if (!base::CommandLine::ForCurrentProcess()->HasSwitch(
918 switches::kSingleProcess))
haraken940efb92017-02-08 05:58:15919 base::Process::TerminateCurrentProcessImmediately(0);
harakenbbfdd9f02017-01-12 07:14:04920}
[email protected]1223d6ef2011-03-28 16:47:50921
harakenbbfdd9f02017-01-12 07:14:04922bool RenderThreadImpl::ShouldBeDestroyed() {
923 DCHECK(base::CommandLine::ForCurrentProcess()->HasSwitch(
924 switches::kSingleProcess));
925 // In a single-process mode, it is unsafe to destruct this renderer thread
926 // because we haven't run the shutdown sequence. Hence we leak the render
927 // thread.
928 //
929 // In this case, we also need to disable at-exit callbacks because some of
930 // the at-exit callbacks are expected to run after the renderer thread
931 // has been destructed.
932 base::AtExitManager::DisableAllAtExitManagers();
933 return false;
initial.commit09911bf2008-07-26 23:55:29934}
935
[email protected]f1a29a02011-10-06 23:08:44936bool RenderThreadImpl::Send(IPC::Message* msg) {
changwan6ed4d432016-05-19 22:03:54937 // There are cases where we want to pump asynchronous messages while waiting
938 // synchronously for the replies to the message to be sent here. However, this
939 // may create an opportunity for re-entrancy into WebKit and other subsystems,
940 // so we need to take care to disable callbacks, timers, and pending network
941 // loads that could trigger such callbacks.
[email protected]38b592902011-04-16 02:08:42942 bool pumping_events = false;
[email protected]80fc08c52010-03-09 07:43:50943 if (msg->is_sync()) {
944 if (msg->is_caller_pumping_messages()) {
945 pumping_events = true;
[email protected]80fc08c52010-03-09 07:43:50946 }
[email protected]c1f50aa2010-02-18 03:46:57947 }
948
[email protected]c1f50aa2010-02-18 03:46:57949 if (pumping_events) {
jdduked73ae5412015-05-11 20:07:16950 renderer_scheduler_->SuspendTimerQueue();
Blink Reformat1c4d759e2017-04-09 16:34:54951 WebView::WillEnterModalLoop();
[email protected]c1f50aa2010-02-18 03:46:57952 }
953
jam8a021512a2015-02-03 18:16:08954 bool rv = ChildThreadImpl::Send(msg);
[email protected]c1f50aa2010-02-18 03:46:57955
956 if (pumping_events) {
Blink Reformat1c4d759e2017-04-09 16:34:54957 WebView::DidExitModalLoop();
jdduked73ae5412015-05-11 20:07:16958 renderer_scheduler_->ResumeTimerQueue();
[email protected]c1f50aa2010-02-18 03:46:57959 }
960
961 return rv;
962}
963
[email protected]f1a29a02011-10-06 23:08:44964IPC::SyncChannel* RenderThreadImpl::GetChannel() {
[email protected]526476902011-10-06 20:34:06965 return channel();
966}
967
[email protected]f1a29a02011-10-06 23:08:44968std::string RenderThreadImpl::GetLocale() {
[email protected]526476902011-10-06 20:34:06969 // The browser process should have passed the locale to the renderer via the
[email protected]dfd53652012-10-25 00:20:02970 // --lang command line flag.
avi83883c82014-12-23 00:08:49971 const base::CommandLine& parsed_command_line =
972 *base::CommandLine::ForCurrentProcess();
[email protected]526476902011-10-06 20:34:06973 const std::string& lang =
974 parsed_command_line.GetSwitchValueASCII(switches::kLang);
[email protected]dfd53652012-10-25 00:20:02975 DCHECK(!lang.empty());
[email protected]526476902011-10-06 20:34:06976 return lang;
977}
978
[email protected]07bb6332012-01-21 01:07:57979IPC::SyncMessageFilter* RenderThreadImpl::GetSyncMessageFilter() {
980 return sync_message_filter();
981}
982
skyostil12262cf2015-05-21 14:49:31983scoped_refptr<base::SingleThreadTaskRunner>
thestig529ad8a2016-07-08 20:30:12984RenderThreadImpl::GetIOTaskRunner() {
skyostil12262cf2015-05-21 14:49:31985 return ChildProcess::current()->io_task_runner();
[email protected]96191d52012-05-17 01:37:11986}
987
avi1023d012015-12-25 02:39:14988void RenderThreadImpl::AddRoute(int32_t routing_id, IPC::Listener* listener) {
jam8a021512a2015-02-03 18:16:08989 ChildThreadImpl::GetRouter()->AddRoute(routing_id, listener);
ben76f52b242016-06-18 05:42:48990 auto it = pending_frame_creates_.find(routing_id);
991 if (it == pending_frame_creates_.end())
rockotf8fdd9b2015-12-16 22:22:35992 return;
993
994 RenderFrameImpl* frame = RenderFrameImpl::FromRoutingID(routing_id);
995 if (!frame)
996 return;
997
ben76f52b242016-06-18 05:42:48998 scoped_refptr<PendingFrameCreate> create(it->second);
dominickn6c1f1cf2016-12-20 06:13:33999 frame->BindFrame(it->second->TakeFrameRequest(), it->second->TakeFrameHost());
ben76f52b242016-06-18 05:42:481000 pending_frame_creates_.erase(it);
[email protected]c1f50aa2010-02-18 03:46:571001}
1002
avi1023d012015-12-25 02:39:141003void RenderThreadImpl::RemoveRoute(int32_t routing_id) {
jam8a021512a2015-02-03 18:16:081004 ChildThreadImpl::GetRouter()->RemoveRoute(routing_id);
[email protected]c1f50aa2010-02-18 03:46:571005}
[email protected]0ec90d522014-03-12 16:28:191006
avi1023d012015-12-25 02:39:141007void RenderThreadImpl::AddEmbeddedWorkerRoute(int32_t routing_id,
[email protected]a620b132014-04-30 22:39:171008 IPC::Listener* listener) {
[email protected]48e52e42014-03-20 06:58:071009 AddRoute(routing_id, listener);
1010 if (devtools_agent_message_filter_.get()) {
[email protected]a620b132014-04-30 22:39:171011 devtools_agent_message_filter_->AddEmbeddedWorkerRouteOnMainThread(
[email protected]48e52e42014-03-20 06:58:071012 routing_id);
1013 }
1014}
1015
avi1023d012015-12-25 02:39:141016void RenderThreadImpl::RemoveEmbeddedWorkerRoute(int32_t routing_id) {
[email protected]48e52e42014-03-20 06:58:071017 RemoveRoute(routing_id);
1018 if (devtools_agent_message_filter_.get()) {
[email protected]a620b132014-04-30 22:39:171019 devtools_agent_message_filter_->RemoveEmbeddedWorkerRouteOnMainThread(
[email protected]48e52e42014-03-20 06:58:071020 routing_id);
1021 }
1022}
1023
ben76f52b242016-06-18 05:42:481024void RenderThreadImpl::RegisterPendingFrameCreate(
rockotf8fdd9b2015-12-16 22:22:351025 int routing_id,
ben76f52b242016-06-18 05:42:481026 mojom::FrameRequest frame_request,
1027 mojom::FrameHostPtr frame_host) {
1028 std::pair<PendingFrameCreateMap::iterator, bool> result =
1029 pending_frame_creates_.insert(std::make_pair(
rockotf8fdd9b2015-12-16 22:22:351030 routing_id,
ben76f52b242016-06-18 05:42:481031 make_scoped_refptr(new PendingFrameCreate(
1032 routing_id, std::move(frame_request), std::move(frame_host)))));
rockotf8fdd9b2015-12-16 22:22:351033 CHECK(result.second) << "Inserting a duplicate item.";
1034}
1035
leon.han06e55662016-03-26 17:19:421036mojom::StoragePartitionService* RenderThreadImpl::GetStoragePartitionService() {
jamc912ca32016-02-24 20:17:311037 return storage_partition_service_.get();
1038}
1039
[email protected]77fc9b92011-10-15 16:20:371040int RenderThreadImpl::GenerateRoutingID() {
rockote261d2112016-09-21 22:22:231041 int32_t routing_id = MSG_ROUTING_NONE;
1042 render_message_filter()->GenerateRoutingID(&routing_id);
[email protected]77fc9b92011-10-15 16:20:371043 return routing_id;
1044}
1045
[email protected]74122042014-04-25 00:07:301046void RenderThreadImpl::AddFilter(IPC::MessageFilter* filter) {
[email protected]42f1d7822009-07-23 18:17:551047 channel()->AddFilter(filter);
1048}
1049
[email protected]74122042014-04-25 00:07:301050void RenderThreadImpl::RemoveFilter(IPC::MessageFilter* filter) {
[email protected]42f1d7822009-07-23 18:17:551051 channel()->RemoveFilter(filter);
1052}
1053
tyoshino832a58a2016-04-18 08:14:081054void RenderThreadImpl::AddObserver(RenderThreadObserver* observer) {
[email protected]526476902011-10-06 20:34:061055 observers_.AddObserver(observer);
nigeltao7cd8d5582016-12-12 06:05:281056 observer->RegisterMojoInterfaces(&associated_interfaces_);
[email protected]526476902011-10-06 20:34:061057}
1058
tyoshino832a58a2016-04-18 08:14:081059void RenderThreadImpl::RemoveObserver(RenderThreadObserver* observer) {
nigeltao7cd8d5582016-12-12 06:05:281060 observer->UnregisterMojoInterfaces(&associated_interfaces_);
[email protected]526476902011-10-06 20:34:061061 observers_.RemoveObserver(observer);
1062}
1063
[email protected]359dfa32011-10-12 01:10:151064void RenderThreadImpl::SetResourceDispatcherDelegate(
[email protected]e9ff79c2012-10-19 21:31:261065 ResourceDispatcherDelegate* delegate) {
[email protected]359dfa32011-10-12 01:10:151066 resource_dispatcher()->set_delegate(delegate);
1067}
1068
vollick1050cc62015-12-03 07:04:541069void RenderThreadImpl::InitializeCompositorThread() {
boliu66024c62016-04-20 04:00:411070 base::Thread::Options options;
vollick1050cc62015-12-03 07:04:541071#if defined(OS_ANDROID)
boliu66024c62016-04-20 04:00:411072 options.priority = base::ThreadPriority::DISPLAY;
vollick1050cc62015-12-03 07:04:541073#endif
altiminc7369bf2017-04-11 14:29:151074 compositor_thread_ =
1075 blink::scheduler::WebThreadBase::CreateCompositorThread(options);
boliu66024c62016-04-20 04:00:411076 blink_platform_impl_->SetCompositorThread(compositor_thread_.get());
1077 compositor_task_runner_ = compositor_thread_->GetTaskRunner();
1078 compositor_task_runner_->PostTask(
1079 FROM_HERE,
1080 base::Bind(base::IgnoreResult(&ThreadRestrictions::SetIOAllowed), false));
reveman7b97c322016-09-20 02:10:581081#if defined(OS_LINUX)
Blink Reformat1c4d759e2017-04-09 16:34:541082 ChildThreadImpl::current()->SetThreadPriority(compositor_thread_->ThreadId(),
reveman7b97c322016-09-20 02:10:581083 base::ThreadPriority::DISPLAY);
1084#endif
vollick1050cc62015-12-03 07:04:541085
boliude5b75b2016-03-11 07:02:141086 SynchronousInputHandlerProxyClient* synchronous_input_handler_proxy_client =
1087 nullptr;
vollick1050cc62015-12-03 07:04:541088#if defined(OS_ANDROID)
boliu66024c62016-04-20 04:00:411089 if (GetContentClient()->UsingSynchronousCompositing()) {
vollick1050cc62015-12-03 07:04:541090 sync_compositor_message_filter_ =
1091 new SynchronousCompositorFilter(compositor_task_runner_);
1092 AddFilter(sync_compositor_message_filter_.get());
boliude5b75b2016-03-11 07:02:141093 synchronous_input_handler_proxy_client =
1094 sync_compositor_message_filter_.get();
vollick1050cc62015-12-03 07:04:541095 }
1096#endif
boliub2768db2016-06-03 23:35:161097 scoped_refptr<InputEventFilter> compositor_input_event_filter(
1098 new InputEventFilter(main_input_callback_.callback(),
1099 main_thread_compositor_task_runner_,
1100 compositor_task_runner_));
1101 InputHandlerManagerClient* input_handler_manager_client =
1102 compositor_input_event_filter.get();
1103 input_event_filter_ = compositor_input_event_filter;
vollick1050cc62015-12-03 07:04:541104 input_handler_manager_.reset(new InputHandlerManager(
1105 compositor_task_runner_, input_handler_manager_client,
boliude5b75b2016-03-11 07:02:141106 synchronous_input_handler_proxy_client, renderer_scheduler_.get()));
vollick1050cc62015-12-03 07:04:541107}
1108
jam75c44222016-03-23 05:34:241109void RenderThreadImpl::InitializeWebKit(
rockot97a86832016-12-10 04:53:061110 const scoped_refptr<base::SingleThreadTaskRunner>& resource_task_queue) {
jam75c44222016-03-23 05:34:241111 DCHECK(!blink_platform_impl_);
[email protected]d1b8fccc2011-08-03 01:20:131112
avi83883c82014-12-23 00:08:491113 const base::CommandLine& command_line =
1114 *base::CommandLine::ForCurrentProcess();
chunyang.daibe874c52014-11-14 06:45:051115
1116#ifdef ENABLE_VTUNE_JIT_INTERFACE
1117 if (command_line.HasSwitch(switches::kEnableVtune))
1118 gin::Debug::SetJitCodeEventHandler(vTune::GetVtuneCodeEventHandler());
1119#endif
1120
rmcilroy4073ae12015-01-08 13:08:101121 SetRuntimeFeaturesDefaultsAndUpdateFromArgs(command_line);
hlopko852ffcf2016-09-16 16:50:591122 GetContentClient()
1123 ->renderer()
1124 ->SetRuntimeFeaturesDefaultsBeforeBlinkInitialization();
rmcilroy4073ae12015-01-08 13:08:101125
sammcbebeb602016-04-06 06:42:551126 blink_platform_impl_.reset(new RendererBlinkPlatformImpl(
ben649b3edd2017-03-23 00:32:021127 renderer_scheduler_.get(), GetConnector()->GetWeakPtr()));
Blink Reformat1c4d759e2017-04-09 16:34:541128 blink::Initialize(blink_platform_impl_.get());
[email protected]d1b8fccc2011-08-03 01:20:131129
Blink Reformat1c4d759e2017-04-09 16:34:541130 v8::Isolate* isolate = blink::MainThreadIsolate();
[email protected]4b5340282014-07-08 11:37:341131 isolate->SetCreateHistogramFunction(CreateHistogram);
1132 isolate->SetAddHistogramSampleFunction(AddHistogramSample);
skyostila37c2a72016-06-29 17:30:071133 renderer_scheduler_->SetRAILModeObserver(this);
[email protected]4b5340282014-07-08 11:37:341134
rmcilroy321f924d2014-11-06 00:56:001135 main_thread_compositor_task_runner_ =
danakj6e3bf8012014-12-16 18:27:531136 renderer_scheduler_->CompositorTaskRunner();
skyostilc30aa402014-10-10 13:49:091137
jdduke691dd572014-12-02 20:47:521138 main_input_callback_.Reset(
1139 base::Bind(base::IgnoreResult(&RenderThreadImpl::OnMessageReceived),
1140 base::Unretained(this)));
1141
jam75c44222016-03-23 05:34:241142 scoped_refptr<base::SingleThreadTaskRunner> resource_task_queue2;
1143 if (resource_task_queue) {
1144 resource_task_queue2 = resource_task_queue;
1145 } else {
1146 resource_task_queue2 = renderer_scheduler_->LoadingTaskRunner();
1147 }
1148 // Add a filter that forces resource messages to be dispatched via a
1149 // particular task runner.
1150 scoped_refptr<ResourceSchedulingFilter> filter(
1151 new ResourceSchedulingFilter(
1152 resource_task_queue2, resource_dispatcher()));
1153 channel()->AddFilter(filter.get());
1154 resource_dispatcher()->SetResourceSchedulingFilter(filter);
1155
1156 // The ChildResourceMessageFilter and the ResourceDispatcher need to use the
1157 // same queue to ensure tasks are executed in the expected order.
1158 child_resource_message_filter()->SetMainThreadTaskRunner(
1159 resource_task_queue2);
1160 resource_dispatcher()->SetMainThreadTaskRunner(resource_task_queue2);
1161
khushalsagard7178e42017-01-20 01:31:491162 if (!command_line.HasSwitch(switches::kDisableThreadedCompositing))
vollick1050cc62015-12-03 07:04:541163 InitializeCompositorThread();
[email protected]a9fb30aa2011-10-06 06:58:461164
jdduke691dd572014-12-02 20:47:521165 if (!input_event_filter_.get()) {
1166 // Always provide an input event filter implementation to ensure consistent
1167 // input event scheduling and prioritization.
1168 // TODO(jdduke): Merge InputEventFilter, InputHandlerManager and
1169 // MainThreadInputEventFilter, crbug.com/436057.
1170 input_event_filter_ = new MainThreadInputEventFilter(
1171 main_input_callback_.callback(), main_thread_compositor_task_runner_);
1172 }
1173 AddFilter(input_event_filter_.get());
1174
skyostil2d3b5bd2015-05-27 15:40:591175 scoped_refptr<base::SingleThreadTaskRunner> compositor_impl_side_task_runner;
vollick1050cc62015-12-03 07:04:541176 if (compositor_task_runner_)
skyostil2d3b5bd2015-05-27 15:40:591177 compositor_impl_side_task_runner = compositor_task_runner_;
[email protected]7f1f63f2013-03-07 06:07:291178 else
skyostil2d3b5bd2015-05-27 15:40:591179 compositor_impl_side_task_runner = base::ThreadTaskRunnerHandle::Get();
[email protected]1842fe22012-08-13 23:24:351180
simonhonga7e3ac42014-11-11 20:50:221181 compositor_message_filter_ = new CompositorForwardingMessageFilter(
skyostil2d3b5bd2015-05-27 15:40:591182 compositor_impl_side_task_runner.get());
simonhonga7e3ac42014-11-11 20:50:221183 AddFilter(compositor_message_filter_.get());
[email protected]1842fe22012-08-13 23:24:351184
[email protected]58436a12012-03-21 17:10:261185 RenderThreadImpl::RegisterSchemes();
1186
xhwang194acae2014-11-12 22:46:331187 RenderMediaClient::Initialize();
1188
[email protected]b146d6d2012-09-11 10:20:051189 devtools_agent_message_filter_ = new DevToolsAgentFilter();
1190 AddFilter(devtools_agent_message_filter_.get());
1191
ulan4a385192015-11-11 10:59:181192 if (GetContentClient()->renderer()->RunIdleHandlerWhenWidgetsHidden()) {
[email protected]1784b2f2011-11-24 10:53:481193 ScheduleIdleHandler(kLongIdleHandlerDelayMs);
ulan4a385192015-11-11 10:59:181194 } else {
1195 // If we do not track widget visibility, then assume conservatively that
1196 // the isolate is in background. This reduces memory usage.
1197 isolate->IsolateInBackgroundNotification();
1198 }
[email protected]2541d1a2013-07-10 07:33:271199
jdduke73220f02015-09-04 17:03:511200 renderer_scheduler_->SetTimerQueueSuspensionWhenBackgroundedEnabled(
1201 GetContentClient()
1202 ->renderer()
1203 ->AllowTimerSuspensionWhenProcessBackgrounded());
1204
reedccf98c52014-10-03 16:40:381205 SkGraphics::SetResourceCacheSingleAllocationByteLimit(
[email protected]dd2c1022014-07-22 23:13:571206 kImageCacheSingleAllocationByteLimit);
1207
reed6e5a72222015-08-06 20:37:161208 // Hook up blink's codecs so skia can call them
reed08cd16372017-02-21 22:11:411209 SkGraphics::SetImageGeneratorFromEncodedDataFactory(
Blink Reformat1c4d759e2017-04-09 16:34:541210 blink::WebImageGenerator::Create);
reed6e5a72222015-08-06 20:37:161211
[email protected]fdeac262014-07-10 12:52:511212 if (command_line.HasSwitch(switches::kMemoryMetrics)) {
1213 memory_observer_.reset(new MemoryObserver());
1214 message_loop()->AddTaskObserver(memory_observer_.get());
1215 }
paritosh.in7e30c902015-04-15 17:04:071216
1217 if (command_line.HasSwitch(switches::kExplicitlyAllowedPorts)) {
1218 std::string allowed_ports =
1219 command_line.GetSwitchValueASCII(switches::kExplicitlyAllowedPorts);
1220 net::SetExplicitlyAllowedPorts(allowed_ports);
1221 }
[email protected]d1b8fccc2011-08-03 01:20:131222}
1223
[email protected]58436a12012-03-21 17:10:261224void RenderThreadImpl::RegisterSchemes() {
mkwst8e94fb32015-05-20 05:05:141225 // chrome:
Blink Reformat1c4d759e2017-04-09 16:34:541226 WebString chrome_scheme(WebString::FromASCII(kChromeUIScheme));
1227 WebSecurityPolicy::RegisterURLSchemeAsDisplayIsolated(chrome_scheme);
1228 WebSecurityPolicy::RegisterURLSchemeAsNotAllowingJavascriptURLs(
mkwst8e94fb32015-05-20 05:05:141229 chrome_scheme);
mkwst8e94fb32015-05-20 05:05:141230
1231 // chrome-devtools:
Blink Reformat1c4d759e2017-04-09 16:34:541232 WebString devtools_scheme(WebString::FromASCII(kChromeDevToolsScheme));
1233 WebSecurityPolicy::RegisterURLSchemeAsDisplayIsolated(devtools_scheme);
meacerce6b66032016-06-02 20:56:051234
1235 // view-source:
Blink Reformat1c4d759e2017-04-09 16:34:541236 WebString view_source_scheme(WebString::FromASCII(kViewSourceScheme));
1237 WebSecurityPolicy::RegisterURLSchemeAsDisplayIsolated(view_source_scheme);
[email protected]58436a12012-03-21 17:10:261238}
1239
[email protected]e6e30ac2014-01-13 21:24:391240void RenderThreadImpl::RecordAction(const base::UserMetricsAction& action) {
[email protected]97880c82013-12-04 07:09:211241 Send(new ViewHostMsg_UserMetricsRecordAction(action.str_));
1242}
1243
1244void RenderThreadImpl::RecordComputedAction(const std::string& action) {
[email protected]526476902011-10-06 20:34:061245 Send(new ViewHostMsg_UserMetricsRecordAction(action));
1246}
1247
dchengcedca5612016-04-09 01:40:151248std::unique_ptr<base::SharedMemory>
1249RenderThreadImpl::HostAllocateSharedMemoryBuffer(size_t size) {
sadrulee3ff1f2016-12-09 04:22:011250 return ChildThreadImpl::AllocateSharedMemory(size);
[email protected]00614a82011-10-07 22:39:311251}
1252
jbauman2f5c1942014-12-06 03:28:241253cc::SharedBitmapManager* RenderThreadImpl::GetSharedBitmapManager() {
1254 return shared_bitmap_manager();
1255}
1256
[email protected]f1a29a02011-10-06 23:08:441257void RenderThreadImpl::RegisterExtension(v8::Extension* extension) {
Blink Reformat1c4d759e2017-04-09 16:34:541258 WebScriptController::RegisterExtension(extension);
[email protected]526476902011-10-06 20:34:061259}
1260
avi1023d012015-12-25 02:39:141261void RenderThreadImpl::ScheduleIdleHandler(int64_t initial_delay_ms) {
[email protected]6593ae12011-11-14 12:09:441262 idle_notification_delay_in_ms_ = initial_delay_ms;
[email protected]526476902011-10-06 20:34:061263 idle_timer_.Stop();
1264 idle_timer_.Start(FROM_HERE,
[email protected]6593ae12011-11-14 12:09:441265 base::TimeDelta::FromMilliseconds(initial_delay_ms),
[email protected]f1a29a02011-10-06 23:08:441266 this, &RenderThreadImpl::IdleHandler);
[email protected]526476902011-10-06 20:34:061267}
1268
[email protected]f1a29a02011-10-06 23:08:441269void RenderThreadImpl::IdleHandler() {
[email protected]1784b2f2011-11-24 10:53:481270 bool run_in_foreground_tab = (widget_count_ > hidden_widget_count_) &&
[email protected]e9ff79c2012-10-19 21:31:261271 GetContentClient()->renderer()->
[email protected]1784b2f2011-11-24 10:53:481272 RunIdleHandlerWhenWidgetsHidden();
1273 if (run_in_foreground_tab) {
jochen5a32aaf2014-09-26 20:37:431274 if (idle_notifications_to_skip_ > 0) {
1275 --idle_notifications_to_skip_;
1276 } else {
ssid0603ca9f2015-06-09 16:48:081277 ReleaseFreeMemory();
jochen5a32aaf2014-09-26 20:37:431278 }
1279 ScheduleIdleHandler(kLongIdleHandlerDelayMs);
[email protected]1784b2f2011-11-24 10:53:481280 return;
1281 }
[email protected]237a14852012-04-28 02:56:381282
ssid0603ca9f2015-06-09 16:48:081283 ReleaseFreeMemory();
[email protected]526476902011-10-06 20:34:061284
[email protected]26e82322014-01-20 14:18:221285 // Continue the idle timer if the webkit shared timer is not suspended or
1286 // something is left to do.
1287 bool continue_timer = !webkit_shared_timer_suspended_;
1288
sullivancd45a3e2014-09-19 14:39:181289 // Schedule next invocation. When the tab is originally hidden, an invocation
1290 // is scheduled for kInitialIdleHandlerDelayMs in
1291 // RenderThreadImpl::WidgetHidden in order to race to a minimal heap.
1292 // After that, idle calls can be much less frequent, so run at a maximum of
1293 // once every kLongIdleHandlerDelayMs.
[email protected]6593ae12011-11-14 12:09:441294 // Dampen the delay using the algorithm (if delay is in seconds):
[email protected]526476902011-10-06 20:34:061295 // delay = delay + 1 / (delay + 2)
1296 // Using floor(delay) has a dampening effect such as:
sullivancd45a3e2014-09-19 14:39:181297 // 30s, 30, 30, 31, 31, 31, 31, 32, 32, ...
[email protected]6593ae12011-11-14 12:09:441298 // If the delay is in milliseconds, the above formula is equivalent to:
1299 // delay_ms / 1000 = delay_ms / 1000 + 1 / (delay_ms / 1000 + 2)
1300 // which is equivalent to
1301 // delay_ms = delay_ms + 1000*1000 / (delay_ms + 2000).
[email protected]26e82322014-01-20 14:18:221302 if (continue_timer) {
sullivancd45a3e2014-09-19 14:39:181303 ScheduleIdleHandler(
1304 std::max(kLongIdleHandlerDelayMs,
1305 idle_notification_delay_in_ms_ +
1306 1000000 / (idle_notification_delay_in_ms_ + 2000)));
[email protected]26e82322014-01-20 14:18:221307
1308 } else {
1309 idle_timer_.Stop();
1310 }
[email protected]526476902011-10-06 20:34:061311
ericwilligers88e69742016-10-17 19:29:551312 for (auto& observer : observers_)
1313 observer.IdleNotification();
[email protected]526476902011-10-06 20:34:061314}
1315
avi1023d012015-12-25 02:39:141316int64_t RenderThreadImpl::GetIdleNotificationDelayInMs() const {
[email protected]6593ae12011-11-14 12:09:441317 return idle_notification_delay_in_ms_;
[email protected]526476902011-10-06 20:34:061318}
1319
[email protected]6593ae12011-11-14 12:09:441320void RenderThreadImpl::SetIdleNotificationDelayInMs(
avi1023d012015-12-25 02:39:141321 int64_t idle_notification_delay_in_ms) {
[email protected]6593ae12011-11-14 12:09:441322 idle_notification_delay_in_ms_ = idle_notification_delay_in_ms;
[email protected]4a7d6392011-09-19 20:55:081323}
1324
[email protected]5b18406362013-06-18 18:46:431325int RenderThreadImpl::PostTaskToAllWebWorkers(const base::Closure& closure) {
kinukoef647412015-12-23 06:10:431326 return WorkerThreadRegistry::Instance()->PostTaskToAllThreads(closure);
[email protected]a9bd323d2013-06-17 20:27:561327}
1328
[email protected]b02f5902012-12-19 07:33:001329bool RenderThreadImpl::ResolveProxy(const GURL& url, std::string* proxy_list) {
1330 bool result = false;
1331 Send(new ViewHostMsg_ResolveProxy(url, &result, proxy_list));
1332 return result;
1333}
1334
[email protected]1784b2f2011-11-24 10:53:481335void RenderThreadImpl::PostponeIdleNotification() {
1336 idle_notifications_to_skip_ = 2;
1337}
1338
dcastagna7f45dada2015-10-19 20:17:351339media::GpuVideoAcceleratorFactories* RenderThreadImpl::GetGpuFactories() {
[email protected]3bb8bb32013-07-11 13:13:031340 DCHECK(IsMainThread());
1341
dcastagna09bd6b32016-02-01 21:54:281342 if (!gpu_factories_.empty()) {
sadrul85cc5d82016-12-20 03:37:411343 scoped_refptr<ui::ContextProviderCommandBuffer> shared_context_provider =
dcastagna09bd6b32016-02-01 21:54:281344 gpu_factories_.back()->ContextProviderMainThread();
1345 if (shared_context_provider) {
1346 cc::ContextProvider::ScopedContextLock lock(
1347 shared_context_provider.get());
1348 if (lock.ContextGL()->GetGraphicsResetStatusKHR() == GL_NO_ERROR) {
leon.han21e0e482017-02-23 04:13:321349 return gpu_factories_.back().get();
dcastagna09bd6b32016-02-01 21:54:281350 } else {
1351 scoped_refptr<base::SingleThreadTaskRunner> media_task_runner =
1352 GetMediaThreadTaskRunner();
1353 media_task_runner->PostTask(
1354 FROM_HERE,
1355 base::Bind(
1356 base::IgnoreResult(
1357 &RendererGpuVideoAcceleratorFactories::CheckContextLost),
leon.han21e0e482017-02-23 04:13:321358 base::Unretained(gpu_factories_.back().get())));
dcastagna09bd6b32016-02-01 21:54:281359 }
1360 }
1361 }
dcastagna7f45dada2015-10-19 20:17:351362
tobiasjsca238b3b2015-06-24 22:53:541363 const base::CommandLine* cmd_line = base::CommandLine::ForCurrentProcess();
1364
danakj0b4b94e32016-05-10 22:33:011365 scoped_refptr<gpu::GpuChannelHost> gpu_channel_host =
sadrul6d310fa2016-08-04 02:12:161366 EstablishGpuChannelSync();
danakj0b4b94e32016-05-10 22:33:011367 if (!gpu_channel_host)
1368 return nullptr;
danakj0dd9e1e2016-05-11 22:15:091369 // This context is only used to create textures and mailbox them, so
1370 // use lower limits than the default.
1371 gpu::SharedMemoryLimits limits = gpu::SharedMemoryLimits::ForMailboxContext();
danakj9a04adc2016-05-16 22:45:071372 bool support_locking = true;
sadrul85cc5d82016-12-20 03:37:411373 scoped_refptr<ui::ContextProviderCommandBuffer> media_context_provider =
danakj9a04adc2016-05-16 22:45:071374 CreateOffscreenContext(gpu_channel_host, limits, support_locking,
ericrka20c1002017-03-13 21:08:131375 ui::command_buffer_metrics::MEDIA_CONTEXT,
danakj0dd9e1e2016-05-11 22:15:091376 gpu::GPU_STREAM_DEFAULT,
1377 gpu::GpuStreamPriority::NORMAL);
danakj0b4b94e32016-05-10 22:33:011378 if (!media_context_provider->BindToCurrentThread())
1379 return nullptr;
danakj0b4b94e32016-05-10 22:33:011380
acolwellb4034942014-08-28 15:42:431381 scoped_refptr<base::SingleThreadTaskRunner> media_task_runner =
1382 GetMediaThreadTaskRunner();
danakj0b4b94e32016-05-10 22:33:011383 const bool enable_video_accelerator =
1384 !cmd_line->HasSwitch(switches::kDisableAcceleratedVideoDecode);
1385 const bool enable_gpu_memory_buffer_video_frames =
dcastagna43c3a86a2016-02-02 21:16:381386#if defined(OS_MACOSX) || defined(OS_LINUX)
dcastagnaa82ed96a2016-05-12 02:52:471387 !cmd_line->HasSwitch(switches::kDisableGpuMemoryBufferVideoFrames) &&
1388 !cmd_line->HasSwitch(switches::kDisableGpuCompositing) &&
1389 !gpu_channel_host->gpu_info().software_rendering;
dcastagnab65e6072015-09-05 07:18:421390#else
danakj0b4b94e32016-05-10 22:33:011391 cmd_line->HasSwitch(switches::kEnableGpuMemoryBufferVideoFrames);
dcastagnab65e6072015-09-05 07:18:421392#endif
dcastagna5077d6d2016-01-27 00:07:051393
danakj0b4b94e32016-05-10 22:33:011394 gpu_factories_.push_back(RendererGpuVideoAcceleratorFactories::Create(
1395 std::move(gpu_channel_host), base::ThreadTaskRunnerHandle::Get(),
1396 media_task_runner, std::move(media_context_provider),
ericrk9151705c2016-07-26 19:53:161397 enable_gpu_memory_buffer_video_frames, buffer_to_texture_target_map_,
danakj0b4b94e32016-05-10 22:33:011398 enable_video_accelerator));
leon.han21e0e482017-02-23 04:13:321399 return gpu_factories_.back().get();
[email protected]3bb8bb32013-07-11 13:13:031400}
1401
sadrul85cc5d82016-12-20 03:37:411402scoped_refptr<ui::ContextProviderCommandBuffer>
[email protected]f10dc472013-09-27 03:31:591403RenderThreadImpl::SharedMainThreadContextProvider() {
[email protected]e06e1122013-03-15 17:12:381404 DCHECK(IsMainThread());
danakje8ec797e2016-04-19 04:08:431405 if (shared_main_thread_contexts_ &&
1406 shared_main_thread_contexts_->ContextGL()->GetGraphicsResetStatusKHR() ==
1407 GL_NO_ERROR)
1408 return shared_main_thread_contexts_;
1409
sadrul6d310fa2016-08-04 02:12:161410 scoped_refptr<gpu::GpuChannelHost> gpu_channel_host(
1411 EstablishGpuChannelSync());
danakje8ec797e2016-04-19 04:08:431412 if (!gpu_channel_host) {
1413 shared_main_thread_contexts_ = nullptr;
1414 return nullptr;
[email protected]c29b7ff2013-03-06 03:51:041415 }
danakje8ec797e2016-04-19 04:08:431416
danakj9a04adc2016-05-16 22:45:071417 bool support_locking = false;
danakjc3983552016-05-03 00:04:351418 shared_main_thread_contexts_ = CreateOffscreenContext(
danakj9a04adc2016-05-16 22:45:071419 std::move(gpu_channel_host), gpu::SharedMemoryLimits(), support_locking,
sadrul85cc5d82016-12-20 03:37:411420 ui::command_buffer_metrics::RENDERER_MAINTHREAD_CONTEXT,
sunnypsd8ce1c22016-05-10 18:02:401421 gpu::GPU_STREAM_DEFAULT, gpu::GpuStreamPriority::NORMAL);
danakje8ec797e2016-04-19 04:08:431422 if (!shared_main_thread_contexts_->BindToCurrentThread())
1423 shared_main_thread_contexts_ = nullptr;
[email protected]f10dc472013-09-27 03:31:591424 return shared_main_thread_contexts_;
[email protected]c29b7ff2013-03-06 03:51:041425}
1426
siva.gunturi5d4feb052015-11-15 16:15:311427#if defined(OS_ANDROID)
boliuf8753bf62016-02-11 20:09:421428
siva.gunturi5d4feb052015-11-15 16:15:311429scoped_refptr<StreamTextureFactory> RenderThreadImpl::GetStreamTexureFactory() {
1430 DCHECK(IsMainThread());
boliu30f1b262016-04-19 00:12:331431 if (!stream_texture_factory_.get() ||
1432 stream_texture_factory_->ContextGL()->GetGraphicsResetStatusKHR() !=
1433 GL_NO_ERROR) {
sadrul85cc5d82016-12-20 03:37:411434 scoped_refptr<ui::ContextProviderCommandBuffer> shared_context_provider =
piman9fc22f32016-05-02 22:21:221435 SharedMainThreadContextProvider();
1436 if (!shared_context_provider) {
penghuange1d86512016-07-08 18:15:001437 stream_texture_factory_ = nullptr;
1438 return nullptr;
siva.gunturi5d4feb052015-11-15 16:15:311439 }
piman9fc22f32016-05-02 22:21:221440 DCHECK(shared_context_provider->GetCommandBufferProxy());
1441 DCHECK(shared_context_provider->GetCommandBufferProxy()->channel());
1442 stream_texture_factory_ =
1443 StreamTextureFactory::Create(std::move(shared_context_provider));
siva.gunturi5d4feb052015-11-15 16:15:311444 }
1445 return stream_texture_factory_;
1446}
boliuf8753bf62016-02-11 20:09:421447
1448bool RenderThreadImpl::EnableStreamTextureCopy() {
boliu30f1b262016-04-19 00:12:331449 return sync_compositor_message_filter_.get();
boliuf8753bf62016-02-11 20:09:421450}
1451
siva.gunturi5d4feb052015-11-15 16:15:311452#endif
1453
[email protected]e9ff79c2012-10-19 21:31:261454AudioRendererMixerManager* RenderThreadImpl::GetAudioRendererMixerManager() {
[email protected]59383c782013-04-17 16:43:271455 if (!audio_renderer_mixer_manager_) {
olka7a4679392016-05-27 15:32:581456 audio_renderer_mixer_manager_ = AudioRendererMixerManager::Create();
[email protected]3958e972012-07-17 00:25:411457 }
1458
1459 return audio_renderer_mixer_manager_.get();
1460}
1461
[email protected]73429ca2014-03-06 06:07:471462base::WaitableEvent* RenderThreadImpl::GetShutdownEvent() {
1463 return ChildProcess::current()->GetShutDownEvent();
1464}
1465
staraz067f58242016-11-07 21:06:411466int32_t RenderThreadImpl::GetClientId() {
1467 return client_id_;
1468}
1469
altiminc8885e82017-01-18 13:11:141470scoped_refptr<base::SingleThreadTaskRunner>
1471RenderThreadImpl::GetTimerTaskRunner() {
1472 return renderer_scheduler_->TimerTaskRunner();
1473}
1474
1475scoped_refptr<base::SingleThreadTaskRunner>
1476RenderThreadImpl::GetLoadingTaskRunner() {
1477 return renderer_scheduler_->LoadingTaskRunner();
1478}
1479
chiniforooshan614d70a2017-03-17 01:19:331480void RenderThreadImpl::SetFieldTrialGroup(const std::string& trial_name,
1481 const std::string& group_name) {
1482 field_trial_syncer_.OnSetFieldTrialGroup(trial_name, group_name);
1483}
1484
rockot067ca55f2016-09-30 22:00:151485void RenderThreadImpl::OnAssociatedInterfaceRequest(
1486 const std::string& name,
1487 mojo::ScopedInterfaceEndpointHandle handle) {
rockot70bbb59492017-01-25 00:56:511488 if (associated_interfaces_.CanBindRequest(name))
1489 associated_interfaces_.BindRequest(name, std::move(handle));
1490 else
1491 ChildThreadImpl::OnAssociatedInterfaceRequest(name, std::move(handle));
rockot067ca55f2016-09-30 22:00:151492}
1493
danakj6e3bf8012014-12-16 18:27:531494bool RenderThreadImpl::IsGpuRasterizationForced() {
1495 return is_gpu_rasterization_forced_;
1496}
1497
sunnypsd8ce1c22016-05-10 18:02:401498bool RenderThreadImpl::IsAsyncWorkerContextEnabled() {
1499 return is_async_worker_context_enabled_;
1500}
1501
senorblancob60ba952015-01-27 19:12:361502int RenderThreadImpl::GetGpuRasterizationMSAASampleCount() {
1503 return gpu_rasterization_msaa_sample_count_;
1504}
1505
danakj6e3bf8012014-12-16 18:27:531506bool RenderThreadImpl::IsLcdTextEnabled() {
1507 return is_lcd_text_enabled_;
1508}
1509
1510bool RenderThreadImpl::IsDistanceFieldTextEnabled() {
1511 return is_distance_field_text_enabled_;
1512}
1513
1514bool RenderThreadImpl::IsZeroCopyEnabled() {
1515 return is_zero_copy_enabled_;
1516}
1517
ericrk1d17f752015-10-20 03:03:071518bool RenderThreadImpl::IsPartialRasterEnabled() {
1519 return is_partial_raster_enabled_;
jbroman5f7f71932015-08-18 16:24:461520}
1521
ccameronc7fcd132015-11-03 20:14:311522bool RenderThreadImpl::IsGpuMemoryBufferCompositorResourcesEnabled() {
1523 return is_gpu_memory_buffer_compositor_resources_enabled_;
1524}
1525
ccamerona7644752014-12-30 01:16:311526bool RenderThreadImpl::IsElasticOverscrollEnabled() {
1527 return is_elastic_overscroll_enabled_;
1528}
1529
ericrk9151705c2016-07-26 19:53:161530const cc::BufferToTextureTargetMap&
1531RenderThreadImpl::GetBufferToTextureTargetMap() {
1532 return buffer_to_texture_target_map_;
danakj6e3bf8012014-12-16 18:27:531533}
vmiura9084b342015-02-03 22:19:571534
danakj6e3bf8012014-12-16 18:27:531535scoped_refptr<base::SingleThreadTaskRunner>
1536RenderThreadImpl::GetCompositorMainThreadTaskRunner() {
1537 return main_thread_compositor_task_runner_;
1538}
1539
1540scoped_refptr<base::SingleThreadTaskRunner>
1541RenderThreadImpl::GetCompositorImplThreadTaskRunner() {
skyostil2d3b5bd2015-05-27 15:40:591542 return compositor_task_runner_;
danakj6e3bf8012014-12-16 18:27:531543}
1544
1545gpu::GpuMemoryBufferManager* RenderThreadImpl::GetGpuMemoryBufferManager() {
sadrul53546592016-12-17 01:44:211546 return gpu_->gpu_memory_buffer_manager();
danakj6e3bf8012014-12-16 18:27:531547}
1548
skyostil529caa292016-08-10 17:44:511549blink::scheduler::RendererScheduler* RenderThreadImpl::GetRendererScheduler() {
danakj6e3bf8012014-12-16 18:27:531550 return renderer_scheduler_.get();
1551}
1552
dchengcedca5612016-04-09 01:40:151553std::unique_ptr<cc::BeginFrameSource>
danakj6e3bf8012014-12-16 18:27:531554RenderThreadImpl::CreateExternalBeginFrameSource(int routing_id) {
ricea29649b92016-08-31 09:30:211555 return base::MakeUnique<CompositorExternalBeginFrameSource>(
1556 compositor_message_filter_.get(), sync_message_filter(), routing_id);
danakj6e3bf8012014-12-16 18:27:531557}
1558
samans09812d32017-03-27 19:51:501559std::unique_ptr<cc::SyntheticBeginFrameSource>
1560RenderThreadImpl::CreateSyntheticBeginFrameSource() {
1561 base::SingleThreadTaskRunner* compositor_impl_side_task_runner =
1562 compositor_task_runner_ ? compositor_task_runner_.get()
1563 : base::ThreadTaskRunnerHandle::Get().get();
1564 return base::MakeUnique<cc::BackToBackBeginFrameSource>(
1565 base::MakeUnique<cc::DelayBasedTimeSource>(
1566 compositor_impl_side_task_runner));
1567}
1568
reveman34b7a1522015-03-23 20:27:471569cc::TaskGraphRunner* RenderThreadImpl::GetTaskGraphRunner() {
prashant.nfad657e2016-06-01 07:52:171570 return categorized_worker_pool_->GetTaskGraphRunner();
reveman34b7a1522015-03-23 20:27:471571}
1572
vmpstrdfd22862015-09-25 17:42:411573bool RenderThreadImpl::AreImageDecodeTasksEnabled() {
1574 return are_image_decode_tasks_enabled_;
reveman34b7a1522015-03-23 20:27:471575}
1576
loyso65c93c602015-08-11 05:15:571577bool RenderThreadImpl::IsThreadedAnimationEnabled() {
1578 return is_threaded_animation_enabled_;
1579}
1580
wjmaclean1d970622017-01-21 22:28:241581bool RenderThreadImpl::IsScrollAnimatorEnabled() {
1582 return is_scroll_animator_enabled_;
1583}
1584
fsamuel4c5c87142017-03-14 03:14:261585bool RenderThreadImpl::IsSurfaceSynchronizationEnabled() {
1586 return is_surface_synchronization_enabled_;
1587}
1588
skyostila37c2a72016-06-29 17:30:071589void RenderThreadImpl::OnRAILModeChanged(v8::RAILMode rail_mode) {
Blink Reformat1c4d759e2017-04-09 16:34:541590 blink::MainThreadIsolate()->SetRAILMode(rail_mode);
1591 blink::SetRAILModeOnWorkerThreadIsolates(rail_mode);
skyostila37c2a72016-06-29 17:30:071592}
1593
[email protected]b3e83de2012-02-07 03:33:281594bool RenderThreadImpl::IsMainThread() {
1595 return !!current();
1596}
1597
torne88b66452016-05-03 13:22:141598void RenderThreadImpl::OnChannelError() {
1599 // In single-process mode, the renderer can't be restarted after shutdown.
1600 // So, if we get a channel error, crash the whole process right now to get a
1601 // more informative stack, since we will otherwise just crash later when we
1602 // try to restart it.
1603 CHECK(!base::CommandLine::ForCurrentProcess()->HasSwitch(
1604 switches::kSingleProcess));
1605 ChildThreadImpl::OnChannelError();
1606}
1607
[email protected]f1a29a02011-10-06 23:08:441608bool RenderThreadImpl::OnControlMessageReceived(const IPC::Message& msg) {
dchenga2d442c22016-10-13 15:39:211609 for (auto& observer : observers_) {
1610 if (observer.OnControlMessageReceived(msg))
[email protected]1223d6ef2011-03-28 16:47:501611 return true;
1612 }
1613
[email protected]70c19a932010-05-14 12:59:111614 // Some messages are handled by delegates.
[email protected]1910fe82012-05-10 00:04:101615 if (appcache_dispatcher_->OnMessageReceived(msg) ||
leon.han7a5714382017-04-16 03:25:001616 dom_storage_dispatcher_->OnMessageReceived(msg)) {
[email protected]a95986a82010-12-24 06:19:281617 return true;
[email protected]1910fe82012-05-10 00:04:101618 }
[email protected]1edc16b82009-04-07 17:45:541619
[email protected]a95986a82010-12-24 06:19:281620 bool handled = true;
[email protected]f1a29a02011-10-06 23:08:441621 IPC_BEGIN_MESSAGE_MAP(RenderThreadImpl, msg)
[email protected]0ec90d522014-03-12 16:28:191622 IPC_MESSAGE_HANDLER(WorkerProcessMsg_CreateWorker, OnCreateNewSharedWorker)
[email protected]a95986a82010-12-24 06:19:281623 IPC_MESSAGE_UNHANDLED(handled = false)
[email protected]8930d472009-02-21 08:05:281624 IPC_END_MESSAGE_MAP()
[email protected]a95986a82010-12-24 06:19:281625 return handled;
initial.commit09911bf2008-07-26 23:55:291626}
1627
jdduke73220f02015-09-04 17:03:511628void RenderThreadImpl::OnProcessBackgrounded(bool backgrounded) {
1629 ChildThreadImpl::OnProcessBackgrounded(backgrounded);
1630
hajimehoshi69093272016-05-13 08:30:581631 if (backgrounded) {
jdduke73220f02015-09-04 17:03:511632 renderer_scheduler_->OnRendererBackgrounded();
tasakb95dbb50c2017-02-08 18:07:501633 needs_to_record_first_active_paint_ = false;
hajimehoshi69093272016-05-13 08:30:581634 } else {
jdduke73220f02015-09-04 17:03:511635 renderer_scheduler_->OnRendererForegrounded();
tasak6ff44032016-11-07 06:45:251636
tasakb46626a2016-10-18 05:54:441637 record_purge_suspend_metric_closure_.Cancel();
tasak07465a72016-10-21 06:38:521638 record_purge_suspend_metric_closure_.Reset(
1639 base::Bind(&RenderThreadImpl::RecordPurgeAndSuspendMetrics,
1640 base::Unretained(this)));
tasak72f64042017-01-19 14:02:531641 record_purge_suspend_growth_metric_closure_.Cancel();
1642 record_purge_suspend_growth_metric_closure_.Reset(
1643 base::Bind(&RenderThreadImpl::RecordPurgeAndSuspendMemoryGrowthMetrics,
1644 base::Unretained(this)));
hajimehoshi69093272016-05-13 08:30:581645 }
1646}
1647
1648void RenderThreadImpl::OnProcessPurgeAndSuspend() {
1649 ChildThreadImpl::OnProcessPurgeAndSuspend();
tasak6ff44032016-11-07 06:45:251650 if (!RendererIsHidden())
hajimehoshi69093272016-05-13 08:30:581651 return;
tasakff1e62422016-12-22 04:53:551652
tasak6ff44032016-11-07 06:45:251653 if (base::FeatureList::IsEnabled(features::kPurgeAndSuspend)) {
wezc80d2d2b02017-02-16 03:28:191654 base::MemoryCoordinatorClientRegistry::GetInstance()->PurgeMemory();
tasak6ff44032016-11-07 06:45:251655 }
tasakb46626a2016-10-18 05:54:441656 // Since purging is not a synchronous task (e.g. v8 GC, oilpan GC, ...),
1657 // we need to wait until the task is finished. So wait 15 seconds and
1658 // update purge+suspend UMA histogram.
1659 // TODO(tasak): use MemoryCoordinator's callback to report purge+suspend
1660 // UMA when MemoryCoordinator is available.
1661 GetRendererScheduler()->DefaultTaskRunner()->PostDelayedTask(
1662 FROM_HERE, record_purge_suspend_metric_closure_.callback(),
1663 base::TimeDelta::FromSeconds(15));
tasakb95dbb50c2017-02-08 18:07:501664 needs_to_record_first_active_paint_ = true;
tasakb46626a2016-10-18 05:54:441665}
1666
1667// TODO(tasak): Replace the following GetMallocUsage() with memory-infra
1668// when it is possible to run memory-infra without tracing.
1669#if defined(OS_WIN)
1670namespace {
1671
1672static size_t GetMallocUsage() {
siggi7fb93a52016-12-12 22:22:151673 // Iterate through whichever heap the CRT is using.
1674 HANDLE crt_heap = reinterpret_cast<HANDLE>(_get_heap_handle());
1675 if (crt_heap == NULL)
tasakb46626a2016-10-18 05:54:441676 return 0;
siggi7fb93a52016-12-12 22:22:151677 if (!::HeapLock(crt_heap))
tasak7415a3db2016-12-12 04:17:141678 return 0 ;
tasakb46626a2016-10-18 05:54:441679 size_t malloc_usage = 0;
tasak7415a3db2016-12-12 04:17:141680 PROCESS_HEAP_ENTRY heap_entry;
1681 heap_entry.lpData = NULL;
siggi7fb93a52016-12-12 22:22:151682 while (::HeapWalk(crt_heap, &heap_entry) != 0) {
tasak7415a3db2016-12-12 04:17:141683 if ((heap_entry.wFlags & PROCESS_HEAP_ENTRY_BUSY) != 0)
1684 malloc_usage += heap_entry.cbData;
tasakb46626a2016-10-18 05:54:441685 }
siggi7fb93a52016-12-12 22:22:151686 ::HeapUnlock(crt_heap);
tasakb46626a2016-10-18 05:54:441687 return malloc_usage;
1688}
1689
1690} // namespace
1691#elif defined(OS_MACOSX) || defined(OS_IOS)
1692namespace {
1693
1694static size_t GetMallocUsage() {
1695 malloc_statistics_t stats = {0};
1696 malloc_zone_statistics(nullptr, &stats);
1697 return stats.size_in_use;
1698}
1699
1700} // namespace
1701#endif
1702
bashia0ba0d42017-04-03 08:11:061703bool RenderThreadImpl::GetRendererMemoryMetrics(
keishi51ed0d52017-01-12 10:04:461704 RendererMemoryMetrics* memory_metrics) const {
1705 DCHECK(memory_metrics);
1706
chrisha05e94f22017-04-05 22:06:041707 // Cache this result, as it can change while this code is running, and is used
1708 // as a divisor below.
1709 size_t render_view_count = RenderView::GetRenderViewCount();
1710
1711 // If there are no render views it doesn't make sense to calculate metrics
1712 // right now.
1713 if (render_view_count == 0)
bashia0ba0d42017-04-03 08:11:061714 return false;
1715
keishi51ed0d52017-01-12 10:04:461716 blink::WebMemoryStatistics blink_stats = blink::WebMemoryStatistics::Get();
1717 memory_metrics->partition_alloc_kb =
Blink Reformat1c4d759e2017-04-09 16:34:541718 blink_stats.partition_alloc_total_allocated_bytes / 1024;
1719 memory_metrics->blink_gc_kb =
1720 blink_stats.blink_gc_total_allocated_bytes / 1024;
keishi51ed0d52017-01-12 10:04:461721#if defined(OS_LINUX) || defined(OS_ANDROID)
1722 struct mallinfo minfo = mallinfo();
1723#if defined(USE_TCMALLOC)
1724 size_t malloc_usage = minfo.uordblks;
1725#else
1726 size_t malloc_usage = minfo.hblkhd + minfo.arena;
1727#endif
1728#else
1729 size_t malloc_usage = GetMallocUsage();
1730#endif
1731 memory_metrics->malloc_mb = malloc_usage / 1024 / 1024;
1732
1733 discardable_memory::ClientDiscardableSharedMemoryManager::Statistics
1734 discardable_stats = discardable_shared_memory_manager_->GetStatistics();
1735 size_t discardable_usage =
1736 discardable_stats.total_size - discardable_stats.freelist_size;
1737 memory_metrics->discardable_kb = discardable_usage / 1024;
1738
1739 size_t v8_usage = 0;
Blink Reformat1c4d759e2017-04-09 16:34:541740 if (v8::Isolate* isolate = blink::MainThreadIsolate()) {
keishi51ed0d52017-01-12 10:04:461741 v8::HeapStatistics v8_heap_statistics;
1742 isolate->GetHeapStatistics(&v8_heap_statistics);
1743 v8_usage = v8_heap_statistics.total_heap_size();
1744 }
1745 // TODO(tasak): Currently only memory usage of mainThreadIsolate() is
1746 // reported. We should collect memory usages of all isolates using
1747 // memory-infra.
1748 memory_metrics->v8_main_thread_isolate_mb = v8_usage / 1024 / 1024;
Blink Reformat1c4d759e2017-04-09 16:34:541749 size_t total_allocated = blink_stats.partition_alloc_total_allocated_bytes +
1750 blink_stats.blink_gc_total_allocated_bytes +
keishi51ed0d52017-01-12 10:04:461751 malloc_usage + v8_usage + discardable_usage;
1752 memory_metrics->total_allocated_mb = total_allocated / 1024 / 1024;
1753 memory_metrics->non_discardable_total_allocated_mb =
1754 (total_allocated - discardable_usage) / 1024 / 1024;
1755 memory_metrics->total_allocated_per_render_view_mb =
chrisha05e94f22017-04-05 22:06:041756 total_allocated / render_view_count / 1024 / 1024;
bashia0ba0d42017-04-03 08:11:061757
1758 return true;
keishi51ed0d52017-01-12 10:04:461759}
1760
tasakb46626a2016-10-18 05:54:441761// TODO(tasak): Once it is possible to use memory-infra without tracing,
1762// we should collect the metrics using memory-infra.
1763// TODO(tasak): We should also report a difference between the memory usages
1764// before and after purging by using memory-infra.
tasak72f64042017-01-19 14:02:531765void RenderThreadImpl::RecordPurgeAndSuspendMetrics() {
tasakb46626a2016-10-18 05:54:441766 // If this renderer is resumed, we should not update UMA.
tasak7e65dad2016-12-16 10:18:251767 if (!RendererIsHidden())
tasakb46626a2016-10-18 05:54:441768 return;
1769
1770 // TODO(tasak): Compare memory metrics between purge-enabled renderers and
1771 // purge-disabled renderers (A/B testing).
keishi51ed0d52017-01-12 10:04:461772 RendererMemoryMetrics memory_metrics;
bashia0ba0d42017-04-03 08:11:061773 if (!GetRendererMemoryMetrics(&memory_metrics))
1774 return;
1775
tasakb46626a2016-10-18 05:54:441776 UMA_HISTOGRAM_MEMORY_KB("PurgeAndSuspend.Memory.PartitionAllocKB",
keishi51ed0d52017-01-12 10:04:461777 memory_metrics.partition_alloc_kb);
tasakb46626a2016-10-18 05:54:441778 UMA_HISTOGRAM_MEMORY_KB("PurgeAndSuspend.Memory.BlinkGCKB",
keishi51ed0d52017-01-12 10:04:461779 memory_metrics.blink_gc_kb);
tasakb46626a2016-10-18 05:54:441780 UMA_HISTOGRAM_MEMORY_MB("PurgeAndSuspend.Memory.MallocMB",
keishi51ed0d52017-01-12 10:04:461781 memory_metrics.malloc_mb);
tasakb46626a2016-10-18 05:54:441782 UMA_HISTOGRAM_MEMORY_KB("PurgeAndSuspend.Memory.DiscardableKB",
keishi51ed0d52017-01-12 10:04:461783 memory_metrics.discardable_kb);
tasakb46626a2016-10-18 05:54:441784 UMA_HISTOGRAM_MEMORY_MB("PurgeAndSuspend.Memory.V8MainThreadIsolateMB",
keishi51ed0d52017-01-12 10:04:461785 memory_metrics.v8_main_thread_isolate_mb);
tasakb46626a2016-10-18 05:54:441786 UMA_HISTOGRAM_MEMORY_MB("PurgeAndSuspend.Memory.TotalAllocatedMB",
keishi51ed0d52017-01-12 10:04:461787 memory_metrics.total_allocated_mb);
tasak72f64042017-01-19 14:02:531788 purge_and_suspend_memory_metrics_ = memory_metrics;
1789
1790 // record how many memory usage increases after purged.
1791 GetRendererScheduler()->DefaultTaskRunner()->PostDelayedTask(
1792 FROM_HERE, record_purge_suspend_growth_metric_closure_.callback(),
1793 base::TimeDelta::FromMinutes(5));
1794 GetRendererScheduler()->DefaultTaskRunner()->PostDelayedTask(
1795 FROM_HERE, record_purge_suspend_growth_metric_closure_.callback(),
1796 base::TimeDelta::FromMinutes(10));
1797 GetRendererScheduler()->DefaultTaskRunner()->PostDelayedTask(
1798 FROM_HERE, record_purge_suspend_growth_metric_closure_.callback(),
1799 base::TimeDelta::FromMinutes(15));
1800}
1801
1802#define GET_MEMORY_GROWTH(current, previous, allocator) \
1803 (current.allocator > previous.allocator \
1804 ? current.allocator - previous.allocator \
1805 : 0)
1806
1807void RenderThreadImpl::RecordPurgeAndSuspendMemoryGrowthMetrics() const {
1808 // If this renderer is resumed, we should not update UMA.
1809 if (!RendererIsHidden())
1810 return;
1811
1812 RendererMemoryMetrics memory_metrics;
bashia0ba0d42017-04-03 08:11:061813 if (!GetRendererMemoryMetrics(&memory_metrics))
1814 return;
1815
tasak72f64042017-01-19 14:02:531816 UMA_HISTOGRAM_MEMORY_KB(
1817 "PurgeAndSuspend.Experimental.MemoryGrowth.PartitionAllocKB",
1818 GET_MEMORY_GROWTH(memory_metrics, purge_and_suspend_memory_metrics_,
1819 partition_alloc_kb));
1820 UMA_HISTOGRAM_MEMORY_KB(
1821 "PurgeAndSuspend.Experimental.MemoryGrowth.BlinkGCKB",
1822 GET_MEMORY_GROWTH(memory_metrics, purge_and_suspend_memory_metrics_,
1823 blink_gc_kb));
tasak9b2c7fe2017-01-31 19:40:341824 UMA_HISTOGRAM_MEMORY_KB(
tasak72f64042017-01-19 14:02:531825 "PurgeAndSuspend.Experimental.MemoryGrowth.MallocKB",
1826 GET_MEMORY_GROWTH(memory_metrics, purge_and_suspend_memory_metrics_,
1827 malloc_mb) * 1024);
1828 UMA_HISTOGRAM_MEMORY_KB(
1829 "PurgeAndSuspend.Experimental.MemoryGrowth.DiscardableKB",
1830 GET_MEMORY_GROWTH(memory_metrics, purge_and_suspend_memory_metrics_,
1831 discardable_kb));
tasak9b2c7fe2017-01-31 19:40:341832 UMA_HISTOGRAM_MEMORY_KB(
tasak72f64042017-01-19 14:02:531833 "PurgeAndSuspend.Experimental.MemoryGrowth.V8MainThreadIsolateKB",
1834 GET_MEMORY_GROWTH(memory_metrics, purge_and_suspend_memory_metrics_,
1835 v8_main_thread_isolate_mb) * 1024);
tasak9b2c7fe2017-01-31 19:40:341836 UMA_HISTOGRAM_MEMORY_KB(
tasak72f64042017-01-19 14:02:531837 "PurgeAndSuspend.Experimental.MemoryGrowth.TotalAllocatedKB",
1838 GET_MEMORY_GROWTH(memory_metrics, purge_and_suspend_memory_metrics_,
1839 total_allocated_mb) * 1024);
jdduke73220f02015-09-04 17:03:511840}
1841
sadrul6d310fa2016-08-04 02:12:161842scoped_refptr<gpu::GpuChannelHost> RenderThreadImpl::EstablishGpuChannelSync() {
[email protected]d13f35d2012-05-18 02:28:151843 TRACE_EVENT0("gpu", "RenderThreadImpl::EstablishGpuChannelSync");
1844
piman9fc22f32016-05-02 22:21:221845 if (gpu_channel_) {
[email protected]1082b1d2010-03-30 00:31:221846 // Do nothing if we already have a GPU channel or are already
1847 // establishing one.
[email protected]7951bfe2013-06-13 01:43:341848 if (!gpu_channel_->IsLost())
piman9fc22f32016-05-02 22:21:221849 return gpu_channel_;
[email protected]6217d392010-03-25 22:08:351850
1851 // Recreate the channel if it has been lost.
piman765e5282015-05-08 03:43:011852 gpu_channel_->DestroyChannel();
penghuange1d86512016-07-08 18:15:001853 gpu_channel_ = nullptr;
[email protected]6217d392010-03-25 22:08:351854 }
1855
sadrul53546592016-12-17 01:44:211856 gpu_channel_ = gpu_->EstablishGpuChannelSync();
1857 if (gpu_channel_)
1858 GetContentClient()->SetGpuInfo(gpu_channel_->gpu_info());
piman9fc22f32016-05-02 22:21:221859 return gpu_channel_;
[email protected]3bf4d532010-03-27 00:23:341860}
1861
fsamuelcf3002e2017-03-20 23:13:471862void RenderThreadImpl::RequestNewCompositorFrameSink(
danakj83066a32016-06-21 02:34:491863 bool use_software,
1864 int routing_id,
1865 scoped_refptr<FrameSwapMessageQueue> frame_swap_message_queue,
fsamuelcf3002e2017-03-20 23:13:471866 const GURL& url,
1867 const CompositorFrameSinkCallback& callback) {
danakj83066a32016-06-21 02:34:491868 const base::CommandLine& command_line =
1869 *base::CommandLine::ForCurrentProcess();
1870 if (command_line.HasSwitch(switches::kDisableGpuCompositing))
1871 use_software = true;
1872
samans09812d32017-03-27 19:51:501873 // In disable gpu vsync mode, also let the renderer tick as fast as it
1874 // can. The top level begin frame source will also be running as a back
1875 // to back begin frame source, but using a synthetic begin frame source
1876 // here reduces latency when in this mode (at least for frames
1877 // starting--it potentially increases it for input on the other hand.)
1878 std::unique_ptr<cc::SyntheticBeginFrameSource> synthetic_begin_frame_source;
1879 if (command_line.HasSwitch(switches::kDisableGpuVsync) &&
1880 command_line.GetSwitchValueASCII(switches::kDisableGpuVsync) != "gpu") {
1881 synthetic_begin_frame_source = CreateSyntheticBeginFrameSource();
1882 }
1883
sadrul943e3b32016-08-04 18:22:591884#if defined(USE_AURA)
fsamuel098eade2017-03-21 18:06:141885 if (!use_software && IsRunningInMash()) {
sadrulbe22c4f2017-03-14 06:59:251886 scoped_refptr<gpu::GpuChannelHost> channel = EstablishGpuChannelSync();
1887 // If the channel could not be established correctly, then return null. This
1888 // would cause the compositor to wait and try again at a later time.
fsamuelcf3002e2017-03-20 23:13:471889 if (!channel) {
1890 callback.Run(nullptr);
1891 return;
1892 }
fsamuel95c974eb2017-03-22 10:00:251893 RendererWindowTreeClient::Get(routing_id)
1894 ->RequestCompositorFrameSink(
1895 gpu_->CreateContextProvider(std::move(channel)),
1896 GetGpuMemoryBufferManager(), callback);
fsamuelcf3002e2017-03-20 23:13:471897 return;
danakj83066a32016-06-21 02:34:491898 }
1899#endif
1900
danakj83066a32016-06-21 02:34:491901 if (command_line.HasSwitch(switches::kEnableVulkan)) {
1902 scoped_refptr<cc::VulkanContextProvider> vulkan_context_provider =
1903 cc::VulkanInProcessContextProvider::Create();
1904 if (vulkan_context_provider) {
1905 DCHECK(!layout_test_mode());
fsamuelcf3002e2017-03-20 23:13:471906 callback.Run(base::MakeUnique<RendererCompositorFrameSink>(
samans2040988b2017-04-11 23:58:351907 routing_id, std::move(synthetic_begin_frame_source),
enne077ba4862016-09-12 20:59:531908 std::move(vulkan_context_provider),
fsamuelcf3002e2017-03-20 23:13:471909 std::move(frame_swap_message_queue)));
1910 return;
danakj83066a32016-06-21 02:34:491911 }
1912 }
1913
1914 // Create a gpu process channel and verify we want to use GPU compositing
1915 // before creating any context providers.
1916 scoped_refptr<gpu::GpuChannelHost> gpu_channel_host;
1917 if (!use_software) {
sadrul6d310fa2016-08-04 02:12:161918 gpu_channel_host = EstablishGpuChannelSync();
danakj83066a32016-06-21 02:34:491919 if (!gpu_channel_host) {
1920 // Cause the compositor to wait and try again.
fsamuelcf3002e2017-03-20 23:13:471921 callback.Run(nullptr);
1922 return;
danakj83066a32016-06-21 02:34:491923 }
1924 // We may get a valid channel, but with a software renderer. In that case,
1925 // disable GPU compositing.
1926 if (gpu_channel_host->gpu_info().software_rendering)
1927 use_software = true;
1928 }
1929
1930 if (use_software) {
1931 DCHECK(!layout_test_mode());
fsamuelcf3002e2017-03-20 23:13:471932 callback.Run(base::MakeUnique<RendererCompositorFrameSink>(
samans2040988b2017-04-11 23:58:351933 routing_id, std::move(synthetic_begin_frame_source), nullptr, nullptr,
1934 nullptr, shared_bitmap_manager(), std::move(frame_swap_message_queue)));
fsamuelcf3002e2017-03-20 23:13:471935 return;
danakj83066a32016-06-21 02:34:491936 }
1937
sadrul85cc5d82016-12-20 03:37:411938 scoped_refptr<ui::ContextProviderCommandBuffer> worker_context_provider =
danakj83066a32016-06-21 02:34:491939 SharedCompositorWorkerContextProvider();
1940 if (!worker_context_provider) {
1941 // Cause the compositor to wait and try again.
fsamuelcf3002e2017-03-20 23:13:471942 callback.Run(nullptr);
1943 return;
danakj83066a32016-06-21 02:34:491944 }
1945
1946 // The renderer compositor context doesn't do a lot of stuff, so we don't
1947 // expect it to need a lot of space for commands or transfer. Raster and
1948 // uploads happen on the worker context instead.
1949 gpu::SharedMemoryLimits limits = gpu::SharedMemoryLimits::ForMailboxContext();
1950
1951 // This is for an offscreen context for the compositor. So the default
1952 // framebuffer doesn't need alpha, depth, stencil, antialiasing.
1953 gpu::gles2::ContextCreationAttribHelper attributes;
1954 attributes.alpha_size = -1;
1955 attributes.depth_size = 0;
1956 attributes.stencil_size = 0;
1957 attributes.samples = 0;
1958 attributes.sample_buffers = 0;
1959 attributes.bind_generates_resource = false;
1960 attributes.lose_context_when_out_of_memory = true;
1961
1962 constexpr bool automatic_flushes = false;
1963 constexpr bool support_locking = false;
1964
1965 // The compositor context shares resources with the worker context unless
1966 // the worker is async.
sadrul85cc5d82016-12-20 03:37:411967 ui::ContextProviderCommandBuffer* share_context =
1968 worker_context_provider.get();
danakj83066a32016-06-21 02:34:491969 if (IsAsyncWorkerContextEnabled())
1970 share_context = nullptr;
1971
sadrul85cc5d82016-12-20 03:37:411972 scoped_refptr<ui::ContextProviderCommandBuffer> context_provider(
1973 new ui::ContextProviderCommandBuffer(
danakja40dd4482016-06-28 01:14:101974 gpu_channel_host, gpu::GPU_STREAM_DEFAULT,
danakj83066a32016-06-21 02:34:491975 gpu::GpuStreamPriority::NORMAL, gpu::kNullSurfaceHandle, url,
pimand488e8b42016-06-30 19:06:591976 automatic_flushes, support_locking, limits, attributes, share_context,
sadrul85cc5d82016-12-20 03:37:411977 ui::command_buffer_metrics::RENDER_COMPOSITOR_CONTEXT));
danakj83066a32016-06-21 02:34:491978
danakj83066a32016-06-21 02:34:491979 if (layout_test_deps_) {
fsamuelcf3002e2017-03-20 23:13:471980 callback.Run(layout_test_deps_->CreateCompositorFrameSink(
jbroman6ccbc7d472016-07-27 04:45:411981 routing_id, std::move(gpu_channel_host), std::move(context_provider),
fsamuelcf3002e2017-03-20 23:13:471982 std::move(worker_context_provider), GetGpuMemoryBufferManager(), this));
1983 return;
danakj83066a32016-06-21 02:34:491984 }
1985
1986#if defined(OS_ANDROID)
1987 if (sync_compositor_message_filter_) {
samans09812d32017-03-27 19:51:501988 std::unique_ptr<cc::BeginFrameSource> begin_frame_source =
1989 synthetic_begin_frame_source
1990 ? std::move(synthetic_begin_frame_source)
1991 : CreateExternalBeginFrameSource(routing_id);
fsamuelcf3002e2017-03-20 23:13:471992 callback.Run(base::MakeUnique<SynchronousCompositorFrameSink>(
danakja40dd4482016-06-28 01:14:101993 std::move(context_provider), std::move(worker_context_provider),
danakje9cf5812017-02-16 22:22:551994 GetGpuMemoryBufferManager(), shared_bitmap_manager(), routing_id,
samans2040988b2017-04-11 23:58:351995 g_next_compositor_frame_sink_id++, std::move(begin_frame_source),
enne077ba4862016-09-12 20:59:531996 sync_compositor_message_filter_.get(),
fsamuelcf3002e2017-03-20 23:13:471997 std::move(frame_swap_message_queue)));
1998 return;
danakj83066a32016-06-21 02:34:491999 }
2000#endif
fsamuelcf3002e2017-03-20 23:13:472001 callback.Run(base::WrapUnique(new RendererCompositorFrameSink(
samans2040988b2017-04-11 23:58:352002 routing_id, std::move(synthetic_begin_frame_source),
2003 std::move(context_provider), std::move(worker_context_provider),
2004 GetGpuMemoryBufferManager(), nullptr,
fsamuelcf3002e2017-03-20 23:13:472005 std::move(frame_swap_message_queue))));
danakj83066a32016-06-21 02:34:492006}
2007
rockot067ca55f2016-09-30 22:00:152008AssociatedInterfaceRegistry*
2009RenderThreadImpl::GetAssociatedInterfaceRegistry() {
2010 return &associated_interfaces_;
2011}
2012
jbroman6ccbc7d472016-07-27 04:45:412013std::unique_ptr<cc::SwapPromise>
2014RenderThreadImpl::RequestCopyOfOutputForLayoutTest(
2015 int32_t routing_id,
2016 std::unique_ptr<cc::CopyOutputRequest> request) {
2017 DCHECK(layout_test_deps_);
2018 return layout_test_deps_->RequestCopyOfOutput(routing_id, std::move(request));
2019}
2020
[email protected]180ef242013-11-07 06:50:462021blink::WebMediaStreamCenter* RenderThreadImpl::CreateMediaStreamCenter(
2022 blink::WebMediaStreamCenterClient* client) {
Brett Wilson0748bf412016-11-22 17:55:462023#if BUILDFLAG(ENABLE_WEBRTC)
[email protected]68e5fee2013-02-18 10:04:222024 if (!media_stream_center_) {
2025 media_stream_center_ = GetContentClient()->renderer()
2026 ->OverrideCreateWebMediaStreamCenter(client);
2027 if (!media_stream_center_) {
dchengcedca5612016-04-09 01:40:152028 std::unique_ptr<MediaStreamCenter> media_stream_center(
[email protected]0107d8a2014-05-16 10:20:342029 new MediaStreamCenter(client, GetPeerConnectionDependencyFactory()));
[email protected]c1298742013-07-17 04:06:322030 media_stream_center_ = media_stream_center.release();
[email protected]68e5fee2013-02-18 10:04:222031 }
2032 }
[email protected]d8cd8372012-03-09 10:49:512033#endif
2034 return media_stream_center_;
2035}
2036
Brett Wilson0748bf412016-11-22 17:55:462037#if BUILDFLAG(ENABLE_WEBRTC)
[email protected]0107d8a2014-05-16 10:20:342038PeerConnectionDependencyFactory*
2039RenderThreadImpl::GetPeerConnectionDependencyFactory() {
[email protected]83e0a482014-05-22 18:07:182040 return peer_connection_factory_.get();
[email protected]6ee10bd2012-09-13 09:01:532041}
[email protected]22fe91d2014-08-12 17:07:122042#endif
[email protected]6ee10bd2012-09-13 09:01:532043
rockot1587e332016-07-27 17:44:142044mojom::RenderFrameMessageFilter*
2045RenderThreadImpl::render_frame_message_filter() {
2046 if (!render_frame_message_filter_)
2047 GetChannel()->GetRemoteAssociatedInterface(&render_frame_message_filter_);
2048 return render_frame_message_filter_.get();
2049}
2050
rockote261d2112016-09-21 22:22:232051mojom::RenderMessageFilter* RenderThreadImpl::render_message_filter() {
2052 if (!render_message_filter_)
2053 GetChannel()->GetRemoteAssociatedInterface(&render_message_filter_);
2054 return render_message_filter_.get();
2055}
2056
penghuang346a46f92016-03-31 21:37:522057gpu::GpuChannelHost* RenderThreadImpl::GetGpuChannel() {
piman9fc22f32016-05-02 22:21:222058 if (!gpu_channel_)
danakj3873e852016-05-05 00:46:072059 return nullptr;
[email protected]7951bfe2013-06-13 01:43:342060 if (gpu_channel_->IsLost())
danakj3873e852016-05-05 00:46:072061 return nullptr;
[email protected]6217d392010-03-25 22:08:352062 return gpu_channel_.get();
2063}
2064
chiniforooshan614d70a2017-03-17 01:19:332065void RenderThreadImpl::OnFieldTrialGroupFinalized(
2066 const std::string& trial_name,
2067 const std::string& group_name) {
2068 mojom::FieldTrialRecorderPtr field_trial_recorder;
ben649b3edd2017-03-23 00:32:022069 GetConnector()->BindInterface(mojom::kBrowserServiceName,
2070 &field_trial_recorder);
chiniforooshan614d70a2017-03-17 01:19:332071 field_trial_recorder->FieldTrialActivated(trial_name);
2072}
2073
rockot067ca55f2016-09-30 22:00:152074void RenderThreadImpl::CreateView(mojom::CreateViewParamsPtr params) {
2075 CompositorDependencies* compositor_deps = this;
wjmaclean1d970622017-01-21 22:28:242076 is_scroll_animator_enabled_ = params->web_preferences.enable_scroll_animator;
rockot067ca55f2016-09-30 22:00:152077 // When bringing in render_view, also bring in webkit's glue and jsbindings.
nickf7b38222016-11-22 21:59:352078 RenderViewImpl::Create(compositor_deps, *params,
2079 RenderWidget::ShowCallback());
rockot067ca55f2016-09-30 22:00:152080}
2081
rockot53be7caf2016-10-04 20:17:082082void RenderThreadImpl::CreateFrame(mojom::CreateFrameParamsPtr params) {
2083 // Debug cases of https://crbug.com/626802.
2084 base::debug::SetCrashKeyValue("newframe_routing_id",
2085 base::IntToString(params->routing_id));
2086 base::debug::SetCrashKeyValue("newframe_proxy_id",
2087 base::IntToString(params->proxy_routing_id));
2088 base::debug::SetCrashKeyValue("newframe_opener_id",
2089 base::IntToString(params->opener_routing_id));
2090 base::debug::SetCrashKeyValue("newframe_parent_id",
2091 base::IntToString(params->parent_routing_id));
2092 base::debug::SetCrashKeyValue("newframe_widget_id",
2093 base::IntToString(
2094 params->widget_params->routing_id));
2095 base::debug::SetCrashKeyValue("newframe_widget_hidden",
2096 params->widget_params->hidden ? "yes" : "no");
2097 base::debug::SetCrashKeyValue("newframe_replicated_origin",
2098 params->replication_state.origin.Serialize());
2099 base::debug::SetCrashKeyValue("newframe_oopifs_possible",
2100 SiteIsolationPolicy::AreCrossProcessFramesPossible() ? "yes" : "no");
2101 CompositorDependencies* compositor_deps = this;
2102 RenderFrameImpl::CreateFrame(
2103 params->routing_id, params->proxy_routing_id, params->opener_routing_id,
2104 params->parent_routing_id, params->previous_sibling_routing_id,
2105 params->replication_state, compositor_deps, *params->widget_params,
2106 params->frame_owner_properties);
2107}
2108
2109void RenderThreadImpl::CreateFrameProxy(
2110 int32_t routing_id,
2111 int32_t render_view_routing_id,
2112 int32_t opener_routing_id,
2113 int32_t parent_routing_id,
2114 const FrameReplicationState& replicated_state) {
2115 // Debug cases of https://crbug.com/575245.
2116 base::debug::SetCrashKeyValue("newproxy_proxy_id",
2117 base::IntToString(routing_id));
2118 base::debug::SetCrashKeyValue("newproxy_view_id",
2119 base::IntToString(render_view_routing_id));
2120 base::debug::SetCrashKeyValue("newproxy_opener_id",
2121 base::IntToString(opener_routing_id));
2122 base::debug::SetCrashKeyValue("newproxy_parent_id",
2123 base::IntToString(parent_routing_id));
nick3b5a21f2016-11-22 23:07:112124 RenderFrameProxy::CreateFrameProxy(
2125 routing_id, render_view_routing_id,
2126 RenderFrameImpl::ResolveOpener(opener_routing_id), parent_routing_id,
2127 replicated_state);
rockot53be7caf2016-10-04 20:17:082128}
2129
rockota2db0da2016-10-18 17:39:112130void RenderThreadImpl::OnNetworkConnectionChanged(
2131 net::NetworkChangeNotifier::ConnectionType type,
2132 double max_bandwidth_mbps) {
2133 bool online = type != net::NetworkChangeNotifier::CONNECTION_NONE;
Blink Reformat1c4d759e2017-04-09 16:34:542134 WebNetworkStateNotifier::SetOnLine(online);
rockota2db0da2016-10-18 17:39:112135 for (auto& observer : observers_)
2136 observer.NetworkStateChanged(online);
Blink Reformat1c4d759e2017-04-09 16:34:542137 WebNetworkStateNotifier::SetWebConnection(
rockota2db0da2016-10-18 17:39:112138 NetConnectionTypeToWebConnectionType(type), max_bandwidth_mbps);
2139}
2140
2141void RenderThreadImpl::SetWebKitSharedTimersSuspended(bool suspend) {
2142#if defined(OS_ANDROID)
2143 if (suspend) {
2144 renderer_scheduler_->SuspendTimerQueue();
2145 } else {
2146 renderer_scheduler_->ResumeTimerQueue();
2147 }
2148 webkit_shared_timer_suspended_ = suspend;
2149#else
2150 NOTREACHED();
2151#endif
2152}
2153
2154void RenderThreadImpl::UpdateScrollbarTheme(
2155 mojom::UpdateScrollbarThemeParamsPtr params) {
2156#if defined(OS_MACOSX)
2157 static_cast<WebScrollbarBehaviorImpl*>(
Blink Reformat1c4d759e2017-04-09 16:34:542158 blink_platform_impl_->ScrollbarBehavior())
rockota2db0da2016-10-18 17:39:112159 ->set_jump_on_track_click(params->jump_on_track_click);
2160
Blink Reformat1c4d759e2017-04-09 16:34:542161 blink::WebScrollbarTheme::UpdateScrollbarsWithNSDefaults(
rockota2db0da2016-10-18 17:39:112162 params->initial_button_delay, params->autoscroll_button_delay,
2163 params->preferred_scroller_style, params->redraw,
2164 params->button_placement);
2165#else
2166 NOTREACHED();
2167#endif
2168}
2169
2170void RenderThreadImpl::OnSystemColorsChanged(
2171 int32_t aqua_color_variant,
2172 const std::string& highlight_text_color,
2173 const std::string& highlight_color) {
2174#if defined(OS_MACOSX)
2175 SystemColorsDidChange(aqua_color_variant, highlight_text_color,
2176 highlight_color);
2177#else
2178 NOTREACHED();
2179#endif
2180}
2181
2182void RenderThreadImpl::PurgePluginListCache(bool reload_pages) {
brettw4b461082016-11-19 18:55:162183#if BUILDFLAG(ENABLE_PLUGINS)
rockota2db0da2016-10-18 17:39:112184 // The call below will cause a GetPlugins call with refresh=true, but at this
2185 // point we already know that the browser has refreshed its list, so disable
2186 // refresh temporarily to prevent each renderer process causing the list to be
2187 // regenerated.
2188 blink_platform_impl_->set_plugin_refresh_allowed(false);
Blink Reformat1c4d759e2017-04-09 16:34:542189 blink::ResetPluginCache(reload_pages);
rockota2db0da2016-10-18 17:39:112190 blink_platform_impl_->set_plugin_refresh_allowed(true);
2191
2192 for (auto& observer : observers_)
2193 observer.PluginListChanged();
2194#else
2195 NOTREACHED();
2196#endif
2197}
2198
[email protected]0ec90d522014-03-12 16:28:192199void RenderThreadImpl::OnCreateNewSharedWorker(
2200 const WorkerProcessMsg_CreateWorker_Params& params) {
2201 // EmbeddedSharedWorkerStub will self-destruct.
mkwstcfa98932016-03-09 13:06:192202 new EmbeddedSharedWorkerStub(
2203 params.url, params.name, params.content_security_policy,
2204 params.security_policy_type, params.creation_address_space,
2205 params.pause_on_start, params.route_id);
[email protected]0ec90d522014-03-12 16:28:192206}
2207
[email protected]5071cb22013-07-10 02:19:062208void RenderThreadImpl::OnMemoryPressure(
2209 base::MemoryPressureListener::MemoryPressureLevel memory_pressure_level) {
hong.zhengb28b5332016-05-11 02:33:392210 TRACE_EVENT0("memory","RenderThreadImpl::OnMemoryPressure");
rmcilroy7fbb3bd52015-02-17 19:02:142211 if (blink_platform_impl_) {
Blink Reformat1c4d759e2017-04-09 16:34:542212 blink::WebMemoryCoordinator::OnMemoryPressure(
bashic577bfc2016-01-08 03:42:352213 static_cast<blink::WebMemoryPressureLevel>(memory_pressure_level));
hajimehoshi7bb39582016-10-12 04:30:572214 }
2215 if (memory_pressure_level ==
2216 base::MemoryPressureListener::MEMORY_PRESSURE_LEVEL_CRITICAL) {
2217 ReleaseFreeMemory();
2218 ClearMemory();
2219 }
2220}
rmcilroyab967c972015-02-17 23:15:002221
hajimehoshi7bb39582016-10-12 04:30:572222void RenderThreadImpl::OnMemoryStateChange(base::MemoryState state) {
hajimehoshi7bb39582016-10-12 04:30:572223 if (blink_platform_impl_) {
Blink Reformat1c4d759e2017-04-09 16:34:542224 blink::WebMemoryCoordinator::OnMemoryStateChange(
hajimehoshi7bb39582016-10-12 04:30:572225 static_cast<blink::MemoryState>(state));
2226 }
bashi233f65e2017-02-09 08:36:032227}
2228
2229void RenderThreadImpl::OnPurgeMemory() {
bashib9058f282017-03-30 01:55:242230 // Record amount of purged memory after 2 seconds. 2 seconds is arbitrary
2231 // but it works most cases.
2232 RendererMemoryMetrics metrics;
bashia0ba0d42017-04-03 08:11:062233 if (!GetRendererMemoryMetrics(&metrics))
2234 return;
2235
bashib9058f282017-03-30 01:55:242236 GetRendererScheduler()->DefaultTaskRunner()->PostDelayedTask(
2237 FROM_HERE,
2238 base::Bind(&RenderThreadImpl::RecordPurgeMemory, base::Unretained(this),
2239 std::move(metrics)),
2240 base::TimeDelta::FromSeconds(2));
2241
bashi233f65e2017-02-09 08:36:032242 OnTrimMemoryImmediately();
2243 ReleaseFreeMemory();
2244 ClearMemory();
2245 if (blink_platform_impl_)
Blink Reformat1c4d759e2017-04-09 16:34:542246 blink::WebMemoryCoordinator::OnPurgeMemory();
hajimehoshi7bb39582016-10-12 04:30:572247}
2248
bashib9058f282017-03-30 01:55:242249void RenderThreadImpl::RecordPurgeMemory(RendererMemoryMetrics before) {
2250 RendererMemoryMetrics after;
bashia0ba0d42017-04-03 08:11:062251 if (!GetRendererMemoryMetrics(&after))
2252 return;
bashib9058f282017-03-30 01:55:242253 int64_t mbytes = static_cast<int64_t>(before.total_allocated_mb) -
2254 static_cast<int64_t>(after.total_allocated_mb);
2255 if (mbytes < 0)
2256 mbytes = 0;
2257 UMA_HISTOGRAM_MEMORY_LARGE_MB("Memory.Experimental.Renderer.PurgedMemory",
2258 mbytes);
2259}
2260
hajimehoshi7bb39582016-10-12 04:30:572261void RenderThreadImpl::ClearMemory() {
2262 // Do not call into blink if it is not initialized.
2263 if (blink_platform_impl_) {
2264 // Purge Skia font cache, by setting it to 0 and then again to the
2265 // previous limit.
2266 size_t font_cache_limit = SkGraphics::SetFontCacheLimit(0);
2267 SkGraphics::SetFontCacheLimit(font_cache_limit);
rmcilroy7fbb3bd52015-02-17 19:02:142268 }
[email protected]5071cb22013-07-10 02:19:062269}
2270
skyostil2d3b5bd2015-05-27 15:40:592271scoped_refptr<base::SingleThreadTaskRunner>
thestig529ad8a2016-07-08 20:30:122272RenderThreadImpl::GetFileThreadTaskRunner() {
fdoraye94d8642016-07-07 19:19:012273 DCHECK(message_loop()->task_runner()->BelongsToCurrentThread());
[email protected]59383c782013-04-17 16:43:272274 if (!file_thread_) {
[email protected]c6a7b862010-08-20 22:19:382275 file_thread_.reset(new base::Thread("Renderer::FILE"));
2276 file_thread_->Start();
2277 }
skyostil2d3b5bd2015-05-27 15:40:592278 return file_thread_->task_runner();
[email protected]c6a7b862010-08-20 22:19:382279}
[email protected]e9ff79c2012-10-19 21:31:262280
acolwellb4034942014-08-28 15:42:432281scoped_refptr<base::SingleThreadTaskRunner>
2282RenderThreadImpl::GetMediaThreadTaskRunner() {
fdoraye94d8642016-07-07 19:19:012283 DCHECK(message_loop()->task_runner()->BelongsToCurrentThread());
[email protected]c1330c82013-06-06 02:23:252284 if (!media_thread_) {
2285 media_thread_.reset(new base::Thread("Media"));
2286 media_thread_->Start();
2287 }
skyostil2d3b5bd2015-05-27 15:40:592288 return media_thread_->task_runner();
[email protected]c1330c82013-06-06 02:23:252289}
2290
dcastagna4517a182015-08-05 19:51:032291base::TaskRunner* RenderThreadImpl::GetWorkerTaskRunner() {
prashant.nfad657e2016-06-01 07:52:172292 return categorized_worker_pool_.get();
dcastagnab880e8f2015-06-30 20:16:062293}
2294
sadrul85cc5d82016-12-20 03:37:412295scoped_refptr<ui::ContextProviderCommandBuffer>
danakj0b4b94e32016-05-10 22:33:012296RenderThreadImpl::SharedCompositorWorkerContextProvider() {
revemand180dfc32015-09-24 00:19:432297 DCHECK(IsMainThread());
2298 // Try to reuse existing shared worker context provider.
revemand180dfc32015-09-24 00:19:432299 if (shared_worker_context_provider_) {
2300 // Note: If context is lost, delete reference after releasing the lock.
boliu11afa7e2016-04-18 18:04:142301 cc::ContextProvider::ScopedContextLock lock(
2302 shared_worker_context_provider_.get());
revemand180dfc32015-09-24 00:19:432303 if (shared_worker_context_provider_->ContextGL()
danakje8ec797e2016-04-19 04:08:432304 ->GetGraphicsResetStatusKHR() == GL_NO_ERROR)
2305 return shared_worker_context_provider_;
revemand180dfc32015-09-24 00:19:432306 }
danakje8ec797e2016-04-19 04:08:432307
sadrul6d310fa2016-08-04 02:12:162308 scoped_refptr<gpu::GpuChannelHost> gpu_channel_host(
2309 EstablishGpuChannelSync());
danakje8ec797e2016-04-19 04:08:432310 if (!gpu_channel_host) {
2311 shared_worker_context_provider_ = nullptr;
2312 return shared_worker_context_provider_;
revemand180dfc32015-09-24 00:19:432313 }
danakje8ec797e2016-04-19 04:08:432314
sunnypsd8ce1c22016-05-10 18:02:402315 int32_t stream_id = gpu::GPU_STREAM_DEFAULT;
2316 gpu::GpuStreamPriority stream_priority = gpu::GpuStreamPriority::NORMAL;
2317 if (is_async_worker_context_enabled_) {
2318 stream_id = gpu_channel_host->GenerateStreamID();
2319 stream_priority = gpu::GpuStreamPriority::LOW;
2320 }
2321
danakj9a04adc2016-05-16 22:45:072322 bool support_locking = true;
danakj0dd9e1e2016-05-11 22:15:092323 shared_worker_context_provider_ = CreateOffscreenContext(
danakj9a04adc2016-05-16 22:45:072324 std::move(gpu_channel_host), gpu::SharedMemoryLimits(), support_locking,
sadrul85cc5d82016-12-20 03:37:412325 ui::command_buffer_metrics::RENDER_WORKER_CONTEXT, stream_id,
danakj0dd9e1e2016-05-11 22:15:092326 stream_priority);
danakje8ec797e2016-04-19 04:08:432327 if (!shared_worker_context_provider_->BindToCurrentThread())
2328 shared_worker_context_provider_ = nullptr;
revemand180dfc32015-09-24 00:19:432329 return shared_worker_context_provider_;
2330}
2331
juncai2f298a82017-04-18 03:51:392332void RenderThreadImpl::SampleGamepads(device::Gamepads* data) {
Blink Reformat1c4d759e2017-04-09 16:34:542333 blink_platform_impl_->SampleGamepads(*data);
[email protected]0ff736562014-05-09 09:09:472334}
2335
rmcilroyaa296052015-04-14 15:35:272336bool RenderThreadImpl::RendererIsHidden() const {
2337 return widget_count_ > 0 && hidden_widget_count_ == widget_count_;
2338}
2339
[email protected]b2db9272014-01-10 17:42:002340void RenderThreadImpl::WidgetCreated() {
rmcilroyaa296052015-04-14 15:35:272341 bool renderer_was_hidden = RendererIsHidden();
[email protected]b2db9272014-01-10 17:42:002342 widget_count_++;
rmcilroyaa296052015-04-14 15:35:272343 if (renderer_was_hidden)
2344 OnRendererVisible();
[email protected]b2db9272014-01-10 17:42:002345}
2346
2347void RenderThreadImpl::WidgetDestroyed() {
rmcilroyaa296052015-04-14 15:35:272348 // TODO(rmcilroy): Remove the restriction that destroyed widgets must be
2349 // unhidden before WidgetDestroyed is called.
2350 DCHECK_GT(widget_count_, 0);
2351 DCHECK_GT(widget_count_, hidden_widget_count_);
[email protected]b2db9272014-01-10 17:42:002352 widget_count_--;
rmcilroyaa296052015-04-14 15:35:272353 if (RendererIsHidden())
2354 OnRendererHidden();
[email protected]b2db9272014-01-10 17:42:002355}
2356
2357void RenderThreadImpl::WidgetHidden() {
2358 DCHECK_LT(hidden_widget_count_, widget_count_);
2359 hidden_widget_count_++;
rmcilroyaa296052015-04-14 15:35:272360 if (RendererIsHidden())
2361 OnRendererHidden();
[email protected]b2db9272014-01-10 17:42:002362}
2363
2364void RenderThreadImpl::WidgetRestored() {
rmcilroyaa296052015-04-14 15:35:272365 bool renderer_was_hidden = RendererIsHidden();
[email protected]b2db9272014-01-10 17:42:002366 DCHECK_GT(hidden_widget_count_, 0);
2367 hidden_widget_count_--;
rmcilroyaa296052015-04-14 15:35:272368 if (renderer_was_hidden)
2369 OnRendererVisible();
2370}
[email protected]b2db9272014-01-10 17:42:002371
rmcilroyaa296052015-04-14 15:35:272372void RenderThreadImpl::OnRendererHidden() {
Blink Reformat1c4d759e2017-04-09 16:34:542373 blink::MainThreadIsolate()->IsolateInBackgroundNotification();
rmcilroyaa296052015-04-14 15:35:272374 // TODO(rmcilroy): Remove IdleHandler and replace it with an IdleTask
2375 // scheduled by the RendererScheduler - http://crbug.com/469210.
ulan4a385192015-11-11 10:59:182376 if (!GetContentClient()->renderer()->RunIdleHandlerWhenWidgetsHidden())
2377 return;
2378 ScheduleIdleHandler(kInitialIdleHandlerDelayMs);
rmcilroyaa296052015-04-14 15:35:272379}
2380
2381void RenderThreadImpl::OnRendererVisible() {
Blink Reformat1c4d759e2017-04-09 16:34:542382 blink::MainThreadIsolate()->IsolateInForegroundNotification();
rmcilroyaa296052015-04-14 15:35:272383 if (!GetContentClient()->renderer()->RunIdleHandlerWhenWidgetsHidden())
[email protected]b2db9272014-01-10 17:42:002384 return;
[email protected]b2db9272014-01-10 17:42:002385 ScheduleIdleHandler(kLongIdleHandlerDelayMs);
2386}
2387
ssid0603ca9f2015-06-09 16:48:082388void RenderThreadImpl::ReleaseFreeMemory() {
2389 base::allocator::ReleaseFreeMemory();
penghuang342762b2016-12-02 21:04:582390 discardable_shared_memory_manager_->ReleaseFreeMemory();
ssid0603ca9f2015-06-09 16:48:082391
2392 if (blink_platform_impl_)
Blink Reformat1c4d759e2017-04-09 16:34:542393 blink::DecommitFreeableMemory();
ssid0603ca9f2015-06-09 16:48:082394}
2395
ben76f52b242016-06-18 05:42:482396RenderThreadImpl::PendingFrameCreate::PendingFrameCreate(
rockotf8fdd9b2015-12-16 22:22:352397 int routing_id,
ben76f52b242016-06-18 05:42:482398 mojom::FrameRequest frame_request,
2399 mojom::FrameHostPtr frame_host)
rockotf8fdd9b2015-12-16 22:22:352400 : routing_id_(routing_id),
ben76f52b242016-06-18 05:42:482401 frame_request_(std::move(frame_request)),
2402 frame_host_(std::move(frame_host)) {
2403 // The RenderFrame may be deleted before the CreateFrame message is received.
2404 // In that case, the RenderFrameHost should cancel the create, which is
2405 // detected by setting an error handler on |frame_host_|.
2406 frame_host_.set_connection_error_handler(base::Bind(
2407 &RenderThreadImpl::PendingFrameCreate::OnConnectionError,
rockotf8fdd9b2015-12-16 22:22:352408 base::Unretained(this)));
2409}
2410
ben76f52b242016-06-18 05:42:482411RenderThreadImpl::PendingFrameCreate::~PendingFrameCreate() {
rockotf8fdd9b2015-12-16 22:22:352412}
2413
ben76f52b242016-06-18 05:42:482414void RenderThreadImpl::PendingFrameCreate::OnConnectionError() {
rockotf8fdd9b2015-12-16 22:22:352415 size_t erased =
ben76f52b242016-06-18 05:42:482416 RenderThreadImpl::current()->pending_frame_creates_.erase(routing_id_);
rockotf8fdd9b2015-12-16 22:22:352417 DCHECK_EQ(1u, erased);
2418}
2419
hong.zhengb28b5332016-05-11 02:33:392420void RenderThreadImpl::OnSyncMemoryPressure(
2421 base::MemoryPressureListener::MemoryPressureLevel memory_pressure_level) {
Blink Reformat1c4d759e2017-04-09 16:34:542422 if (!blink::MainThreadIsolate())
hong.zhengb28b5332016-05-11 02:33:392423 return;
2424
2425 v8::MemoryPressureLevel v8_memory_pressure_level =
2426 static_cast<v8::MemoryPressureLevel>(memory_pressure_level);
2427
2428 // In order to reduce performance impact, translate critical level to
2429 // moderate level for foregroud renderer.
2430 if (!RendererIsHidden() &&
2431 v8_memory_pressure_level == v8::MemoryPressureLevel::kCritical)
2432 v8_memory_pressure_level = v8::MemoryPressureLevel::kModerate;
2433
Blink Reformat1c4d759e2017-04-09 16:34:542434 blink::MainThreadIsolate()->MemoryPressureNotification(
hong.zhengb28b5332016-05-11 02:33:392435 v8_memory_pressure_level);
2436 blink::MemoryPressureNotificationToWorkerThreadIsolates(
2437 v8_memory_pressure_level);
2438}
2439
bashic4b4afcb2016-08-23 06:37:522440// Note that this would be called only when memory_coordinator is enabled.
2441// OnSyncMemoryPressure() is never called in that case.
2442void RenderThreadImpl::OnTrimMemoryImmediately() {
Blink Reformat1c4d759e2017-04-09 16:34:542443 if (blink::MainThreadIsolate()) {
2444 blink::MainThreadIsolate()->MemoryPressureNotification(
bashic4b4afcb2016-08-23 06:37:522445 v8::MemoryPressureLevel::kCritical);
2446 blink::MemoryPressureNotificationToWorkerThreadIsolates(
2447 v8::MemoryPressureLevel::kCritical);
2448 }
2449}
2450
rockot067ca55f2016-09-30 22:00:152451void RenderThreadImpl::OnRendererInterfaceRequest(
2452 mojom::RendererAssociatedRequest request) {
2453 DCHECK(!renderer_binding_.is_bound());
2454 renderer_binding_.Bind(std::move(request));
2455}
bashic4b4afcb2016-08-23 06:37:522456
[email protected]e9ff79c2012-10-19 21:31:262457} // namespace content