blob: da073cb259b6df21e665df76ab06b0951da9b183 [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"
gabf64a25e2017-05-12 19:42:5624#include "base/message_loop/message_loop.h"
[email protected]835d7c82010-10-14 04:38:3825#include "base/metrics/field_trial.h"
asvitkine8d51e9d2016-09-02 23:55:4326#include "base/metrics/histogram_macros.h"
[email protected]433df472012-03-07 20:33:3927#include "base/path_service.h"
tasakb46626a2016-10-18 05:54:4428#include "base/process/process_metrics.h"
fdoray2df4a9e2016-07-18 23:47:1629#include "base/run_loop.h"
[email protected]21aa99682013-06-11 07:17:0130#include "base/strings/string16.h"
[email protected]1e1d1e12014-01-17 16:14:2931#include "base/strings/string_number_conversions.h"
hablichd6a4f122015-10-28 11:34:4932#include "base/strings/string_split.h"
ccameron6728bae32015-01-09 20:18:0633#include "base/strings/sys_string_conversions.h"
[email protected]74ebfb12013-06-07 20:48:0034#include "base/strings/utf_string_conversions.h"
fdoray50a38342016-11-21 20:46:0435#include "base/threading/sequenced_worker_pool.h"
reveman34b7a1522015-03-23 20:27:4736#include "base/threading/simple_thread.h"
[email protected]1357c322010-12-30 22:18:5637#include "base/threading/thread_local.h"
[email protected]d293572a2013-05-23 18:50:4538#include "base/threading/thread_restrictions.h"
gab30f26df2016-05-11 19:37:5539#include "base/threading/thread_task_runner_handle.h"
ccameron9c48d1d42016-09-22 01:46:0140#include "base/trace_event/memory_dump_manager.h"
primiano9e38d552015-01-28 04:18:0141#include "base/trace_event/trace_event.h"
[email protected]7a4de7a62010-08-17 18:38:2442#include "base/values.h"
avi1023d012015-12-25 02:39:1443#include "build/build_config.h"
jbroman0d302162015-09-05 05:46:2344#include "cc/base/histograms.h"
[email protected]d72493152014-01-08 17:37:4545#include "cc/base/switches.h"
[email protected]38564622014-08-19 02:47:1846#include "cc/blink/web_layer_impl.h"
ericrk9151705c2016-07-26 19:53:1647#include "cc/output/buffer_to_texture_target_map.h"
danakj1120f4c2016-09-15 02:05:3248#include "cc/output/compositor_frame_sink.h"
jbroman6ccbc7d472016-07-27 04:45:4149#include "cc/output/copy_output_request.h"
danakj83066a32016-06-21 02:34:4950#include "cc/output/vulkan_in_process_context_provider.h"
danakj920156852015-05-18 20:22:2951#include "cc/raster/task_graph_runner.h"
vollick1050cc62015-12-03 07:04:5452#include "cc/trees/layer_tree_host_common.h"
loysoa6edaaff2015-05-25 03:26:4453#include "cc/trees/layer_tree_settings.h"
penghuangd81c1a62016-11-02 20:06:0654#include "components/discardable_memory/client/client_discardable_shared_memory_manager.h"
dalecurtis4a9839a2017-05-04 23:40:4755#include "components/metrics/public/interfaces/single_sample_metrics.mojom.h"
56#include "components/metrics/single_sample_metrics.h"
[email protected]a8cb3b73b2013-08-12 05:50:5057#include "content/child/appcache/appcache_dispatcher.h"
58#include "content/child/appcache/appcache_frontend_impl.h"
dmurph1fb98482016-03-30 21:14:2659#include "content/child/blob_storage/blob_message_filter.h"
[email protected]10208ea2013-06-06 20:08:0360#include "content/child/child_histogram_message_filter.h"
alexclarke0bc36e8d32014-12-17 17:29:2061#include "content/child/child_resource_message_filter.h"
[email protected]fdeac262014-07-10 12:52:5162#include "content/child/content_child_helpers.h"
[email protected]89c36f82013-07-17 06:23:2763#include "content/child/db_message_filter.h"
[email protected]c7199a6e2013-06-04 12:56:0164#include "content/child/indexed_db/indexed_db_dispatcher.h"
bashia6264042016-09-15 04:49:5165#include "content/child/memory/child_memory_coordinator_impl.h"
[email protected]10208ea2013-06-06 20:08:0366#include "content/child/resource_dispatcher.h"
alexclarke0bc36e8d32014-12-17 17:29:2067#include "content/child/resource_scheduling_filter.h"
[email protected]643255da2013-06-12 20:55:1368#include "content/child/runtime_features.h"
[email protected]57cf97882013-06-26 20:39:0169#include "content/child/thread_safe_sender.h"
[email protected]c7199a6e2013-06-04 12:56:0170#include "content/child/web_database_observer_impl.h"
kinukoef647412015-12-23 06:10:4371#include "content/child/worker_thread_registry.h"
[email protected]bdae9812011-10-15 00:33:0372#include "content/common/child_process_messages.h"
[email protected]89c36f82013-07-17 06:23:2773#include "content/common/content_constants_internal.h"
[email protected]5f2aa722013-08-07 16:59:4174#include "content/common/dom_storage/dom_storage_messages.h"
thakis18e426412017-03-15 12:06:3775#include "content/common/features.h"
chiniforooshan614d70a2017-03-17 01:19:3376#include "content/common/field_trial_recorder.mojom.h"
[email protected]82307f6b2014-08-07 03:30:1277#include "content/common/frame_messages.h"
raymesbba82b32016-07-19 00:41:3878#include "content/common/frame_owner_properties.h"
sunnyps8f9139e2017-05-12 17:53:2579#include "content/common/gpu_stream_constants.h"
avia7c3f51c2015-09-16 00:30:3180#include "content/common/render_process_messages.h"
[email protected]94dc971d2011-03-05 19:08:3281#include "content/common/resource_messages.h"
alexmos68734212016-08-27 00:06:3182#include "content/common/site_isolation_policy.h"
[email protected]778574e2011-03-21 22:03:5083#include "content/common/view_messages.h"
[email protected]0ec90d522014-03-12 16:28:1984#include "content/common/worker_messages.h"
[email protected]a458504b2012-07-23 19:57:0685#include "content/public/common/content_constants.h"
bashia6264042016-09-15 04:49:5186#include "content/public/common/content_features.h"
[email protected]433df472012-03-07 20:33:3987#include "content/public/common/content_paths.h"
[email protected]c08950d22011-10-13 22:20:2988#include "content/public/common/content_switches.h"
[email protected]daf82f82011-10-31 22:35:3189#include "content/public/common/renderer_preferences.h"
benbd9dc802017-04-19 01:37:4390#include "content/public/common/service_manager_connection.h"
ben649b3edd2017-03-23 00:32:0291#include "content/public/common/service_names.mojom.h"
benbd9dc802017-04-19 01:37:4392#include "content/public/common/simple_connection_filter.h"
[email protected]58436a12012-03-21 17:10:2693#include "content/public/common/url_constants.h"
[email protected]d344114c2011-10-01 01:24:3494#include "content/public/renderer/content_renderer_client.h"
tyoshino832a58a2016-04-18 08:14:0895#include "content/public/renderer/render_thread_observer.h"
[email protected]64ffa0442011-10-03 22:08:3696#include "content/public/renderer/render_view_visitor.h"
fsamuel6c1dfeb2014-12-18 19:21:3397#include "content/renderer/browser_plugin/browser_plugin_manager.h"
jsbell279efb42015-03-31 17:02:4698#include "content/renderer/cache_storage/cache_storage_dispatcher.h"
99#include "content/renderer/cache_storage/cache_storage_message_filter.h"
prashant.nfad657e2016-06-01 07:52:17100#include "content/renderer/categorized_worker_pool.h"
[email protected]70019152012-12-19 11:44:19101#include "content/renderer/devtools/devtools_agent_filter.h"
[email protected]1910fe82012-05-10 00:04:10102#include "content/renderer/dom_storage/dom_storage_dispatcher.h"
103#include "content/renderer/dom_storage/webstoragearea_impl.h"
104#include "content/renderer/dom_storage/webstoragenamespace_impl.h"
simonhonga7e3ac42014-11-11 20:50:22105#include "content/renderer/gpu/compositor_external_begin_frame_source.h"
106#include "content/renderer/gpu/compositor_forwarding_message_filter.h"
danakj83066a32016-06-21 02:34:49107#include "content/renderer/gpu/frame_swap_message_queue.h"
danakj1120f4c2016-09-15 02:05:32108#include "content/renderer/gpu/renderer_compositor_frame_sink.h"
[email protected]7a72d452013-12-13 10:01:13109#include "content/renderer/input/input_event_filter.h"
110#include "content/renderer/input/input_handler_manager.h"
jdduke691dd572014-12-02 20:47:52111#include "content/renderer/input/main_thread_input_event_filter.h"
[email protected]f7eb0a392011-07-12 10:19:51112#include "content/renderer/media/audio_input_message_filter.h"
113#include "content/renderer/media/audio_message_filter.h"
[email protected]3958e972012-07-17 00:25:41114#include "content/renderer/media/audio_renderer_mixer_manager.h"
[email protected]d8cd8372012-03-09 10:49:51115#include "content/renderer/media/media_stream_center.h"
[email protected]a9875152013-06-22 04:03:03116#include "content/renderer/media/midi_message_filter.h"
xhwang194acae2014-11-12 22:46:33117#include "content/renderer/media/render_media_client.h"
[email protected]2329bfc72014-02-28 02:03:21118#include "content/renderer/media/renderer_gpu_video_accelerator_factories.h"
[email protected]80b161a2011-06-27 17:42:11119#include "content/renderer/media/video_capture_impl_manager.h"
[email protected]d7ff5fb2014-05-29 19:50:25120#include "content/renderer/net_info_helper.h"
[email protected]4761cf12012-09-12 10:37:55121#include "content/renderer/p2p/socket_dispatcher.h"
[email protected]82307f6b2014-08-07 03:30:12122#include "content/renderer/render_frame_proxy.h"
[email protected]8704f89b2011-04-15 00:30:05123#include "content/renderer/render_process_impl.h"
[email protected]310ebd6302011-10-10 19:06:28124#include "content/renderer/render_view_impl.h"
tfarina556a7232014-10-05 01:02:09125#include "content/renderer/renderer_blink_platform_impl.h"
jdduke94ae1f32015-02-05 06:27:13126#include "content/renderer/scheduler/resource_dispatch_throttler.h"
shimazu5de409e42016-09-29 08:45:28127#include "content/renderer/service_worker/embedded_worker_instance_client_impl.h"
mek27c9d742015-07-16 18:30:18128#include "content/renderer/service_worker/service_worker_context_client.h"
kinuko5af4ffe2015-06-09 03:38:46129#include "content/renderer/service_worker/service_worker_context_message_filter.h"
[email protected]0ec90d522014-03-12 16:28:19130#include "content/renderer/shared_worker/embedded_shared_worker_stub.h"
juncai2f298a82017-04-18 03:51:39131#include "device/gamepad/public/cpp/gamepads.h"
chunyang.daibe874c52014-11-14 06:45:05132#include "gin/public/debug.h"
dongseong.hwang72183b02014-12-08 10:41:55133#include "gpu/GLES2/gl2extchromium.h"
danakj6f4e1e22016-04-20 03:27:34134#include "gpu/command_buffer/client/shared_memory_limits.h"
danakj870925d42016-05-03 20:07:38135#include "gpu/ipc/client/command_buffer_proxy_impl.h"
penghuang346a46f92016-03-31 21:37:52136#include "gpu/ipc/client/gpu_channel_host.h"
[email protected]46f36a492010-07-28 19:36:41137#include "ipc/ipc_channel_handle.h"
amistryd4aa70d2016-06-23 07:52:37138#include "ipc/ipc_channel_mojo.h"
[email protected]cb6037d2009-11-16 22:55:17139#include "ipc/ipc_platform_file.h"
[email protected]433df472012-03-07 20:33:39140#include "media/base/media.h"
chcunningham9a285ed2017-03-08 21:48:56141#include "media/base/media_switches.h"
Brett Wilson0748bf412016-11-22 17:55:46142#include "media/media_features.h"
servolk8b3b39b2015-03-03 19:08:18143#include "media/renderers/gpu_video_accelerator_factories.h"
rockot85dce0862015-11-13 01:33:59144#include "mojo/public/cpp/bindings/strong_binding.h"
[email protected]620161e2011-03-07 18:05:26145#include "net/base/net_errors.h"
eroman9ab64842015-07-21 05:07:52146#include "net/base/port_util.h"
hablichd6a4f122015-10-28 11:34:49147#include "net/base/registry_controlled_domains/registry_controlled_domain.h"
tfarina7a4a7fd2016-01-20 14:23:44148#include "net/base/url_util.h"
brettw4b461082016-11-19 18:55:16149#include "ppapi/features/features.h"
benbd9dc802017-04-19 01:37:43150#include "services/service_manager/public/cpp/binder_registry.h"
penghuangd6843e42016-12-17 13:57:20151#include "services/service_manager/public/cpp/connector.h"
rockot734fb662016-10-15 16:41:30152#include "services/service_manager/public/cpp/interface_provider.h"
xlai11ac7802017-04-07 20:13:18153#include "services/ui/public/cpp/bitmap/child_shared_bitmap_manager.h"
sadrul85cc5d82016-12-20 03:37:41154#include "services/ui/public/cpp/gpu/context_provider_command_buffer.h"
penghuangd6843e42016-12-17 13:57:20155#include "services/ui/public/interfaces/constants.mojom.h"
[email protected]b48c53ad2014-02-05 21:59:18156#include "skia/ext/event_tracer_impl.h"
ssid59c969162015-07-28 13:02:58157#include "skia/ext/skia_memory_dump_provider.h"
kinukoed1ed1d2017-02-08 09:13:43158#include "third_party/WebKit/public/platform/WebCache.h"
reed6e5a72222015-08-06 20:37:16159#include "third_party/WebKit/public/platform/WebImageGenerator.h"
bashi5f4c78922016-08-18 23:06:08160#include "third_party/WebKit/public/platform/WebMemoryCoordinator.h"
kinukofbfee762017-03-08 04:01:06161#include "third_party/WebKit/public/platform/WebNetworkStateNotifier.h"
[email protected]89c36f82013-07-17 06:23:27162#include "third_party/WebKit/public/platform/WebString.h"
skyostil457b0a12014-09-09 10:12:07163#include "third_party/WebKit/public/platform/WebThread.h"
altiminc7369bf2017-04-11 14:29:15164#include "third_party/WebKit/public/platform/scheduler/child/webthread_base.h"
skyostil529caa292016-08-10 17:44:51165#include "third_party/WebKit/public/platform/scheduler/renderer/renderer_scheduler.h"
[email protected]2255a9332013-06-17 05:12:31166#include "third_party/WebKit/public/web/WebDatabase.h"
167#include "third_party/WebKit/public/web/WebDocument.h"
168#include "third_party/WebKit/public/web/WebFrame.h"
169#include "third_party/WebKit/public/web/WebKit.h"
[email protected]2255a9332013-06-17 05:12:31170#include "third_party/WebKit/public/web/WebRuntimeFeatures.h"
171#include "third_party/WebKit/public/web/WebScriptController.h"
172#include "third_party/WebKit/public/web/WebSecurityPolicy.h"
[email protected]2255a9332013-06-17 05:12:31173#include "third_party/WebKit/public/web/WebView.h"
[email protected]ddbb53342014-01-06 10:59:47174#include "third_party/skia/include/core/SkGraphics.h"
[email protected]c49201a2012-05-24 11:04:57175#include "ui/base/layout.h"
[email protected]18ad6772011-09-20 21:51:32176#include "ui/base/ui_base_switches.h"
mlamouri7c149652017-03-24 00:00:09177#include "ui/display/display_switches.h"
ennee292bdc2016-09-15 19:57:15178#include "ui/gl/gl_switches.h"
[email protected]2c62b562009-01-27 19:04:50179
[email protected]33b02992014-03-01 01:06:29180#if defined(OS_ANDROID)
181#include <cpu-features.h>
boliubee541f42015-11-05 00:52:53182#include "content/renderer/android/synchronous_compositor_filter.h"
danakj1120f4c2016-09-15 02:05:32183#include "content/renderer/android/synchronous_compositor_frame_sink.h"
boliue81d16132016-04-26 00:54:41184#include "content/renderer/media/android/stream_texture_factory.h"
dalecurtis88af3932016-02-20 00:12:20185#include "media/base/android/media_codec_util.h"
[email protected]33b02992014-03-01 01:06:29186#endif
187
188#if defined(OS_MACOSX)
ccamerona7644752014-12-30 01:16:31189#include "base/mac/mac_util.h"
rsesek1efb3c32015-09-29 15:39:50190#include "content/renderer/theme_helper_mac.h"
[email protected]33b02992014-03-01 01:06:29191#include "content/renderer/webscrollbarbehavior_impl_mac.h"
192#endif
193
[email protected]da00a2882009-03-09 17:51:19194#if defined(OS_WIN)
195#include <windows.h>
196#include <objbase.h>
197#endif
198
Brett Wilson0748bf412016-11-22 17:55:46199#if BUILDFLAG(ENABLE_WEBRTC)
liushouqun517b1292016-09-14 05:58:59200#include "content/renderer/media/aec_dump_message_filter.h"
[email protected]22fe91d2014-08-12 17:07:12201#include "content/renderer/media/peer_connection_tracker.h"
202#include "content/renderer/media/rtc_peer_connection_handler.h"
203#include "content/renderer/media/webrtc/peer_connection_dependency_factory.h"
[email protected]22fe91d2014-08-12 17:07:12204#endif
205
chunyang.daibe874c52014-11-14 06:45:05206#ifdef ENABLE_VTUNE_JIT_INTERFACE
207#include "v8/src/third_party/vtune/v8-vtune.h"
208#endif
209
bend32292b2016-10-07 00:21:58210#include "content/public/common/service_manager_connection.h"
fsamuel2545ecc2015-12-05 00:44:46211#include "content/renderer/mus/render_widget_window_tree_client_factory.h"
sadrul602ce1362017-01-26 06:41:10212#include "content/renderer/mus/renderer_window_tree_client.h"
sadrul04cfa892016-12-09 17:53:49213#include "services/ui/public/cpp/gpu/gpu.h"
fsamuel6c6da0232015-11-26 05:13:46214
ochangdd89a1e2016-06-08 16:39:01215#if defined(ENABLE_IPC_FUZZER)
216#include "content/common/external_ipc_dumper.h"
217#endif
218
tasakb46626a2016-10-18 05:54:44219#if defined(OS_MACOSX)
220#include <malloc/malloc.h>
221#else
222#include <malloc.h>
223#endif
224
[email protected]d293572a2013-05-23 18:50:45225using base::ThreadRestrictions;
[email protected]180ef242013-11-07 06:50:46226using blink::WebDocument;
227using blink::WebFrame;
228using blink::WebNetworkStateNotifier;
229using blink::WebRuntimeFeatures;
230using blink::WebScriptController;
231using blink::WebSecurityPolicy;
232using blink::WebString;
233using blink::WebView;
[email protected]e9ff79c2012-10-19 21:31:26234
235namespace content {
initial.commit09911bf2008-07-26 23:55:29236
[email protected]42f1d7822009-07-23 18:17:55237namespace {
[email protected]da9ccfb2012-01-28 00:34:40238
avi1023d012015-12-25 02:39:14239const int64_t kInitialIdleHandlerDelayMs = 1000;
240const int64_t kLongIdleHandlerDelayMs = 30 * 1000;
[email protected]bee16aab2009-08-26 15:55:03241
jdduke94ae1f32015-02-05 06:27:13242#if defined(OS_ANDROID)
243// On Android, resource messages can each take ~1.5ms to dispatch on the browser
244// IO thread. Limiting the message rate to 3/frame at 60hz ensures that the
245// induced work takes but a fraction (~1/4) of the overall frame budget.
246const int kMaxResourceRequestsPerFlushWhenThrottled = 3;
247#else
248const int kMaxResourceRequestsPerFlushWhenThrottled = 8;
249#endif
250const double kThrottledResourceRequestFlushPeriodS = 1. / 60.;
251
[email protected]dd2c1022014-07-22 23:13:57252// Maximum allocation size allowed for image scaling filters that
253// require pre-scaling. Skia will fallback to a filter that doesn't
254// require pre-scaling if the default filter would require an
255// allocation that exceeds this limit.
256const size_t kImageCacheSingleAllocationByteLimit = 64 * 1024 * 1024;
257
samans2040988b2017-04-11 23:58:35258#if defined(OS_ANDROID)
danakj83066a32016-06-21 02:34:49259// Unique identifier for each output surface created.
danakj1120f4c2016-09-15 02:05:32260uint32_t g_next_compositor_frame_sink_id = 1;
samans2040988b2017-04-11 23:58:35261#endif
danakj83066a32016-06-21 02:34:49262
rockot5c478a72016-09-28 23:14:18263// An implementation of mojom::RenderMessageFilter which can be mocked out
264// for tests which may indirectly send messages over this interface.
265mojom::RenderMessageFilter* g_render_message_filter_for_testing;
266
olegmax045f7fb12017-05-19 07:58:55267// An implementation of RendererBlinkPlatformImpl which can be mocked out
268// for tests.
269RendererBlinkPlatformImpl* g_current_blink_platform_impl_for_testing;
270
[email protected]f1a29a02011-10-06 23:08:44271// Keep the global RenderThreadImpl in a TLS slot so it is impossible to access
[email protected]f3ede412010-06-21 22:52:16272// incorrectly from the wrong thread.
scottmg5e65e3a2017-03-08 08:48:46273base::LazyInstance<base::ThreadLocalPointer<RenderThreadImpl>>::DestructorAtExit
[email protected]6de0fd1d2011-11-15 13:31:49274 lazy_tls = LAZY_INSTANCE_INITIALIZER;
[email protected]1edc16b82009-04-07 17:45:54275
hong.zhengb28b5332016-05-11 02:33:39276// v8::MemoryPressureLevel should correspond to base::MemoryPressureListener.
277static_assert(static_cast<v8::MemoryPressureLevel>(
278 base::MemoryPressureListener::MEMORY_PRESSURE_LEVEL_NONE) ==
279 v8::MemoryPressureLevel::kNone, "none level not align");
280static_assert(static_cast<v8::MemoryPressureLevel>(
281 base::MemoryPressureListener::MEMORY_PRESSURE_LEVEL_MODERATE) ==
282 v8::MemoryPressureLevel::kModerate, "moderate level not align");
283static_assert(static_cast<v8::MemoryPressureLevel>(
284 base::MemoryPressureListener::MEMORY_PRESSURE_LEVEL_CRITICAL) ==
285 v8::MemoryPressureLevel::kCritical, "critical level not align");
286
hong.zheng2e296f822016-06-29 02:47:44287// WebMemoryPressureLevel should correspond to base::MemoryPressureListener.
288static_assert(static_cast<blink::WebMemoryPressureLevel>(
Blink Reformat1c4d759e2017-04-09 16:34:54289 base::MemoryPressureListener::MEMORY_PRESSURE_LEVEL_NONE) ==
290 blink::kWebMemoryPressureLevelNone,
291 "blink::WebMemoryPressureLevelNone not align");
292static_assert(
293 static_cast<blink::WebMemoryPressureLevel>(
294 base::MemoryPressureListener::MEMORY_PRESSURE_LEVEL_MODERATE) ==
295 blink::kWebMemoryPressureLevelModerate,
296 "blink::WebMemoryPressureLevelModerate not align");
297static_assert(
298 static_cast<blink::WebMemoryPressureLevel>(
299 base::MemoryPressureListener::MEMORY_PRESSURE_LEVEL_CRITICAL) ==
300 blink::kWebMemoryPressureLevelCritical,
301 "blink::WebMemoryPressureLevelCritical not align");
hong.zheng2e296f822016-06-29 02:47:44302
[email protected]b2d98762012-09-03 17:04:06303void* CreateHistogram(
[email protected]d1b8fccc2011-08-03 01:20:13304 const char *name, int min, int max, size_t buckets) {
305 if (min <= 0)
306 min = 1;
[email protected]b2d98762012-09-03 17:04:06307 std::string histogram_name;
308 RenderThreadImpl* render_thread_impl = RenderThreadImpl::current();
309 if (render_thread_impl) { // Can be null in tests.
310 histogram_name = render_thread_impl->
311 histogram_customizer()->ConvertToCustomHistogramName(name);
312 } else {
313 histogram_name = std::string(name);
314 }
[email protected]de415552013-01-23 04:12:17315 base::HistogramBase* histogram = base::Histogram::FactoryGet(
[email protected]b2d98762012-09-03 17:04:06316 histogram_name, min, max, buckets,
317 base::Histogram::kUmaTargetedHistogramFlag);
[email protected]d1b8fccc2011-08-03 01:20:13318 return histogram;
319}
320
[email protected]b2d98762012-09-03 17:04:06321void AddHistogramSample(void* hist, int sample) {
[email protected]d1b8fccc2011-08-03 01:20:13322 base::Histogram* histogram = static_cast<base::Histogram*>(hist);
323 histogram->Add(sample);
324}
325
ben76f52b242016-06-18 05:42:48326class FrameFactoryImpl : public mojom::FrameFactory {
rockotf8fdd9b2015-12-16 22:22:35327 public:
benf28ce882017-05-02 16:15:49328 explicit FrameFactoryImpl(const service_manager::BindSourceInfo& source_info)
329 : source_info_(source_info), routing_id_highmark_(-1) {}
rockotf8fdd9b2015-12-16 22:22:35330
ben76f52b242016-06-18 05:42:48331 private:
332 // mojom::FrameFactory:
csharrison95f01e922017-04-24 18:52:35333 void CreateFrame(
334 int32_t frame_routing_id,
335 mojom::FrameRequest frame_request,
336 mojom::FrameHostInterfaceBrokerPtr frame_host_interface_broker) override {
rockotf8fdd9b2015-12-16 22:22:35337 // TODO(morrita): This is for investigating http://crbug.com/415059 and
338 // should be removed once it is fixed.
339 CHECK_LT(routing_id_highmark_, frame_routing_id);
340 routing_id_highmark_ = frame_routing_id;
341
342 RenderFrameImpl* frame = RenderFrameImpl::FromRoutingID(frame_routing_id);
343 // We can receive a GetServiceProviderForFrame message for a frame not yet
rockot067ca55f2016-09-30 22:00:15344 // created due to a race between the message and a
345 // mojom::Renderer::CreateView IPC that triggers creation of the RenderFrame
346 // we want.
rockotf8fdd9b2015-12-16 22:22:35347 if (!frame) {
ben76f52b242016-06-18 05:42:48348 RenderThreadImpl::current()->RegisterPendingFrameCreate(
benf28ce882017-05-02 16:15:49349 source_info_, frame_routing_id, std::move(frame_request),
csharrison95f01e922017-04-24 18:52:35350 std::move(frame_host_interface_broker));
rockotf8fdd9b2015-12-16 22:22:35351 return;
352 }
353
benf28ce882017-05-02 16:15:49354 frame->BindFrame(source_info_, std::move(frame_request),
csharrison95f01e922017-04-24 18:52:35355 std::move(frame_host_interface_broker));
rockotf8fdd9b2015-12-16 22:22:35356 }
357
358 private:
benf28ce882017-05-02 16:15:49359 service_manager::BindSourceInfo source_info_;
rockotf8fdd9b2015-12-16 22:22:35360 int32_t routing_id_highmark_;
rockotf8fdd9b2015-12-16 22:22:35361};
362
benf28ce882017-05-02 16:15:49363void CreateFrameFactory(const service_manager::BindSourceInfo& source_info,
364 mojom::FrameFactoryRequest request) {
365 mojo::MakeStrongBinding(base::MakeUnique<FrameFactoryImpl>(source_info),
rockot8e66a08d2016-09-13 00:48:21366 std::move(request));
rockotf8fdd9b2015-12-16 22:22:35367}
368
sadrul85cc5d82016-12-20 03:37:41369scoped_refptr<ui::ContextProviderCommandBuffer> CreateOffscreenContext(
danakjc3983552016-05-03 00:04:35370 scoped_refptr<gpu::GpuChannelHost> gpu_channel_host,
danakj0dd9e1e2016-05-11 22:15:09371 const gpu::SharedMemoryLimits& limits,
danakj9a04adc2016-05-16 22:45:07372 bool support_locking,
sadrul85cc5d82016-12-20 03:37:41373 ui::command_buffer_metrics::ContextType type,
sunnypsd8ce1c22016-05-10 18:02:40374 int32_t stream_id,
sunnyps8f9139e2017-05-12 17:53:25375 gpu::SchedulingPriority stream_priority) {
danakje8ec797e2016-04-19 04:08:43376 DCHECK(gpu_channel_host);
377 // This is used to create a few different offscreen contexts:
378 // - The shared main thread context (offscreen) used by blink for canvas.
379 // - The worker context (offscreen) used for GPU raster and video decoding.
380 // This is for an offscreen context, so the default framebuffer doesn't need
381 // alpha, depth, stencil, antialiasing.
382 gpu::gles2::ContextCreationAttribHelper attributes;
383 attributes.alpha_size = -1;
384 attributes.depth_size = 0;
385 attributes.stencil_size = 0;
386 attributes.samples = 0;
387 attributes.sample_buffers = 0;
388 attributes.bind_generates_resource = false;
389 attributes.lose_context_when_out_of_memory = true;
sunnypsd8ce1c22016-05-10 18:02:40390 const bool automatic_flushes = false;
sadrul85cc5d82016-12-20 03:37:41391 return make_scoped_refptr(new ui::ContextProviderCommandBuffer(
sunnypsd8ce1c22016-05-10 18:02:40392 std::move(gpu_channel_host), stream_id, stream_priority,
393 gpu::kNullSurfaceHandle,
zmo09ea813b2017-01-20 23:38:36394 GURL("chrome://gpu/RenderThreadImpl::CreateOffscreenContext/" +
395 ui::command_buffer_metrics::ContextTypeToString(type)),
pimand488e8b42016-06-30 19:06:59396 automatic_flushes, support_locking, limits, attributes, nullptr, type));
danakje8ec797e2016-04-19 04:08:43397}
398
penghuange1d86512016-07-08 18:15:00399bool IsRunningInMash() {
400 const base::CommandLine* cmdline = base::CommandLine::ForCurrentProcess();
401 return cmdline->HasSwitch(switches::kIsRunningInMash);
402}
403
dalecurtis4a9839a2017-05-04 23:40:47404// Hook that allows single-sample metric code from //components/metrics to
405// connect from the renderer process to the browser process.
406void CreateSingleSampleMetricsProvider(
407 scoped_refptr<base::SingleThreadTaskRunner> task_runner,
408 service_manager::Connector* connector,
409 metrics::mojom::SingleSampleMetricsProviderRequest request) {
410 if (task_runner->BelongsToCurrentThread()) {
411 connector->BindInterface(mojom::kBrowserServiceName, std::move(request));
412 return;
413 }
414
415 task_runner->PostTask(
416 FROM_HERE,
417 base::Bind(&CreateSingleSampleMetricsProvider, std::move(task_runner),
418 connector, base::Passed(&request)));
419}
420
[email protected]b2d98762012-09-03 17:04:06421} // namespace
422
[email protected]fdeac262014-07-10 12:52:51423// For measuring memory usage after each task. Behind a command line flag.
424class MemoryObserver : public base::MessageLoop::TaskObserver {
425 public:
426 MemoryObserver() {}
dcheng6d18e402014-10-21 12:32:52427 ~MemoryObserver() override {}
[email protected]fdeac262014-07-10 12:52:51428
dcheng6d18e402014-10-21 12:32:52429 void WillProcessTask(const base::PendingTask& pending_task) override {}
[email protected]fdeac262014-07-10 12:52:51430
dcheng6d18e402014-10-21 12:32:52431 void DidProcessTask(const base::PendingTask& pending_task) override {
asvitkinec0fb8022014-08-26 04:39:35432 LOCAL_HISTOGRAM_MEMORY_KB("Memory.RendererUsed", GetMemoryUsageKB());
[email protected]fdeac262014-07-10 12:52:51433 }
434
435 private:
436 DISALLOW_COPY_AND_ASSIGN(MemoryObserver);
437};
438
[email protected]b2d98762012-09-03 17:04:06439RenderThreadImpl::HistogramCustomizer::HistogramCustomizer() {
440 custom_histograms_.insert("V8.MemoryExternalFragmentationTotal");
441 custom_histograms_.insert("V8.MemoryHeapSampleTotalCommitted");
442 custom_histograms_.insert("V8.MemoryHeapSampleTotalUsed");
hablich4598ddc2015-11-07 18:37:28443 custom_histograms_.insert("V8.MemoryHeapUsed");
444 custom_histograms_.insert("V8.MemoryHeapCommitted");
[email protected]b2d98762012-09-03 17:04:06445}
446
447RenderThreadImpl::HistogramCustomizer::~HistogramCustomizer() {}
448
449void RenderThreadImpl::HistogramCustomizer::RenderViewNavigatedToHost(
450 const std::string& host, size_t view_count) {
avi83883c82014-12-23 00:08:49451 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
452 switches::kDisableHistogramCustomizer)) {
[email protected]9baee832012-12-10 11:07:15453 return;
454 }
[email protected]b2d98762012-09-03 17:04:06455 // Check if all RenderViews are displaying a page from the same host. If there
456 // is only one RenderView, the common host is this view's host. If there are
457 // many, check if this one shares the common host of the other
458 // RenderViews. It's ok to not detect some cases where the RenderViews share a
459 // common host. This information is only used for producing custom histograms.
460 if (view_count == 1)
461 SetCommonHost(host);
462 else if (host != common_host_)
463 SetCommonHost(std::string());
464}
465
466std::string RenderThreadImpl::HistogramCustomizer::ConvertToCustomHistogramName(
467 const char* histogram_name) const {
468 std::string name(histogram_name);
469 if (!common_host_histogram_suffix_.empty() &&
470 custom_histograms_.find(name) != custom_histograms_.end())
471 name += common_host_histogram_suffix_;
472 return name;
473}
474
475void RenderThreadImpl::HistogramCustomizer::SetCommonHost(
476 const std::string& host) {
477 if (host != common_host_) {
478 common_host_ = host;
479 common_host_histogram_suffix_ = HostToCustomHistogramSuffix(host);
Blink Reformat1c4d759e2017-04-09 16:34:54480 blink::MainThreadIsolate()->SetCreateHistogramFunction(CreateHistogram);
[email protected]b2d98762012-09-03 17:04:06481 }
482}
483
hablichd6a4f122015-10-28 11:34:49484std::string RenderThreadImpl::HistogramCustomizer::HostToCustomHistogramSuffix(
485 const std::string& host) {
486 if (host == "mail.google.com")
487 return ".gmail";
488 if (host == "docs.google.com" || host == "drive.google.com")
489 return ".docs";
490 if (host == "plus.google.com")
491 return ".plus";
492 if (host == "inbox.google.com")
493 return ".inbox";
hpayerdd4def052016-02-06 19:06:10494 if (host == "calendar.google.com")
495 return ".calendar";
hablichd6a4f122015-10-28 11:34:49496 if (host == "www.youtube.com")
497 return ".youtube";
498 if (IsAlexaTop10NonGoogleSite(host))
499 return ".top10";
500
501 return std::string();
502}
503
504bool RenderThreadImpl::HistogramCustomizer::IsAlexaTop10NonGoogleSite(
505 const std::string& host) {
506 // The Top10 sites have different TLD and/or subdomains depending on the
507 // localization.
508 if (host == "sina.com.cn")
509 return true;
510
511 std::string sanitized_host =
512 net::registry_controlled_domains::GetDomainAndRegistry(
513 host, net::registry_controlled_domains::INCLUDE_PRIVATE_REGISTRIES);
514
515 if (sanitized_host == "facebook.com")
516 return true;
517 if (sanitized_host == "baidu.com")
518 return true;
519 if (sanitized_host == "qq.com")
520 return true;
521 if (sanitized_host == "twitter.com")
522 return true;
523 if (sanitized_host == "taobao.com")
524 return true;
525 if (sanitized_host == "live.com")
526 return true;
527
528 if (!sanitized_host.empty()) {
529 std::vector<base::StringPiece> host_tokens = base::SplitStringPiece(
530 sanitized_host, ".", base::TRIM_WHITESPACE, base::SPLIT_WANT_NONEMPTY);
531
532 if (host_tokens.size() >= 2) {
533 if ((host_tokens[0] == "yahoo") || (host_tokens[0] == "amazon") ||
534 (host_tokens[0] == "wikipedia")) {
535 return true;
536 }
537 }
538 }
539 return false;
540}
541
leon.han2c0f9f12015-07-11 02:01:19542// static
543RenderThreadImpl* RenderThreadImpl::Create(
544 const InProcessChildThreadParams& params) {
skyostil529caa292016-08-10 17:44:51545 std::unique_ptr<blink::scheduler::RendererScheduler> renderer_scheduler =
546 blink::scheduler::RendererScheduler::Create();
jam75c44222016-03-23 05:34:24547 scoped_refptr<base::SingleThreadTaskRunner> test_task_counter;
548 return new RenderThreadImpl(
549 params, std::move(renderer_scheduler), test_task_counter);
leon.han2c0f9f12015-07-11 02:01:19550}
551
552// static
553RenderThreadImpl* RenderThreadImpl::Create(
dchengcedca5612016-04-09 01:40:15554 std::unique_ptr<base::MessageLoop> main_message_loop,
skyostil529caa292016-08-10 17:44:51555 std::unique_ptr<blink::scheduler::RendererScheduler> renderer_scheduler) {
dcheng07945f632015-12-26 07:59:32556 return new RenderThreadImpl(std::move(main_message_loop),
557 std::move(renderer_scheduler));
leon.han2c0f9f12015-07-11 02:01:19558}
559
rockot5c478a72016-09-28 23:14:18560// static
[email protected]f1a29a02011-10-06 23:08:44561RenderThreadImpl* RenderThreadImpl::current() {
[email protected]526476902011-10-06 20:34:06562 return lazy_tls.Pointer()->Get();
563}
564
rockot5c478a72016-09-28 23:14:18565// static
566mojom::RenderMessageFilter* RenderThreadImpl::current_render_message_filter() {
567 if (g_render_message_filter_for_testing)
568 return g_render_message_filter_for_testing;
569 DCHECK(current());
570 return current()->render_message_filter();
571}
572
573// static
olegmax045f7fb12017-05-19 07:58:55574RendererBlinkPlatformImpl* RenderThreadImpl::current_blink_platform_impl() {
575 if (g_current_blink_platform_impl_for_testing)
576 return g_current_blink_platform_impl_for_testing;
577 DCHECK(current());
578 return current()->blink_platform_impl();
579}
580
581// static
rockot5c478a72016-09-28 23:14:18582void RenderThreadImpl::SetRenderMessageFilterForTesting(
583 mojom::RenderMessageFilter* render_message_filter) {
584 g_render_message_filter_for_testing = render_message_filter;
585}
586
olegmax045f7fb12017-05-19 07:58:55587// static
588void RenderThreadImpl::SetRendererBlinkPlatformImplForTesting(
589 RendererBlinkPlatformImpl* blink_platform_impl) {
590 g_current_blink_platform_impl_for_testing = blink_platform_impl;
591}
592
staraz067f58242016-11-07 21:06:41593// In single-process mode used for debugging, we don't pass a renderer client
594// ID via command line because RenderThreadImpl lives in the same process as
595// the browser
leon.han2c0f9f12015-07-11 02:01:19596RenderThreadImpl::RenderThreadImpl(
597 const InProcessChildThreadParams& params,
skyostil529caa292016-08-10 17:44:51598 std::unique_ptr<blink::scheduler::RendererScheduler> scheduler,
rockot97a86832016-12-10 04:53:06599 const scoped_refptr<base::SingleThreadTaskRunner>& resource_task_queue)
morritac6238ab2015-03-18 01:48:29600 : ChildThreadImpl(Options::Builder()
prashant.nfad657e2016-06-01 07:52:17601 .InBrowserProcess(params)
bend32292b2016-10-07 00:21:58602 .AutoStartServiceManagerConnection(false)
ben5be0b9132016-08-03 00:17:18603 .ConnectToBrowser(true)
prashant.nfad657e2016-06-01 07:52:17604 .Build()),
dcheng07945f632015-12-26 07:59:32605 renderer_scheduler_(std::move(scheduler)),
rockot067ca55f2016-09-30 22:00:15606 categorized_worker_pool_(new CategorizedWorkerPool()),
staraz067f58242016-11-07 21:06:41607 renderer_binding_(this),
chiniforooshan614d70a2017-03-17 01:19:33608 client_id_(1),
609 field_trial_syncer_(this) {
jam75c44222016-03-23 05:34:24610 Init(resource_task_queue);
morritac6238ab2015-03-18 01:48:29611}
612
[email protected]42f1d7822009-07-23 18:17:55613// When we run plugins in process, we actually run them on the render thread,
614// which means that we need to make the render thread pump UI events.
haraken53f081d2014-11-11 01:03:40615RenderThreadImpl::RenderThreadImpl(
dchengcedca5612016-04-09 01:40:15616 std::unique_ptr<base::MessageLoop> main_message_loop,
skyostil529caa292016-08-10 17:44:51617 std::unique_ptr<blink::scheduler::RendererScheduler> scheduler)
rockotcef38272016-07-15 22:47:47618 : ChildThreadImpl(Options::Builder()
bend32292b2016-10-07 00:21:58619 .AutoStartServiceManagerConnection(false)
ben5be0b9132016-08-03 00:17:18620 .ConnectToBrowser(true)
rockotcef38272016-07-15 22:47:47621 .Build()),
dcheng07945f632015-12-26 07:59:32622 renderer_scheduler_(std::move(scheduler)),
623 main_message_loop_(std::move(main_message_loop)),
rockot067ca55f2016-09-30 22:00:15624 categorized_worker_pool_(new CategorizedWorkerPool()),
wjmaclean1d970622017-01-21 22:28:24625 is_scroll_animator_enabled_(false),
fsamuel4c5c87142017-03-14 03:14:26626 is_surface_synchronization_enabled_(false),
chiniforooshan614d70a2017-03-17 01:19:33627 renderer_binding_(this),
628 field_trial_syncer_(this) {
jam75c44222016-03-23 05:34:24629 scoped_refptr<base::SingleThreadTaskRunner> test_task_counter;
staraz067f58242016-11-07 21:06:41630 DCHECK(base::CommandLine::ForCurrentProcess()->HasSwitch(
631 switches::kRendererClientId));
632 base::StringToInt(base::CommandLine::ForCurrentProcess()->GetSwitchValueASCII(
633 switches::kRendererClientId),
634 &client_id_);
jam75c44222016-03-23 05:34:24635 Init(test_task_counter);
haraken53f081d2014-11-11 01:03:40636}
637
jam75c44222016-03-23 05:34:24638void RenderThreadImpl::Init(
rockot97a86832016-12-10 04:53:06639 const scoped_refptr<base::SingleThreadTaskRunner>& resource_task_queue) {
fdorayf6d86242015-10-08 16:49:53640 TRACE_EVENT0("startup", "RenderThreadImpl::Init");
[email protected]a872ea1f2010-08-11 04:45:33641
ssidb2e3ece2015-02-09 16:02:20642 base::trace_event::TraceLog::GetInstance()->SetThreadSortIndex(
[email protected]91a2aea2013-07-08 23:14:39643 base::PlatformThread::CurrentId(),
644 kTraceEventRendererMainThreadSortIndex);
645
thakis18e426412017-03-15 12:06:37646#if BUILDFLAG(USE_EXTERNAL_POPUP_MENU)
sievers9dff72052015-11-16 18:35:57647 // On Mac and Android Java UI, the select popups are rendered by the browser.
Blink Reformat1c4d759e2017-04-09 16:34:54648 blink::WebView::SetUseExternalPopupMenus(true);
[email protected]53c607c2011-03-21 23:19:04649#endif
650
[email protected]94f9a0f682009-06-15 18:30:30651 lazy_tls.Pointer()->Set(this);
[email protected]b3e83de2012-02-07 03:33:28652
[email protected]06c694d2012-02-01 22:26:16653 // Register this object as the main thread.
654 ChildProcess::current()->set_main_thread(this);
655
dalecurtis4a9839a2017-05-04 23:40:47656 metrics::InitializeSingleSampleMetricsFactory(
657 base::BindRepeating(&CreateSingleSampleMetricsProvider,
658 message_loop()->task_runner(), GetConnector()));
659
ben649b3edd2017-03-23 00:32:02660 gpu_ = ui::Gpu::Create(
661 GetConnector(),
662 IsRunningInMash() ? ui::mojom::kServiceName : mojom::kBrowserServiceName,
663 GetIOTaskRunner());
penghuange1d86512016-07-08 18:15:00664
xlai11ac7802017-04-07 20:13:18665 cc::mojom::SharedBitmapManagerAssociatedPtr shared_bitmap_manager_ptr;
666 render_message_filter()->GetSharedBitmapManager(
667 mojo::MakeRequest(&shared_bitmap_manager_ptr));
668 shared_bitmap_manager_.reset(new ui::ChildSharedBitmapManager(
669 cc::mojom::ThreadSafeSharedBitmapManagerAssociatedPtr::Create(
670 shared_bitmap_manager_ptr.PassInterface(),
671 GetChannel()->ipc_task_runner_refptr())));
jcivelli0f21bd52016-12-07 21:21:33672
jam75c44222016-03-23 05:34:24673 InitializeWebKit(resource_task_queue);
674
[email protected]31f87132010-04-21 23:36:21675 // In single process the single process is all there is.
[email protected]26e82322014-01-20 14:18:22676 webkit_shared_timer_suspended_ = false;
[email protected]bee16aab2009-08-26 15:55:03677 widget_count_ = 0;
678 hidden_widget_count_ = 0;
[email protected]6593ae12011-11-14 12:09:44679 idle_notification_delay_in_ms_ = kInitialIdleHandlerDelayMs;
[email protected]1784b2f2011-11-24 10:53:48680 idle_notifications_to_skip_ = 0;
[email protected]8d86fce2009-02-26 23:37:55681
[email protected]d5b2fdf2013-06-05 09:36:55682 appcache_dispatcher_.reset(
[email protected]a8cb3b73b2013-08-12 05:50:50683 new AppCacheDispatcher(Get(), new AppCacheFrontendImpl()));
[email protected]1910fe82012-05-10 00:04:10684 dom_storage_dispatcher_.reset(new DomStorageDispatcher());
reillyg39fb4662016-11-22 20:27:17685 main_thread_indexed_db_dispatcher_.reset(new IndexedDBDispatcher());
jsbellabadb9b2015-03-23 21:03:44686 main_thread_cache_storage_dispatcher_.reset(
jsbell279efb42015-03-31 17:02:46687 new CacheStorageDispatcher(thread_safe_sender()));
[email protected]dd9241932010-02-24 19:23:13688
jdduke94ae1f32015-02-05 06:27:13689 // Note: This may reorder messages from the ResourceDispatcher with respect to
690 // other subsystems.
691 resource_dispatch_throttler_.reset(new ResourceDispatchThrottler(
692 static_cast<RenderThread*>(this), renderer_scheduler_.get(),
693 base::TimeDelta::FromSecondsD(kThrottledResourceRequestFlushPeriodS),
694 kMaxResourceRequestsPerFlushWhenThrottled));
695 resource_dispatcher()->set_message_sender(resource_dispatch_throttler_.get());
696
thestig529ad8a2016-07-08 20:30:12697 blob_message_filter_ = new BlobMessageFilter(GetFileThreadTaskRunner());
dmurph1fb98482016-03-30 21:14:26698 AddFilter(blob_message_filter_.get());
[email protected]017022b2009-07-27 23:06:34699 db_message_filter_ = new DBMessageFilter();
700 AddFilter(db_message_filter_.get());
[email protected]dd9241932010-02-24 19:23:13701
[email protected]45048072014-01-14 13:51:29702 vc_manager_.reset(new VideoCaptureImplManager());
[email protected]c9c43a02013-12-17 08:59:54703
fsamuel6c1dfeb2014-12-18 19:21:33704 browser_plugin_manager_.reset(new BrowserPluginManager());
705 AddObserver(browser_plugin_manager_.get());
706
Brett Wilson0748bf412016-11-22 17:55:46707#if BUILDFLAG(ENABLE_WEBRTC)
[email protected]af089972013-01-10 04:04:40708 peer_connection_tracker_.reset(new PeerConnectionTracker());
709 AddObserver(peer_connection_tracker_.get());
710
thestig529ad8a2016-07-08 20:30:12711 p2p_socket_dispatcher_ = new P2PSocketDispatcher(GetIOTaskRunner().get());
[email protected]fc72bb12013-06-02 21:13:46712 AddFilter(p2p_socket_dispatcher_.get());
[email protected]921480f62013-07-20 03:42:57713
ivocadd54f0d2015-12-18 23:17:05714 peer_connection_factory_.reset(
715 new PeerConnectionDependencyFactory(p2p_socket_dispatcher_.get()));
716
skyostil2d3b5bd2015-05-27 15:40:59717 aec_dump_message_filter_ = new AecDumpMessageFilter(
thestig529ad8a2016-07-08 20:30:12718 GetIOTaskRunner(), message_loop()->task_runner());
ivocadd54f0d2015-12-18 23:17:05719
[email protected]da9f30a2014-06-18 19:39:04720 AddFilter(aec_dump_message_filter_.get());
721
Brett Wilson0748bf412016-11-22 17:55:46722#endif // BUILDFLAG(ENABLE_WEBRTC)
[email protected]e25f4d72011-06-08 20:58:46723
thestig529ad8a2016-07-08 20:30:12724 audio_input_message_filter_ = new AudioInputMessageFilter(GetIOTaskRunner());
[email protected]f7eb0a392011-07-12 10:19:51725 AddFilter(audio_input_message_filter_.get());
726
thestig529ad8a2016-07-08 20:30:12727 audio_message_filter_ = new AudioMessageFilter(GetIOTaskRunner());
[email protected]f7eb0a392011-07-12 10:19:51728 AddFilter(audio_message_filter_.get());
729
thestig529ad8a2016-07-08 20:30:12730 midi_message_filter_ = new MidiMessageFilter(GetIOTaskRunner());
[email protected]a9875152013-06-22 04:03:03731 AddFilter(midi_message_filter_.get());
732
jsbellabadb9b2015-03-23 21:03:44733 AddFilter((new CacheStorageMessageFilter(thread_safe_sender()))->GetFilter());
734
kinuko5af4ffe2015-06-09 03:38:46735 AddFilter((new ServiceWorkerContextMessageFilter())->GetFilter());
[email protected]ddbb53342014-01-06 10:59:47736
sadrul943e3b32016-08-04 18:22:59737#if defined(USE_AURA)
fsamuel098eade2017-03-21 18:06:14738 if (IsRunningInMash()) {
bend32292b2016-10-07 00:21:58739 CreateRenderWidgetWindowTreeClientFactory(GetServiceManagerConnection());
rockotcef38272016-07-15 22:47:47740 }
741#endif
742
benbd9dc802017-04-19 01:37:43743 auto registry = base::MakeUnique<service_manager::BinderRegistry>();
744 registry->AddInterface(base::Bind(&CreateFrameFactory),
745 base::ThreadTaskRunnerHandle::Get());
746 registry->AddInterface(base::Bind(&EmbeddedWorkerInstanceClientImpl::Create),
747 base::ThreadTaskRunnerHandle::Get());
748 GetServiceManagerConnection()->AddConnectionFilter(
749 base::MakeUnique<SimpleConnectionFilter>(std::move(registry)));
rockotcef38272016-07-15 22:47:47750
[email protected]e9ff79c2012-10-19 21:31:26751 GetContentClient()->renderer()->RenderThreadStarted();
[email protected]6779aa12011-03-29 17:32:24752
benbd9dc802017-04-19 01:37:43753 StartServiceManagerConnection();
754
chiniforooshan614d70a2017-03-17 01:19:33755 field_trial_syncer_.InitFieldTrialObserving(
756 *base::CommandLine::ForCurrentProcess(), switches::kSingleProcess);
757
rockot067ca55f2016-09-30 22:00:15758 GetAssociatedInterfaceRegistry()->AddInterface(
759 base::Bind(&RenderThreadImpl::OnRendererInterfaceRequest,
760 base::Unretained(this)));
761
[email protected]b48c53ad2014-02-05 21:59:18762 InitSkiaEventTracer();
ssid59c969162015-07-28 13:02:58763 base::trace_event::MemoryDumpManager::GetInstance()->RegisterDumpProvider(
primiano186d6bfe2015-10-30 13:21:40764 skia::SkiaMemoryDumpProvider::GetInstance(), "Skia", nullptr);
[email protected]b48c53ad2014-02-05 21:59:18765
avi83883c82014-12-23 00:08:49766 const base::CommandLine& command_line =
767 *base::CommandLine::ForCurrentProcess();
[email protected]e54ab492012-06-12 19:40:01768
ochangdd89a1e2016-06-08 16:39:01769#if defined(ENABLE_IPC_FUZZER)
770 if (command_line.HasSwitch(switches::kIpcDumpDirectory)) {
771 base::FilePath dump_directory =
772 command_line.GetSwitchValuePath(switches::kIpcDumpDirectory);
773 IPC::ChannelProxy::OutgoingMessageFilter* filter =
774 LoadExternalIPCDumper(dump_directory);
775 GetChannel()->set_outgoing_message_filter(filter);
776 }
777#endif
778
jbroman0d302162015-09-05 05:46:23779 cc::SetClientNameForMetrics("Renderer");
loysoa6edaaff2015-05-25 03:26:44780
loyso65c93c602015-08-11 05:15:57781 is_threaded_animation_enabled_ =
782 !command_line.HasSwitch(cc::switches::kDisableThreadedAnimation);
783
fsamuel4c5c87142017-03-14 03:14:26784 is_surface_synchronization_enabled_ =
785 command_line.HasSwitch(cc::switches::kEnableSurfaceSynchronization);
786
reveman91a0a872014-11-04 03:40:32787 is_zero_copy_enabled_ = command_line.HasSwitch(switches::kEnableZeroCopy);
ericrk1d17f752015-10-20 03:03:07788 is_partial_raster_enabled_ =
dongseong.hwang23db47f2016-03-08 07:50:02789 !command_line.HasSwitch(switches::kDisablePartialRaster);
ccameronc7fcd132015-11-03 20:14:31790 is_gpu_memory_buffer_compositor_resources_enabled_ = command_line.HasSwitch(
791 switches::kEnableGpuMemoryBufferCompositorResources);
[email protected]a23530d2014-03-11 06:04:14792
jame1f453c2016-03-21 15:51:34793#if defined(OS_MACOSX)
thakis114a1ef2016-04-26 16:02:59794 base::ScopedCFTypeRef<CFStringRef> key(
795 base::SysUTF8ToCFStringRef("NSScrollViewRubberbanding"));
796 Boolean key_exists = false;
797 Boolean value = CFPreferencesGetAppBooleanValue(
798 key, kCFPreferencesCurrentApplication, &key_exists);
799 is_elastic_overscroll_enabled_ = !key_exists || value;
ccamerona7644752014-12-30 01:16:31800#else
801 is_elastic_overscroll_enabled_ = false;
802#endif
803
danakje6eb185c2015-02-27 23:52:05804 std::string image_texture_target_string =
dcastagna7f2f7192015-06-16 18:44:35805 command_line.GetSwitchValueASCII(switches::kContentImageTextureTarget);
ericrk9151705c2016-07-26 19:53:16806 buffer_to_texture_target_map_ =
807 cc::StringToBufferToTextureTargetMap(image_texture_target_string);
reveman44b807f12014-11-26 02:44:50808
[email protected]a23530d2014-03-11 06:04:14809 if (command_line.HasSwitch(switches::kDisableLCDText)) {
810 is_lcd_text_enabled_ = false;
811 } else if (command_line.HasSwitch(switches::kEnableLCDText)) {
812 is_lcd_text_enabled_ = true;
813 } else {
814#if defined(OS_ANDROID)
815 is_lcd_text_enabled_ = false;
816#else
817 is_lcd_text_enabled_ = true;
818#endif
819 }
820
[email protected]b8d82c22014-03-31 20:12:46821 is_gpu_rasterization_forced_ =
822 command_line.HasSwitch(switches::kForceGpuRasterization);
sunnypsd8ce1c22016-05-10 18:02:40823 is_async_worker_context_enabled_ =
824 command_line.HasSwitch(switches::kEnableGpuAsyncWorkerContext);
[email protected]a23530d2014-03-11 06:04:14825
senorblancob60ba952015-01-27 19:12:36826 if (command_line.HasSwitch(switches::kGpuRasterizationMSAASampleCount)) {
827 std::string string_value = command_line.GetSwitchValueASCII(
828 switches::kGpuRasterizationMSAASampleCount);
829 bool parsed_msaa_sample_count =
830 base::StringToInt(string_value, &gpu_rasterization_msaa_sample_count_);
831 DCHECK(parsed_msaa_sample_count) << string_value;
832 DCHECK_GE(gpu_rasterization_msaa_sample_count_, 0);
833 } else {
senorblanco2a5b0e12015-08-14 21:55:37834 gpu_rasterization_msaa_sample_count_ = -1;
senorblancob60ba952015-01-27 19:12:36835 }
836
[email protected]b242b142014-05-07 14:48:49837 if (command_line.HasSwitch(switches::kDisableDistanceFieldText)) {
838 is_distance_field_text_enabled_ = false;
839 } else if (command_line.HasSwitch(switches::kEnableDistanceFieldText)) {
840 is_distance_field_text_enabled_ = true;
841 } else {
842 is_distance_field_text_enabled_ = false;
843 }
844
[email protected]433df472012-03-07 20:33:39845 // Note that under Linux, the media library will normally already have
846 // been initialized by the Zygote before this instance became a Renderer.
chcunninghamfd11b3c2015-06-09 02:09:42847 media::InitializeMediaLibrary();
[email protected]433df472012-03-07 20:33:39848
dalecurtis88af3932016-02-20 00:12:20849#if defined(OS_ANDROID)
850 if (!command_line.HasSwitch(switches::kDisableAcceleratedVideoDecode) &&
851 media::MediaCodecUtil::IsMediaCodecAvailable()) {
852 media::EnablePlatformDecoderSupport();
853 }
854#endif
855
hubbee6c6eb342017-03-15 20:34:11856 if (base::CommandLine::ForCurrentProcess()->HasSwitch(switches::kEnableHDR) ||
chcunningham9a285ed2017-03-08 21:48:56857 base::CommandLine::ForCurrentProcess()->HasSwitch(
858 switches::kEnableNewVp9CodecString)) {
859 media::EnableNewVp9CodecStringSupport();
860 }
861
bashi296ebda2017-03-28 03:27:09862 memory_pressure_listener_.reset(new base::MemoryPressureListener(
863 base::Bind(&RenderThreadImpl::OnMemoryPressure, base::Unretained(this)),
864 base::Bind(&RenderThreadImpl::OnSyncMemoryPressure,
865 base::Unretained(this))));
866
867 if (base::FeatureList::IsEnabled(features::kMemoryCoordinator)) {
868 // Disable MemoryPressureListener when memory coordinator is enabled.
869 base::MemoryPressureListener::SetNotificationsSuppressed(true);
870
871 // TODO(bashi): Revisit how to manage the lifetime of
872 // ChildMemoryCoordinatorImpl.
873 // https://codereview.chromium.org/2094583002/#msg52
874 mojom::MemoryCoordinatorHandlePtr parent_coordinator;
875 GetConnector()->BindInterface(mojom::kBrowserServiceName,
876 mojo::MakeRequest(&parent_coordinator));
877 memory_coordinator_ = CreateChildMemoryCoordinator(
878 std::move(parent_coordinator), this);
879 }
880
danakj16275d4c2015-06-11 19:23:51881 int num_raster_threads = 0;
882 std::string string_value =
883 command_line.GetSwitchValueASCII(switches::kNumRasterThreads);
884 bool parsed_num_raster_threads =
885 base::StringToInt(string_value, &num_raster_threads);
886 DCHECK(parsed_num_raster_threads) << string_value;
887 DCHECK_GT(num_raster_threads, 0);
vmiura78b69282015-02-14 00:01:17888
prashant.nfad657e2016-06-01 07:52:17889 categorized_worker_pool_->Start(num_raster_threads);
[email protected]1e1d1e12014-01-17 16:14:29890
penghuang342762b2016-12-02 21:04:58891 discardable_memory::mojom::DiscardableSharedMemoryManagerPtr manager_ptr;
penghuangd6843e42016-12-17 13:57:20892 if (IsRunningInMash()) {
893#if defined(USE_AURA)
benbd3c2482017-01-07 05:48:21894 GetServiceManagerConnection()->GetConnector()->BindInterface(
penghuangd6843e42016-12-17 13:57:20895 ui::mojom::kServiceName, &manager_ptr);
896#else
897 NOTREACHED();
898#endif
899 } else {
ben649b3edd2017-03-23 00:32:02900 ChildThread::Get()->GetConnector()->BindInterface(
901 mojom::kBrowserServiceName, mojo::MakeRequest(&manager_ptr));
penghuangd6843e42016-12-17 13:57:20902 }
903
penghuang342762b2016-12-02 21:04:58904 discardable_shared_memory_manager_ = base::MakeUnique<
905 discardable_memory::ClientDiscardableSharedMemoryManager>(
906 std::move(manager_ptr), GetIOTaskRunner());
907
boliu9760e212015-06-23 22:49:06908 // TODO(boliu): In single process, browser main loop should set up the
909 // discardable memory manager, and should skip this if kSingleProcess.
910 // See crbug.com/503724.
911 base::DiscardableMemoryAllocator::SetInstance(
penghuang342762b2016-12-02 21:04:58912 discardable_shared_memory_manager_.get());
revemancb5a66af2014-10-25 00:34:39913
ben649b3edd2017-03-23 00:32:02914 GetConnector()->BindInterface(mojom::kBrowserServiceName,
915 mojo::MakeRequest(&storage_partition_service_));
hajimehoshi69093272016-05-13 08:30:58916
reveman7b97c322016-09-20 02:10:58917#if defined(OS_LINUX)
918 ChildProcess::current()->SetIOThreadPriority(base::ThreadPriority::DISPLAY);
919 ChildThreadImpl::current()->SetThreadPriority(
lukasza6710dbd2017-04-07 20:58:03920 categorized_worker_pool_->background_worker_thread_id(),
reveman7b97c322016-09-20 02:10:58921 base::ThreadPriority::BACKGROUND);
922#endif
923
tasakbb0640b2017-05-15 09:02:26924 process_foregrounded_count_ = 0;
tasakb95dbb50c2017-02-08 18:07:50925 needs_to_record_first_active_paint_ = false;
hajimehoshi7bb39582016-10-12 04:30:57926
927 base::MemoryCoordinatorClientRegistry::GetInstance()->Register(this);
fdoray50a38342016-11-21 20:46:04928
929 // If this renderer doesn't run inside the browser process, enable
930 // SequencedWorkerPool. Otherwise, it should already have been enabled.
931 // TODO(fdoray): Remove this once the SequencedWorkerPool to TaskScheduler
932 // redirection experiment concludes https://crbug.com/622400.
933 if (!command_line.HasSwitch(switches::kSingleProcess))
934 base::SequencedWorkerPool::EnableForProcess();
samans2040988b2017-04-11 23:58:35935
936 GetConnector()->BindInterface(mojom::kBrowserServiceName,
937 mojo::MakeRequest(&frame_sink_provider_));
initial.commit09911bf2008-07-26 23:55:29938}
939
[email protected]f1a29a02011-10-06 23:08:44940RenderThreadImpl::~RenderThreadImpl() {
[email protected]ce79d8512013-04-22 22:44:41941}
942
943void RenderThreadImpl::Shutdown() {
harakenbbfdd9f02017-01-12 07:14:04944 // In a multi-process mode, we immediately exit the renderer.
945 // Historically we had a graceful shutdown sequence here but it was
946 // 1) a waste of performance and 2) a source of lots of complicated
947 // crashes caused by shutdown ordering. Immediate exit eliminates
948 // those problems.
cbrunia3f655b2017-03-20 11:36:41949
950 // Give the V8 isolate a chance to dump internal stats useful for performance
951 // evaluation and debugging.
Blink Reformat1c4d759e2017-04-09 16:34:54952 blink::MainThreadIsolate()->DumpAndResetStats();
cbrunia3f655b2017-03-20 11:36:41953
harakenbbfdd9f02017-01-12 07:14:04954 // In a single-process mode, we cannot call _exit(0) in Shutdown() because
955 // it will exit the process before the browser side is ready to exit.
956 if (!base::CommandLine::ForCurrentProcess()->HasSwitch(
957 switches::kSingleProcess))
haraken940efb92017-02-08 05:58:15958 base::Process::TerminateCurrentProcessImmediately(0);
harakenbbfdd9f02017-01-12 07:14:04959}
[email protected]1223d6ef2011-03-28 16:47:50960
harakenbbfdd9f02017-01-12 07:14:04961bool RenderThreadImpl::ShouldBeDestroyed() {
962 DCHECK(base::CommandLine::ForCurrentProcess()->HasSwitch(
963 switches::kSingleProcess));
964 // In a single-process mode, it is unsafe to destruct this renderer thread
965 // because we haven't run the shutdown sequence. Hence we leak the render
966 // thread.
967 //
968 // In this case, we also need to disable at-exit callbacks because some of
969 // the at-exit callbacks are expected to run after the renderer thread
970 // has been destructed.
971 base::AtExitManager::DisableAllAtExitManagers();
972 return false;
initial.commit09911bf2008-07-26 23:55:29973}
974
[email protected]f1a29a02011-10-06 23:08:44975bool RenderThreadImpl::Send(IPC::Message* msg) {
changwan6ed4d432016-05-19 22:03:54976 // There are cases where we want to pump asynchronous messages while waiting
977 // synchronously for the replies to the message to be sent here. However, this
978 // may create an opportunity for re-entrancy into WebKit and other subsystems,
979 // so we need to take care to disable callbacks, timers, and pending network
980 // loads that could trigger such callbacks.
[email protected]38b592902011-04-16 02:08:42981 bool pumping_events = false;
[email protected]80fc08c52010-03-09 07:43:50982 if (msg->is_sync()) {
983 if (msg->is_caller_pumping_messages()) {
984 pumping_events = true;
[email protected]80fc08c52010-03-09 07:43:50985 }
[email protected]c1f50aa2010-02-18 03:46:57986 }
987
[email protected]c1f50aa2010-02-18 03:46:57988 if (pumping_events) {
jdduked73ae5412015-05-11 20:07:16989 renderer_scheduler_->SuspendTimerQueue();
Blink Reformat1c4d759e2017-04-09 16:34:54990 WebView::WillEnterModalLoop();
[email protected]c1f50aa2010-02-18 03:46:57991 }
992
jam8a021512a2015-02-03 18:16:08993 bool rv = ChildThreadImpl::Send(msg);
[email protected]c1f50aa2010-02-18 03:46:57994
995 if (pumping_events) {
Blink Reformat1c4d759e2017-04-09 16:34:54996 WebView::DidExitModalLoop();
jdduked73ae5412015-05-11 20:07:16997 renderer_scheduler_->ResumeTimerQueue();
[email protected]c1f50aa2010-02-18 03:46:57998 }
999
1000 return rv;
1001}
1002
[email protected]f1a29a02011-10-06 23:08:441003IPC::SyncChannel* RenderThreadImpl::GetChannel() {
[email protected]526476902011-10-06 20:34:061004 return channel();
1005}
1006
[email protected]f1a29a02011-10-06 23:08:441007std::string RenderThreadImpl::GetLocale() {
[email protected]526476902011-10-06 20:34:061008 // The browser process should have passed the locale to the renderer via the
[email protected]dfd53652012-10-25 00:20:021009 // --lang command line flag.
avi83883c82014-12-23 00:08:491010 const base::CommandLine& parsed_command_line =
1011 *base::CommandLine::ForCurrentProcess();
[email protected]526476902011-10-06 20:34:061012 const std::string& lang =
1013 parsed_command_line.GetSwitchValueASCII(switches::kLang);
[email protected]dfd53652012-10-25 00:20:021014 DCHECK(!lang.empty());
[email protected]526476902011-10-06 20:34:061015 return lang;
1016}
1017
[email protected]07bb6332012-01-21 01:07:571018IPC::SyncMessageFilter* RenderThreadImpl::GetSyncMessageFilter() {
1019 return sync_message_filter();
1020}
1021
skyostil12262cf2015-05-21 14:49:311022scoped_refptr<base::SingleThreadTaskRunner>
thestig529ad8a2016-07-08 20:30:121023RenderThreadImpl::GetIOTaskRunner() {
skyostil12262cf2015-05-21 14:49:311024 return ChildProcess::current()->io_task_runner();
[email protected]96191d52012-05-17 01:37:111025}
1026
avi1023d012015-12-25 02:39:141027void RenderThreadImpl::AddRoute(int32_t routing_id, IPC::Listener* listener) {
jam8a021512a2015-02-03 18:16:081028 ChildThreadImpl::GetRouter()->AddRoute(routing_id, listener);
ben76f52b242016-06-18 05:42:481029 auto it = pending_frame_creates_.find(routing_id);
1030 if (it == pending_frame_creates_.end())
rockotf8fdd9b2015-12-16 22:22:351031 return;
1032
1033 RenderFrameImpl* frame = RenderFrameImpl::FromRoutingID(routing_id);
1034 if (!frame)
1035 return;
1036
ben76f52b242016-06-18 05:42:481037 scoped_refptr<PendingFrameCreate> create(it->second);
benf28ce882017-05-02 16:15:491038 frame->BindFrame(it->second->browser_info(), it->second->TakeFrameRequest(),
csharrison95f01e922017-04-24 18:52:351039 it->second->TakeInterfaceBroker());
ben76f52b242016-06-18 05:42:481040 pending_frame_creates_.erase(it);
[email protected]c1f50aa2010-02-18 03:46:571041}
1042
avi1023d012015-12-25 02:39:141043void RenderThreadImpl::RemoveRoute(int32_t routing_id) {
jam8a021512a2015-02-03 18:16:081044 ChildThreadImpl::GetRouter()->RemoveRoute(routing_id);
[email protected]c1f50aa2010-02-18 03:46:571045}
[email protected]0ec90d522014-03-12 16:28:191046
avi1023d012015-12-25 02:39:141047void RenderThreadImpl::AddEmbeddedWorkerRoute(int32_t routing_id,
[email protected]a620b132014-04-30 22:39:171048 IPC::Listener* listener) {
[email protected]48e52e42014-03-20 06:58:071049 AddRoute(routing_id, listener);
1050 if (devtools_agent_message_filter_.get()) {
[email protected]a620b132014-04-30 22:39:171051 devtools_agent_message_filter_->AddEmbeddedWorkerRouteOnMainThread(
[email protected]48e52e42014-03-20 06:58:071052 routing_id);
1053 }
1054}
1055
avi1023d012015-12-25 02:39:141056void RenderThreadImpl::RemoveEmbeddedWorkerRoute(int32_t routing_id) {
[email protected]48e52e42014-03-20 06:58:071057 RemoveRoute(routing_id);
1058 if (devtools_agent_message_filter_.get()) {
[email protected]a620b132014-04-30 22:39:171059 devtools_agent_message_filter_->RemoveEmbeddedWorkerRouteOnMainThread(
[email protected]48e52e42014-03-20 06:58:071060 routing_id);
1061 }
1062}
1063
ben76f52b242016-06-18 05:42:481064void RenderThreadImpl::RegisterPendingFrameCreate(
benf28ce882017-05-02 16:15:491065 const service_manager::BindSourceInfo& browser_info,
rockotf8fdd9b2015-12-16 22:22:351066 int routing_id,
ben76f52b242016-06-18 05:42:481067 mojom::FrameRequest frame_request,
csharrison95f01e922017-04-24 18:52:351068 mojom::FrameHostInterfaceBrokerPtr frame_host_interface_broker) {
ben76f52b242016-06-18 05:42:481069 std::pair<PendingFrameCreateMap::iterator, bool> result =
1070 pending_frame_creates_.insert(std::make_pair(
csharrison95f01e922017-04-24 18:52:351071 routing_id, make_scoped_refptr(new PendingFrameCreate(
benf28ce882017-05-02 16:15:491072 browser_info, routing_id, std::move(frame_request),
csharrison95f01e922017-04-24 18:52:351073 std::move(frame_host_interface_broker)))));
rockotf8fdd9b2015-12-16 22:22:351074 CHECK(result.second) << "Inserting a duplicate item.";
1075}
1076
leon.han06e55662016-03-26 17:19:421077mojom::StoragePartitionService* RenderThreadImpl::GetStoragePartitionService() {
jamc912ca32016-02-24 20:17:311078 return storage_partition_service_.get();
1079}
1080
[email protected]77fc9b92011-10-15 16:20:371081int RenderThreadImpl::GenerateRoutingID() {
rockote261d2112016-09-21 22:22:231082 int32_t routing_id = MSG_ROUTING_NONE;
1083 render_message_filter()->GenerateRoutingID(&routing_id);
[email protected]77fc9b92011-10-15 16:20:371084 return routing_id;
1085}
1086
[email protected]74122042014-04-25 00:07:301087void RenderThreadImpl::AddFilter(IPC::MessageFilter* filter) {
[email protected]42f1d7822009-07-23 18:17:551088 channel()->AddFilter(filter);
1089}
1090
[email protected]74122042014-04-25 00:07:301091void RenderThreadImpl::RemoveFilter(IPC::MessageFilter* filter) {
[email protected]42f1d7822009-07-23 18:17:551092 channel()->RemoveFilter(filter);
1093}
1094
tyoshino832a58a2016-04-18 08:14:081095void RenderThreadImpl::AddObserver(RenderThreadObserver* observer) {
[email protected]526476902011-10-06 20:34:061096 observers_.AddObserver(observer);
nigeltao7cd8d5582016-12-12 06:05:281097 observer->RegisterMojoInterfaces(&associated_interfaces_);
[email protected]526476902011-10-06 20:34:061098}
1099
tyoshino832a58a2016-04-18 08:14:081100void RenderThreadImpl::RemoveObserver(RenderThreadObserver* observer) {
nigeltao7cd8d5582016-12-12 06:05:281101 observer->UnregisterMojoInterfaces(&associated_interfaces_);
[email protected]526476902011-10-06 20:34:061102 observers_.RemoveObserver(observer);
1103}
1104
[email protected]359dfa32011-10-12 01:10:151105void RenderThreadImpl::SetResourceDispatcherDelegate(
[email protected]e9ff79c2012-10-19 21:31:261106 ResourceDispatcherDelegate* delegate) {
[email protected]359dfa32011-10-12 01:10:151107 resource_dispatcher()->set_delegate(delegate);
1108}
1109
vollick1050cc62015-12-03 07:04:541110void RenderThreadImpl::InitializeCompositorThread() {
boliu66024c62016-04-20 04:00:411111 base::Thread::Options options;
vollick1050cc62015-12-03 07:04:541112#if defined(OS_ANDROID)
boliu66024c62016-04-20 04:00:411113 options.priority = base::ThreadPriority::DISPLAY;
vollick1050cc62015-12-03 07:04:541114#endif
altiminc7369bf2017-04-11 14:29:151115 compositor_thread_ =
1116 blink::scheduler::WebThreadBase::CreateCompositorThread(options);
boliu66024c62016-04-20 04:00:411117 blink_platform_impl_->SetCompositorThread(compositor_thread_.get());
1118 compositor_task_runner_ = compositor_thread_->GetTaskRunner();
1119 compositor_task_runner_->PostTask(
1120 FROM_HERE,
1121 base::Bind(base::IgnoreResult(&ThreadRestrictions::SetIOAllowed), false));
reveman7b97c322016-09-20 02:10:581122#if defined(OS_LINUX)
Blink Reformat1c4d759e2017-04-09 16:34:541123 ChildThreadImpl::current()->SetThreadPriority(compositor_thread_->ThreadId(),
reveman7b97c322016-09-20 02:10:581124 base::ThreadPriority::DISPLAY);
1125#endif
vollick1050cc62015-12-03 07:04:541126
boliude5b75b2016-03-11 07:02:141127 SynchronousInputHandlerProxyClient* synchronous_input_handler_proxy_client =
1128 nullptr;
vollick1050cc62015-12-03 07:04:541129#if defined(OS_ANDROID)
boliu66024c62016-04-20 04:00:411130 if (GetContentClient()->UsingSynchronousCompositing()) {
vollick1050cc62015-12-03 07:04:541131 sync_compositor_message_filter_ =
1132 new SynchronousCompositorFilter(compositor_task_runner_);
1133 AddFilter(sync_compositor_message_filter_.get());
boliude5b75b2016-03-11 07:02:141134 synchronous_input_handler_proxy_client =
1135 sync_compositor_message_filter_.get();
vollick1050cc62015-12-03 07:04:541136 }
1137#endif
boliub2768db2016-06-03 23:35:161138 scoped_refptr<InputEventFilter> compositor_input_event_filter(
1139 new InputEventFilter(main_input_callback_.callback(),
1140 main_thread_compositor_task_runner_,
1141 compositor_task_runner_));
1142 InputHandlerManagerClient* input_handler_manager_client =
1143 compositor_input_event_filter.get();
1144 input_event_filter_ = compositor_input_event_filter;
vollick1050cc62015-12-03 07:04:541145 input_handler_manager_.reset(new InputHandlerManager(
1146 compositor_task_runner_, input_handler_manager_client,
boliude5b75b2016-03-11 07:02:141147 synchronous_input_handler_proxy_client, renderer_scheduler_.get()));
vollick1050cc62015-12-03 07:04:541148}
1149
jam75c44222016-03-23 05:34:241150void RenderThreadImpl::InitializeWebKit(
rockot97a86832016-12-10 04:53:061151 const scoped_refptr<base::SingleThreadTaskRunner>& resource_task_queue) {
jam75c44222016-03-23 05:34:241152 DCHECK(!blink_platform_impl_);
[email protected]d1b8fccc2011-08-03 01:20:131153
avi83883c82014-12-23 00:08:491154 const base::CommandLine& command_line =
1155 *base::CommandLine::ForCurrentProcess();
chunyang.daibe874c52014-11-14 06:45:051156
1157#ifdef ENABLE_VTUNE_JIT_INTERFACE
1158 if (command_line.HasSwitch(switches::kEnableVtune))
1159 gin::Debug::SetJitCodeEventHandler(vTune::GetVtuneCodeEventHandler());
1160#endif
1161
rmcilroy4073ae12015-01-08 13:08:101162 SetRuntimeFeaturesDefaultsAndUpdateFromArgs(command_line);
hlopko852ffcf2016-09-16 16:50:591163 GetContentClient()
1164 ->renderer()
1165 ->SetRuntimeFeaturesDefaultsBeforeBlinkInitialization();
rmcilroy4073ae12015-01-08 13:08:101166
sammcbebeb602016-04-06 06:42:551167 blink_platform_impl_.reset(new RendererBlinkPlatformImpl(
ben649b3edd2017-03-23 00:32:021168 renderer_scheduler_.get(), GetConnector()->GetWeakPtr()));
Blink Reformat1c4d759e2017-04-09 16:34:541169 blink::Initialize(blink_platform_impl_.get());
[email protected]d1b8fccc2011-08-03 01:20:131170
Blink Reformat1c4d759e2017-04-09 16:34:541171 v8::Isolate* isolate = blink::MainThreadIsolate();
[email protected]4b5340282014-07-08 11:37:341172 isolate->SetCreateHistogramFunction(CreateHistogram);
1173 isolate->SetAddHistogramSampleFunction(AddHistogramSample);
skyostila37c2a72016-06-29 17:30:071174 renderer_scheduler_->SetRAILModeObserver(this);
[email protected]4b5340282014-07-08 11:37:341175
rmcilroy321f924d2014-11-06 00:56:001176 main_thread_compositor_task_runner_ =
danakj6e3bf8012014-12-16 18:27:531177 renderer_scheduler_->CompositorTaskRunner();
skyostilc30aa402014-10-10 13:49:091178
jdduke691dd572014-12-02 20:47:521179 main_input_callback_.Reset(
1180 base::Bind(base::IgnoreResult(&RenderThreadImpl::OnMessageReceived),
1181 base::Unretained(this)));
1182
jam75c44222016-03-23 05:34:241183 scoped_refptr<base::SingleThreadTaskRunner> resource_task_queue2;
1184 if (resource_task_queue) {
1185 resource_task_queue2 = resource_task_queue;
1186 } else {
1187 resource_task_queue2 = renderer_scheduler_->LoadingTaskRunner();
1188 }
1189 // Add a filter that forces resource messages to be dispatched via a
1190 // particular task runner.
1191 scoped_refptr<ResourceSchedulingFilter> filter(
1192 new ResourceSchedulingFilter(
1193 resource_task_queue2, resource_dispatcher()));
1194 channel()->AddFilter(filter.get());
1195 resource_dispatcher()->SetResourceSchedulingFilter(filter);
1196
1197 // The ChildResourceMessageFilter and the ResourceDispatcher need to use the
1198 // same queue to ensure tasks are executed in the expected order.
1199 child_resource_message_filter()->SetMainThreadTaskRunner(
1200 resource_task_queue2);
horoe6120582017-04-26 01:48:591201 resource_dispatcher()->SetThreadTaskRunner(resource_task_queue2);
jam75c44222016-03-23 05:34:241202
khushalsagard7178e42017-01-20 01:31:491203 if (!command_line.HasSwitch(switches::kDisableThreadedCompositing))
vollick1050cc62015-12-03 07:04:541204 InitializeCompositorThread();
[email protected]a9fb30aa2011-10-06 06:58:461205
jdduke691dd572014-12-02 20:47:521206 if (!input_event_filter_.get()) {
1207 // Always provide an input event filter implementation to ensure consistent
1208 // input event scheduling and prioritization.
1209 // TODO(jdduke): Merge InputEventFilter, InputHandlerManager and
1210 // MainThreadInputEventFilter, crbug.com/436057.
1211 input_event_filter_ = new MainThreadInputEventFilter(
1212 main_input_callback_.callback(), main_thread_compositor_task_runner_);
1213 }
1214 AddFilter(input_event_filter_.get());
1215
skyostil2d3b5bd2015-05-27 15:40:591216 scoped_refptr<base::SingleThreadTaskRunner> compositor_impl_side_task_runner;
vollick1050cc62015-12-03 07:04:541217 if (compositor_task_runner_)
skyostil2d3b5bd2015-05-27 15:40:591218 compositor_impl_side_task_runner = compositor_task_runner_;
[email protected]7f1f63f2013-03-07 06:07:291219 else
skyostil2d3b5bd2015-05-27 15:40:591220 compositor_impl_side_task_runner = base::ThreadTaskRunnerHandle::Get();
[email protected]1842fe22012-08-13 23:24:351221
simonhonga7e3ac42014-11-11 20:50:221222 compositor_message_filter_ = new CompositorForwardingMessageFilter(
skyostil2d3b5bd2015-05-27 15:40:591223 compositor_impl_side_task_runner.get());
simonhonga7e3ac42014-11-11 20:50:221224 AddFilter(compositor_message_filter_.get());
[email protected]1842fe22012-08-13 23:24:351225
[email protected]58436a12012-03-21 17:10:261226 RenderThreadImpl::RegisterSchemes();
1227
xhwang194acae2014-11-12 22:46:331228 RenderMediaClient::Initialize();
1229
[email protected]b146d6d2012-09-11 10:20:051230 devtools_agent_message_filter_ = new DevToolsAgentFilter();
1231 AddFilter(devtools_agent_message_filter_.get());
1232
ulan4a385192015-11-11 10:59:181233 if (GetContentClient()->renderer()->RunIdleHandlerWhenWidgetsHidden()) {
[email protected]1784b2f2011-11-24 10:53:481234 ScheduleIdleHandler(kLongIdleHandlerDelayMs);
ulan4a385192015-11-11 10:59:181235 } else {
1236 // If we do not track widget visibility, then assume conservatively that
1237 // the isolate is in background. This reduces memory usage.
1238 isolate->IsolateInBackgroundNotification();
1239 }
[email protected]2541d1a2013-07-10 07:33:271240
jdduke73220f02015-09-04 17:03:511241 renderer_scheduler_->SetTimerQueueSuspensionWhenBackgroundedEnabled(
1242 GetContentClient()
1243 ->renderer()
1244 ->AllowTimerSuspensionWhenProcessBackgrounded());
1245
reedccf98c52014-10-03 16:40:381246 SkGraphics::SetResourceCacheSingleAllocationByteLimit(
[email protected]dd2c1022014-07-22 23:13:571247 kImageCacheSingleAllocationByteLimit);
1248
reed6e5a72222015-08-06 20:37:161249 // Hook up blink's codecs so skia can call them
reed08cd16372017-02-21 22:11:411250 SkGraphics::SetImageGeneratorFromEncodedDataFactory(
Blink Reformat1c4d759e2017-04-09 16:34:541251 blink::WebImageGenerator::Create);
reed6e5a72222015-08-06 20:37:161252
[email protected]fdeac262014-07-10 12:52:511253 if (command_line.HasSwitch(switches::kMemoryMetrics)) {
1254 memory_observer_.reset(new MemoryObserver());
1255 message_loop()->AddTaskObserver(memory_observer_.get());
1256 }
paritosh.in7e30c902015-04-15 17:04:071257
1258 if (command_line.HasSwitch(switches::kExplicitlyAllowedPorts)) {
1259 std::string allowed_ports =
1260 command_line.GetSwitchValueASCII(switches::kExplicitlyAllowedPorts);
1261 net::SetExplicitlyAllowedPorts(allowed_ports);
1262 }
[email protected]d1b8fccc2011-08-03 01:20:131263}
1264
[email protected]58436a12012-03-21 17:10:261265void RenderThreadImpl::RegisterSchemes() {
mkwst8e94fb32015-05-20 05:05:141266 // chrome:
Blink Reformat1c4d759e2017-04-09 16:34:541267 WebString chrome_scheme(WebString::FromASCII(kChromeUIScheme));
1268 WebSecurityPolicy::RegisterURLSchemeAsDisplayIsolated(chrome_scheme);
1269 WebSecurityPolicy::RegisterURLSchemeAsNotAllowingJavascriptURLs(
mkwst8e94fb32015-05-20 05:05:141270 chrome_scheme);
mkwst8e94fb32015-05-20 05:05:141271
1272 // chrome-devtools:
Blink Reformat1c4d759e2017-04-09 16:34:541273 WebString devtools_scheme(WebString::FromASCII(kChromeDevToolsScheme));
1274 WebSecurityPolicy::RegisterURLSchemeAsDisplayIsolated(devtools_scheme);
meacerce6b66032016-06-02 20:56:051275
1276 // view-source:
Blink Reformat1c4d759e2017-04-09 16:34:541277 WebString view_source_scheme(WebString::FromASCII(kViewSourceScheme));
1278 WebSecurityPolicy::RegisterURLSchemeAsDisplayIsolated(view_source_scheme);
[email protected]58436a12012-03-21 17:10:261279}
1280
[email protected]e6e30ac2014-01-13 21:24:391281void RenderThreadImpl::RecordAction(const base::UserMetricsAction& action) {
[email protected]97880c82013-12-04 07:09:211282 Send(new ViewHostMsg_UserMetricsRecordAction(action.str_));
1283}
1284
1285void RenderThreadImpl::RecordComputedAction(const std::string& action) {
[email protected]526476902011-10-06 20:34:061286 Send(new ViewHostMsg_UserMetricsRecordAction(action));
1287}
1288
dchengcedca5612016-04-09 01:40:151289std::unique_ptr<base::SharedMemory>
1290RenderThreadImpl::HostAllocateSharedMemoryBuffer(size_t size) {
sadrulee3ff1f2016-12-09 04:22:011291 return ChildThreadImpl::AllocateSharedMemory(size);
[email protected]00614a82011-10-07 22:39:311292}
1293
jbauman2f5c1942014-12-06 03:28:241294cc::SharedBitmapManager* RenderThreadImpl::GetSharedBitmapManager() {
1295 return shared_bitmap_manager();
1296}
1297
[email protected]f1a29a02011-10-06 23:08:441298void RenderThreadImpl::RegisterExtension(v8::Extension* extension) {
Blink Reformat1c4d759e2017-04-09 16:34:541299 WebScriptController::RegisterExtension(extension);
[email protected]526476902011-10-06 20:34:061300}
1301
avi1023d012015-12-25 02:39:141302void RenderThreadImpl::ScheduleIdleHandler(int64_t initial_delay_ms) {
[email protected]6593ae12011-11-14 12:09:441303 idle_notification_delay_in_ms_ = initial_delay_ms;
[email protected]526476902011-10-06 20:34:061304 idle_timer_.Stop();
1305 idle_timer_.Start(FROM_HERE,
[email protected]6593ae12011-11-14 12:09:441306 base::TimeDelta::FromMilliseconds(initial_delay_ms),
[email protected]f1a29a02011-10-06 23:08:441307 this, &RenderThreadImpl::IdleHandler);
[email protected]526476902011-10-06 20:34:061308}
1309
[email protected]f1a29a02011-10-06 23:08:441310void RenderThreadImpl::IdleHandler() {
[email protected]1784b2f2011-11-24 10:53:481311 bool run_in_foreground_tab = (widget_count_ > hidden_widget_count_) &&
[email protected]e9ff79c2012-10-19 21:31:261312 GetContentClient()->renderer()->
[email protected]1784b2f2011-11-24 10:53:481313 RunIdleHandlerWhenWidgetsHidden();
1314 if (run_in_foreground_tab) {
jochen5a32aaf2014-09-26 20:37:431315 if (idle_notifications_to_skip_ > 0) {
1316 --idle_notifications_to_skip_;
1317 } else {
ssid0603ca9f2015-06-09 16:48:081318 ReleaseFreeMemory();
jochen5a32aaf2014-09-26 20:37:431319 }
1320 ScheduleIdleHandler(kLongIdleHandlerDelayMs);
[email protected]1784b2f2011-11-24 10:53:481321 return;
1322 }
[email protected]237a14852012-04-28 02:56:381323
ssid0603ca9f2015-06-09 16:48:081324 ReleaseFreeMemory();
[email protected]526476902011-10-06 20:34:061325
[email protected]26e82322014-01-20 14:18:221326 // Continue the idle timer if the webkit shared timer is not suspended or
1327 // something is left to do.
1328 bool continue_timer = !webkit_shared_timer_suspended_;
1329
sullivancd45a3e2014-09-19 14:39:181330 // Schedule next invocation. When the tab is originally hidden, an invocation
1331 // is scheduled for kInitialIdleHandlerDelayMs in
1332 // RenderThreadImpl::WidgetHidden in order to race to a minimal heap.
1333 // After that, idle calls can be much less frequent, so run at a maximum of
1334 // once every kLongIdleHandlerDelayMs.
[email protected]6593ae12011-11-14 12:09:441335 // Dampen the delay using the algorithm (if delay is in seconds):
[email protected]526476902011-10-06 20:34:061336 // delay = delay + 1 / (delay + 2)
1337 // Using floor(delay) has a dampening effect such as:
sullivancd45a3e2014-09-19 14:39:181338 // 30s, 30, 30, 31, 31, 31, 31, 32, 32, ...
[email protected]6593ae12011-11-14 12:09:441339 // If the delay is in milliseconds, the above formula is equivalent to:
1340 // delay_ms / 1000 = delay_ms / 1000 + 1 / (delay_ms / 1000 + 2)
1341 // which is equivalent to
1342 // delay_ms = delay_ms + 1000*1000 / (delay_ms + 2000).
[email protected]26e82322014-01-20 14:18:221343 if (continue_timer) {
sullivancd45a3e2014-09-19 14:39:181344 ScheduleIdleHandler(
1345 std::max(kLongIdleHandlerDelayMs,
1346 idle_notification_delay_in_ms_ +
1347 1000000 / (idle_notification_delay_in_ms_ + 2000)));
[email protected]26e82322014-01-20 14:18:221348
1349 } else {
1350 idle_timer_.Stop();
1351 }
[email protected]526476902011-10-06 20:34:061352
ericwilligers88e69742016-10-17 19:29:551353 for (auto& observer : observers_)
1354 observer.IdleNotification();
[email protected]526476902011-10-06 20:34:061355}
1356
avi1023d012015-12-25 02:39:141357int64_t RenderThreadImpl::GetIdleNotificationDelayInMs() const {
[email protected]6593ae12011-11-14 12:09:441358 return idle_notification_delay_in_ms_;
[email protected]526476902011-10-06 20:34:061359}
1360
[email protected]6593ae12011-11-14 12:09:441361void RenderThreadImpl::SetIdleNotificationDelayInMs(
avi1023d012015-12-25 02:39:141362 int64_t idle_notification_delay_in_ms) {
[email protected]6593ae12011-11-14 12:09:441363 idle_notification_delay_in_ms_ = idle_notification_delay_in_ms;
[email protected]4a7d6392011-09-19 20:55:081364}
1365
[email protected]5b18406362013-06-18 18:46:431366int RenderThreadImpl::PostTaskToAllWebWorkers(const base::Closure& closure) {
kinukoef647412015-12-23 06:10:431367 return WorkerThreadRegistry::Instance()->PostTaskToAllThreads(closure);
[email protected]a9bd323d2013-06-17 20:27:561368}
1369
[email protected]b02f5902012-12-19 07:33:001370bool RenderThreadImpl::ResolveProxy(const GURL& url, std::string* proxy_list) {
1371 bool result = false;
1372 Send(new ViewHostMsg_ResolveProxy(url, &result, proxy_list));
1373 return result;
1374}
1375
[email protected]1784b2f2011-11-24 10:53:481376void RenderThreadImpl::PostponeIdleNotification() {
1377 idle_notifications_to_skip_ = 2;
1378}
1379
dcastagna7f45dada2015-10-19 20:17:351380media::GpuVideoAcceleratorFactories* RenderThreadImpl::GetGpuFactories() {
[email protected]3bb8bb32013-07-11 13:13:031381 DCHECK(IsMainThread());
1382
dcastagna09bd6b32016-02-01 21:54:281383 if (!gpu_factories_.empty()) {
sadrul85cc5d82016-12-20 03:37:411384 scoped_refptr<ui::ContextProviderCommandBuffer> shared_context_provider =
dcastagna09bd6b32016-02-01 21:54:281385 gpu_factories_.back()->ContextProviderMainThread();
1386 if (shared_context_provider) {
1387 cc::ContextProvider::ScopedContextLock lock(
1388 shared_context_provider.get());
1389 if (lock.ContextGL()->GetGraphicsResetStatusKHR() == GL_NO_ERROR) {
leon.han21e0e482017-02-23 04:13:321390 return gpu_factories_.back().get();
dcastagna09bd6b32016-02-01 21:54:281391 } else {
1392 scoped_refptr<base::SingleThreadTaskRunner> media_task_runner =
1393 GetMediaThreadTaskRunner();
1394 media_task_runner->PostTask(
1395 FROM_HERE,
1396 base::Bind(
1397 base::IgnoreResult(
1398 &RendererGpuVideoAcceleratorFactories::CheckContextLost),
leon.han21e0e482017-02-23 04:13:321399 base::Unretained(gpu_factories_.back().get())));
dcastagna09bd6b32016-02-01 21:54:281400 }
1401 }
1402 }
dcastagna7f45dada2015-10-19 20:17:351403
tobiasjsca238b3b2015-06-24 22:53:541404 const base::CommandLine* cmd_line = base::CommandLine::ForCurrentProcess();
1405
danakj0b4b94e32016-05-10 22:33:011406 scoped_refptr<gpu::GpuChannelHost> gpu_channel_host =
sadrul6d310fa2016-08-04 02:12:161407 EstablishGpuChannelSync();
danakj0b4b94e32016-05-10 22:33:011408 if (!gpu_channel_host)
1409 return nullptr;
danakj0dd9e1e2016-05-11 22:15:091410 // This context is only used to create textures and mailbox them, so
1411 // use lower limits than the default.
1412 gpu::SharedMemoryLimits limits = gpu::SharedMemoryLimits::ForMailboxContext();
danakj9a04adc2016-05-16 22:45:071413 bool support_locking = true;
sadrul85cc5d82016-12-20 03:37:411414 scoped_refptr<ui::ContextProviderCommandBuffer> media_context_provider =
danakj9a04adc2016-05-16 22:45:071415 CreateOffscreenContext(gpu_channel_host, limits, support_locking,
ericrka20c1002017-03-13 21:08:131416 ui::command_buffer_metrics::MEDIA_CONTEXT,
sunnyps8f9139e2017-05-12 17:53:251417 kGpuStreamIdDefault, kGpuStreamPriorityDefault);
danakj0b4b94e32016-05-10 22:33:011418 if (!media_context_provider->BindToCurrentThread())
1419 return nullptr;
danakj0b4b94e32016-05-10 22:33:011420
acolwellb4034942014-08-28 15:42:431421 scoped_refptr<base::SingleThreadTaskRunner> media_task_runner =
1422 GetMediaThreadTaskRunner();
danakj0b4b94e32016-05-10 22:33:011423 const bool enable_video_accelerator =
1424 !cmd_line->HasSwitch(switches::kDisableAcceleratedVideoDecode);
1425 const bool enable_gpu_memory_buffer_video_frames =
dcastagna43c3a86a2016-02-02 21:16:381426#if defined(OS_MACOSX) || defined(OS_LINUX)
dcastagnaa82ed96a2016-05-12 02:52:471427 !cmd_line->HasSwitch(switches::kDisableGpuMemoryBufferVideoFrames) &&
1428 !cmd_line->HasSwitch(switches::kDisableGpuCompositing) &&
1429 !gpu_channel_host->gpu_info().software_rendering;
jbaumana0bb8982017-05-05 19:50:531430#elif defined(OS_WIN)
1431 !cmd_line->HasSwitch(switches::kDisableGpuMemoryBufferVideoFrames) &&
1432 !cmd_line->HasSwitch(switches::kDisableGpuCompositing) &&
1433 !gpu_channel_host->gpu_info().software_rendering &&
1434 (cmd_line->HasSwitch(switches::kEnableGpuMemoryBufferVideoFrames) ||
1435 gpu_channel_host->gpu_info().supports_overlays);
dcastagnab65e6072015-09-05 07:18:421436#else
danakj0b4b94e32016-05-10 22:33:011437 cmd_line->HasSwitch(switches::kEnableGpuMemoryBufferVideoFrames);
dcastagnab65e6072015-09-05 07:18:421438#endif
dcastagna5077d6d2016-01-27 00:07:051439
danakj0b4b94e32016-05-10 22:33:011440 gpu_factories_.push_back(RendererGpuVideoAcceleratorFactories::Create(
1441 std::move(gpu_channel_host), base::ThreadTaskRunnerHandle::Get(),
1442 media_task_runner, std::move(media_context_provider),
ericrk9151705c2016-07-26 19:53:161443 enable_gpu_memory_buffer_video_frames, buffer_to_texture_target_map_,
danakj0b4b94e32016-05-10 22:33:011444 enable_video_accelerator));
leon.han21e0e482017-02-23 04:13:321445 return gpu_factories_.back().get();
[email protected]3bb8bb32013-07-11 13:13:031446}
1447
sadrul85cc5d82016-12-20 03:37:411448scoped_refptr<ui::ContextProviderCommandBuffer>
[email protected]f10dc472013-09-27 03:31:591449RenderThreadImpl::SharedMainThreadContextProvider() {
[email protected]e06e1122013-03-15 17:12:381450 DCHECK(IsMainThread());
danakje8ec797e2016-04-19 04:08:431451 if (shared_main_thread_contexts_ &&
1452 shared_main_thread_contexts_->ContextGL()->GetGraphicsResetStatusKHR() ==
1453 GL_NO_ERROR)
1454 return shared_main_thread_contexts_;
1455
sadrul6d310fa2016-08-04 02:12:161456 scoped_refptr<gpu::GpuChannelHost> gpu_channel_host(
1457 EstablishGpuChannelSync());
danakje8ec797e2016-04-19 04:08:431458 if (!gpu_channel_host) {
1459 shared_main_thread_contexts_ = nullptr;
1460 return nullptr;
[email protected]c29b7ff2013-03-06 03:51:041461 }
danakje8ec797e2016-04-19 04:08:431462
danakj9a04adc2016-05-16 22:45:071463 bool support_locking = false;
danakjc3983552016-05-03 00:04:351464 shared_main_thread_contexts_ = CreateOffscreenContext(
danakj9a04adc2016-05-16 22:45:071465 std::move(gpu_channel_host), gpu::SharedMemoryLimits(), support_locking,
sadrul85cc5d82016-12-20 03:37:411466 ui::command_buffer_metrics::RENDERER_MAINTHREAD_CONTEXT,
sunnyps8f9139e2017-05-12 17:53:251467 kGpuStreamIdDefault, kGpuStreamPriorityDefault);
danakje8ec797e2016-04-19 04:08:431468 if (!shared_main_thread_contexts_->BindToCurrentThread())
1469 shared_main_thread_contexts_ = nullptr;
[email protected]f10dc472013-09-27 03:31:591470 return shared_main_thread_contexts_;
[email protected]c29b7ff2013-03-06 03:51:041471}
1472
siva.gunturi5d4feb052015-11-15 16:15:311473#if defined(OS_ANDROID)
boliuf8753bf62016-02-11 20:09:421474
siva.gunturi5d4feb052015-11-15 16:15:311475scoped_refptr<StreamTextureFactory> RenderThreadImpl::GetStreamTexureFactory() {
1476 DCHECK(IsMainThread());
boliu30f1b262016-04-19 00:12:331477 if (!stream_texture_factory_.get() ||
1478 stream_texture_factory_->ContextGL()->GetGraphicsResetStatusKHR() !=
1479 GL_NO_ERROR) {
sadrul85cc5d82016-12-20 03:37:411480 scoped_refptr<ui::ContextProviderCommandBuffer> shared_context_provider =
piman9fc22f32016-05-02 22:21:221481 SharedMainThreadContextProvider();
1482 if (!shared_context_provider) {
penghuange1d86512016-07-08 18:15:001483 stream_texture_factory_ = nullptr;
1484 return nullptr;
siva.gunturi5d4feb052015-11-15 16:15:311485 }
piman9fc22f32016-05-02 22:21:221486 DCHECK(shared_context_provider->GetCommandBufferProxy());
1487 DCHECK(shared_context_provider->GetCommandBufferProxy()->channel());
1488 stream_texture_factory_ =
1489 StreamTextureFactory::Create(std::move(shared_context_provider));
siva.gunturi5d4feb052015-11-15 16:15:311490 }
1491 return stream_texture_factory_;
1492}
boliuf8753bf62016-02-11 20:09:421493
1494bool RenderThreadImpl::EnableStreamTextureCopy() {
boliu30f1b262016-04-19 00:12:331495 return sync_compositor_message_filter_.get();
boliuf8753bf62016-02-11 20:09:421496}
1497
siva.gunturi5d4feb052015-11-15 16:15:311498#endif
1499
[email protected]e9ff79c2012-10-19 21:31:261500AudioRendererMixerManager* RenderThreadImpl::GetAudioRendererMixerManager() {
[email protected]59383c782013-04-17 16:43:271501 if (!audio_renderer_mixer_manager_) {
olka7a4679392016-05-27 15:32:581502 audio_renderer_mixer_manager_ = AudioRendererMixerManager::Create();
[email protected]3958e972012-07-17 00:25:411503 }
1504
1505 return audio_renderer_mixer_manager_.get();
1506}
1507
[email protected]73429ca2014-03-06 06:07:471508base::WaitableEvent* RenderThreadImpl::GetShutdownEvent() {
1509 return ChildProcess::current()->GetShutDownEvent();
1510}
1511
staraz067f58242016-11-07 21:06:411512int32_t RenderThreadImpl::GetClientId() {
1513 return client_id_;
1514}
1515
altiminc8885e82017-01-18 13:11:141516scoped_refptr<base::SingleThreadTaskRunner>
1517RenderThreadImpl::GetTimerTaskRunner() {
1518 return renderer_scheduler_->TimerTaskRunner();
1519}
1520
1521scoped_refptr<base::SingleThreadTaskRunner>
1522RenderThreadImpl::GetLoadingTaskRunner() {
1523 return renderer_scheduler_->LoadingTaskRunner();
1524}
1525
chiniforooshan614d70a2017-03-17 01:19:331526void RenderThreadImpl::SetFieldTrialGroup(const std::string& trial_name,
1527 const std::string& group_name) {
1528 field_trial_syncer_.OnSetFieldTrialGroup(trial_name, group_name);
1529}
1530
rockot067ca55f2016-09-30 22:00:151531void RenderThreadImpl::OnAssociatedInterfaceRequest(
1532 const std::string& name,
1533 mojo::ScopedInterfaceEndpointHandle handle) {
rockot70bbb59492017-01-25 00:56:511534 if (associated_interfaces_.CanBindRequest(name))
1535 associated_interfaces_.BindRequest(name, std::move(handle));
1536 else
1537 ChildThreadImpl::OnAssociatedInterfaceRequest(name, std::move(handle));
rockot067ca55f2016-09-30 22:00:151538}
1539
danakj6e3bf8012014-12-16 18:27:531540bool RenderThreadImpl::IsGpuRasterizationForced() {
1541 return is_gpu_rasterization_forced_;
1542}
1543
sunnypsd8ce1c22016-05-10 18:02:401544bool RenderThreadImpl::IsAsyncWorkerContextEnabled() {
1545 return is_async_worker_context_enabled_;
1546}
1547
senorblancob60ba952015-01-27 19:12:361548int RenderThreadImpl::GetGpuRasterizationMSAASampleCount() {
1549 return gpu_rasterization_msaa_sample_count_;
1550}
1551
danakj6e3bf8012014-12-16 18:27:531552bool RenderThreadImpl::IsLcdTextEnabled() {
1553 return is_lcd_text_enabled_;
1554}
1555
1556bool RenderThreadImpl::IsDistanceFieldTextEnabled() {
1557 return is_distance_field_text_enabled_;
1558}
1559
1560bool RenderThreadImpl::IsZeroCopyEnabled() {
1561 return is_zero_copy_enabled_;
1562}
1563
ericrk1d17f752015-10-20 03:03:071564bool RenderThreadImpl::IsPartialRasterEnabled() {
1565 return is_partial_raster_enabled_;
jbroman5f7f71932015-08-18 16:24:461566}
1567
ccameronc7fcd132015-11-03 20:14:311568bool RenderThreadImpl::IsGpuMemoryBufferCompositorResourcesEnabled() {
1569 return is_gpu_memory_buffer_compositor_resources_enabled_;
1570}
1571
ccamerona7644752014-12-30 01:16:311572bool RenderThreadImpl::IsElasticOverscrollEnabled() {
1573 return is_elastic_overscroll_enabled_;
1574}
1575
ericrk9151705c2016-07-26 19:53:161576const cc::BufferToTextureTargetMap&
1577RenderThreadImpl::GetBufferToTextureTargetMap() {
1578 return buffer_to_texture_target_map_;
danakj6e3bf8012014-12-16 18:27:531579}
vmiura9084b342015-02-03 22:19:571580
danakj6e3bf8012014-12-16 18:27:531581scoped_refptr<base::SingleThreadTaskRunner>
1582RenderThreadImpl::GetCompositorMainThreadTaskRunner() {
1583 return main_thread_compositor_task_runner_;
1584}
1585
1586scoped_refptr<base::SingleThreadTaskRunner>
1587RenderThreadImpl::GetCompositorImplThreadTaskRunner() {
skyostil2d3b5bd2015-05-27 15:40:591588 return compositor_task_runner_;
danakj6e3bf8012014-12-16 18:27:531589}
1590
1591gpu::GpuMemoryBufferManager* RenderThreadImpl::GetGpuMemoryBufferManager() {
sadrul53546592016-12-17 01:44:211592 return gpu_->gpu_memory_buffer_manager();
danakj6e3bf8012014-12-16 18:27:531593}
1594
skyostil529caa292016-08-10 17:44:511595blink::scheduler::RendererScheduler* RenderThreadImpl::GetRendererScheduler() {
danakj6e3bf8012014-12-16 18:27:531596 return renderer_scheduler_.get();
1597}
1598
dchengcedca5612016-04-09 01:40:151599std::unique_ptr<cc::BeginFrameSource>
danakj6e3bf8012014-12-16 18:27:531600RenderThreadImpl::CreateExternalBeginFrameSource(int routing_id) {
ricea29649b92016-08-31 09:30:211601 return base::MakeUnique<CompositorExternalBeginFrameSource>(
1602 compositor_message_filter_.get(), sync_message_filter(), routing_id);
danakj6e3bf8012014-12-16 18:27:531603}
1604
samans09812d32017-03-27 19:51:501605std::unique_ptr<cc::SyntheticBeginFrameSource>
1606RenderThreadImpl::CreateSyntheticBeginFrameSource() {
1607 base::SingleThreadTaskRunner* compositor_impl_side_task_runner =
1608 compositor_task_runner_ ? compositor_task_runner_.get()
1609 : base::ThreadTaskRunnerHandle::Get().get();
1610 return base::MakeUnique<cc::BackToBackBeginFrameSource>(
1611 base::MakeUnique<cc::DelayBasedTimeSource>(
1612 compositor_impl_side_task_runner));
1613}
1614
reveman34b7a1522015-03-23 20:27:471615cc::TaskGraphRunner* RenderThreadImpl::GetTaskGraphRunner() {
prashant.nfad657e2016-06-01 07:52:171616 return categorized_worker_pool_->GetTaskGraphRunner();
reveman34b7a1522015-03-23 20:27:471617}
1618
loyso65c93c602015-08-11 05:15:571619bool RenderThreadImpl::IsThreadedAnimationEnabled() {
1620 return is_threaded_animation_enabled_;
1621}
1622
wjmaclean1d970622017-01-21 22:28:241623bool RenderThreadImpl::IsScrollAnimatorEnabled() {
1624 return is_scroll_animator_enabled_;
1625}
1626
fsamuel4c5c87142017-03-14 03:14:261627bool RenderThreadImpl::IsSurfaceSynchronizationEnabled() {
1628 return is_surface_synchronization_enabled_;
1629}
1630
skyostila37c2a72016-06-29 17:30:071631void RenderThreadImpl::OnRAILModeChanged(v8::RAILMode rail_mode) {
Blink Reformat1c4d759e2017-04-09 16:34:541632 blink::MainThreadIsolate()->SetRAILMode(rail_mode);
1633 blink::SetRAILModeOnWorkerThreadIsolates(rail_mode);
skyostila37c2a72016-06-29 17:30:071634}
1635
[email protected]b3e83de2012-02-07 03:33:281636bool RenderThreadImpl::IsMainThread() {
1637 return !!current();
1638}
1639
torne88b66452016-05-03 13:22:141640void RenderThreadImpl::OnChannelError() {
1641 // In single-process mode, the renderer can't be restarted after shutdown.
1642 // So, if we get a channel error, crash the whole process right now to get a
1643 // more informative stack, since we will otherwise just crash later when we
1644 // try to restart it.
1645 CHECK(!base::CommandLine::ForCurrentProcess()->HasSwitch(
1646 switches::kSingleProcess));
1647 ChildThreadImpl::OnChannelError();
1648}
1649
[email protected]f1a29a02011-10-06 23:08:441650bool RenderThreadImpl::OnControlMessageReceived(const IPC::Message& msg) {
dchenga2d442c22016-10-13 15:39:211651 for (auto& observer : observers_) {
1652 if (observer.OnControlMessageReceived(msg))
[email protected]1223d6ef2011-03-28 16:47:501653 return true;
1654 }
1655
[email protected]70c19a932010-05-14 12:59:111656 // Some messages are handled by delegates.
[email protected]1910fe82012-05-10 00:04:101657 if (appcache_dispatcher_->OnMessageReceived(msg) ||
leon.han7a5714382017-04-16 03:25:001658 dom_storage_dispatcher_->OnMessageReceived(msg)) {
[email protected]a95986a82010-12-24 06:19:281659 return true;
[email protected]1910fe82012-05-10 00:04:101660 }
[email protected]1edc16b82009-04-07 17:45:541661
[email protected]a95986a82010-12-24 06:19:281662 bool handled = true;
[email protected]f1a29a02011-10-06 23:08:441663 IPC_BEGIN_MESSAGE_MAP(RenderThreadImpl, msg)
[email protected]0ec90d522014-03-12 16:28:191664 IPC_MESSAGE_HANDLER(WorkerProcessMsg_CreateWorker, OnCreateNewSharedWorker)
[email protected]a95986a82010-12-24 06:19:281665 IPC_MESSAGE_UNHANDLED(handled = false)
[email protected]8930d472009-02-21 08:05:281666 IPC_END_MESSAGE_MAP()
[email protected]a95986a82010-12-24 06:19:281667 return handled;
initial.commit09911bf2008-07-26 23:55:291668}
1669
jdduke73220f02015-09-04 17:03:511670void RenderThreadImpl::OnProcessBackgrounded(bool backgrounded) {
1671 ChildThreadImpl::OnProcessBackgrounded(backgrounded);
1672
hajimehoshi69093272016-05-13 08:30:581673 if (backgrounded) {
jdduke73220f02015-09-04 17:03:511674 renderer_scheduler_->OnRendererBackgrounded();
tasakb95dbb50c2017-02-08 18:07:501675 needs_to_record_first_active_paint_ = false;
hajimehoshi69093272016-05-13 08:30:581676 } else {
jdduke73220f02015-09-04 17:03:511677 renderer_scheduler_->OnRendererForegrounded();
tasakbb0640b2017-05-15 09:02:261678 process_foregrounded_count_++;
hajimehoshi69093272016-05-13 08:30:581679 }
1680}
1681
1682void RenderThreadImpl::OnProcessPurgeAndSuspend() {
1683 ChildThreadImpl::OnProcessPurgeAndSuspend();
tasak6ff44032016-11-07 06:45:251684 if (!RendererIsHidden())
hajimehoshi69093272016-05-13 08:30:581685 return;
tasakff1e62422016-12-22 04:53:551686
tasakc4de4672017-04-26 02:37:361687 if (!base::FeatureList::IsEnabled(features::kPurgeAndSuspend))
1688 return;
1689
1690 base::MemoryCoordinatorClientRegistry::GetInstance()->PurgeMemory();
tasakb95dbb50c2017-02-08 18:07:501691 needs_to_record_first_active_paint_ = true;
tasakc4de4672017-04-26 02:37:361692
1693 RendererMemoryMetrics memory_metrics;
1694 if (!GetRendererMemoryMetrics(&memory_metrics))
1695 return;
1696
1697 purge_and_suspend_memory_metrics_ = memory_metrics;
tasakb46626a2016-10-18 05:54:441698}
1699
1700// TODO(tasak): Replace the following GetMallocUsage() with memory-infra
1701// when it is possible to run memory-infra without tracing.
1702#if defined(OS_WIN)
1703namespace {
1704
1705static size_t GetMallocUsage() {
siggi7fb93a52016-12-12 22:22:151706 // Iterate through whichever heap the CRT is using.
1707 HANDLE crt_heap = reinterpret_cast<HANDLE>(_get_heap_handle());
1708 if (crt_heap == NULL)
tasakb46626a2016-10-18 05:54:441709 return 0;
siggi7fb93a52016-12-12 22:22:151710 if (!::HeapLock(crt_heap))
tasak7415a3db2016-12-12 04:17:141711 return 0 ;
tasakb46626a2016-10-18 05:54:441712 size_t malloc_usage = 0;
tasak7415a3db2016-12-12 04:17:141713 PROCESS_HEAP_ENTRY heap_entry;
1714 heap_entry.lpData = NULL;
siggi7fb93a52016-12-12 22:22:151715 while (::HeapWalk(crt_heap, &heap_entry) != 0) {
tasak7415a3db2016-12-12 04:17:141716 if ((heap_entry.wFlags & PROCESS_HEAP_ENTRY_BUSY) != 0)
1717 malloc_usage += heap_entry.cbData;
tasakb46626a2016-10-18 05:54:441718 }
siggi7fb93a52016-12-12 22:22:151719 ::HeapUnlock(crt_heap);
tasakb46626a2016-10-18 05:54:441720 return malloc_usage;
1721}
1722
1723} // namespace
1724#elif defined(OS_MACOSX) || defined(OS_IOS)
1725namespace {
1726
1727static size_t GetMallocUsage() {
1728 malloc_statistics_t stats = {0};
1729 malloc_zone_statistics(nullptr, &stats);
1730 return stats.size_in_use;
1731}
1732
1733} // namespace
1734#endif
1735
bashia0ba0d42017-04-03 08:11:061736bool RenderThreadImpl::GetRendererMemoryMetrics(
keishi51ed0d52017-01-12 10:04:461737 RendererMemoryMetrics* memory_metrics) const {
1738 DCHECK(memory_metrics);
1739
chrisha05e94f22017-04-05 22:06:041740 // Cache this result, as it can change while this code is running, and is used
1741 // as a divisor below.
1742 size_t render_view_count = RenderView::GetRenderViewCount();
1743
1744 // If there are no render views it doesn't make sense to calculate metrics
1745 // right now.
1746 if (render_view_count == 0)
bashia0ba0d42017-04-03 08:11:061747 return false;
1748
keishi51ed0d52017-01-12 10:04:461749 blink::WebMemoryStatistics blink_stats = blink::WebMemoryStatistics::Get();
1750 memory_metrics->partition_alloc_kb =
Blink Reformat1c4d759e2017-04-09 16:34:541751 blink_stats.partition_alloc_total_allocated_bytes / 1024;
1752 memory_metrics->blink_gc_kb =
1753 blink_stats.blink_gc_total_allocated_bytes / 1024;
keishi51ed0d52017-01-12 10:04:461754#if defined(OS_LINUX) || defined(OS_ANDROID)
1755 struct mallinfo minfo = mallinfo();
1756#if defined(USE_TCMALLOC)
1757 size_t malloc_usage = minfo.uordblks;
1758#else
1759 size_t malloc_usage = minfo.hblkhd + minfo.arena;
1760#endif
1761#else
1762 size_t malloc_usage = GetMallocUsage();
1763#endif
1764 memory_metrics->malloc_mb = malloc_usage / 1024 / 1024;
1765
1766 discardable_memory::ClientDiscardableSharedMemoryManager::Statistics
1767 discardable_stats = discardable_shared_memory_manager_->GetStatistics();
1768 size_t discardable_usage =
1769 discardable_stats.total_size - discardable_stats.freelist_size;
1770 memory_metrics->discardable_kb = discardable_usage / 1024;
1771
1772 size_t v8_usage = 0;
Blink Reformat1c4d759e2017-04-09 16:34:541773 if (v8::Isolate* isolate = blink::MainThreadIsolate()) {
keishi51ed0d52017-01-12 10:04:461774 v8::HeapStatistics v8_heap_statistics;
1775 isolate->GetHeapStatistics(&v8_heap_statistics);
1776 v8_usage = v8_heap_statistics.total_heap_size();
1777 }
1778 // TODO(tasak): Currently only memory usage of mainThreadIsolate() is
1779 // reported. We should collect memory usages of all isolates using
1780 // memory-infra.
1781 memory_metrics->v8_main_thread_isolate_mb = v8_usage / 1024 / 1024;
Blink Reformat1c4d759e2017-04-09 16:34:541782 size_t total_allocated = blink_stats.partition_alloc_total_allocated_bytes +
1783 blink_stats.blink_gc_total_allocated_bytes +
keishi51ed0d52017-01-12 10:04:461784 malloc_usage + v8_usage + discardable_usage;
1785 memory_metrics->total_allocated_mb = total_allocated / 1024 / 1024;
1786 memory_metrics->non_discardable_total_allocated_mb =
1787 (total_allocated - discardable_usage) / 1024 / 1024;
1788 memory_metrics->total_allocated_per_render_view_mb =
chrisha05e94f22017-04-05 22:06:041789 total_allocated / render_view_count / 1024 / 1024;
bashia0ba0d42017-04-03 08:11:061790
1791 return true;
keishi51ed0d52017-01-12 10:04:461792}
1793
tasak72f64042017-01-19 14:02:531794#define GET_MEMORY_GROWTH(current, previous, allocator) \
1795 (current.allocator > previous.allocator \
1796 ? current.allocator - previous.allocator \
1797 : 0)
1798
tasakbb0640b2017-05-15 09:02:261799#define UMA_HISTOGRAM_MEMORY_GROWTH_KB(basename, suffix, memory_usage) \
1800 { \
1801 std::string histogram_name = \
1802 base::StringPrintf("%s.%s", basename, suffix); \
1803 UMA_HISTOGRAM_MEMORY_KB(histogram_name, memory_usage); \
1804 }
1805
1806void RenderThreadImpl::RecordPurgeAndSuspendMemoryGrowthMetrics(
1807 const char* suffix,
1808 int foregrounded_count_when_purged) {
tasak72f64042017-01-19 14:02:531809 // If this renderer is resumed, we should not update UMA.
1810 if (!RendererIsHidden())
1811 return;
tasakbb0640b2017-05-15 09:02:261812 if (foregrounded_count_when_purged != process_foregrounded_count_)
1813 return;
tasak72f64042017-01-19 14:02:531814
1815 RendererMemoryMetrics memory_metrics;
bashia0ba0d42017-04-03 08:11:061816 if (!GetRendererMemoryMetrics(&memory_metrics))
1817 return;
1818
tasakbb0640b2017-05-15 09:02:261819 UMA_HISTOGRAM_MEMORY_GROWTH_KB(
1820 "PurgeAndSuspend.Experimental.MemoryGrowth.PartitionAllocKB", suffix,
tasak72f64042017-01-19 14:02:531821 GET_MEMORY_GROWTH(memory_metrics, purge_and_suspend_memory_metrics_,
1822 partition_alloc_kb));
tasakbb0640b2017-05-15 09:02:261823 UMA_HISTOGRAM_MEMORY_GROWTH_KB(
1824 "PurgeAndSuspend.Experimental.MemoryGrowth.BlinkGCKB", suffix,
tasak72f64042017-01-19 14:02:531825 GET_MEMORY_GROWTH(memory_metrics, purge_and_suspend_memory_metrics_,
1826 blink_gc_kb));
tasakbb0640b2017-05-15 09:02:261827 UMA_HISTOGRAM_MEMORY_GROWTH_KB(
1828 "PurgeAndSuspend.Experimental.MemoryGrowth.MallocKB", suffix,
tasak72f64042017-01-19 14:02:531829 GET_MEMORY_GROWTH(memory_metrics, purge_and_suspend_memory_metrics_,
tasakbb0640b2017-05-15 09:02:261830 malloc_mb) *
1831 1024);
1832 UMA_HISTOGRAM_MEMORY_GROWTH_KB(
1833 "PurgeAndSuspend.Experimental.MemoryGrowth.DiscardableKB", suffix,
tasak72f64042017-01-19 14:02:531834 GET_MEMORY_GROWTH(memory_metrics, purge_and_suspend_memory_metrics_,
1835 discardable_kb));
tasakbb0640b2017-05-15 09:02:261836 UMA_HISTOGRAM_MEMORY_GROWTH_KB(
1837 "PurgeAndSuspend.Experimental.MemoryGrowth.V8MainThreadIsolateKB", suffix,
tasak72f64042017-01-19 14:02:531838 GET_MEMORY_GROWTH(memory_metrics, purge_and_suspend_memory_metrics_,
tasakbb0640b2017-05-15 09:02:261839 v8_main_thread_isolate_mb) *
1840 1024);
1841 UMA_HISTOGRAM_MEMORY_GROWTH_KB(
1842 "PurgeAndSuspend.Experimental.MemoryGrowth.TotalAllocatedKB", suffix,
tasak72f64042017-01-19 14:02:531843 GET_MEMORY_GROWTH(memory_metrics, purge_and_suspend_memory_metrics_,
tasakbb0640b2017-05-15 09:02:261844 total_allocated_mb) *
1845 1024);
jdduke73220f02015-09-04 17:03:511846}
1847
sadrul6d310fa2016-08-04 02:12:161848scoped_refptr<gpu::GpuChannelHost> RenderThreadImpl::EstablishGpuChannelSync() {
[email protected]d13f35d2012-05-18 02:28:151849 TRACE_EVENT0("gpu", "RenderThreadImpl::EstablishGpuChannelSync");
1850
piman9fc22f32016-05-02 22:21:221851 if (gpu_channel_) {
[email protected]1082b1d2010-03-30 00:31:221852 // Do nothing if we already have a GPU channel or are already
1853 // establishing one.
[email protected]7951bfe2013-06-13 01:43:341854 if (!gpu_channel_->IsLost())
piman9fc22f32016-05-02 22:21:221855 return gpu_channel_;
[email protected]6217d392010-03-25 22:08:351856
1857 // Recreate the channel if it has been lost.
piman765e5282015-05-08 03:43:011858 gpu_channel_->DestroyChannel();
penghuange1d86512016-07-08 18:15:001859 gpu_channel_ = nullptr;
[email protected]6217d392010-03-25 22:08:351860 }
1861
sadrul53546592016-12-17 01:44:211862 gpu_channel_ = gpu_->EstablishGpuChannelSync();
1863 if (gpu_channel_)
1864 GetContentClient()->SetGpuInfo(gpu_channel_->gpu_info());
piman9fc22f32016-05-02 22:21:221865 return gpu_channel_;
[email protected]3bf4d532010-03-27 00:23:341866}
1867
fsamuelcf3002e2017-03-20 23:13:471868void RenderThreadImpl::RequestNewCompositorFrameSink(
danakj83066a32016-06-21 02:34:491869 bool use_software,
1870 int routing_id,
1871 scoped_refptr<FrameSwapMessageQueue> frame_swap_message_queue,
fsamuelcf3002e2017-03-20 23:13:471872 const GURL& url,
1873 const CompositorFrameSinkCallback& callback) {
danakj83066a32016-06-21 02:34:491874 const base::CommandLine& command_line =
1875 *base::CommandLine::ForCurrentProcess();
1876 if (command_line.HasSwitch(switches::kDisableGpuCompositing))
1877 use_software = true;
1878
samans09812d32017-03-27 19:51:501879 // In disable gpu vsync mode, also let the renderer tick as fast as it
1880 // can. The top level begin frame source will also be running as a back
1881 // to back begin frame source, but using a synthetic begin frame source
1882 // here reduces latency when in this mode (at least for frames
1883 // starting--it potentially increases it for input on the other hand.)
1884 std::unique_ptr<cc::SyntheticBeginFrameSource> synthetic_begin_frame_source;
1885 if (command_line.HasSwitch(switches::kDisableGpuVsync) &&
1886 command_line.GetSwitchValueASCII(switches::kDisableGpuVsync) != "gpu") {
1887 synthetic_begin_frame_source = CreateSyntheticBeginFrameSource();
1888 }
1889
sadrul943e3b32016-08-04 18:22:591890#if defined(USE_AURA)
fsamuel098eade2017-03-21 18:06:141891 if (!use_software && IsRunningInMash()) {
sadrulbe22c4f2017-03-14 06:59:251892 scoped_refptr<gpu::GpuChannelHost> channel = EstablishGpuChannelSync();
1893 // If the channel could not be established correctly, then return null. This
1894 // would cause the compositor to wait and try again at a later time.
fsamuelcf3002e2017-03-20 23:13:471895 if (!channel) {
1896 callback.Run(nullptr);
1897 return;
1898 }
fsamuel95c974eb2017-03-22 10:00:251899 RendererWindowTreeClient::Get(routing_id)
1900 ->RequestCompositorFrameSink(
1901 gpu_->CreateContextProvider(std::move(channel)),
1902 GetGpuMemoryBufferManager(), callback);
fsamuelcf3002e2017-03-20 23:13:471903 return;
danakj83066a32016-06-21 02:34:491904 }
1905#endif
1906
danakj83066a32016-06-21 02:34:491907 if (command_line.HasSwitch(switches::kEnableVulkan)) {
1908 scoped_refptr<cc::VulkanContextProvider> vulkan_context_provider =
1909 cc::VulkanInProcessContextProvider::Create();
1910 if (vulkan_context_provider) {
1911 DCHECK(!layout_test_mode());
fsamuelcf3002e2017-03-20 23:13:471912 callback.Run(base::MakeUnique<RendererCompositorFrameSink>(
samans2040988b2017-04-11 23:58:351913 routing_id, std::move(synthetic_begin_frame_source),
enne077ba4862016-09-12 20:59:531914 std::move(vulkan_context_provider),
fsamuelcf3002e2017-03-20 23:13:471915 std::move(frame_swap_message_queue)));
1916 return;
danakj83066a32016-06-21 02:34:491917 }
1918 }
1919
1920 // Create a gpu process channel and verify we want to use GPU compositing
1921 // before creating any context providers.
1922 scoped_refptr<gpu::GpuChannelHost> gpu_channel_host;
1923 if (!use_software) {
sadrul6d310fa2016-08-04 02:12:161924 gpu_channel_host = EstablishGpuChannelSync();
danakj83066a32016-06-21 02:34:491925 if (!gpu_channel_host) {
1926 // Cause the compositor to wait and try again.
fsamuelcf3002e2017-03-20 23:13:471927 callback.Run(nullptr);
1928 return;
danakj83066a32016-06-21 02:34:491929 }
1930 // We may get a valid channel, but with a software renderer. In that case,
1931 // disable GPU compositing.
1932 if (gpu_channel_host->gpu_info().software_rendering)
1933 use_software = true;
1934 }
1935
1936 if (use_software) {
1937 DCHECK(!layout_test_mode());
fsamuelcf3002e2017-03-20 23:13:471938 callback.Run(base::MakeUnique<RendererCompositorFrameSink>(
samans2040988b2017-04-11 23:58:351939 routing_id, std::move(synthetic_begin_frame_source), nullptr, nullptr,
1940 nullptr, shared_bitmap_manager(), std::move(frame_swap_message_queue)));
fsamuelcf3002e2017-03-20 23:13:471941 return;
danakj83066a32016-06-21 02:34:491942 }
1943
sadrul85cc5d82016-12-20 03:37:411944 scoped_refptr<ui::ContextProviderCommandBuffer> worker_context_provider =
danakj83066a32016-06-21 02:34:491945 SharedCompositorWorkerContextProvider();
1946 if (!worker_context_provider) {
1947 // Cause the compositor to wait and try again.
fsamuelcf3002e2017-03-20 23:13:471948 callback.Run(nullptr);
1949 return;
danakj83066a32016-06-21 02:34:491950 }
1951
1952 // The renderer compositor context doesn't do a lot of stuff, so we don't
1953 // expect it to need a lot of space for commands or transfer. Raster and
1954 // uploads happen on the worker context instead.
1955 gpu::SharedMemoryLimits limits = gpu::SharedMemoryLimits::ForMailboxContext();
1956
1957 // This is for an offscreen context for the compositor. So the default
1958 // framebuffer doesn't need alpha, depth, stencil, antialiasing.
1959 gpu::gles2::ContextCreationAttribHelper attributes;
1960 attributes.alpha_size = -1;
1961 attributes.depth_size = 0;
1962 attributes.stencil_size = 0;
1963 attributes.samples = 0;
1964 attributes.sample_buffers = 0;
1965 attributes.bind_generates_resource = false;
1966 attributes.lose_context_when_out_of_memory = true;
1967
1968 constexpr bool automatic_flushes = false;
1969 constexpr bool support_locking = false;
1970
1971 // The compositor context shares resources with the worker context unless
1972 // the worker is async.
sadrul85cc5d82016-12-20 03:37:411973 ui::ContextProviderCommandBuffer* share_context =
1974 worker_context_provider.get();
danakj83066a32016-06-21 02:34:491975 if (IsAsyncWorkerContextEnabled())
1976 share_context = nullptr;
1977
sadrul85cc5d82016-12-20 03:37:411978 scoped_refptr<ui::ContextProviderCommandBuffer> context_provider(
1979 new ui::ContextProviderCommandBuffer(
sunnyps8f9139e2017-05-12 17:53:251980 gpu_channel_host, kGpuStreamIdDefault, kGpuStreamPriorityDefault,
1981 gpu::kNullSurfaceHandle, url, automatic_flushes, support_locking,
1982 limits, attributes, share_context,
sadrul85cc5d82016-12-20 03:37:411983 ui::command_buffer_metrics::RENDER_COMPOSITOR_CONTEXT));
danakj83066a32016-06-21 02:34:491984
danakj83066a32016-06-21 02:34:491985 if (layout_test_deps_) {
fsamuelcf3002e2017-03-20 23:13:471986 callback.Run(layout_test_deps_->CreateCompositorFrameSink(
jbroman6ccbc7d472016-07-27 04:45:411987 routing_id, std::move(gpu_channel_host), std::move(context_provider),
fsamuelcf3002e2017-03-20 23:13:471988 std::move(worker_context_provider), GetGpuMemoryBufferManager(), this));
1989 return;
danakj83066a32016-06-21 02:34:491990 }
1991
1992#if defined(OS_ANDROID)
1993 if (sync_compositor_message_filter_) {
samans09812d32017-03-27 19:51:501994 std::unique_ptr<cc::BeginFrameSource> begin_frame_source =
1995 synthetic_begin_frame_source
1996 ? std::move(synthetic_begin_frame_source)
1997 : CreateExternalBeginFrameSource(routing_id);
fsamuelcf3002e2017-03-20 23:13:471998 callback.Run(base::MakeUnique<SynchronousCompositorFrameSink>(
danakja40dd4482016-06-28 01:14:101999 std::move(context_provider), std::move(worker_context_provider),
danakje9cf5812017-02-16 22:22:552000 GetGpuMemoryBufferManager(), shared_bitmap_manager(), routing_id,
samans2040988b2017-04-11 23:58:352001 g_next_compositor_frame_sink_id++, std::move(begin_frame_source),
enne077ba4862016-09-12 20:59:532002 sync_compositor_message_filter_.get(),
fsamuelcf3002e2017-03-20 23:13:472003 std::move(frame_swap_message_queue)));
2004 return;
danakj83066a32016-06-21 02:34:492005 }
2006#endif
fsamuelcf3002e2017-03-20 23:13:472007 callback.Run(base::WrapUnique(new RendererCompositorFrameSink(
samans2040988b2017-04-11 23:58:352008 routing_id, std::move(synthetic_begin_frame_source),
2009 std::move(context_provider), std::move(worker_context_provider),
2010 GetGpuMemoryBufferManager(), nullptr,
fsamuelcf3002e2017-03-20 23:13:472011 std::move(frame_swap_message_queue))));
danakj83066a32016-06-21 02:34:492012}
2013
rockot067ca55f2016-09-30 22:00:152014AssociatedInterfaceRegistry*
2015RenderThreadImpl::GetAssociatedInterfaceRegistry() {
2016 return &associated_interfaces_;
2017}
2018
jbroman6ccbc7d472016-07-27 04:45:412019std::unique_ptr<cc::SwapPromise>
2020RenderThreadImpl::RequestCopyOfOutputForLayoutTest(
2021 int32_t routing_id,
2022 std::unique_ptr<cc::CopyOutputRequest> request) {
2023 DCHECK(layout_test_deps_);
2024 return layout_test_deps_->RequestCopyOfOutput(routing_id, std::move(request));
2025}
2026
altimineb6bd1962017-05-03 14:52:382027std::unique_ptr<blink::WebMediaStreamCenter>
2028RenderThreadImpl::CreateMediaStreamCenter(
[email protected]180ef242013-11-07 06:50:462029 blink::WebMediaStreamCenterClient* client) {
altimineb6bd1962017-05-03 14:52:382030 std::unique_ptr<blink::WebMediaStreamCenter> media_stream_center;
Brett Wilson0748bf412016-11-22 17:55:462031#if BUILDFLAG(ENABLE_WEBRTC)
altimineb6bd1962017-05-03 14:52:382032 if (!media_stream_center) {
2033 media_stream_center =
2034 GetContentClient()->renderer()->OverrideCreateWebMediaStreamCenter(
2035 client);
2036 if (!media_stream_center) {
2037 media_stream_center = base::MakeUnique<MediaStreamCenter>(
2038 client, GetPeerConnectionDependencyFactory());
[email protected]68e5fee2013-02-18 10:04:222039 }
2040 }
[email protected]d8cd8372012-03-09 10:49:512041#endif
altimineb6bd1962017-05-03 14:52:382042 return media_stream_center;
[email protected]d8cd8372012-03-09 10:49:512043}
2044
Brett Wilson0748bf412016-11-22 17:55:462045#if BUILDFLAG(ENABLE_WEBRTC)
[email protected]0107d8a2014-05-16 10:20:342046PeerConnectionDependencyFactory*
2047RenderThreadImpl::GetPeerConnectionDependencyFactory() {
[email protected]83e0a482014-05-22 18:07:182048 return peer_connection_factory_.get();
[email protected]6ee10bd2012-09-13 09:01:532049}
[email protected]22fe91d2014-08-12 17:07:122050#endif
[email protected]6ee10bd2012-09-13 09:01:532051
rockot1587e332016-07-27 17:44:142052mojom::RenderFrameMessageFilter*
2053RenderThreadImpl::render_frame_message_filter() {
2054 if (!render_frame_message_filter_)
2055 GetChannel()->GetRemoteAssociatedInterface(&render_frame_message_filter_);
2056 return render_frame_message_filter_.get();
2057}
2058
rockote261d2112016-09-21 22:22:232059mojom::RenderMessageFilter* RenderThreadImpl::render_message_filter() {
2060 if (!render_message_filter_)
2061 GetChannel()->GetRemoteAssociatedInterface(&render_message_filter_);
2062 return render_message_filter_.get();
2063}
2064
penghuang346a46f92016-03-31 21:37:522065gpu::GpuChannelHost* RenderThreadImpl::GetGpuChannel() {
piman9fc22f32016-05-02 22:21:222066 if (!gpu_channel_)
danakj3873e852016-05-05 00:46:072067 return nullptr;
[email protected]7951bfe2013-06-13 01:43:342068 if (gpu_channel_->IsLost())
danakj3873e852016-05-05 00:46:072069 return nullptr;
[email protected]6217d392010-03-25 22:08:352070 return gpu_channel_.get();
2071}
2072
chiniforooshan614d70a2017-03-17 01:19:332073void RenderThreadImpl::OnFieldTrialGroupFinalized(
2074 const std::string& trial_name,
2075 const std::string& group_name) {
2076 mojom::FieldTrialRecorderPtr field_trial_recorder;
ben649b3edd2017-03-23 00:32:022077 GetConnector()->BindInterface(mojom::kBrowserServiceName,
2078 &field_trial_recorder);
chiniforooshan614d70a2017-03-17 01:19:332079 field_trial_recorder->FieldTrialActivated(trial_name);
2080}
2081
rockot067ca55f2016-09-30 22:00:152082void RenderThreadImpl::CreateView(mojom::CreateViewParamsPtr params) {
2083 CompositorDependencies* compositor_deps = this;
wjmaclean1d970622017-01-21 22:28:242084 is_scroll_animator_enabled_ = params->web_preferences.enable_scroll_animator;
rockot067ca55f2016-09-30 22:00:152085 // When bringing in render_view, also bring in webkit's glue and jsbindings.
nickf7b38222016-11-22 21:59:352086 RenderViewImpl::Create(compositor_deps, *params,
2087 RenderWidget::ShowCallback());
rockot067ca55f2016-09-30 22:00:152088}
2089
rockot53be7caf2016-10-04 20:17:082090void RenderThreadImpl::CreateFrame(mojom::CreateFrameParamsPtr params) {
2091 // Debug cases of https://crbug.com/626802.
2092 base::debug::SetCrashKeyValue("newframe_routing_id",
2093 base::IntToString(params->routing_id));
2094 base::debug::SetCrashKeyValue("newframe_proxy_id",
2095 base::IntToString(params->proxy_routing_id));
2096 base::debug::SetCrashKeyValue("newframe_opener_id",
2097 base::IntToString(params->opener_routing_id));
2098 base::debug::SetCrashKeyValue("newframe_parent_id",
2099 base::IntToString(params->parent_routing_id));
2100 base::debug::SetCrashKeyValue("newframe_widget_id",
2101 base::IntToString(
2102 params->widget_params->routing_id));
2103 base::debug::SetCrashKeyValue("newframe_widget_hidden",
2104 params->widget_params->hidden ? "yes" : "no");
2105 base::debug::SetCrashKeyValue("newframe_replicated_origin",
2106 params->replication_state.origin.Serialize());
2107 base::debug::SetCrashKeyValue("newframe_oopifs_possible",
2108 SiteIsolationPolicy::AreCrossProcessFramesPossible() ? "yes" : "no");
2109 CompositorDependencies* compositor_deps = this;
2110 RenderFrameImpl::CreateFrame(
2111 params->routing_id, params->proxy_routing_id, params->opener_routing_id,
2112 params->parent_routing_id, params->previous_sibling_routing_id,
2113 params->replication_state, compositor_deps, *params->widget_params,
2114 params->frame_owner_properties);
2115}
2116
2117void RenderThreadImpl::CreateFrameProxy(
2118 int32_t routing_id,
2119 int32_t render_view_routing_id,
2120 int32_t opener_routing_id,
2121 int32_t parent_routing_id,
2122 const FrameReplicationState& replicated_state) {
nick3b5a21f2016-11-22 23:07:112123 RenderFrameProxy::CreateFrameProxy(
2124 routing_id, render_view_routing_id,
2125 RenderFrameImpl::ResolveOpener(opener_routing_id), parent_routing_id,
2126 replicated_state);
rockot53be7caf2016-10-04 20:17:082127}
2128
rockota2db0da2016-10-18 17:39:112129void RenderThreadImpl::OnNetworkConnectionChanged(
2130 net::NetworkChangeNotifier::ConnectionType type,
2131 double max_bandwidth_mbps) {
2132 bool online = type != net::NetworkChangeNotifier::CONNECTION_NONE;
Blink Reformat1c4d759e2017-04-09 16:34:542133 WebNetworkStateNotifier::SetOnLine(online);
rockota2db0da2016-10-18 17:39:112134 for (auto& observer : observers_)
2135 observer.NetworkStateChanged(online);
Blink Reformat1c4d759e2017-04-09 16:34:542136 WebNetworkStateNotifier::SetWebConnection(
rockota2db0da2016-10-18 17:39:112137 NetConnectionTypeToWebConnectionType(type), max_bandwidth_mbps);
2138}
2139
tbansal15973c32017-05-10 18:40:442140void RenderThreadImpl::OnNetworkQualityChanged(
2141 double http_rtt_msec,
2142 double transport_rtt_msec,
2143 double downlink_throughput_kbps) {
2144 UMA_HISTOGRAM_BOOLEAN("NQE.RenderThreadNotified", true);
2145 // TODO(tbansal): https://crbug.com/719108. Notify WebNetworkStateNotifier of
2146 // the change in the network quality.
2147}
2148
rockota2db0da2016-10-18 17:39:112149void RenderThreadImpl::SetWebKitSharedTimersSuspended(bool suspend) {
2150#if defined(OS_ANDROID)
2151 if (suspend) {
2152 renderer_scheduler_->SuspendTimerQueue();
2153 } else {
2154 renderer_scheduler_->ResumeTimerQueue();
2155 }
2156 webkit_shared_timer_suspended_ = suspend;
2157#else
2158 NOTREACHED();
2159#endif
2160}
2161
2162void RenderThreadImpl::UpdateScrollbarTheme(
2163 mojom::UpdateScrollbarThemeParamsPtr params) {
2164#if defined(OS_MACOSX)
2165 static_cast<WebScrollbarBehaviorImpl*>(
Blink Reformat1c4d759e2017-04-09 16:34:542166 blink_platform_impl_->ScrollbarBehavior())
rockota2db0da2016-10-18 17:39:112167 ->set_jump_on_track_click(params->jump_on_track_click);
2168
Blink Reformat1c4d759e2017-04-09 16:34:542169 blink::WebScrollbarTheme::UpdateScrollbarsWithNSDefaults(
rockota2db0da2016-10-18 17:39:112170 params->initial_button_delay, params->autoscroll_button_delay,
2171 params->preferred_scroller_style, params->redraw,
2172 params->button_placement);
2173#else
2174 NOTREACHED();
2175#endif
2176}
2177
2178void RenderThreadImpl::OnSystemColorsChanged(
2179 int32_t aqua_color_variant,
2180 const std::string& highlight_text_color,
2181 const std::string& highlight_color) {
2182#if defined(OS_MACOSX)
2183 SystemColorsDidChange(aqua_color_variant, highlight_text_color,
2184 highlight_color);
2185#else
2186 NOTREACHED();
2187#endif
2188}
2189
2190void RenderThreadImpl::PurgePluginListCache(bool reload_pages) {
brettw4b461082016-11-19 18:55:162191#if BUILDFLAG(ENABLE_PLUGINS)
rockota2db0da2016-10-18 17:39:112192 // The call below will cause a GetPlugins call with refresh=true, but at this
2193 // point we already know that the browser has refreshed its list, so disable
2194 // refresh temporarily to prevent each renderer process causing the list to be
2195 // regenerated.
2196 blink_platform_impl_->set_plugin_refresh_allowed(false);
Blink Reformat1c4d759e2017-04-09 16:34:542197 blink::ResetPluginCache(reload_pages);
rockota2db0da2016-10-18 17:39:112198 blink_platform_impl_->set_plugin_refresh_allowed(true);
2199
2200 for (auto& observer : observers_)
2201 observer.PluginListChanged();
2202#else
2203 NOTREACHED();
2204#endif
2205}
2206
[email protected]0ec90d522014-03-12 16:28:192207void RenderThreadImpl::OnCreateNewSharedWorker(
2208 const WorkerProcessMsg_CreateWorker_Params& params) {
2209 // EmbeddedSharedWorkerStub will self-destruct.
mkwstcfa98932016-03-09 13:06:192210 new EmbeddedSharedWorkerStub(
2211 params.url, params.name, params.content_security_policy,
2212 params.security_policy_type, params.creation_address_space,
horoed54f832017-05-21 05:25:472213 params.pause_on_start, params.route_id, params.data_saver_enabled);
[email protected]0ec90d522014-03-12 16:28:192214}
2215
[email protected]5071cb22013-07-10 02:19:062216void RenderThreadImpl::OnMemoryPressure(
2217 base::MemoryPressureListener::MemoryPressureLevel memory_pressure_level) {
hong.zhengb28b5332016-05-11 02:33:392218 TRACE_EVENT0("memory","RenderThreadImpl::OnMemoryPressure");
rmcilroy7fbb3bd52015-02-17 19:02:142219 if (blink_platform_impl_) {
Blink Reformat1c4d759e2017-04-09 16:34:542220 blink::WebMemoryCoordinator::OnMemoryPressure(
bashic577bfc2016-01-08 03:42:352221 static_cast<blink::WebMemoryPressureLevel>(memory_pressure_level));
hajimehoshi7bb39582016-10-12 04:30:572222 }
2223 if (memory_pressure_level ==
2224 base::MemoryPressureListener::MEMORY_PRESSURE_LEVEL_CRITICAL) {
2225 ReleaseFreeMemory();
2226 ClearMemory();
2227 }
2228}
rmcilroyab967c972015-02-17 23:15:002229
hajimehoshi7bb39582016-10-12 04:30:572230void RenderThreadImpl::OnMemoryStateChange(base::MemoryState state) {
hajimehoshi7bb39582016-10-12 04:30:572231 if (blink_platform_impl_) {
Blink Reformat1c4d759e2017-04-09 16:34:542232 blink::WebMemoryCoordinator::OnMemoryStateChange(
hajimehoshi7bb39582016-10-12 04:30:572233 static_cast<blink::MemoryState>(state));
2234 }
bashi233f65e2017-02-09 08:36:032235}
2236
2237void RenderThreadImpl::OnPurgeMemory() {
bashib9058f282017-03-30 01:55:242238 // Record amount of purged memory after 2 seconds. 2 seconds is arbitrary
2239 // but it works most cases.
2240 RendererMemoryMetrics metrics;
bashia0ba0d42017-04-03 08:11:062241 if (!GetRendererMemoryMetrics(&metrics))
2242 return;
2243
bashib9058f282017-03-30 01:55:242244 GetRendererScheduler()->DefaultTaskRunner()->PostDelayedTask(
2245 FROM_HERE,
2246 base::Bind(&RenderThreadImpl::RecordPurgeMemory, base::Unretained(this),
2247 std::move(metrics)),
2248 base::TimeDelta::FromSeconds(2));
2249
bashi233f65e2017-02-09 08:36:032250 OnTrimMemoryImmediately();
2251 ReleaseFreeMemory();
2252 ClearMemory();
2253 if (blink_platform_impl_)
Blink Reformat1c4d759e2017-04-09 16:34:542254 blink::WebMemoryCoordinator::OnPurgeMemory();
hajimehoshi7bb39582016-10-12 04:30:572255}
2256
bashib9058f282017-03-30 01:55:242257void RenderThreadImpl::RecordPurgeMemory(RendererMemoryMetrics before) {
2258 RendererMemoryMetrics after;
bashia0ba0d42017-04-03 08:11:062259 if (!GetRendererMemoryMetrics(&after))
2260 return;
bashib9058f282017-03-30 01:55:242261 int64_t mbytes = static_cast<int64_t>(before.total_allocated_mb) -
2262 static_cast<int64_t>(after.total_allocated_mb);
2263 if (mbytes < 0)
2264 mbytes = 0;
2265 UMA_HISTOGRAM_MEMORY_LARGE_MB("Memory.Experimental.Renderer.PurgedMemory",
2266 mbytes);
2267}
2268
hajimehoshi7bb39582016-10-12 04:30:572269void RenderThreadImpl::ClearMemory() {
2270 // Do not call into blink if it is not initialized.
2271 if (blink_platform_impl_) {
2272 // Purge Skia font cache, by setting it to 0 and then again to the
2273 // previous limit.
2274 size_t font_cache_limit = SkGraphics::SetFontCacheLimit(0);
2275 SkGraphics::SetFontCacheLimit(font_cache_limit);
rmcilroy7fbb3bd52015-02-17 19:02:142276 }
[email protected]5071cb22013-07-10 02:19:062277}
2278
skyostil2d3b5bd2015-05-27 15:40:592279scoped_refptr<base::SingleThreadTaskRunner>
thestig529ad8a2016-07-08 20:30:122280RenderThreadImpl::GetFileThreadTaskRunner() {
fdoraye94d8642016-07-07 19:19:012281 DCHECK(message_loop()->task_runner()->BelongsToCurrentThread());
[email protected]59383c782013-04-17 16:43:272282 if (!file_thread_) {
[email protected]c6a7b862010-08-20 22:19:382283 file_thread_.reset(new base::Thread("Renderer::FILE"));
2284 file_thread_->Start();
2285 }
skyostil2d3b5bd2015-05-27 15:40:592286 return file_thread_->task_runner();
[email protected]c6a7b862010-08-20 22:19:382287}
[email protected]e9ff79c2012-10-19 21:31:262288
acolwellb4034942014-08-28 15:42:432289scoped_refptr<base::SingleThreadTaskRunner>
2290RenderThreadImpl::GetMediaThreadTaskRunner() {
fdoraye94d8642016-07-07 19:19:012291 DCHECK(message_loop()->task_runner()->BelongsToCurrentThread());
[email protected]c1330c82013-06-06 02:23:252292 if (!media_thread_) {
2293 media_thread_.reset(new base::Thread("Media"));
2294 media_thread_->Start();
2295 }
skyostil2d3b5bd2015-05-27 15:40:592296 return media_thread_->task_runner();
[email protected]c1330c82013-06-06 02:23:252297}
2298
dcastagna4517a182015-08-05 19:51:032299base::TaskRunner* RenderThreadImpl::GetWorkerTaskRunner() {
prashant.nfad657e2016-06-01 07:52:172300 return categorized_worker_pool_.get();
dcastagnab880e8f2015-06-30 20:16:062301}
2302
sadrul85cc5d82016-12-20 03:37:412303scoped_refptr<ui::ContextProviderCommandBuffer>
danakj0b4b94e32016-05-10 22:33:012304RenderThreadImpl::SharedCompositorWorkerContextProvider() {
revemand180dfc32015-09-24 00:19:432305 DCHECK(IsMainThread());
2306 // Try to reuse existing shared worker context provider.
revemand180dfc32015-09-24 00:19:432307 if (shared_worker_context_provider_) {
2308 // Note: If context is lost, delete reference after releasing the lock.
boliu11afa7e2016-04-18 18:04:142309 cc::ContextProvider::ScopedContextLock lock(
2310 shared_worker_context_provider_.get());
revemand180dfc32015-09-24 00:19:432311 if (shared_worker_context_provider_->ContextGL()
danakje8ec797e2016-04-19 04:08:432312 ->GetGraphicsResetStatusKHR() == GL_NO_ERROR)
2313 return shared_worker_context_provider_;
revemand180dfc32015-09-24 00:19:432314 }
danakje8ec797e2016-04-19 04:08:432315
sadrul6d310fa2016-08-04 02:12:162316 scoped_refptr<gpu::GpuChannelHost> gpu_channel_host(
2317 EstablishGpuChannelSync());
danakje8ec797e2016-04-19 04:08:432318 if (!gpu_channel_host) {
2319 shared_worker_context_provider_ = nullptr;
2320 return shared_worker_context_provider_;
revemand180dfc32015-09-24 00:19:432321 }
danakje8ec797e2016-04-19 04:08:432322
sunnyps8f9139e2017-05-12 17:53:252323 int32_t stream_id = kGpuStreamIdDefault;
2324 gpu::SchedulingPriority stream_priority = kGpuStreamPriorityDefault;
sunnypsd8ce1c22016-05-10 18:02:402325 if (is_async_worker_context_enabled_) {
sunnyps8f9139e2017-05-12 17:53:252326 stream_id = kGpuStreamIdWorker;
2327 stream_priority = kGpuStreamPriorityWorker;
sunnypsd8ce1c22016-05-10 18:02:402328 }
2329
danakj9a04adc2016-05-16 22:45:072330 bool support_locking = true;
danakj0dd9e1e2016-05-11 22:15:092331 shared_worker_context_provider_ = CreateOffscreenContext(
danakj9a04adc2016-05-16 22:45:072332 std::move(gpu_channel_host), gpu::SharedMemoryLimits(), support_locking,
sadrul85cc5d82016-12-20 03:37:412333 ui::command_buffer_metrics::RENDER_WORKER_CONTEXT, stream_id,
danakj0dd9e1e2016-05-11 22:15:092334 stream_priority);
danakje8ec797e2016-04-19 04:08:432335 if (!shared_worker_context_provider_->BindToCurrentThread())
2336 shared_worker_context_provider_ = nullptr;
revemand180dfc32015-09-24 00:19:432337 return shared_worker_context_provider_;
2338}
2339
juncai2f298a82017-04-18 03:51:392340void RenderThreadImpl::SampleGamepads(device::Gamepads* data) {
Blink Reformat1c4d759e2017-04-09 16:34:542341 blink_platform_impl_->SampleGamepads(*data);
[email protected]0ff736562014-05-09 09:09:472342}
2343
rmcilroyaa296052015-04-14 15:35:272344bool RenderThreadImpl::RendererIsHidden() const {
2345 return widget_count_ > 0 && hidden_widget_count_ == widget_count_;
2346}
2347
[email protected]b2db9272014-01-10 17:42:002348void RenderThreadImpl::WidgetCreated() {
rmcilroyaa296052015-04-14 15:35:272349 bool renderer_was_hidden = RendererIsHidden();
[email protected]b2db9272014-01-10 17:42:002350 widget_count_++;
rmcilroyaa296052015-04-14 15:35:272351 if (renderer_was_hidden)
2352 OnRendererVisible();
[email protected]b2db9272014-01-10 17:42:002353}
2354
2355void RenderThreadImpl::WidgetDestroyed() {
rmcilroyaa296052015-04-14 15:35:272356 // TODO(rmcilroy): Remove the restriction that destroyed widgets must be
2357 // unhidden before WidgetDestroyed is called.
2358 DCHECK_GT(widget_count_, 0);
2359 DCHECK_GT(widget_count_, hidden_widget_count_);
[email protected]b2db9272014-01-10 17:42:002360 widget_count_--;
rmcilroyaa296052015-04-14 15:35:272361 if (RendererIsHidden())
2362 OnRendererHidden();
[email protected]b2db9272014-01-10 17:42:002363}
2364
2365void RenderThreadImpl::WidgetHidden() {
2366 DCHECK_LT(hidden_widget_count_, widget_count_);
2367 hidden_widget_count_++;
rmcilroyaa296052015-04-14 15:35:272368 if (RendererIsHidden())
2369 OnRendererHidden();
[email protected]b2db9272014-01-10 17:42:002370}
2371
2372void RenderThreadImpl::WidgetRestored() {
rmcilroyaa296052015-04-14 15:35:272373 bool renderer_was_hidden = RendererIsHidden();
[email protected]b2db9272014-01-10 17:42:002374 DCHECK_GT(hidden_widget_count_, 0);
2375 hidden_widget_count_--;
rmcilroyaa296052015-04-14 15:35:272376 if (renderer_was_hidden)
2377 OnRendererVisible();
2378}
[email protected]b2db9272014-01-10 17:42:002379
rmcilroyaa296052015-04-14 15:35:272380void RenderThreadImpl::OnRendererHidden() {
Blink Reformat1c4d759e2017-04-09 16:34:542381 blink::MainThreadIsolate()->IsolateInBackgroundNotification();
rmcilroyaa296052015-04-14 15:35:272382 // TODO(rmcilroy): Remove IdleHandler and replace it with an IdleTask
2383 // scheduled by the RendererScheduler - http://crbug.com/469210.
ulan4a385192015-11-11 10:59:182384 if (!GetContentClient()->renderer()->RunIdleHandlerWhenWidgetsHidden())
2385 return;
2386 ScheduleIdleHandler(kInitialIdleHandlerDelayMs);
rmcilroyaa296052015-04-14 15:35:272387}
2388
2389void RenderThreadImpl::OnRendererVisible() {
Blink Reformat1c4d759e2017-04-09 16:34:542390 blink::MainThreadIsolate()->IsolateInForegroundNotification();
rmcilroyaa296052015-04-14 15:35:272391 if (!GetContentClient()->renderer()->RunIdleHandlerWhenWidgetsHidden())
[email protected]b2db9272014-01-10 17:42:002392 return;
[email protected]b2db9272014-01-10 17:42:002393 ScheduleIdleHandler(kLongIdleHandlerDelayMs);
2394}
2395
ssid0603ca9f2015-06-09 16:48:082396void RenderThreadImpl::ReleaseFreeMemory() {
2397 base::allocator::ReleaseFreeMemory();
penghuang342762b2016-12-02 21:04:582398 discardable_shared_memory_manager_->ReleaseFreeMemory();
ssid0603ca9f2015-06-09 16:48:082399
2400 if (blink_platform_impl_)
Blink Reformat1c4d759e2017-04-09 16:34:542401 blink::DecommitFreeableMemory();
ssid0603ca9f2015-06-09 16:48:082402}
2403
ben76f52b242016-06-18 05:42:482404RenderThreadImpl::PendingFrameCreate::PendingFrameCreate(
benf28ce882017-05-02 16:15:492405 const service_manager::BindSourceInfo& browser_info,
rockotf8fdd9b2015-12-16 22:22:352406 int routing_id,
ben76f52b242016-06-18 05:42:482407 mojom::FrameRequest frame_request,
csharrison95f01e922017-04-24 18:52:352408 mojom::FrameHostInterfaceBrokerPtr frame_host_interface_broker)
benf28ce882017-05-02 16:15:492409 : browser_info_(browser_info),
2410 routing_id_(routing_id),
ben76f52b242016-06-18 05:42:482411 frame_request_(std::move(frame_request)),
csharrison95f01e922017-04-24 18:52:352412 frame_host_interface_broker_(std::move(frame_host_interface_broker)) {
ben76f52b242016-06-18 05:42:482413 // The RenderFrame may be deleted before the CreateFrame message is received.
2414 // In that case, the RenderFrameHost should cancel the create, which is
csharrison95f01e922017-04-24 18:52:352415 // detected by setting an error handler on |frame_host_interface_broker_|.
2416 frame_host_interface_broker_.set_connection_error_handler(
2417 base::Bind(&RenderThreadImpl::PendingFrameCreate::OnConnectionError,
2418 base::Unretained(this)));
rockotf8fdd9b2015-12-16 22:22:352419}
2420
ben76f52b242016-06-18 05:42:482421RenderThreadImpl::PendingFrameCreate::~PendingFrameCreate() {
rockotf8fdd9b2015-12-16 22:22:352422}
2423
ben76f52b242016-06-18 05:42:482424void RenderThreadImpl::PendingFrameCreate::OnConnectionError() {
rockotf8fdd9b2015-12-16 22:22:352425 size_t erased =
ben76f52b242016-06-18 05:42:482426 RenderThreadImpl::current()->pending_frame_creates_.erase(routing_id_);
rockotf8fdd9b2015-12-16 22:22:352427 DCHECK_EQ(1u, erased);
2428}
2429
hong.zhengb28b5332016-05-11 02:33:392430void RenderThreadImpl::OnSyncMemoryPressure(
2431 base::MemoryPressureListener::MemoryPressureLevel memory_pressure_level) {
Blink Reformat1c4d759e2017-04-09 16:34:542432 if (!blink::MainThreadIsolate())
hong.zhengb28b5332016-05-11 02:33:392433 return;
2434
2435 v8::MemoryPressureLevel v8_memory_pressure_level =
2436 static_cast<v8::MemoryPressureLevel>(memory_pressure_level);
2437
2438 // In order to reduce performance impact, translate critical level to
2439 // moderate level for foregroud renderer.
2440 if (!RendererIsHidden() &&
2441 v8_memory_pressure_level == v8::MemoryPressureLevel::kCritical)
2442 v8_memory_pressure_level = v8::MemoryPressureLevel::kModerate;
2443
Blink Reformat1c4d759e2017-04-09 16:34:542444 blink::MainThreadIsolate()->MemoryPressureNotification(
hong.zhengb28b5332016-05-11 02:33:392445 v8_memory_pressure_level);
2446 blink::MemoryPressureNotificationToWorkerThreadIsolates(
2447 v8_memory_pressure_level);
2448}
2449
bashic4b4afcb2016-08-23 06:37:522450// Note that this would be called only when memory_coordinator is enabled.
2451// OnSyncMemoryPressure() is never called in that case.
2452void RenderThreadImpl::OnTrimMemoryImmediately() {
Blink Reformat1c4d759e2017-04-09 16:34:542453 if (blink::MainThreadIsolate()) {
2454 blink::MainThreadIsolate()->MemoryPressureNotification(
bashic4b4afcb2016-08-23 06:37:522455 v8::MemoryPressureLevel::kCritical);
2456 blink::MemoryPressureNotificationToWorkerThreadIsolates(
2457 v8::MemoryPressureLevel::kCritical);
2458 }
2459}
2460
rockot067ca55f2016-09-30 22:00:152461void RenderThreadImpl::OnRendererInterfaceRequest(
2462 mojom::RendererAssociatedRequest request) {
2463 DCHECK(!renderer_binding_.is_bound());
2464 renderer_binding_.Bind(std::move(request));
2465}
bashic4b4afcb2016-08-23 06:37:522466
[email protected]e9ff79c2012-10-19 21:31:262467} // namespace content