blob: ec0cca1b26b26bd366b2f302fb15838ca0fbfdae [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"
tasaka27961a2017-05-24 07:33:2526#include "base/metrics/histogram_functions.h"
asvitkine8d51e9d2016-09-02 23:55:4327#include "base/metrics/histogram_macros.h"
[email protected]433df472012-03-07 20:33:3928#include "base/path_service.h"
tasakb46626a2016-10-18 05:54:4429#include "base/process/process_metrics.h"
fdoray2df4a9e2016-07-18 23:47:1630#include "base/run_loop.h"
[email protected]21aa99682013-06-11 07:17:0131#include "base/strings/string16.h"
[email protected]1e1d1e12014-01-17 16:14:2932#include "base/strings/string_number_conversions.h"
hablichd6a4f122015-10-28 11:34:4933#include "base/strings/string_split.h"
ccameron6728bae32015-01-09 20:18:0634#include "base/strings/sys_string_conversions.h"
[email protected]74ebfb12013-06-07 20:48:0035#include "base/strings/utf_string_conversions.h"
fdoray50a38342016-11-21 20:46:0436#include "base/threading/sequenced_worker_pool.h"
reveman34b7a1522015-03-23 20:27:4737#include "base/threading/simple_thread.h"
[email protected]1357c322010-12-30 22:18:5638#include "base/threading/thread_local.h"
[email protected]d293572a2013-05-23 18:50:4539#include "base/threading/thread_restrictions.h"
gab30f26df2016-05-11 19:37:5540#include "base/threading/thread_task_runner_handle.h"
ccameron9c48d1d42016-09-22 01:46:0141#include "base/trace_event/memory_dump_manager.h"
primiano9e38d552015-01-28 04:18:0142#include "base/trace_event/trace_event.h"
[email protected]7a4de7a62010-08-17 18:38:2443#include "base/values.h"
avi1023d012015-12-25 02:39:1444#include "build/build_config.h"
jbroman0d302162015-09-05 05:46:2345#include "cc/base/histograms.h"
[email protected]d72493152014-01-08 17:37:4546#include "cc/base/switches.h"
[email protected]38564622014-08-19 02:47:1847#include "cc/blink/web_layer_impl.h"
jbroman6ccbc7d472016-07-27 04:45:4148#include "cc/output/copy_output_request.h"
danakjc7afae52017-06-20 21:12:4149#include "cc/output/layer_tree_frame_sink.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"
danakjc7afae52017-06-20 21:12:4157#include "components/viz/client/client_layer_tree_frame_sink.h"
danakj92429852017-06-29 00:19:0358#include "components/viz/client/client_shared_bitmap_manager.h"
samans7e6675cc2017-06-05 20:16:0859#include "components/viz/client/local_surface_id_provider.h"
Fady Samuel1d744b22017-07-10 21:23:5560#include "components/viz/common/resources/buffer_to_texture_target_map.h"
[email protected]a8cb3b73b2013-08-12 05:50:5061#include "content/child/appcache/appcache_dispatcher.h"
62#include "content/child/appcache/appcache_frontend_impl.h"
dmurph1fb98482016-03-30 21:14:2663#include "content/child/blob_storage/blob_message_filter.h"
[email protected]10208ea2013-06-06 20:08:0364#include "content/child/child_histogram_message_filter.h"
alexclarke0bc36e8d32014-12-17 17:29:2065#include "content/child/child_resource_message_filter.h"
[email protected]89c36f82013-07-17 06:23:2766#include "content/child/db_message_filter.h"
[email protected]c7199a6e2013-06-04 12:56:0167#include "content/child/indexed_db/indexed_db_dispatcher.h"
bashia6264042016-09-15 04:49:5168#include "content/child/memory/child_memory_coordinator_impl.h"
[email protected]10208ea2013-06-06 20:08:0369#include "content/child/resource_dispatcher.h"
alexclarke0bc36e8d32014-12-17 17:29:2070#include "content/child/resource_scheduling_filter.h"
[email protected]643255da2013-06-12 20:55:1371#include "content/child/runtime_features.h"
[email protected]57cf97882013-06-26 20:39:0172#include "content/child/thread_safe_sender.h"
[email protected]c7199a6e2013-06-04 12:56:0173#include "content/child/web_database_observer_impl.h"
kinukoef647412015-12-23 06:10:4374#include "content/child/worker_thread_registry.h"
[email protected]bdae9812011-10-15 00:33:0375#include "content/common/child_process_messages.h"
[email protected]89c36f82013-07-17 06:23:2776#include "content/common/content_constants_internal.h"
[email protected]5f2aa722013-08-07 16:59:4177#include "content/common/dom_storage/dom_storage_messages.h"
thakis18e426412017-03-15 12:06:3778#include "content/common/features.h"
chiniforooshan614d70a2017-03-17 01:19:3379#include "content/common/field_trial_recorder.mojom.h"
[email protected]82307f6b2014-08-07 03:30:1280#include "content/common/frame_messages.h"
raymesbba82b32016-07-19 00:41:3881#include "content/common/frame_owner_properties.h"
sunnyps8f9139e2017-05-12 17:53:2582#include "content/common/gpu_stream_constants.h"
avia7c3f51c2015-09-16 00:30:3183#include "content/common/render_process_messages.h"
[email protected]94dc971d2011-03-05 19:08:3284#include "content/common/resource_messages.h"
alexmos68734212016-08-27 00:06:3185#include "content/common/site_isolation_policy.h"
[email protected]778574e2011-03-21 22:03:5086#include "content/common/view_messages.h"
[email protected]0ec90d522014-03-12 16:28:1987#include "content/common/worker_messages.h"
[email protected]a458504b2012-07-23 19:57:0688#include "content/public/common/content_constants.h"
bashia6264042016-09-15 04:49:5189#include "content/public/common/content_features.h"
[email protected]433df472012-03-07 20:33:3990#include "content/public/common/content_paths.h"
[email protected]c08950d22011-10-13 22:20:2991#include "content/public/common/content_switches.h"
[email protected]daf82f82011-10-31 22:35:3192#include "content/public/common/renderer_preferences.h"
benbd9dc802017-04-19 01:37:4393#include "content/public/common/service_manager_connection.h"
ben649b3edd2017-03-23 00:32:0294#include "content/public/common/service_names.mojom.h"
benbd9dc802017-04-19 01:37:4395#include "content/public/common/simple_connection_filter.h"
[email protected]58436a12012-03-21 17:10:2696#include "content/public/common/url_constants.h"
[email protected]d344114c2011-10-01 01:24:3497#include "content/public/renderer/content_renderer_client.h"
tyoshino832a58a2016-04-18 08:14:0898#include "content/public/renderer/render_thread_observer.h"
[email protected]64ffa0442011-10-03 22:08:3699#include "content/public/renderer/render_view_visitor.h"
fsamuel6c1dfeb2014-12-18 19:21:33100#include "content/renderer/browser_plugin/browser_plugin_manager.h"
jsbell279efb42015-03-31 17:02:46101#include "content/renderer/cache_storage/cache_storage_dispatcher.h"
102#include "content/renderer/cache_storage/cache_storage_message_filter.h"
prashant.nfad657e2016-06-01 07:52:17103#include "content/renderer/categorized_worker_pool.h"
[email protected]70019152012-12-19 11:44:19104#include "content/renderer/devtools/devtools_agent_filter.h"
[email protected]1910fe82012-05-10 00:04:10105#include "content/renderer/dom_storage/dom_storage_dispatcher.h"
106#include "content/renderer/dom_storage/webstoragearea_impl.h"
107#include "content/renderer/dom_storage/webstoragenamespace_impl.h"
tbansalb612c5d2017-05-25 18:53:06108#include "content/renderer/effective_connection_type_helper.h"
simonhonga7e3ac42014-11-11 20:50:22109#include "content/renderer/gpu/compositor_external_begin_frame_source.h"
110#include "content/renderer/gpu/compositor_forwarding_message_filter.h"
danakj83066a32016-06-21 02:34:49111#include "content/renderer/gpu/frame_swap_message_queue.h"
[email protected]7a72d452013-12-13 10:01:13112#include "content/renderer/input/input_event_filter.h"
113#include "content/renderer/input/input_handler_manager.h"
jdduke691dd572014-12-02 20:47:52114#include "content/renderer/input/main_thread_input_event_filter.h"
[email protected]f7eb0a392011-07-12 10:19:51115#include "content/renderer/media/audio_input_message_filter.h"
116#include "content/renderer/media/audio_message_filter.h"
[email protected]3958e972012-07-17 00:25:41117#include "content/renderer/media/audio_renderer_mixer_manager.h"
Miguel Casas-Sanchezcfcca5d52017-07-07 02:32:59118#include "content/renderer/media/gpu/gpu_video_accelerator_factories_impl.h"
[email protected]d8cd8372012-03-09 10:49:51119#include "content/renderer/media/media_stream_center.h"
[email protected]a9875152013-06-22 04:03:03120#include "content/renderer/media/midi_message_filter.h"
xhwang194acae2014-11-12 22:46:33121#include "content/renderer/media/render_media_client.h"
[email protected]80b161a2011-06-27 17:42:11122#include "content/renderer/media/video_capture_impl_manager.h"
[email protected]d7ff5fb2014-05-29 19:50:25123#include "content/renderer/net_info_helper.h"
[email protected]4761cf12012-09-12 10:37:55124#include "content/renderer/p2p/socket_dispatcher.h"
[email protected]82307f6b2014-08-07 03:30:12125#include "content/renderer/render_frame_proxy.h"
[email protected]8704f89b2011-04-15 00:30:05126#include "content/renderer/render_process_impl.h"
[email protected]310ebd6302011-10-10 19:06:28127#include "content/renderer/render_view_impl.h"
tfarina556a7232014-10-05 01:02:09128#include "content/renderer/renderer_blink_platform_impl.h"
jdduke94ae1f32015-02-05 06:27:13129#include "content/renderer/scheduler/resource_dispatch_throttler.h"
shimazu5de409e42016-09-29 08:45:28130#include "content/renderer/service_worker/embedded_worker_instance_client_impl.h"
mek27c9d742015-07-16 18:30:18131#include "content/renderer/service_worker/service_worker_context_client.h"
kinuko5af4ffe2015-06-09 03:38:46132#include "content/renderer/service_worker/service_worker_context_message_filter.h"
[email protected]0ec90d522014-03-12 16:28:19133#include "content/renderer/shared_worker/embedded_shared_worker_stub.h"
juncai2f298a82017-04-18 03:51:39134#include "device/gamepad/public/cpp/gamepads.h"
chunyang.daibe874c52014-11-14 06:45:05135#include "gin/public/debug.h"
dongseong.hwang72183b02014-12-08 10:41:55136#include "gpu/GLES2/gl2extchromium.h"
danakj6f4e1e22016-04-20 03:27:34137#include "gpu/command_buffer/client/shared_memory_limits.h"
danakj870925d42016-05-03 20:07:38138#include "gpu/ipc/client/command_buffer_proxy_impl.h"
penghuang346a46f92016-03-31 21:37:52139#include "gpu/ipc/client/gpu_channel_host.h"
[email protected]46f36a492010-07-28 19:36:41140#include "ipc/ipc_channel_handle.h"
amistryd4aa70d2016-06-23 07:52:37141#include "ipc/ipc_channel_mojo.h"
[email protected]cb6037d2009-11-16 22:55:17142#include "ipc/ipc_platform_file.h"
[email protected]433df472012-03-07 20:33:39143#include "media/base/media.h"
chcunningham9a285ed2017-03-08 21:48:56144#include "media/base/media_switches.h"
Brett Wilson0748bf412016-11-22 17:55:46145#include "media/media_features.h"
servolk8b3b39b2015-03-03 19:08:18146#include "media/renderers/gpu_video_accelerator_factories.h"
rockot85dce0862015-11-13 01:33:59147#include "mojo/public/cpp/bindings/strong_binding.h"
[email protected]620161e2011-03-07 18:05:26148#include "net/base/net_errors.h"
eroman9ab64842015-07-21 05:07:52149#include "net/base/port_util.h"
hablichd6a4f122015-10-28 11:34:49150#include "net/base/registry_controlled_domains/registry_controlled_domain.h"
tfarina7a4a7fd2016-01-20 14:23:44151#include "net/base/url_util.h"
brettw4b461082016-11-19 18:55:16152#include "ppapi/features/features.h"
benbd9dc802017-04-19 01:37:43153#include "services/service_manager/public/cpp/binder_registry.h"
penghuangd6843e42016-12-17 13:57:20154#include "services/service_manager/public/cpp/connector.h"
rockot734fb662016-10-15 16:41:30155#include "services/service_manager/public/cpp/interface_provider.h"
sadrul85cc5d82016-12-20 03:37:41156#include "services/ui/public/cpp/gpu/context_provider_command_buffer.h"
penghuangd6843e42016-12-17 13:57:20157#include "services/ui/public/interfaces/constants.mojom.h"
[email protected]b48c53ad2014-02-05 21:59:18158#include "skia/ext/event_tracer_impl.h"
ssid59c969162015-07-28 13:02:58159#include "skia/ext/skia_memory_dump_provider.h"
kinukoed1ed1d2017-02-08 09:13:43160#include "third_party/WebKit/public/platform/WebCache.h"
reed6e5a72222015-08-06 20:37:16161#include "third_party/WebKit/public/platform/WebImageGenerator.h"
bashi5f4c78922016-08-18 23:06:08162#include "third_party/WebKit/public/platform/WebMemoryCoordinator.h"
kinukofbfee762017-03-08 04:01:06163#include "third_party/WebKit/public/platform/WebNetworkStateNotifier.h"
nverne61d2da872017-05-24 10:15:30164#include "third_party/WebKit/public/platform/WebRuntimeFeatures.h"
[email protected]89c36f82013-07-17 06:23:27165#include "third_party/WebKit/public/platform/WebString.h"
skyostil457b0a12014-09-09 10:12:07166#include "third_party/WebKit/public/platform/WebThread.h"
altiminc7369bf2017-04-11 14:29:15167#include "third_party/WebKit/public/platform/scheduler/child/webthread_base.h"
skyostil529caa292016-08-10 17:44:51168#include "third_party/WebKit/public/platform/scheduler/renderer/renderer_scheduler.h"
[email protected]2255a9332013-06-17 05:12:31169#include "third_party/WebKit/public/web/WebDatabase.h"
170#include "third_party/WebKit/public/web/WebDocument.h"
171#include "third_party/WebKit/public/web/WebFrame.h"
172#include "third_party/WebKit/public/web/WebKit.h"
[email protected]2255a9332013-06-17 05:12:31173#include "third_party/WebKit/public/web/WebScriptController.h"
174#include "third_party/WebKit/public/web/WebSecurityPolicy.h"
[email protected]2255a9332013-06-17 05:12:31175#include "third_party/WebKit/public/web/WebView.h"
David Benjaminb946811c2017-06-26 23:34:29176#include "third_party/boringssl/src/include/openssl/evp.h"
[email protected]ddbb53342014-01-06 10:59:47177#include "third_party/skia/include/core/SkGraphics.h"
[email protected]c49201a2012-05-24 11:04:57178#include "ui/base/layout.h"
[email protected]18ad6772011-09-20 21:51:32179#include "ui/base/ui_base_switches.h"
mlamouri7c149652017-03-24 00:00:09180#include "ui/display/display_switches.h"
ennee292bdc2016-09-15 19:57:15181#include "ui/gl/gl_switches.h"
[email protected]2c62b562009-01-27 19:04:50182
[email protected]33b02992014-03-01 01:06:29183#if defined(OS_ANDROID)
184#include <cpu-features.h>
boliubee541f42015-11-05 00:52:53185#include "content/renderer/android/synchronous_compositor_filter.h"
danakjc7afae52017-06-20 21:12:41186#include "content/renderer/android/synchronous_layer_tree_frame_sink.h"
boliue81d16132016-04-26 00:54:41187#include "content/renderer/media/android/stream_texture_factory.h"
dalecurtis88af3932016-02-20 00:12:20188#include "media/base/android/media_codec_util.h"
[email protected]33b02992014-03-01 01:06:29189#endif
190
191#if defined(OS_MACOSX)
ccamerona7644752014-12-30 01:16:31192#include "base/mac/mac_util.h"
lgrey023fd362017-06-08 19:20:52193#include "base/process/process.h"
194#include "content/common/mac/app_nap_activity.h"
rsesek1efb3c32015-09-29 15:39:50195#include "content/renderer/theme_helper_mac.h"
[email protected]33b02992014-03-01 01:06:29196#include "content/renderer/webscrollbarbehavior_impl_mac.h"
197#endif
198
[email protected]da00a2882009-03-09 17:51:19199#if defined(OS_WIN)
200#include <windows.h>
201#include <objbase.h>
202#endif
203
Brett Wilson0748bf412016-11-22 17:55:46204#if BUILDFLAG(ENABLE_WEBRTC)
liushouqun517b1292016-09-14 05:58:59205#include "content/renderer/media/aec_dump_message_filter.h"
[email protected]22fe91d2014-08-12 17:07:12206#include "content/renderer/media/peer_connection_tracker.h"
207#include "content/renderer/media/rtc_peer_connection_handler.h"
208#include "content/renderer/media/webrtc/peer_connection_dependency_factory.h"
[email protected]22fe91d2014-08-12 17:07:12209#endif
210
chunyang.daibe874c52014-11-14 06:45:05211#ifdef ENABLE_VTUNE_JIT_INTERFACE
212#include "v8/src/third_party/vtune/v8-vtune.h"
213#endif
214
bend32292b2016-10-07 00:21:58215#include "content/public/common/service_manager_connection.h"
fsamuel2545ecc2015-12-05 00:44:46216#include "content/renderer/mus/render_widget_window_tree_client_factory.h"
sadrul602ce1362017-01-26 06:41:10217#include "content/renderer/mus/renderer_window_tree_client.h"
sadrul04cfa892016-12-09 17:53:49218#include "services/ui/public/cpp/gpu/gpu.h"
fsamuel6c6da0232015-11-26 05:13:46219
ochangdd89a1e2016-06-08 16:39:01220#if defined(ENABLE_IPC_FUZZER)
221#include "content/common/external_ipc_dumper.h"
222#endif
223
tasakb46626a2016-10-18 05:54:44224#if defined(OS_MACOSX)
225#include <malloc/malloc.h>
226#else
227#include <malloc.h>
228#endif
229
[email protected]d293572a2013-05-23 18:50:45230using base::ThreadRestrictions;
[email protected]180ef242013-11-07 06:50:46231using blink::WebDocument;
232using blink::WebFrame;
233using blink::WebNetworkStateNotifier;
234using blink::WebRuntimeFeatures;
235using blink::WebScriptController;
236using blink::WebSecurityPolicy;
237using blink::WebString;
238using blink::WebView;
[email protected]e9ff79c2012-10-19 21:31:26239
240namespace content {
initial.commit09911bf2008-07-26 23:55:29241
[email protected]42f1d7822009-07-23 18:17:55242namespace {
[email protected]da9ccfb2012-01-28 00:34:40243
avi1023d012015-12-25 02:39:14244const int64_t kInitialIdleHandlerDelayMs = 1000;
245const int64_t kLongIdleHandlerDelayMs = 30 * 1000;
[email protected]bee16aab2009-08-26 15:55:03246
jdduke94ae1f32015-02-05 06:27:13247#if defined(OS_ANDROID)
248// On Android, resource messages can each take ~1.5ms to dispatch on the browser
249// IO thread. Limiting the message rate to 3/frame at 60hz ensures that the
250// induced work takes but a fraction (~1/4) of the overall frame budget.
251const int kMaxResourceRequestsPerFlushWhenThrottled = 3;
252#else
253const int kMaxResourceRequestsPerFlushWhenThrottled = 8;
254#endif
255const double kThrottledResourceRequestFlushPeriodS = 1. / 60.;
256
[email protected]dd2c1022014-07-22 23:13:57257// Maximum allocation size allowed for image scaling filters that
258// require pre-scaling. Skia will fallback to a filter that doesn't
259// require pre-scaling if the default filter would require an
260// allocation that exceeds this limit.
261const size_t kImageCacheSingleAllocationByteLimit = 64 * 1024 * 1024;
262
samans2040988b2017-04-11 23:58:35263#if defined(OS_ANDROID)
danakj83066a32016-06-21 02:34:49264// Unique identifier for each output surface created.
danakjc7afae52017-06-20 21:12:41265uint32_t g_next_layer_tree_frame_sink_id = 1;
samans2040988b2017-04-11 23:58:35266#endif
danakj83066a32016-06-21 02:34:49267
rockot5c478a72016-09-28 23:14:18268// An implementation of mojom::RenderMessageFilter which can be mocked out
269// for tests which may indirectly send messages over this interface.
270mojom::RenderMessageFilter* g_render_message_filter_for_testing;
271
olegmax045f7fb12017-05-19 07:58:55272// An implementation of RendererBlinkPlatformImpl which can be mocked out
273// for tests.
274RendererBlinkPlatformImpl* g_current_blink_platform_impl_for_testing;
275
[email protected]f1a29a02011-10-06 23:08:44276// Keep the global RenderThreadImpl in a TLS slot so it is impossible to access
[email protected]f3ede412010-06-21 22:52:16277// incorrectly from the wrong thread.
scottmg5e65e3a2017-03-08 08:48:46278base::LazyInstance<base::ThreadLocalPointer<RenderThreadImpl>>::DestructorAtExit
[email protected]6de0fd1d2011-11-15 13:31:49279 lazy_tls = LAZY_INSTANCE_INITIALIZER;
[email protected]1edc16b82009-04-07 17:45:54280
hong.zhengb28b5332016-05-11 02:33:39281// v8::MemoryPressureLevel should correspond to base::MemoryPressureListener.
282static_assert(static_cast<v8::MemoryPressureLevel>(
283 base::MemoryPressureListener::MEMORY_PRESSURE_LEVEL_NONE) ==
284 v8::MemoryPressureLevel::kNone, "none level not align");
285static_assert(static_cast<v8::MemoryPressureLevel>(
286 base::MemoryPressureListener::MEMORY_PRESSURE_LEVEL_MODERATE) ==
287 v8::MemoryPressureLevel::kModerate, "moderate level not align");
288static_assert(static_cast<v8::MemoryPressureLevel>(
289 base::MemoryPressureListener::MEMORY_PRESSURE_LEVEL_CRITICAL) ==
290 v8::MemoryPressureLevel::kCritical, "critical level not align");
291
hong.zheng2e296f822016-06-29 02:47:44292// WebMemoryPressureLevel should correspond to base::MemoryPressureListener.
293static_assert(static_cast<blink::WebMemoryPressureLevel>(
Blink Reformat1c4d759e2017-04-09 16:34:54294 base::MemoryPressureListener::MEMORY_PRESSURE_LEVEL_NONE) ==
295 blink::kWebMemoryPressureLevelNone,
296 "blink::WebMemoryPressureLevelNone not align");
297static_assert(
298 static_cast<blink::WebMemoryPressureLevel>(
299 base::MemoryPressureListener::MEMORY_PRESSURE_LEVEL_MODERATE) ==
300 blink::kWebMemoryPressureLevelModerate,
301 "blink::WebMemoryPressureLevelModerate not align");
302static_assert(
303 static_cast<blink::WebMemoryPressureLevel>(
304 base::MemoryPressureListener::MEMORY_PRESSURE_LEVEL_CRITICAL) ==
305 blink::kWebMemoryPressureLevelCritical,
306 "blink::WebMemoryPressureLevelCritical not align");
hong.zheng2e296f822016-06-29 02:47:44307
[email protected]b2d98762012-09-03 17:04:06308void* CreateHistogram(
[email protected]d1b8fccc2011-08-03 01:20:13309 const char *name, int min, int max, size_t buckets) {
310 if (min <= 0)
311 min = 1;
[email protected]b2d98762012-09-03 17:04:06312 std::string histogram_name;
313 RenderThreadImpl* render_thread_impl = RenderThreadImpl::current();
314 if (render_thread_impl) { // Can be null in tests.
315 histogram_name = render_thread_impl->
316 histogram_customizer()->ConvertToCustomHistogramName(name);
317 } else {
318 histogram_name = std::string(name);
319 }
[email protected]de415552013-01-23 04:12:17320 base::HistogramBase* histogram = base::Histogram::FactoryGet(
[email protected]b2d98762012-09-03 17:04:06321 histogram_name, min, max, buckets,
322 base::Histogram::kUmaTargetedHistogramFlag);
[email protected]d1b8fccc2011-08-03 01:20:13323 return histogram;
324}
325
[email protected]b2d98762012-09-03 17:04:06326void AddHistogramSample(void* hist, int sample) {
[email protected]d1b8fccc2011-08-03 01:20:13327 base::Histogram* histogram = static_cast<base::Histogram*>(hist);
328 histogram->Add(sample);
329}
330
ben76f52b242016-06-18 05:42:48331class FrameFactoryImpl : public mojom::FrameFactory {
rockotf8fdd9b2015-12-16 22:22:35332 public:
benf28ce882017-05-02 16:15:49333 explicit FrameFactoryImpl(const service_manager::BindSourceInfo& source_info)
334 : source_info_(source_info), routing_id_highmark_(-1) {}
rockotf8fdd9b2015-12-16 22:22:35335
ben76f52b242016-06-18 05:42:48336 private:
337 // mojom::FrameFactory:
csharrison95f01e922017-04-24 18:52:35338 void CreateFrame(
339 int32_t frame_routing_id,
340 mojom::FrameRequest frame_request,
341 mojom::FrameHostInterfaceBrokerPtr frame_host_interface_broker) override {
rockotf8fdd9b2015-12-16 22:22:35342 // TODO(morrita): This is for investigating http://crbug.com/415059 and
343 // should be removed once it is fixed.
344 CHECK_LT(routing_id_highmark_, frame_routing_id);
345 routing_id_highmark_ = frame_routing_id;
346
347 RenderFrameImpl* frame = RenderFrameImpl::FromRoutingID(frame_routing_id);
348 // We can receive a GetServiceProviderForFrame message for a frame not yet
rockot067ca55f2016-09-30 22:00:15349 // created due to a race between the message and a
350 // mojom::Renderer::CreateView IPC that triggers creation of the RenderFrame
351 // we want.
rockotf8fdd9b2015-12-16 22:22:35352 if (!frame) {
ben76f52b242016-06-18 05:42:48353 RenderThreadImpl::current()->RegisterPendingFrameCreate(
benf28ce882017-05-02 16:15:49354 source_info_, frame_routing_id, std::move(frame_request),
csharrison95f01e922017-04-24 18:52:35355 std::move(frame_host_interface_broker));
rockotf8fdd9b2015-12-16 22:22:35356 return;
357 }
358
benf28ce882017-05-02 16:15:49359 frame->BindFrame(source_info_, std::move(frame_request),
csharrison95f01e922017-04-24 18:52:35360 std::move(frame_host_interface_broker));
rockotf8fdd9b2015-12-16 22:22:35361 }
362
363 private:
benf28ce882017-05-02 16:15:49364 service_manager::BindSourceInfo source_info_;
rockotf8fdd9b2015-12-16 22:22:35365 int32_t routing_id_highmark_;
rockotf8fdd9b2015-12-16 22:22:35366};
367
benf28ce882017-05-02 16:15:49368void CreateFrameFactory(const service_manager::BindSourceInfo& source_info,
369 mojom::FrameFactoryRequest request) {
370 mojo::MakeStrongBinding(base::MakeUnique<FrameFactoryImpl>(source_info),
rockot8e66a08d2016-09-13 00:48:21371 std::move(request));
rockotf8fdd9b2015-12-16 22:22:35372}
373
sadrul85cc5d82016-12-20 03:37:41374scoped_refptr<ui::ContextProviderCommandBuffer> CreateOffscreenContext(
danakjc3983552016-05-03 00:04:35375 scoped_refptr<gpu::GpuChannelHost> gpu_channel_host,
danakj0dd9e1e2016-05-11 22:15:09376 const gpu::SharedMemoryLimits& limits,
danakj9a04adc2016-05-16 22:45:07377 bool support_locking,
sadrul85cc5d82016-12-20 03:37:41378 ui::command_buffer_metrics::ContextType type,
sunnypsd8ce1c22016-05-10 18:02:40379 int32_t stream_id,
sunnyps8f9139e2017-05-12 17:53:25380 gpu::SchedulingPriority stream_priority) {
danakje8ec797e2016-04-19 04:08:43381 DCHECK(gpu_channel_host);
382 // This is used to create a few different offscreen contexts:
383 // - The shared main thread context (offscreen) used by blink for canvas.
384 // - The worker context (offscreen) used for GPU raster and video decoding.
385 // This is for an offscreen context, so the default framebuffer doesn't need
386 // alpha, depth, stencil, antialiasing.
387 gpu::gles2::ContextCreationAttribHelper attributes;
388 attributes.alpha_size = -1;
389 attributes.depth_size = 0;
390 attributes.stencil_size = 0;
391 attributes.samples = 0;
392 attributes.sample_buffers = 0;
393 attributes.bind_generates_resource = false;
394 attributes.lose_context_when_out_of_memory = true;
sunnypsd8ce1c22016-05-10 18:02:40395 const bool automatic_flushes = false;
sadrul85cc5d82016-12-20 03:37:41396 return make_scoped_refptr(new ui::ContextProviderCommandBuffer(
sunnypsd8ce1c22016-05-10 18:02:40397 std::move(gpu_channel_host), stream_id, stream_priority,
398 gpu::kNullSurfaceHandle,
zmo09ea813b2017-01-20 23:38:36399 GURL("chrome://gpu/RenderThreadImpl::CreateOffscreenContext/" +
400 ui::command_buffer_metrics::ContextTypeToString(type)),
pimand488e8b42016-06-30 19:06:59401 automatic_flushes, support_locking, limits, attributes, nullptr, type));
danakje8ec797e2016-04-19 04:08:43402}
403
penghuange1d86512016-07-08 18:15:00404bool IsRunningInMash() {
405 const base::CommandLine* cmdline = base::CommandLine::ForCurrentProcess();
406 return cmdline->HasSwitch(switches::kIsRunningInMash);
407}
408
dalecurtis4a9839a2017-05-04 23:40:47409// Hook that allows single-sample metric code from //components/metrics to
410// connect from the renderer process to the browser process.
411void CreateSingleSampleMetricsProvider(
412 scoped_refptr<base::SingleThreadTaskRunner> task_runner,
413 service_manager::Connector* connector,
414 metrics::mojom::SingleSampleMetricsProviderRequest request) {
415 if (task_runner->BelongsToCurrentThread()) {
416 connector->BindInterface(mojom::kBrowserServiceName, std::move(request));
417 return;
418 }
419
420 task_runner->PostTask(
421 FROM_HERE,
422 base::Bind(&CreateSingleSampleMetricsProvider, std::move(task_runner),
423 connector, base::Passed(&request)));
424}
425
samans7e6675cc2017-06-05 20:16:08426class RendererLocalSurfaceIdProvider : public viz::LocalSurfaceIdProvider {
427 public:
428 const cc::LocalSurfaceId& GetLocalSurfaceIdForFrame(
429 const cc::CompositorFrame& frame) override {
430 auto new_surface_properties =
431 RenderWidgetSurfaceProperties::FromCompositorFrame(frame);
432 if (!local_surface_id_.is_valid() ||
433 new_surface_properties != surface_properties_) {
434 local_surface_id_ = local_surface_id_allocator_.GenerateId();
435 surface_properties_ = new_surface_properties;
436 }
437 return local_surface_id_;
438 }
439
440 private:
441 cc::LocalSurfaceIdAllocator local_surface_id_allocator_;
442 cc::LocalSurfaceId local_surface_id_;
443 RenderWidgetSurfaceProperties surface_properties_;
444};
445
[email protected]b2d98762012-09-03 17:04:06446} // namespace
447
[email protected]b2d98762012-09-03 17:04:06448RenderThreadImpl::HistogramCustomizer::HistogramCustomizer() {
449 custom_histograms_.insert("V8.MemoryExternalFragmentationTotal");
450 custom_histograms_.insert("V8.MemoryHeapSampleTotalCommitted");
451 custom_histograms_.insert("V8.MemoryHeapSampleTotalUsed");
hablich4598ddc2015-11-07 18:37:28452 custom_histograms_.insert("V8.MemoryHeapUsed");
453 custom_histograms_.insert("V8.MemoryHeapCommitted");
[email protected]b2d98762012-09-03 17:04:06454}
455
456RenderThreadImpl::HistogramCustomizer::~HistogramCustomizer() {}
457
458void RenderThreadImpl::HistogramCustomizer::RenderViewNavigatedToHost(
459 const std::string& host, size_t view_count) {
avi83883c82014-12-23 00:08:49460 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
461 switches::kDisableHistogramCustomizer)) {
[email protected]9baee832012-12-10 11:07:15462 return;
463 }
[email protected]b2d98762012-09-03 17:04:06464 // Check if all RenderViews are displaying a page from the same host. If there
465 // is only one RenderView, the common host is this view's host. If there are
466 // many, check if this one shares the common host of the other
467 // RenderViews. It's ok to not detect some cases where the RenderViews share a
468 // common host. This information is only used for producing custom histograms.
469 if (view_count == 1)
470 SetCommonHost(host);
471 else if (host != common_host_)
472 SetCommonHost(std::string());
473}
474
475std::string RenderThreadImpl::HistogramCustomizer::ConvertToCustomHistogramName(
476 const char* histogram_name) const {
477 std::string name(histogram_name);
478 if (!common_host_histogram_suffix_.empty() &&
479 custom_histograms_.find(name) != custom_histograms_.end())
480 name += common_host_histogram_suffix_;
481 return name;
482}
483
484void RenderThreadImpl::HistogramCustomizer::SetCommonHost(
485 const std::string& host) {
486 if (host != common_host_) {
487 common_host_ = host;
488 common_host_histogram_suffix_ = HostToCustomHistogramSuffix(host);
Blink Reformat1c4d759e2017-04-09 16:34:54489 blink::MainThreadIsolate()->SetCreateHistogramFunction(CreateHistogram);
[email protected]b2d98762012-09-03 17:04:06490 }
491}
492
hablichd6a4f122015-10-28 11:34:49493std::string RenderThreadImpl::HistogramCustomizer::HostToCustomHistogramSuffix(
494 const std::string& host) {
495 if (host == "mail.google.com")
496 return ".gmail";
497 if (host == "docs.google.com" || host == "drive.google.com")
498 return ".docs";
499 if (host == "plus.google.com")
500 return ".plus";
501 if (host == "inbox.google.com")
502 return ".inbox";
hpayerdd4def052016-02-06 19:06:10503 if (host == "calendar.google.com")
504 return ".calendar";
hablichd6a4f122015-10-28 11:34:49505 if (host == "www.youtube.com")
506 return ".youtube";
507 if (IsAlexaTop10NonGoogleSite(host))
508 return ".top10";
509
510 return std::string();
511}
512
513bool RenderThreadImpl::HistogramCustomizer::IsAlexaTop10NonGoogleSite(
514 const std::string& host) {
515 // The Top10 sites have different TLD and/or subdomains depending on the
516 // localization.
517 if (host == "sina.com.cn")
518 return true;
519
520 std::string sanitized_host =
521 net::registry_controlled_domains::GetDomainAndRegistry(
522 host, net::registry_controlled_domains::INCLUDE_PRIVATE_REGISTRIES);
523
524 if (sanitized_host == "facebook.com")
525 return true;
526 if (sanitized_host == "baidu.com")
527 return true;
528 if (sanitized_host == "qq.com")
529 return true;
530 if (sanitized_host == "twitter.com")
531 return true;
532 if (sanitized_host == "taobao.com")
533 return true;
534 if (sanitized_host == "live.com")
535 return true;
536
537 if (!sanitized_host.empty()) {
538 std::vector<base::StringPiece> host_tokens = base::SplitStringPiece(
539 sanitized_host, ".", base::TRIM_WHITESPACE, base::SPLIT_WANT_NONEMPTY);
540
541 if (host_tokens.size() >= 2) {
542 if ((host_tokens[0] == "yahoo") || (host_tokens[0] == "amazon") ||
543 (host_tokens[0] == "wikipedia")) {
544 return true;
545 }
546 }
547 }
548 return false;
549}
550
leon.han2c0f9f12015-07-11 02:01:19551// static
552RenderThreadImpl* RenderThreadImpl::Create(
553 const InProcessChildThreadParams& params) {
skyostil529caa292016-08-10 17:44:51554 std::unique_ptr<blink::scheduler::RendererScheduler> renderer_scheduler =
555 blink::scheduler::RendererScheduler::Create();
jam75c44222016-03-23 05:34:24556 scoped_refptr<base::SingleThreadTaskRunner> test_task_counter;
557 return new RenderThreadImpl(
558 params, std::move(renderer_scheduler), test_task_counter);
leon.han2c0f9f12015-07-11 02:01:19559}
560
561// static
562RenderThreadImpl* RenderThreadImpl::Create(
dchengcedca5612016-04-09 01:40:15563 std::unique_ptr<base::MessageLoop> main_message_loop,
skyostil529caa292016-08-10 17:44:51564 std::unique_ptr<blink::scheduler::RendererScheduler> renderer_scheduler) {
dcheng07945f632015-12-26 07:59:32565 return new RenderThreadImpl(std::move(main_message_loop),
566 std::move(renderer_scheduler));
leon.han2c0f9f12015-07-11 02:01:19567}
568
rockot5c478a72016-09-28 23:14:18569// static
[email protected]f1a29a02011-10-06 23:08:44570RenderThreadImpl* RenderThreadImpl::current() {
[email protected]526476902011-10-06 20:34:06571 return lazy_tls.Pointer()->Get();
572}
573
rockot5c478a72016-09-28 23:14:18574// static
575mojom::RenderMessageFilter* RenderThreadImpl::current_render_message_filter() {
576 if (g_render_message_filter_for_testing)
577 return g_render_message_filter_for_testing;
578 DCHECK(current());
579 return current()->render_message_filter();
580}
581
582// static
olegmax045f7fb12017-05-19 07:58:55583RendererBlinkPlatformImpl* RenderThreadImpl::current_blink_platform_impl() {
584 if (g_current_blink_platform_impl_for_testing)
585 return g_current_blink_platform_impl_for_testing;
586 DCHECK(current());
587 return current()->blink_platform_impl();
588}
589
590// static
rockot5c478a72016-09-28 23:14:18591void RenderThreadImpl::SetRenderMessageFilterForTesting(
592 mojom::RenderMessageFilter* render_message_filter) {
593 g_render_message_filter_for_testing = render_message_filter;
594}
595
olegmax045f7fb12017-05-19 07:58:55596// static
597void RenderThreadImpl::SetRendererBlinkPlatformImplForTesting(
598 RendererBlinkPlatformImpl* blink_platform_impl) {
599 g_current_blink_platform_impl_for_testing = blink_platform_impl;
600}
601
staraz067f58242016-11-07 21:06:41602// In single-process mode used for debugging, we don't pass a renderer client
603// ID via command line because RenderThreadImpl lives in the same process as
604// the browser
leon.han2c0f9f12015-07-11 02:01:19605RenderThreadImpl::RenderThreadImpl(
606 const InProcessChildThreadParams& params,
skyostil529caa292016-08-10 17:44:51607 std::unique_ptr<blink::scheduler::RendererScheduler> scheduler,
rockot97a86832016-12-10 04:53:06608 const scoped_refptr<base::SingleThreadTaskRunner>& resource_task_queue)
morritac6238ab2015-03-18 01:48:29609 : ChildThreadImpl(Options::Builder()
prashant.nfad657e2016-06-01 07:52:17610 .InBrowserProcess(params)
bend32292b2016-10-07 00:21:58611 .AutoStartServiceManagerConnection(false)
ben5be0b9132016-08-03 00:17:18612 .ConnectToBrowser(true)
prashant.nfad657e2016-06-01 07:52:17613 .Build()),
dcheng07945f632015-12-26 07:59:32614 renderer_scheduler_(std::move(scheduler)),
rockot067ca55f2016-09-30 22:00:15615 categorized_worker_pool_(new CategorizedWorkerPool()),
staraz067f58242016-11-07 21:06:41616 renderer_binding_(this),
chiniforooshan614d70a2017-03-17 01:19:33617 client_id_(1),
618 field_trial_syncer_(this) {
jam75c44222016-03-23 05:34:24619 Init(resource_task_queue);
morritac6238ab2015-03-18 01:48:29620}
621
[email protected]42f1d7822009-07-23 18:17:55622// When we run plugins in process, we actually run them on the render thread,
623// which means that we need to make the render thread pump UI events.
haraken53f081d2014-11-11 01:03:40624RenderThreadImpl::RenderThreadImpl(
dchengcedca5612016-04-09 01:40:15625 std::unique_ptr<base::MessageLoop> main_message_loop,
skyostil529caa292016-08-10 17:44:51626 std::unique_ptr<blink::scheduler::RendererScheduler> scheduler)
rockotcef38272016-07-15 22:47:47627 : ChildThreadImpl(Options::Builder()
bend32292b2016-10-07 00:21:58628 .AutoStartServiceManagerConnection(false)
ben5be0b9132016-08-03 00:17:18629 .ConnectToBrowser(true)
rockotcef38272016-07-15 22:47:47630 .Build()),
dcheng07945f632015-12-26 07:59:32631 renderer_scheduler_(std::move(scheduler)),
632 main_message_loop_(std::move(main_message_loop)),
rockot067ca55f2016-09-30 22:00:15633 categorized_worker_pool_(new CategorizedWorkerPool()),
wjmaclean1d970622017-01-21 22:28:24634 is_scroll_animator_enabled_(false),
chiniforooshan614d70a2017-03-17 01:19:33635 renderer_binding_(this),
636 field_trial_syncer_(this) {
jam75c44222016-03-23 05:34:24637 scoped_refptr<base::SingleThreadTaskRunner> test_task_counter;
staraz067f58242016-11-07 21:06:41638 DCHECK(base::CommandLine::ForCurrentProcess()->HasSwitch(
639 switches::kRendererClientId));
640 base::StringToInt(base::CommandLine::ForCurrentProcess()->GetSwitchValueASCII(
641 switches::kRendererClientId),
642 &client_id_);
jam75c44222016-03-23 05:34:24643 Init(test_task_counter);
haraken53f081d2014-11-11 01:03:40644}
645
jam75c44222016-03-23 05:34:24646void RenderThreadImpl::Init(
rockot97a86832016-12-10 04:53:06647 const scoped_refptr<base::SingleThreadTaskRunner>& resource_task_queue) {
fdorayf6d86242015-10-08 16:49:53648 TRACE_EVENT0("startup", "RenderThreadImpl::Init");
[email protected]a872ea1f2010-08-11 04:45:33649
ssidb2e3ece2015-02-09 16:02:20650 base::trace_event::TraceLog::GetInstance()->SetThreadSortIndex(
[email protected]91a2aea2013-07-08 23:14:39651 base::PlatformThread::CurrentId(),
652 kTraceEventRendererMainThreadSortIndex);
653
thakis18e426412017-03-15 12:06:37654#if BUILDFLAG(USE_EXTERNAL_POPUP_MENU)
sievers9dff72052015-11-16 18:35:57655 // On Mac and Android Java UI, the select popups are rendered by the browser.
Blink Reformat1c4d759e2017-04-09 16:34:54656 blink::WebView::SetUseExternalPopupMenus(true);
[email protected]53c607c2011-03-21 23:19:04657#endif
658
[email protected]94f9a0f682009-06-15 18:30:30659 lazy_tls.Pointer()->Set(this);
[email protected]b3e83de2012-02-07 03:33:28660
[email protected]06c694d2012-02-01 22:26:16661 // Register this object as the main thread.
662 ChildProcess::current()->set_main_thread(this);
663
dalecurtis4a9839a2017-05-04 23:40:47664 metrics::InitializeSingleSampleMetricsFactory(
665 base::BindRepeating(&CreateSingleSampleMetricsProvider,
666 message_loop()->task_runner(), GetConnector()));
667
ben649b3edd2017-03-23 00:32:02668 gpu_ = ui::Gpu::Create(
669 GetConnector(),
670 IsRunningInMash() ? ui::mojom::kServiceName : mojom::kBrowserServiceName,
671 GetIOTaskRunner());
penghuange1d86512016-07-08 18:15:00672
danakj92429852017-06-29 00:19:03673 cc::mojom::SharedBitmapAllocationNotifierAssociatedPtr
674 shared_bitmap_allocation_notifier_ptr;
675 render_message_filter()->GetSharedBitmapAllocationNotifier(
676 mojo::MakeRequest(&shared_bitmap_allocation_notifier_ptr));
677 shared_bitmap_manager_ = base::MakeUnique<viz::ClientSharedBitmapManager>(
678 cc::mojom::ThreadSafeSharedBitmapAllocationNotifierAssociatedPtr::Create(
679 shared_bitmap_allocation_notifier_ptr.PassInterface(),
680 GetChannel()->ipc_task_runner_refptr()));
jcivelli0f21bd52016-12-07 21:21:33681
jam75c44222016-03-23 05:34:24682 InitializeWebKit(resource_task_queue);
683
[email protected]31f87132010-04-21 23:36:21684 // In single process the single process is all there is.
[email protected]26e82322014-01-20 14:18:22685 webkit_shared_timer_suspended_ = false;
[email protected]bee16aab2009-08-26 15:55:03686 widget_count_ = 0;
687 hidden_widget_count_ = 0;
[email protected]6593ae12011-11-14 12:09:44688 idle_notification_delay_in_ms_ = kInitialIdleHandlerDelayMs;
[email protected]1784b2f2011-11-24 10:53:48689 idle_notifications_to_skip_ = 0;
[email protected]8d86fce2009-02-26 23:37:55690
[email protected]d5b2fdf2013-06-05 09:36:55691 appcache_dispatcher_.reset(
[email protected]a8cb3b73b2013-08-12 05:50:50692 new AppCacheDispatcher(Get(), new AppCacheFrontendImpl()));
[email protected]1910fe82012-05-10 00:04:10693 dom_storage_dispatcher_.reset(new DomStorageDispatcher());
reillyg39fb4662016-11-22 20:27:17694 main_thread_indexed_db_dispatcher_.reset(new IndexedDBDispatcher());
jsbellabadb9b2015-03-23 21:03:44695 main_thread_cache_storage_dispatcher_.reset(
jsbell279efb42015-03-31 17:02:46696 new CacheStorageDispatcher(thread_safe_sender()));
[email protected]dd9241932010-02-24 19:23:13697
jdduke94ae1f32015-02-05 06:27:13698 // Note: This may reorder messages from the ResourceDispatcher with respect to
699 // other subsystems.
700 resource_dispatch_throttler_.reset(new ResourceDispatchThrottler(
701 static_cast<RenderThread*>(this), renderer_scheduler_.get(),
702 base::TimeDelta::FromSecondsD(kThrottledResourceRequestFlushPeriodS),
703 kMaxResourceRequestsPerFlushWhenThrottled));
704 resource_dispatcher()->set_message_sender(resource_dispatch_throttler_.get());
705
thestig529ad8a2016-07-08 20:30:12706 blob_message_filter_ = new BlobMessageFilter(GetFileThreadTaskRunner());
dmurph1fb98482016-03-30 21:14:26707 AddFilter(blob_message_filter_.get());
[email protected]017022b2009-07-27 23:06:34708 db_message_filter_ = new DBMessageFilter();
709 AddFilter(db_message_filter_.get());
[email protected]dd9241932010-02-24 19:23:13710
[email protected]45048072014-01-14 13:51:29711 vc_manager_.reset(new VideoCaptureImplManager());
[email protected]c9c43a02013-12-17 08:59:54712
fsamuel6c1dfeb2014-12-18 19:21:33713 browser_plugin_manager_.reset(new BrowserPluginManager());
714 AddObserver(browser_plugin_manager_.get());
715
Brett Wilson0748bf412016-11-22 17:55:46716#if BUILDFLAG(ENABLE_WEBRTC)
[email protected]af089972013-01-10 04:04:40717 peer_connection_tracker_.reset(new PeerConnectionTracker());
718 AddObserver(peer_connection_tracker_.get());
719
thestig529ad8a2016-07-08 20:30:12720 p2p_socket_dispatcher_ = new P2PSocketDispatcher(GetIOTaskRunner().get());
[email protected]fc72bb12013-06-02 21:13:46721 AddFilter(p2p_socket_dispatcher_.get());
[email protected]921480f62013-07-20 03:42:57722
ivocadd54f0d2015-12-18 23:17:05723 peer_connection_factory_.reset(
724 new PeerConnectionDependencyFactory(p2p_socket_dispatcher_.get()));
725
skyostil2d3b5bd2015-05-27 15:40:59726 aec_dump_message_filter_ = new AecDumpMessageFilter(
thestig529ad8a2016-07-08 20:30:12727 GetIOTaskRunner(), message_loop()->task_runner());
ivocadd54f0d2015-12-18 23:17:05728
[email protected]da9f30a2014-06-18 19:39:04729 AddFilter(aec_dump_message_filter_.get());
730
Brett Wilson0748bf412016-11-22 17:55:46731#endif // BUILDFLAG(ENABLE_WEBRTC)
[email protected]e25f4d72011-06-08 20:58:46732
thestig529ad8a2016-07-08 20:30:12733 audio_input_message_filter_ = new AudioInputMessageFilter(GetIOTaskRunner());
[email protected]f7eb0a392011-07-12 10:19:51734 AddFilter(audio_input_message_filter_.get());
735
Max Morind4c4887d2017-06-08 07:41:34736 scoped_refptr<AudioMessageFilter> audio_message_filter;
737 if (!base::FeatureList::IsEnabled(
738 features::kUseMojoAudioOutputStreamFactory)) {
739 // In case we shouldn't use mojo factories, we need to create an
740 // AudioMessageFilter which |audio_ipc_factory_| can use for IPC.
741 audio_message_filter =
742 base::MakeRefCounted<AudioMessageFilter>(GetIOTaskRunner());
743 AddFilter(audio_message_filter.get());
744 }
745
maxmorin017ba8c62017-06-02 10:23:09746 audio_ipc_factory_.emplace(std::move(audio_message_filter),
747 GetIOTaskRunner());
[email protected]f7eb0a392011-07-12 10:19:51748
thestig529ad8a2016-07-08 20:30:12749 midi_message_filter_ = new MidiMessageFilter(GetIOTaskRunner());
[email protected]a9875152013-06-22 04:03:03750 AddFilter(midi_message_filter_.get());
751
jsbellabadb9b2015-03-23 21:03:44752 AddFilter((new CacheStorageMessageFilter(thread_safe_sender()))->GetFilter());
753
kinuko5af4ffe2015-06-09 03:38:46754 AddFilter((new ServiceWorkerContextMessageFilter())->GetFilter());
[email protected]ddbb53342014-01-06 10:59:47755
sadrul943e3b32016-08-04 18:22:59756#if defined(USE_AURA)
fsamuel098eade2017-03-21 18:06:14757 if (IsRunningInMash()) {
bend32292b2016-10-07 00:21:58758 CreateRenderWidgetWindowTreeClientFactory(GetServiceManagerConnection());
rockotcef38272016-07-15 22:47:47759 }
760#endif
761
benbd9dc802017-04-19 01:37:43762 auto registry = base::MakeUnique<service_manager::BinderRegistry>();
763 registry->AddInterface(base::Bind(&CreateFrameFactory),
764 base::ThreadTaskRunnerHandle::Get());
Matt Falkenhagen38ab68b2017-06-28 08:33:23765 registry->AddInterface(base::Bind(&EmbeddedWorkerInstanceClientImpl::Create,
766 base::TimeTicks::Now()),
benbd9dc802017-04-19 01:37:43767 base::ThreadTaskRunnerHandle::Get());
768 GetServiceManagerConnection()->AddConnectionFilter(
769 base::MakeUnique<SimpleConnectionFilter>(std::move(registry)));
rockotcef38272016-07-15 22:47:47770
[email protected]e9ff79c2012-10-19 21:31:26771 GetContentClient()->renderer()->RenderThreadStarted();
[email protected]6779aa12011-03-29 17:32:24772
benbd9dc802017-04-19 01:37:43773 StartServiceManagerConnection();
774
chiniforooshan614d70a2017-03-17 01:19:33775 field_trial_syncer_.InitFieldTrialObserving(
776 *base::CommandLine::ForCurrentProcess(), switches::kSingleProcess);
777
rockot067ca55f2016-09-30 22:00:15778 GetAssociatedInterfaceRegistry()->AddInterface(
779 base::Bind(&RenderThreadImpl::OnRendererInterfaceRequest,
780 base::Unretained(this)));
781
[email protected]b48c53ad2014-02-05 21:59:18782 InitSkiaEventTracer();
ssid59c969162015-07-28 13:02:58783 base::trace_event::MemoryDumpManager::GetInstance()->RegisterDumpProvider(
primiano186d6bfe2015-10-30 13:21:40784 skia::SkiaMemoryDumpProvider::GetInstance(), "Skia", nullptr);
[email protected]b48c53ad2014-02-05 21:59:18785
avi83883c82014-12-23 00:08:49786 const base::CommandLine& command_line =
787 *base::CommandLine::ForCurrentProcess();
[email protected]e54ab492012-06-12 19:40:01788
ochangdd89a1e2016-06-08 16:39:01789#if defined(ENABLE_IPC_FUZZER)
790 if (command_line.HasSwitch(switches::kIpcDumpDirectory)) {
791 base::FilePath dump_directory =
792 command_line.GetSwitchValuePath(switches::kIpcDumpDirectory);
793 IPC::ChannelProxy::OutgoingMessageFilter* filter =
794 LoadExternalIPCDumper(dump_directory);
795 GetChannel()->set_outgoing_message_filter(filter);
796 }
797#endif
798
jbroman0d302162015-09-05 05:46:23799 cc::SetClientNameForMetrics("Renderer");
loysoa6edaaff2015-05-25 03:26:44800
loyso65c93c602015-08-11 05:15:57801 is_threaded_animation_enabled_ =
802 !command_line.HasSwitch(cc::switches::kDisableThreadedAnimation);
803
reveman91a0a872014-11-04 03:40:32804 is_zero_copy_enabled_ = command_line.HasSwitch(switches::kEnableZeroCopy);
ericrk1d17f752015-10-20 03:03:07805 is_partial_raster_enabled_ =
dongseong.hwang23db47f2016-03-08 07:50:02806 !command_line.HasSwitch(switches::kDisablePartialRaster);
ccameronc7fcd132015-11-03 20:14:31807 is_gpu_memory_buffer_compositor_resources_enabled_ = command_line.HasSwitch(
808 switches::kEnableGpuMemoryBufferCompositorResources);
[email protected]a23530d2014-03-11 06:04:14809
jame1f453c2016-03-21 15:51:34810#if defined(OS_MACOSX)
thakis114a1ef2016-04-26 16:02:59811 base::ScopedCFTypeRef<CFStringRef> key(
812 base::SysUTF8ToCFStringRef("NSScrollViewRubberbanding"));
813 Boolean key_exists = false;
814 Boolean value = CFPreferencesGetAppBooleanValue(
815 key, kCFPreferencesCurrentApplication, &key_exists);
816 is_elastic_overscroll_enabled_ = !key_exists || value;
lgrey023fd362017-06-08 19:20:52817
818 if (base::Process::IsAppNapEnabled()) {
819 AppNapActivity::InitializeAppNapSupport();
820 }
ccamerona7644752014-12-30 01:16:31821#else
822 is_elastic_overscroll_enabled_ = false;
823#endif
824
danakje6eb185c2015-02-27 23:52:05825 std::string image_texture_target_string =
dcastagna7f2f7192015-06-16 18:44:35826 command_line.GetSwitchValueASCII(switches::kContentImageTextureTarget);
ericrk9151705c2016-07-26 19:53:16827 buffer_to_texture_target_map_ =
Fady Samuel1d744b22017-07-10 21:23:55828 viz::StringToBufferToTextureTargetMap(image_texture_target_string);
reveman44b807f12014-11-26 02:44:50829
[email protected]a23530d2014-03-11 06:04:14830 if (command_line.HasSwitch(switches::kDisableLCDText)) {
831 is_lcd_text_enabled_ = false;
832 } else if (command_line.HasSwitch(switches::kEnableLCDText)) {
833 is_lcd_text_enabled_ = true;
834 } else {
835#if defined(OS_ANDROID)
836 is_lcd_text_enabled_ = false;
837#else
838 is_lcd_text_enabled_ = true;
839#endif
840 }
841
[email protected]b8d82c22014-03-31 20:12:46842 is_gpu_rasterization_forced_ =
843 command_line.HasSwitch(switches::kForceGpuRasterization);
sunnypsd8ce1c22016-05-10 18:02:40844 is_async_worker_context_enabled_ =
845 command_line.HasSwitch(switches::kEnableGpuAsyncWorkerContext);
[email protected]a23530d2014-03-11 06:04:14846
senorblancob60ba952015-01-27 19:12:36847 if (command_line.HasSwitch(switches::kGpuRasterizationMSAASampleCount)) {
848 std::string string_value = command_line.GetSwitchValueASCII(
849 switches::kGpuRasterizationMSAASampleCount);
850 bool parsed_msaa_sample_count =
851 base::StringToInt(string_value, &gpu_rasterization_msaa_sample_count_);
852 DCHECK(parsed_msaa_sample_count) << string_value;
853 DCHECK_GE(gpu_rasterization_msaa_sample_count_, 0);
854 } else {
senorblanco2a5b0e12015-08-14 21:55:37855 gpu_rasterization_msaa_sample_count_ = -1;
senorblancob60ba952015-01-27 19:12:36856 }
857
[email protected]b242b142014-05-07 14:48:49858 if (command_line.HasSwitch(switches::kDisableDistanceFieldText)) {
859 is_distance_field_text_enabled_ = false;
860 } else if (command_line.HasSwitch(switches::kEnableDistanceFieldText)) {
861 is_distance_field_text_enabled_ = true;
862 } else {
863 is_distance_field_text_enabled_ = false;
864 }
865
[email protected]433df472012-03-07 20:33:39866 // Note that under Linux, the media library will normally already have
867 // been initialized by the Zygote before this instance became a Renderer.
chcunninghamfd11b3c2015-06-09 02:09:42868 media::InitializeMediaLibrary();
[email protected]433df472012-03-07 20:33:39869
dalecurtis88af3932016-02-20 00:12:20870#if defined(OS_ANDROID)
871 if (!command_line.HasSwitch(switches::kDisableAcceleratedVideoDecode) &&
872 media::MediaCodecUtil::IsMediaCodecAvailable()) {
873 media::EnablePlatformDecoderSupport();
874 }
875#endif
876
bashi296ebda2017-03-28 03:27:09877 memory_pressure_listener_.reset(new base::MemoryPressureListener(
878 base::Bind(&RenderThreadImpl::OnMemoryPressure, base::Unretained(this)),
879 base::Bind(&RenderThreadImpl::OnSyncMemoryPressure,
880 base::Unretained(this))));
881
882 if (base::FeatureList::IsEnabled(features::kMemoryCoordinator)) {
883 // Disable MemoryPressureListener when memory coordinator is enabled.
884 base::MemoryPressureListener::SetNotificationsSuppressed(true);
885
886 // TODO(bashi): Revisit how to manage the lifetime of
887 // ChildMemoryCoordinatorImpl.
888 // https://codereview.chromium.org/2094583002/#msg52
889 mojom::MemoryCoordinatorHandlePtr parent_coordinator;
890 GetConnector()->BindInterface(mojom::kBrowserServiceName,
891 mojo::MakeRequest(&parent_coordinator));
892 memory_coordinator_ = CreateChildMemoryCoordinator(
893 std::move(parent_coordinator), this);
894 }
895
danakj16275d4c2015-06-11 19:23:51896 int num_raster_threads = 0;
897 std::string string_value =
898 command_line.GetSwitchValueASCII(switches::kNumRasterThreads);
899 bool parsed_num_raster_threads =
900 base::StringToInt(string_value, &num_raster_threads);
901 DCHECK(parsed_num_raster_threads) << string_value;
902 DCHECK_GT(num_raster_threads, 0);
vmiura78b69282015-02-14 00:01:17903
prashant.nfad657e2016-06-01 07:52:17904 categorized_worker_pool_->Start(num_raster_threads);
[email protected]1e1d1e12014-01-17 16:14:29905
penghuang342762b2016-12-02 21:04:58906 discardable_memory::mojom::DiscardableSharedMemoryManagerPtr manager_ptr;
penghuangd6843e42016-12-17 13:57:20907 if (IsRunningInMash()) {
908#if defined(USE_AURA)
benbd3c2482017-01-07 05:48:21909 GetServiceManagerConnection()->GetConnector()->BindInterface(
penghuangd6843e42016-12-17 13:57:20910 ui::mojom::kServiceName, &manager_ptr);
911#else
912 NOTREACHED();
913#endif
914 } else {
ben649b3edd2017-03-23 00:32:02915 ChildThread::Get()->GetConnector()->BindInterface(
916 mojom::kBrowserServiceName, mojo::MakeRequest(&manager_ptr));
penghuangd6843e42016-12-17 13:57:20917 }
918
penghuang342762b2016-12-02 21:04:58919 discardable_shared_memory_manager_ = base::MakeUnique<
920 discardable_memory::ClientDiscardableSharedMemoryManager>(
921 std::move(manager_ptr), GetIOTaskRunner());
922
boliu9760e212015-06-23 22:49:06923 // TODO(boliu): In single process, browser main loop should set up the
924 // discardable memory manager, and should skip this if kSingleProcess.
925 // See crbug.com/503724.
926 base::DiscardableMemoryAllocator::SetInstance(
penghuang342762b2016-12-02 21:04:58927 discardable_shared_memory_manager_.get());
revemancb5a66af2014-10-25 00:34:39928
ben649b3edd2017-03-23 00:32:02929 GetConnector()->BindInterface(mojom::kBrowserServiceName,
930 mojo::MakeRequest(&storage_partition_service_));
hajimehoshi69093272016-05-13 08:30:58931
reveman7b97c322016-09-20 02:10:58932#if defined(OS_LINUX)
933 ChildProcess::current()->SetIOThreadPriority(base::ThreadPriority::DISPLAY);
934 ChildThreadImpl::current()->SetThreadPriority(
lukasza6710dbd2017-04-07 20:58:03935 categorized_worker_pool_->background_worker_thread_id(),
reveman7b97c322016-09-20 02:10:58936 base::ThreadPriority::BACKGROUND);
937#endif
938
tasakbb0640b2017-05-15 09:02:26939 process_foregrounded_count_ = 0;
tasakb95dbb50c2017-02-08 18:07:50940 needs_to_record_first_active_paint_ = false;
hajimehoshi7bb39582016-10-12 04:30:57941
942 base::MemoryCoordinatorClientRegistry::GetInstance()->Register(this);
fdoray50a38342016-11-21 20:46:04943
944 // If this renderer doesn't run inside the browser process, enable
945 // SequencedWorkerPool. Otherwise, it should already have been enabled.
946 // TODO(fdoray): Remove this once the SequencedWorkerPool to TaskScheduler
947 // redirection experiment concludes https://crbug.com/622400.
948 if (!command_line.HasSwitch(switches::kSingleProcess))
949 base::SequencedWorkerPool::EnableForProcess();
samans2040988b2017-04-11 23:58:35950
David Benjaminb946811c2017-06-26 23:34:29951 EVP_set_buggy_rsa_parser(
952 base::FeatureList::IsEnabled(features::kBuggyRSAParser));
953
samans2040988b2017-04-11 23:58:35954 GetConnector()->BindInterface(mojom::kBrowserServiceName,
955 mojo::MakeRequest(&frame_sink_provider_));
initial.commit09911bf2008-07-26 23:55:29956}
957
[email protected]f1a29a02011-10-06 23:08:44958RenderThreadImpl::~RenderThreadImpl() {
[email protected]ce79d8512013-04-22 22:44:41959}
960
961void RenderThreadImpl::Shutdown() {
harakenbbfdd9f02017-01-12 07:14:04962 // In a multi-process mode, we immediately exit the renderer.
963 // Historically we had a graceful shutdown sequence here but it was
964 // 1) a waste of performance and 2) a source of lots of complicated
965 // crashes caused by shutdown ordering. Immediate exit eliminates
966 // those problems.
cbrunia3f655b2017-03-20 11:36:41967
968 // Give the V8 isolate a chance to dump internal stats useful for performance
969 // evaluation and debugging.
Blink Reformat1c4d759e2017-04-09 16:34:54970 blink::MainThreadIsolate()->DumpAndResetStats();
cbrunia3f655b2017-03-20 11:36:41971
Adithya Srinivasandf421e82017-06-01 14:36:11972 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
973 switches::kDumpBlinkRuntimeCallStats))
974 blink::LogRuntimeCallStats();
975
harakenbbfdd9f02017-01-12 07:14:04976 // In a single-process mode, we cannot call _exit(0) in Shutdown() because
977 // it will exit the process before the browser side is ready to exit.
978 if (!base::CommandLine::ForCurrentProcess()->HasSwitch(
979 switches::kSingleProcess))
haraken940efb92017-02-08 05:58:15980 base::Process::TerminateCurrentProcessImmediately(0);
harakenbbfdd9f02017-01-12 07:14:04981}
[email protected]1223d6ef2011-03-28 16:47:50982
harakenbbfdd9f02017-01-12 07:14:04983bool RenderThreadImpl::ShouldBeDestroyed() {
984 DCHECK(base::CommandLine::ForCurrentProcess()->HasSwitch(
985 switches::kSingleProcess));
986 // In a single-process mode, it is unsafe to destruct this renderer thread
987 // because we haven't run the shutdown sequence. Hence we leak the render
988 // thread.
989 //
990 // In this case, we also need to disable at-exit callbacks because some of
991 // the at-exit callbacks are expected to run after the renderer thread
992 // has been destructed.
993 base::AtExitManager::DisableAllAtExitManagers();
994 return false;
initial.commit09911bf2008-07-26 23:55:29995}
996
[email protected]f1a29a02011-10-06 23:08:44997bool RenderThreadImpl::Send(IPC::Message* msg) {
changwan6ed4d432016-05-19 22:03:54998 // There are cases where we want to pump asynchronous messages while waiting
999 // synchronously for the replies to the message to be sent here. However, this
1000 // may create an opportunity for re-entrancy into WebKit and other subsystems,
1001 // so we need to take care to disable callbacks, timers, and pending network
1002 // loads that could trigger such callbacks.
[email protected]38b592902011-04-16 02:08:421003 bool pumping_events = false;
[email protected]80fc08c52010-03-09 07:43:501004 if (msg->is_sync()) {
1005 if (msg->is_caller_pumping_messages()) {
1006 pumping_events = true;
[email protected]80fc08c52010-03-09 07:43:501007 }
[email protected]c1f50aa2010-02-18 03:46:571008 }
1009
[email protected]c1f50aa2010-02-18 03:46:571010 if (pumping_events) {
jdduked73ae5412015-05-11 20:07:161011 renderer_scheduler_->SuspendTimerQueue();
Blink Reformat1c4d759e2017-04-09 16:34:541012 WebView::WillEnterModalLoop();
[email protected]c1f50aa2010-02-18 03:46:571013 }
1014
jam8a021512a2015-02-03 18:16:081015 bool rv = ChildThreadImpl::Send(msg);
[email protected]c1f50aa2010-02-18 03:46:571016
1017 if (pumping_events) {
Blink Reformat1c4d759e2017-04-09 16:34:541018 WebView::DidExitModalLoop();
jdduked73ae5412015-05-11 20:07:161019 renderer_scheduler_->ResumeTimerQueue();
[email protected]c1f50aa2010-02-18 03:46:571020 }
1021
1022 return rv;
1023}
1024
[email protected]f1a29a02011-10-06 23:08:441025IPC::SyncChannel* RenderThreadImpl::GetChannel() {
[email protected]526476902011-10-06 20:34:061026 return channel();
1027}
1028
[email protected]f1a29a02011-10-06 23:08:441029std::string RenderThreadImpl::GetLocale() {
[email protected]526476902011-10-06 20:34:061030 // The browser process should have passed the locale to the renderer via the
[email protected]dfd53652012-10-25 00:20:021031 // --lang command line flag.
avi83883c82014-12-23 00:08:491032 const base::CommandLine& parsed_command_line =
1033 *base::CommandLine::ForCurrentProcess();
[email protected]526476902011-10-06 20:34:061034 const std::string& lang =
1035 parsed_command_line.GetSwitchValueASCII(switches::kLang);
[email protected]dfd53652012-10-25 00:20:021036 DCHECK(!lang.empty());
[email protected]526476902011-10-06 20:34:061037 return lang;
1038}
1039
[email protected]07bb6332012-01-21 01:07:571040IPC::SyncMessageFilter* RenderThreadImpl::GetSyncMessageFilter() {
1041 return sync_message_filter();
1042}
1043
avi1023d012015-12-25 02:39:141044void RenderThreadImpl::AddRoute(int32_t routing_id, IPC::Listener* listener) {
jam8a021512a2015-02-03 18:16:081045 ChildThreadImpl::GetRouter()->AddRoute(routing_id, listener);
ben76f52b242016-06-18 05:42:481046 auto it = pending_frame_creates_.find(routing_id);
1047 if (it == pending_frame_creates_.end())
rockotf8fdd9b2015-12-16 22:22:351048 return;
1049
1050 RenderFrameImpl* frame = RenderFrameImpl::FromRoutingID(routing_id);
1051 if (!frame)
1052 return;
1053
ben76f52b242016-06-18 05:42:481054 scoped_refptr<PendingFrameCreate> create(it->second);
benf28ce882017-05-02 16:15:491055 frame->BindFrame(it->second->browser_info(), it->second->TakeFrameRequest(),
csharrison95f01e922017-04-24 18:52:351056 it->second->TakeInterfaceBroker());
ben76f52b242016-06-18 05:42:481057 pending_frame_creates_.erase(it);
[email protected]c1f50aa2010-02-18 03:46:571058}
1059
avi1023d012015-12-25 02:39:141060void RenderThreadImpl::RemoveRoute(int32_t routing_id) {
jam8a021512a2015-02-03 18:16:081061 ChildThreadImpl::GetRouter()->RemoveRoute(routing_id);
[email protected]c1f50aa2010-02-18 03:46:571062}
[email protected]0ec90d522014-03-12 16:28:191063
avi1023d012015-12-25 02:39:141064void RenderThreadImpl::AddEmbeddedWorkerRoute(int32_t routing_id,
[email protected]a620b132014-04-30 22:39:171065 IPC::Listener* listener) {
[email protected]48e52e42014-03-20 06:58:071066 AddRoute(routing_id, listener);
1067 if (devtools_agent_message_filter_.get()) {
[email protected]a620b132014-04-30 22:39:171068 devtools_agent_message_filter_->AddEmbeddedWorkerRouteOnMainThread(
[email protected]48e52e42014-03-20 06:58:071069 routing_id);
1070 }
1071}
1072
avi1023d012015-12-25 02:39:141073void RenderThreadImpl::RemoveEmbeddedWorkerRoute(int32_t routing_id) {
[email protected]48e52e42014-03-20 06:58:071074 RemoveRoute(routing_id);
1075 if (devtools_agent_message_filter_.get()) {
[email protected]a620b132014-04-30 22:39:171076 devtools_agent_message_filter_->RemoveEmbeddedWorkerRouteOnMainThread(
[email protected]48e52e42014-03-20 06:58:071077 routing_id);
1078 }
1079}
1080
ben76f52b242016-06-18 05:42:481081void RenderThreadImpl::RegisterPendingFrameCreate(
benf28ce882017-05-02 16:15:491082 const service_manager::BindSourceInfo& browser_info,
rockotf8fdd9b2015-12-16 22:22:351083 int routing_id,
ben76f52b242016-06-18 05:42:481084 mojom::FrameRequest frame_request,
csharrison95f01e922017-04-24 18:52:351085 mojom::FrameHostInterfaceBrokerPtr frame_host_interface_broker) {
ben76f52b242016-06-18 05:42:481086 std::pair<PendingFrameCreateMap::iterator, bool> result =
1087 pending_frame_creates_.insert(std::make_pair(
csharrison95f01e922017-04-24 18:52:351088 routing_id, make_scoped_refptr(new PendingFrameCreate(
benf28ce882017-05-02 16:15:491089 browser_info, routing_id, std::move(frame_request),
csharrison95f01e922017-04-24 18:52:351090 std::move(frame_host_interface_broker)))));
rockotf8fdd9b2015-12-16 22:22:351091 CHECK(result.second) << "Inserting a duplicate item.";
1092}
1093
leon.han06e55662016-03-26 17:19:421094mojom::StoragePartitionService* RenderThreadImpl::GetStoragePartitionService() {
jamc912ca32016-02-24 20:17:311095 return storage_partition_service_.get();
1096}
1097
jam188f19f2017-06-07 03:56:241098mojom::RendererHost* RenderThreadImpl::GetRendererHost() {
1099 if (!renderer_host_) {
1100 GetConnector()->BindInterface(mojom::kBrowserServiceName,
1101 mojo::MakeRequest(&renderer_host_));
1102 }
1103 return renderer_host_.get();
1104}
1105
1106mojom::URLLoaderFactory* RenderThreadImpl::GetBlobURLLoaderFactory() {
1107 if (!blob_url_loader_factory_) {
1108 GetRendererHost()->GetBlobURLLoaderFactory(
1109 mojo::MakeRequest(&blob_url_loader_factory_));
1110 }
1111 return blob_url_loader_factory_.get();
1112}
1113
[email protected]77fc9b92011-10-15 16:20:371114int RenderThreadImpl::GenerateRoutingID() {
rockote261d2112016-09-21 22:22:231115 int32_t routing_id = MSG_ROUTING_NONE;
1116 render_message_filter()->GenerateRoutingID(&routing_id);
[email protected]77fc9b92011-10-15 16:20:371117 return routing_id;
1118}
1119
[email protected]74122042014-04-25 00:07:301120void RenderThreadImpl::AddFilter(IPC::MessageFilter* filter) {
[email protected]42f1d7822009-07-23 18:17:551121 channel()->AddFilter(filter);
1122}
1123
[email protected]74122042014-04-25 00:07:301124void RenderThreadImpl::RemoveFilter(IPC::MessageFilter* filter) {
[email protected]42f1d7822009-07-23 18:17:551125 channel()->RemoveFilter(filter);
1126}
1127
tyoshino832a58a2016-04-18 08:14:081128void RenderThreadImpl::AddObserver(RenderThreadObserver* observer) {
[email protected]526476902011-10-06 20:34:061129 observers_.AddObserver(observer);
nigeltao7cd8d5582016-12-12 06:05:281130 observer->RegisterMojoInterfaces(&associated_interfaces_);
[email protected]526476902011-10-06 20:34:061131}
1132
tyoshino832a58a2016-04-18 08:14:081133void RenderThreadImpl::RemoveObserver(RenderThreadObserver* observer) {
nigeltao7cd8d5582016-12-12 06:05:281134 observer->UnregisterMojoInterfaces(&associated_interfaces_);
[email protected]526476902011-10-06 20:34:061135 observers_.RemoveObserver(observer);
1136}
1137
[email protected]359dfa32011-10-12 01:10:151138void RenderThreadImpl::SetResourceDispatcherDelegate(
[email protected]e9ff79c2012-10-19 21:31:261139 ResourceDispatcherDelegate* delegate) {
[email protected]359dfa32011-10-12 01:10:151140 resource_dispatcher()->set_delegate(delegate);
1141}
1142
vollick1050cc62015-12-03 07:04:541143void RenderThreadImpl::InitializeCompositorThread() {
boliu66024c62016-04-20 04:00:411144 base::Thread::Options options;
vollick1050cc62015-12-03 07:04:541145#if defined(OS_ANDROID)
boliu66024c62016-04-20 04:00:411146 options.priority = base::ThreadPriority::DISPLAY;
vollick1050cc62015-12-03 07:04:541147#endif
altiminc7369bf2017-04-11 14:29:151148 compositor_thread_ =
1149 blink::scheduler::WebThreadBase::CreateCompositorThread(options);
boliu66024c62016-04-20 04:00:411150 blink_platform_impl_->SetCompositorThread(compositor_thread_.get());
1151 compositor_task_runner_ = compositor_thread_->GetTaskRunner();
1152 compositor_task_runner_->PostTask(
1153 FROM_HERE,
1154 base::Bind(base::IgnoreResult(&ThreadRestrictions::SetIOAllowed), false));
reveman7b97c322016-09-20 02:10:581155#if defined(OS_LINUX)
Blink Reformat1c4d759e2017-04-09 16:34:541156 ChildThreadImpl::current()->SetThreadPriority(compositor_thread_->ThreadId(),
reveman7b97c322016-09-20 02:10:581157 base::ThreadPriority::DISPLAY);
1158#endif
vollick1050cc62015-12-03 07:04:541159
boliude5b75b2016-03-11 07:02:141160 SynchronousInputHandlerProxyClient* synchronous_input_handler_proxy_client =
1161 nullptr;
vollick1050cc62015-12-03 07:04:541162#if defined(OS_ANDROID)
boliu66024c62016-04-20 04:00:411163 if (GetContentClient()->UsingSynchronousCompositing()) {
vollick1050cc62015-12-03 07:04:541164 sync_compositor_message_filter_ =
1165 new SynchronousCompositorFilter(compositor_task_runner_);
1166 AddFilter(sync_compositor_message_filter_.get());
boliude5b75b2016-03-11 07:02:141167 synchronous_input_handler_proxy_client =
1168 sync_compositor_message_filter_.get();
vollick1050cc62015-12-03 07:04:541169 }
1170#endif
boliub2768db2016-06-03 23:35:161171 scoped_refptr<InputEventFilter> compositor_input_event_filter(
1172 new InputEventFilter(main_input_callback_.callback(),
1173 main_thread_compositor_task_runner_,
1174 compositor_task_runner_));
1175 InputHandlerManagerClient* input_handler_manager_client =
1176 compositor_input_event_filter.get();
1177 input_event_filter_ = compositor_input_event_filter;
vollick1050cc62015-12-03 07:04:541178 input_handler_manager_.reset(new InputHandlerManager(
1179 compositor_task_runner_, input_handler_manager_client,
boliude5b75b2016-03-11 07:02:141180 synchronous_input_handler_proxy_client, renderer_scheduler_.get()));
vollick1050cc62015-12-03 07:04:541181}
1182
jam75c44222016-03-23 05:34:241183void RenderThreadImpl::InitializeWebKit(
rockot97a86832016-12-10 04:53:061184 const scoped_refptr<base::SingleThreadTaskRunner>& resource_task_queue) {
jam75c44222016-03-23 05:34:241185 DCHECK(!blink_platform_impl_);
[email protected]d1b8fccc2011-08-03 01:20:131186
avi83883c82014-12-23 00:08:491187 const base::CommandLine& command_line =
1188 *base::CommandLine::ForCurrentProcess();
chunyang.daibe874c52014-11-14 06:45:051189
1190#ifdef ENABLE_VTUNE_JIT_INTERFACE
1191 if (command_line.HasSwitch(switches::kEnableVtune))
1192 gin::Debug::SetJitCodeEventHandler(vTune::GetVtuneCodeEventHandler());
1193#endif
1194
rmcilroy4073ae12015-01-08 13:08:101195 SetRuntimeFeaturesDefaultsAndUpdateFromArgs(command_line);
hlopko852ffcf2016-09-16 16:50:591196 GetContentClient()
1197 ->renderer()
1198 ->SetRuntimeFeaturesDefaultsBeforeBlinkInitialization();
rmcilroy4073ae12015-01-08 13:08:101199
sammcbebeb602016-04-06 06:42:551200 blink_platform_impl_.reset(new RendererBlinkPlatformImpl(
ben649b3edd2017-03-23 00:32:021201 renderer_scheduler_.get(), GetConnector()->GetWeakPtr()));
Blink Reformat1c4d759e2017-04-09 16:34:541202 blink::Initialize(blink_platform_impl_.get());
[email protected]d1b8fccc2011-08-03 01:20:131203
Blink Reformat1c4d759e2017-04-09 16:34:541204 v8::Isolate* isolate = blink::MainThreadIsolate();
[email protected]4b5340282014-07-08 11:37:341205 isolate->SetCreateHistogramFunction(CreateHistogram);
1206 isolate->SetAddHistogramSampleFunction(AddHistogramSample);
skyostila37c2a72016-06-29 17:30:071207 renderer_scheduler_->SetRAILModeObserver(this);
[email protected]4b5340282014-07-08 11:37:341208
rmcilroy321f924d2014-11-06 00:56:001209 main_thread_compositor_task_runner_ =
danakj6e3bf8012014-12-16 18:27:531210 renderer_scheduler_->CompositorTaskRunner();
skyostilc30aa402014-10-10 13:49:091211
jdduke691dd572014-12-02 20:47:521212 main_input_callback_.Reset(
1213 base::Bind(base::IgnoreResult(&RenderThreadImpl::OnMessageReceived),
1214 base::Unretained(this)));
1215
jam75c44222016-03-23 05:34:241216 scoped_refptr<base::SingleThreadTaskRunner> resource_task_queue2;
1217 if (resource_task_queue) {
1218 resource_task_queue2 = resource_task_queue;
1219 } else {
1220 resource_task_queue2 = renderer_scheduler_->LoadingTaskRunner();
1221 }
1222 // Add a filter that forces resource messages to be dispatched via a
1223 // particular task runner.
1224 scoped_refptr<ResourceSchedulingFilter> filter(
1225 new ResourceSchedulingFilter(
1226 resource_task_queue2, resource_dispatcher()));
1227 channel()->AddFilter(filter.get());
1228 resource_dispatcher()->SetResourceSchedulingFilter(filter);
1229
1230 // The ChildResourceMessageFilter and the ResourceDispatcher need to use the
1231 // same queue to ensure tasks are executed in the expected order.
1232 child_resource_message_filter()->SetMainThreadTaskRunner(
1233 resource_task_queue2);
horoe6120582017-04-26 01:48:591234 resource_dispatcher()->SetThreadTaskRunner(resource_task_queue2);
jam75c44222016-03-23 05:34:241235
khushalsagard7178e42017-01-20 01:31:491236 if (!command_line.HasSwitch(switches::kDisableThreadedCompositing))
vollick1050cc62015-12-03 07:04:541237 InitializeCompositorThread();
[email protected]a9fb30aa2011-10-06 06:58:461238
jdduke691dd572014-12-02 20:47:521239 if (!input_event_filter_.get()) {
1240 // Always provide an input event filter implementation to ensure consistent
1241 // input event scheduling and prioritization.
1242 // TODO(jdduke): Merge InputEventFilter, InputHandlerManager and
1243 // MainThreadInputEventFilter, crbug.com/436057.
1244 input_event_filter_ = new MainThreadInputEventFilter(
1245 main_input_callback_.callback(), main_thread_compositor_task_runner_);
1246 }
1247 AddFilter(input_event_filter_.get());
1248
skyostil2d3b5bd2015-05-27 15:40:591249 scoped_refptr<base::SingleThreadTaskRunner> compositor_impl_side_task_runner;
vollick1050cc62015-12-03 07:04:541250 if (compositor_task_runner_)
skyostil2d3b5bd2015-05-27 15:40:591251 compositor_impl_side_task_runner = compositor_task_runner_;
[email protected]7f1f63f2013-03-07 06:07:291252 else
skyostil2d3b5bd2015-05-27 15:40:591253 compositor_impl_side_task_runner = base::ThreadTaskRunnerHandle::Get();
[email protected]1842fe22012-08-13 23:24:351254
simonhonga7e3ac42014-11-11 20:50:221255 compositor_message_filter_ = new CompositorForwardingMessageFilter(
skyostil2d3b5bd2015-05-27 15:40:591256 compositor_impl_side_task_runner.get());
simonhonga7e3ac42014-11-11 20:50:221257 AddFilter(compositor_message_filter_.get());
[email protected]1842fe22012-08-13 23:24:351258
[email protected]58436a12012-03-21 17:10:261259 RenderThreadImpl::RegisterSchemes();
1260
xhwang194acae2014-11-12 22:46:331261 RenderMediaClient::Initialize();
1262
[email protected]b146d6d2012-09-11 10:20:051263 devtools_agent_message_filter_ = new DevToolsAgentFilter();
1264 AddFilter(devtools_agent_message_filter_.get());
1265
ulan4a385192015-11-11 10:59:181266 if (GetContentClient()->renderer()->RunIdleHandlerWhenWidgetsHidden()) {
[email protected]1784b2f2011-11-24 10:53:481267 ScheduleIdleHandler(kLongIdleHandlerDelayMs);
ulan4a385192015-11-11 10:59:181268 } else {
1269 // If we do not track widget visibility, then assume conservatively that
1270 // the isolate is in background. This reduces memory usage.
1271 isolate->IsolateInBackgroundNotification();
1272 }
[email protected]2541d1a2013-07-10 07:33:271273
jdduke73220f02015-09-04 17:03:511274 renderer_scheduler_->SetTimerQueueSuspensionWhenBackgroundedEnabled(
1275 GetContentClient()
1276 ->renderer()
1277 ->AllowTimerSuspensionWhenProcessBackgrounded());
1278
reedccf98c52014-10-03 16:40:381279 SkGraphics::SetResourceCacheSingleAllocationByteLimit(
[email protected]dd2c1022014-07-22 23:13:571280 kImageCacheSingleAllocationByteLimit);
1281
reed6e5a72222015-08-06 20:37:161282 // Hook up blink's codecs so skia can call them
reed08cd16372017-02-21 22:11:411283 SkGraphics::SetImageGeneratorFromEncodedDataFactory(
Blink Reformat1c4d759e2017-04-09 16:34:541284 blink::WebImageGenerator::Create);
reed6e5a72222015-08-06 20:37:161285
paritosh.in7e30c902015-04-15 17:04:071286 if (command_line.HasSwitch(switches::kExplicitlyAllowedPorts)) {
1287 std::string allowed_ports =
1288 command_line.GetSwitchValueASCII(switches::kExplicitlyAllowedPorts);
1289 net::SetExplicitlyAllowedPorts(allowed_ports);
1290 }
[email protected]d1b8fccc2011-08-03 01:20:131291}
1292
[email protected]58436a12012-03-21 17:10:261293void RenderThreadImpl::RegisterSchemes() {
mkwst8e94fb32015-05-20 05:05:141294 // chrome:
Blink Reformat1c4d759e2017-04-09 16:34:541295 WebString chrome_scheme(WebString::FromASCII(kChromeUIScheme));
1296 WebSecurityPolicy::RegisterURLSchemeAsDisplayIsolated(chrome_scheme);
1297 WebSecurityPolicy::RegisterURLSchemeAsNotAllowingJavascriptURLs(
mkwst8e94fb32015-05-20 05:05:141298 chrome_scheme);
mkwst8e94fb32015-05-20 05:05:141299
1300 // chrome-devtools:
Blink Reformat1c4d759e2017-04-09 16:34:541301 WebString devtools_scheme(WebString::FromASCII(kChromeDevToolsScheme));
1302 WebSecurityPolicy::RegisterURLSchemeAsDisplayIsolated(devtools_scheme);
meacerce6b66032016-06-02 20:56:051303
1304 // view-source:
Blink Reformat1c4d759e2017-04-09 16:34:541305 WebString view_source_scheme(WebString::FromASCII(kViewSourceScheme));
1306 WebSecurityPolicy::RegisterURLSchemeAsDisplayIsolated(view_source_scheme);
[email protected]58436a12012-03-21 17:10:261307}
1308
[email protected]e6e30ac2014-01-13 21:24:391309void RenderThreadImpl::RecordAction(const base::UserMetricsAction& action) {
[email protected]97880c82013-12-04 07:09:211310 Send(new ViewHostMsg_UserMetricsRecordAction(action.str_));
1311}
1312
1313void RenderThreadImpl::RecordComputedAction(const std::string& action) {
[email protected]526476902011-10-06 20:34:061314 Send(new ViewHostMsg_UserMetricsRecordAction(action));
1315}
1316
dchengcedca5612016-04-09 01:40:151317std::unique_ptr<base::SharedMemory>
1318RenderThreadImpl::HostAllocateSharedMemoryBuffer(size_t size) {
sadrulee3ff1f2016-12-09 04:22:011319 return ChildThreadImpl::AllocateSharedMemory(size);
[email protected]00614a82011-10-07 22:39:311320}
1321
jbauman2f5c1942014-12-06 03:28:241322cc::SharedBitmapManager* RenderThreadImpl::GetSharedBitmapManager() {
1323 return shared_bitmap_manager();
1324}
1325
[email protected]f1a29a02011-10-06 23:08:441326void RenderThreadImpl::RegisterExtension(v8::Extension* extension) {
Blink Reformat1c4d759e2017-04-09 16:34:541327 WebScriptController::RegisterExtension(extension);
[email protected]526476902011-10-06 20:34:061328}
1329
avi1023d012015-12-25 02:39:141330void RenderThreadImpl::ScheduleIdleHandler(int64_t initial_delay_ms) {
[email protected]6593ae12011-11-14 12:09:441331 idle_notification_delay_in_ms_ = initial_delay_ms;
[email protected]526476902011-10-06 20:34:061332 idle_timer_.Stop();
1333 idle_timer_.Start(FROM_HERE,
[email protected]6593ae12011-11-14 12:09:441334 base::TimeDelta::FromMilliseconds(initial_delay_ms),
[email protected]f1a29a02011-10-06 23:08:441335 this, &RenderThreadImpl::IdleHandler);
[email protected]526476902011-10-06 20:34:061336}
1337
[email protected]f1a29a02011-10-06 23:08:441338void RenderThreadImpl::IdleHandler() {
[email protected]1784b2f2011-11-24 10:53:481339 bool run_in_foreground_tab = (widget_count_ > hidden_widget_count_) &&
[email protected]e9ff79c2012-10-19 21:31:261340 GetContentClient()->renderer()->
[email protected]1784b2f2011-11-24 10:53:481341 RunIdleHandlerWhenWidgetsHidden();
1342 if (run_in_foreground_tab) {
jochen5a32aaf2014-09-26 20:37:431343 if (idle_notifications_to_skip_ > 0) {
1344 --idle_notifications_to_skip_;
1345 } else {
ssid0603ca9f2015-06-09 16:48:081346 ReleaseFreeMemory();
jochen5a32aaf2014-09-26 20:37:431347 }
1348 ScheduleIdleHandler(kLongIdleHandlerDelayMs);
[email protected]1784b2f2011-11-24 10:53:481349 return;
1350 }
[email protected]237a14852012-04-28 02:56:381351
ssid0603ca9f2015-06-09 16:48:081352 ReleaseFreeMemory();
[email protected]526476902011-10-06 20:34:061353
[email protected]26e82322014-01-20 14:18:221354 // Continue the idle timer if the webkit shared timer is not suspended or
1355 // something is left to do.
1356 bool continue_timer = !webkit_shared_timer_suspended_;
1357
sullivancd45a3e2014-09-19 14:39:181358 // Schedule next invocation. When the tab is originally hidden, an invocation
1359 // is scheduled for kInitialIdleHandlerDelayMs in
1360 // RenderThreadImpl::WidgetHidden in order to race to a minimal heap.
1361 // After that, idle calls can be much less frequent, so run at a maximum of
1362 // once every kLongIdleHandlerDelayMs.
[email protected]6593ae12011-11-14 12:09:441363 // Dampen the delay using the algorithm (if delay is in seconds):
[email protected]526476902011-10-06 20:34:061364 // delay = delay + 1 / (delay + 2)
1365 // Using floor(delay) has a dampening effect such as:
sullivancd45a3e2014-09-19 14:39:181366 // 30s, 30, 30, 31, 31, 31, 31, 32, 32, ...
[email protected]6593ae12011-11-14 12:09:441367 // If the delay is in milliseconds, the above formula is equivalent to:
1368 // delay_ms / 1000 = delay_ms / 1000 + 1 / (delay_ms / 1000 + 2)
1369 // which is equivalent to
1370 // delay_ms = delay_ms + 1000*1000 / (delay_ms + 2000).
[email protected]26e82322014-01-20 14:18:221371 if (continue_timer) {
sullivancd45a3e2014-09-19 14:39:181372 ScheduleIdleHandler(
1373 std::max(kLongIdleHandlerDelayMs,
1374 idle_notification_delay_in_ms_ +
1375 1000000 / (idle_notification_delay_in_ms_ + 2000)));
[email protected]26e82322014-01-20 14:18:221376
1377 } else {
1378 idle_timer_.Stop();
1379 }
[email protected]526476902011-10-06 20:34:061380
ericwilligers88e69742016-10-17 19:29:551381 for (auto& observer : observers_)
1382 observer.IdleNotification();
[email protected]526476902011-10-06 20:34:061383}
1384
avi1023d012015-12-25 02:39:141385int64_t RenderThreadImpl::GetIdleNotificationDelayInMs() const {
[email protected]6593ae12011-11-14 12:09:441386 return idle_notification_delay_in_ms_;
[email protected]526476902011-10-06 20:34:061387}
1388
[email protected]6593ae12011-11-14 12:09:441389void RenderThreadImpl::SetIdleNotificationDelayInMs(
avi1023d012015-12-25 02:39:141390 int64_t idle_notification_delay_in_ms) {
[email protected]6593ae12011-11-14 12:09:441391 idle_notification_delay_in_ms_ = idle_notification_delay_in_ms;
[email protected]4a7d6392011-09-19 20:55:081392}
1393
[email protected]5b18406362013-06-18 18:46:431394int RenderThreadImpl::PostTaskToAllWebWorkers(const base::Closure& closure) {
kinukoef647412015-12-23 06:10:431395 return WorkerThreadRegistry::Instance()->PostTaskToAllThreads(closure);
[email protected]a9bd323d2013-06-17 20:27:561396}
1397
[email protected]b02f5902012-12-19 07:33:001398bool RenderThreadImpl::ResolveProxy(const GURL& url, std::string* proxy_list) {
1399 bool result = false;
1400 Send(new ViewHostMsg_ResolveProxy(url, &result, proxy_list));
1401 return result;
1402}
1403
[email protected]1784b2f2011-11-24 10:53:481404void RenderThreadImpl::PostponeIdleNotification() {
1405 idle_notifications_to_skip_ = 2;
1406}
1407
dcastagna7f45dada2015-10-19 20:17:351408media::GpuVideoAcceleratorFactories* RenderThreadImpl::GetGpuFactories() {
[email protected]3bb8bb32013-07-11 13:13:031409 DCHECK(IsMainThread());
1410
dcastagna09bd6b32016-02-01 21:54:281411 if (!gpu_factories_.empty()) {
sadrul85cc5d82016-12-20 03:37:411412 scoped_refptr<ui::ContextProviderCommandBuffer> shared_context_provider =
dcastagna09bd6b32016-02-01 21:54:281413 gpu_factories_.back()->ContextProviderMainThread();
1414 if (shared_context_provider) {
1415 cc::ContextProvider::ScopedContextLock lock(
1416 shared_context_provider.get());
1417 if (lock.ContextGL()->GetGraphicsResetStatusKHR() == GL_NO_ERROR) {
leon.han21e0e482017-02-23 04:13:321418 return gpu_factories_.back().get();
dcastagna09bd6b32016-02-01 21:54:281419 } else {
1420 scoped_refptr<base::SingleThreadTaskRunner> media_task_runner =
1421 GetMediaThreadTaskRunner();
1422 media_task_runner->PostTask(
1423 FROM_HERE,
Miguel Casas-Sanchezcfcca5d52017-07-07 02:32:591424 base::Bind(base::IgnoreResult(
1425 &GpuVideoAcceleratorFactoriesImpl::CheckContextLost),
1426 base::Unretained(gpu_factories_.back().get())));
dcastagna09bd6b32016-02-01 21:54:281427 }
1428 }
1429 }
dcastagna7f45dada2015-10-19 20:17:351430
tobiasjsca238b3b2015-06-24 22:53:541431 const base::CommandLine* cmd_line = base::CommandLine::ForCurrentProcess();
1432
danakj0b4b94e32016-05-10 22:33:011433 scoped_refptr<gpu::GpuChannelHost> gpu_channel_host =
sadrul6d310fa2016-08-04 02:12:161434 EstablishGpuChannelSync();
danakj0b4b94e32016-05-10 22:33:011435 if (!gpu_channel_host)
1436 return nullptr;
danakj0dd9e1e2016-05-11 22:15:091437 // This context is only used to create textures and mailbox them, so
1438 // use lower limits than the default.
1439 gpu::SharedMemoryLimits limits = gpu::SharedMemoryLimits::ForMailboxContext();
danakj9a04adc2016-05-16 22:45:071440 bool support_locking = true;
sadrul85cc5d82016-12-20 03:37:411441 scoped_refptr<ui::ContextProviderCommandBuffer> media_context_provider =
danakj9a04adc2016-05-16 22:45:071442 CreateOffscreenContext(gpu_channel_host, limits, support_locking,
ericrka20c1002017-03-13 21:08:131443 ui::command_buffer_metrics::MEDIA_CONTEXT,
sunnyps8f9139e2017-05-12 17:53:251444 kGpuStreamIdDefault, kGpuStreamPriorityDefault);
danakj0b4b94e32016-05-10 22:33:011445 if (!media_context_provider->BindToCurrentThread())
1446 return nullptr;
danakj0b4b94e32016-05-10 22:33:011447
acolwellb4034942014-08-28 15:42:431448 scoped_refptr<base::SingleThreadTaskRunner> media_task_runner =
1449 GetMediaThreadTaskRunner();
danakj0b4b94e32016-05-10 22:33:011450 const bool enable_video_accelerator =
1451 !cmd_line->HasSwitch(switches::kDisableAcceleratedVideoDecode);
1452 const bool enable_gpu_memory_buffer_video_frames =
dcastagna43c3a86a2016-02-02 21:16:381453#if defined(OS_MACOSX) || defined(OS_LINUX)
dcastagnaa82ed96a2016-05-12 02:52:471454 !cmd_line->HasSwitch(switches::kDisableGpuMemoryBufferVideoFrames) &&
1455 !cmd_line->HasSwitch(switches::kDisableGpuCompositing) &&
1456 !gpu_channel_host->gpu_info().software_rendering;
jbaumana0bb8982017-05-05 19:50:531457#elif defined(OS_WIN)
1458 !cmd_line->HasSwitch(switches::kDisableGpuMemoryBufferVideoFrames) &&
1459 !cmd_line->HasSwitch(switches::kDisableGpuCompositing) &&
1460 !gpu_channel_host->gpu_info().software_rendering &&
1461 (cmd_line->HasSwitch(switches::kEnableGpuMemoryBufferVideoFrames) ||
1462 gpu_channel_host->gpu_info().supports_overlays);
dcastagnab65e6072015-09-05 07:18:421463#else
danakj0b4b94e32016-05-10 22:33:011464 cmd_line->HasSwitch(switches::kEnableGpuMemoryBufferVideoFrames);
dcastagnab65e6072015-09-05 07:18:421465#endif
dcastagna5077d6d2016-01-27 00:07:051466
Miguel Casas-Sanchezcfcca5d52017-07-07 02:32:591467 gpu_factories_.push_back(GpuVideoAcceleratorFactoriesImpl::Create(
danakj0b4b94e32016-05-10 22:33:011468 std::move(gpu_channel_host), base::ThreadTaskRunnerHandle::Get(),
1469 media_task_runner, std::move(media_context_provider),
ericrk9151705c2016-07-26 19:53:161470 enable_gpu_memory_buffer_video_frames, buffer_to_texture_target_map_,
danakj0b4b94e32016-05-10 22:33:011471 enable_video_accelerator));
leon.han21e0e482017-02-23 04:13:321472 return gpu_factories_.back().get();
[email protected]3bb8bb32013-07-11 13:13:031473}
1474
sadrul85cc5d82016-12-20 03:37:411475scoped_refptr<ui::ContextProviderCommandBuffer>
[email protected]f10dc472013-09-27 03:31:591476RenderThreadImpl::SharedMainThreadContextProvider() {
[email protected]e06e1122013-03-15 17:12:381477 DCHECK(IsMainThread());
danakje8ec797e2016-04-19 04:08:431478 if (shared_main_thread_contexts_ &&
1479 shared_main_thread_contexts_->ContextGL()->GetGraphicsResetStatusKHR() ==
1480 GL_NO_ERROR)
1481 return shared_main_thread_contexts_;
1482
sadrul6d310fa2016-08-04 02:12:161483 scoped_refptr<gpu::GpuChannelHost> gpu_channel_host(
1484 EstablishGpuChannelSync());
danakje8ec797e2016-04-19 04:08:431485 if (!gpu_channel_host) {
1486 shared_main_thread_contexts_ = nullptr;
1487 return nullptr;
[email protected]c29b7ff2013-03-06 03:51:041488 }
danakje8ec797e2016-04-19 04:08:431489
danakj9a04adc2016-05-16 22:45:071490 bool support_locking = false;
danakjc3983552016-05-03 00:04:351491 shared_main_thread_contexts_ = CreateOffscreenContext(
danakj9a04adc2016-05-16 22:45:071492 std::move(gpu_channel_host), gpu::SharedMemoryLimits(), support_locking,
sadrul85cc5d82016-12-20 03:37:411493 ui::command_buffer_metrics::RENDERER_MAINTHREAD_CONTEXT,
sunnyps8f9139e2017-05-12 17:53:251494 kGpuStreamIdDefault, kGpuStreamPriorityDefault);
danakje8ec797e2016-04-19 04:08:431495 if (!shared_main_thread_contexts_->BindToCurrentThread())
1496 shared_main_thread_contexts_ = nullptr;
[email protected]f10dc472013-09-27 03:31:591497 return shared_main_thread_contexts_;
[email protected]c29b7ff2013-03-06 03:51:041498}
1499
siva.gunturi5d4feb052015-11-15 16:15:311500#if defined(OS_ANDROID)
boliuf8753bf62016-02-11 20:09:421501
siva.gunturi5d4feb052015-11-15 16:15:311502scoped_refptr<StreamTextureFactory> RenderThreadImpl::GetStreamTexureFactory() {
1503 DCHECK(IsMainThread());
boliu30f1b262016-04-19 00:12:331504 if (!stream_texture_factory_.get() ||
1505 stream_texture_factory_->ContextGL()->GetGraphicsResetStatusKHR() !=
1506 GL_NO_ERROR) {
sadrul85cc5d82016-12-20 03:37:411507 scoped_refptr<ui::ContextProviderCommandBuffer> shared_context_provider =
piman9fc22f32016-05-02 22:21:221508 SharedMainThreadContextProvider();
1509 if (!shared_context_provider) {
penghuange1d86512016-07-08 18:15:001510 stream_texture_factory_ = nullptr;
1511 return nullptr;
siva.gunturi5d4feb052015-11-15 16:15:311512 }
piman9fc22f32016-05-02 22:21:221513 DCHECK(shared_context_provider->GetCommandBufferProxy());
1514 DCHECK(shared_context_provider->GetCommandBufferProxy()->channel());
1515 stream_texture_factory_ =
1516 StreamTextureFactory::Create(std::move(shared_context_provider));
siva.gunturi5d4feb052015-11-15 16:15:311517 }
1518 return stream_texture_factory_;
1519}
boliuf8753bf62016-02-11 20:09:421520
1521bool RenderThreadImpl::EnableStreamTextureCopy() {
boliu30f1b262016-04-19 00:12:331522 return sync_compositor_message_filter_.get();
boliuf8753bf62016-02-11 20:09:421523}
1524
siva.gunturi5d4feb052015-11-15 16:15:311525#endif
1526
[email protected]e9ff79c2012-10-19 21:31:261527AudioRendererMixerManager* RenderThreadImpl::GetAudioRendererMixerManager() {
[email protected]59383c782013-04-17 16:43:271528 if (!audio_renderer_mixer_manager_) {
olka7a4679392016-05-27 15:32:581529 audio_renderer_mixer_manager_ = AudioRendererMixerManager::Create();
[email protected]3958e972012-07-17 00:25:411530 }
1531
1532 return audio_renderer_mixer_manager_.get();
1533}
1534
[email protected]73429ca2014-03-06 06:07:471535base::WaitableEvent* RenderThreadImpl::GetShutdownEvent() {
1536 return ChildProcess::current()->GetShutDownEvent();
1537}
1538
staraz067f58242016-11-07 21:06:411539int32_t RenderThreadImpl::GetClientId() {
1540 return client_id_;
1541}
1542
altiminc8885e82017-01-18 13:11:141543scoped_refptr<base::SingleThreadTaskRunner>
1544RenderThreadImpl::GetTimerTaskRunner() {
1545 return renderer_scheduler_->TimerTaskRunner();
1546}
1547
1548scoped_refptr<base::SingleThreadTaskRunner>
1549RenderThreadImpl::GetLoadingTaskRunner() {
1550 return renderer_scheduler_->LoadingTaskRunner();
1551}
1552
chiniforooshan614d70a2017-03-17 01:19:331553void RenderThreadImpl::SetFieldTrialGroup(const std::string& trial_name,
1554 const std::string& group_name) {
1555 field_trial_syncer_.OnSetFieldTrialGroup(trial_name, group_name);
1556}
1557
rockot067ca55f2016-09-30 22:00:151558void RenderThreadImpl::OnAssociatedInterfaceRequest(
1559 const std::string& name,
1560 mojo::ScopedInterfaceEndpointHandle handle) {
rockot70bbb59492017-01-25 00:56:511561 if (associated_interfaces_.CanBindRequest(name))
1562 associated_interfaces_.BindRequest(name, std::move(handle));
1563 else
1564 ChildThreadImpl::OnAssociatedInterfaceRequest(name, std::move(handle));
rockot067ca55f2016-09-30 22:00:151565}
1566
weilifabbf7572017-05-22 19:05:161567scoped_refptr<base::SingleThreadTaskRunner>
1568RenderThreadImpl::GetIOTaskRunner() {
1569 return ChildProcess::current()->io_task_runner();
1570}
1571
danakj6e3bf8012014-12-16 18:27:531572bool RenderThreadImpl::IsGpuRasterizationForced() {
1573 return is_gpu_rasterization_forced_;
1574}
1575
sunnypsd8ce1c22016-05-10 18:02:401576bool RenderThreadImpl::IsAsyncWorkerContextEnabled() {
1577 return is_async_worker_context_enabled_;
1578}
1579
senorblancob60ba952015-01-27 19:12:361580int RenderThreadImpl::GetGpuRasterizationMSAASampleCount() {
1581 return gpu_rasterization_msaa_sample_count_;
1582}
1583
danakj6e3bf8012014-12-16 18:27:531584bool RenderThreadImpl::IsLcdTextEnabled() {
1585 return is_lcd_text_enabled_;
1586}
1587
1588bool RenderThreadImpl::IsDistanceFieldTextEnabled() {
1589 return is_distance_field_text_enabled_;
1590}
1591
1592bool RenderThreadImpl::IsZeroCopyEnabled() {
1593 return is_zero_copy_enabled_;
1594}
1595
ericrk1d17f752015-10-20 03:03:071596bool RenderThreadImpl::IsPartialRasterEnabled() {
1597 return is_partial_raster_enabled_;
jbroman5f7f71932015-08-18 16:24:461598}
1599
ccameronc7fcd132015-11-03 20:14:311600bool RenderThreadImpl::IsGpuMemoryBufferCompositorResourcesEnabled() {
1601 return is_gpu_memory_buffer_compositor_resources_enabled_;
1602}
1603
ccamerona7644752014-12-30 01:16:311604bool RenderThreadImpl::IsElasticOverscrollEnabled() {
1605 return is_elastic_overscroll_enabled_;
1606}
1607
Fady Samuel1d744b22017-07-10 21:23:551608const viz::BufferToTextureTargetMap&
ericrk9151705c2016-07-26 19:53:161609RenderThreadImpl::GetBufferToTextureTargetMap() {
1610 return buffer_to_texture_target_map_;
danakj6e3bf8012014-12-16 18:27:531611}
vmiura9084b342015-02-03 22:19:571612
danakj6e3bf8012014-12-16 18:27:531613scoped_refptr<base::SingleThreadTaskRunner>
1614RenderThreadImpl::GetCompositorMainThreadTaskRunner() {
1615 return main_thread_compositor_task_runner_;
1616}
1617
1618scoped_refptr<base::SingleThreadTaskRunner>
1619RenderThreadImpl::GetCompositorImplThreadTaskRunner() {
skyostil2d3b5bd2015-05-27 15:40:591620 return compositor_task_runner_;
danakj6e3bf8012014-12-16 18:27:531621}
1622
1623gpu::GpuMemoryBufferManager* RenderThreadImpl::GetGpuMemoryBufferManager() {
sadrul53546592016-12-17 01:44:211624 return gpu_->gpu_memory_buffer_manager();
danakj6e3bf8012014-12-16 18:27:531625}
1626
skyostil529caa292016-08-10 17:44:511627blink::scheduler::RendererScheduler* RenderThreadImpl::GetRendererScheduler() {
danakj6e3bf8012014-12-16 18:27:531628 return renderer_scheduler_.get();
1629}
1630
dchengcedca5612016-04-09 01:40:151631std::unique_ptr<cc::BeginFrameSource>
danakj6e3bf8012014-12-16 18:27:531632RenderThreadImpl::CreateExternalBeginFrameSource(int routing_id) {
ricea29649b92016-08-31 09:30:211633 return base::MakeUnique<CompositorExternalBeginFrameSource>(
1634 compositor_message_filter_.get(), sync_message_filter(), routing_id);
danakj6e3bf8012014-12-16 18:27:531635}
1636
samans09812d32017-03-27 19:51:501637std::unique_ptr<cc::SyntheticBeginFrameSource>
1638RenderThreadImpl::CreateSyntheticBeginFrameSource() {
1639 base::SingleThreadTaskRunner* compositor_impl_side_task_runner =
1640 compositor_task_runner_ ? compositor_task_runner_.get()
1641 : base::ThreadTaskRunnerHandle::Get().get();
1642 return base::MakeUnique<cc::BackToBackBeginFrameSource>(
1643 base::MakeUnique<cc::DelayBasedTimeSource>(
1644 compositor_impl_side_task_runner));
1645}
1646
reveman34b7a1522015-03-23 20:27:471647cc::TaskGraphRunner* RenderThreadImpl::GetTaskGraphRunner() {
prashant.nfad657e2016-06-01 07:52:171648 return categorized_worker_pool_->GetTaskGraphRunner();
reveman34b7a1522015-03-23 20:27:471649}
1650
loyso65c93c602015-08-11 05:15:571651bool RenderThreadImpl::IsThreadedAnimationEnabled() {
1652 return is_threaded_animation_enabled_;
1653}
1654
wjmaclean1d970622017-01-21 22:28:241655bool RenderThreadImpl::IsScrollAnimatorEnabled() {
1656 return is_scroll_animator_enabled_;
1657}
1658
skyostila37c2a72016-06-29 17:30:071659void RenderThreadImpl::OnRAILModeChanged(v8::RAILMode rail_mode) {
Blink Reformat1c4d759e2017-04-09 16:34:541660 blink::MainThreadIsolate()->SetRAILMode(rail_mode);
1661 blink::SetRAILModeOnWorkerThreadIsolates(rail_mode);
skyostila37c2a72016-06-29 17:30:071662}
1663
[email protected]b3e83de2012-02-07 03:33:281664bool RenderThreadImpl::IsMainThread() {
1665 return !!current();
1666}
1667
torne88b66452016-05-03 13:22:141668void RenderThreadImpl::OnChannelError() {
1669 // In single-process mode, the renderer can't be restarted after shutdown.
1670 // So, if we get a channel error, crash the whole process right now to get a
1671 // more informative stack, since we will otherwise just crash later when we
1672 // try to restart it.
1673 CHECK(!base::CommandLine::ForCurrentProcess()->HasSwitch(
1674 switches::kSingleProcess));
1675 ChildThreadImpl::OnChannelError();
1676}
1677
[email protected]f1a29a02011-10-06 23:08:441678bool RenderThreadImpl::OnControlMessageReceived(const IPC::Message& msg) {
dchenga2d442c22016-10-13 15:39:211679 for (auto& observer : observers_) {
1680 if (observer.OnControlMessageReceived(msg))
[email protected]1223d6ef2011-03-28 16:47:501681 return true;
1682 }
1683
[email protected]70c19a932010-05-14 12:59:111684 // Some messages are handled by delegates.
[email protected]1910fe82012-05-10 00:04:101685 if (appcache_dispatcher_->OnMessageReceived(msg) ||
leon.han7a5714382017-04-16 03:25:001686 dom_storage_dispatcher_->OnMessageReceived(msg)) {
[email protected]a95986a82010-12-24 06:19:281687 return true;
[email protected]1910fe82012-05-10 00:04:101688 }
[email protected]1edc16b82009-04-07 17:45:541689
[email protected]a95986a82010-12-24 06:19:281690 bool handled = true;
[email protected]f1a29a02011-10-06 23:08:441691 IPC_BEGIN_MESSAGE_MAP(RenderThreadImpl, msg)
[email protected]0ec90d522014-03-12 16:28:191692 IPC_MESSAGE_HANDLER(WorkerProcessMsg_CreateWorker, OnCreateNewSharedWorker)
[email protected]a95986a82010-12-24 06:19:281693 IPC_MESSAGE_UNHANDLED(handled = false)
[email protected]8930d472009-02-21 08:05:281694 IPC_END_MESSAGE_MAP()
[email protected]a95986a82010-12-24 06:19:281695 return handled;
initial.commit09911bf2008-07-26 23:55:291696}
1697
jdduke73220f02015-09-04 17:03:511698void RenderThreadImpl::OnProcessBackgrounded(bool backgrounded) {
1699 ChildThreadImpl::OnProcessBackgrounded(backgrounded);
1700
Alexander Timin771b3372017-06-15 13:26:471701 renderer_scheduler_->SetRendererBackgrounded(backgrounded);
hajimehoshi69093272016-05-13 08:30:581702 if (backgrounded) {
tasakb95dbb50c2017-02-08 18:07:501703 needs_to_record_first_active_paint_ = false;
tasak335a1872017-06-14 09:50:231704 GetRendererScheduler()->DefaultTaskRunner()->PostDelayedTask(
1705 FROM_HERE,
1706 base::Bind(&RenderThreadImpl::RecordMemoryUsageAfterBackgrounded,
1707 base::Unretained(this), "5min", process_foregrounded_count_),
1708 base::TimeDelta::FromMinutes(5));
1709 GetRendererScheduler()->DefaultTaskRunner()->PostDelayedTask(
1710 FROM_HERE,
1711 base::Bind(&RenderThreadImpl::RecordMemoryUsageAfterBackgrounded,
1712 base::Unretained(this), "10min",
1713 process_foregrounded_count_),
1714 base::TimeDelta::FromMinutes(10));
1715 GetRendererScheduler()->DefaultTaskRunner()->PostDelayedTask(
1716 FROM_HERE,
1717 base::Bind(&RenderThreadImpl::RecordMemoryUsageAfterBackgrounded,
1718 base::Unretained(this), "15min",
1719 process_foregrounded_count_),
1720 base::TimeDelta::FromMinutes(15));
hajimehoshi69093272016-05-13 08:30:581721 } else {
tasakbb0640b2017-05-15 09:02:261722 process_foregrounded_count_++;
hajimehoshi69093272016-05-13 08:30:581723 }
1724}
1725
1726void RenderThreadImpl::OnProcessPurgeAndSuspend() {
1727 ChildThreadImpl::OnProcessPurgeAndSuspend();
tasak6ff44032016-11-07 06:45:251728 if (!RendererIsHidden())
hajimehoshi69093272016-05-13 08:30:581729 return;
tasakff1e62422016-12-22 04:53:551730
tasakc4de4672017-04-26 02:37:361731 if (!base::FeatureList::IsEnabled(features::kPurgeAndSuspend))
1732 return;
1733
1734 base::MemoryCoordinatorClientRegistry::GetInstance()->PurgeMemory();
tasakb95dbb50c2017-02-08 18:07:501735 needs_to_record_first_active_paint_ = true;
tasakc4de4672017-04-26 02:37:361736
1737 RendererMemoryMetrics memory_metrics;
1738 if (!GetRendererMemoryMetrics(&memory_metrics))
1739 return;
1740
1741 purge_and_suspend_memory_metrics_ = memory_metrics;
tasaka27961a2017-05-24 07:33:251742 GetRendererScheduler()->DefaultTaskRunner()->PostDelayedTask(
1743 FROM_HERE,
1744 base::Bind(&RenderThreadImpl::RecordPurgeAndSuspendMemoryGrowthMetrics,
1745 base::Unretained(this), "30min", process_foregrounded_count_),
1746 base::TimeDelta::FromMinutes(30));
1747 GetRendererScheduler()->DefaultTaskRunner()->PostDelayedTask(
1748 FROM_HERE,
1749 base::Bind(&RenderThreadImpl::RecordPurgeAndSuspendMemoryGrowthMetrics,
1750 base::Unretained(this), "60min", process_foregrounded_count_),
1751 base::TimeDelta::FromMinutes(60));
1752 GetRendererScheduler()->DefaultTaskRunner()->PostDelayedTask(
1753 FROM_HERE,
1754 base::Bind(&RenderThreadImpl::RecordPurgeAndSuspendMemoryGrowthMetrics,
1755 base::Unretained(this), "90min", process_foregrounded_count_),
1756 base::TimeDelta::FromMinutes(90));
tasakb46626a2016-10-18 05:54:441757}
1758
bashia0ba0d42017-04-03 08:11:061759bool RenderThreadImpl::GetRendererMemoryMetrics(
keishi51ed0d52017-01-12 10:04:461760 RendererMemoryMetrics* memory_metrics) const {
1761 DCHECK(memory_metrics);
1762
chrisha05e94f22017-04-05 22:06:041763 // Cache this result, as it can change while this code is running, and is used
1764 // as a divisor below.
1765 size_t render_view_count = RenderView::GetRenderViewCount();
1766
1767 // If there are no render views it doesn't make sense to calculate metrics
1768 // right now.
1769 if (render_view_count == 0)
bashia0ba0d42017-04-03 08:11:061770 return false;
1771
keishi51ed0d52017-01-12 10:04:461772 blink::WebMemoryStatistics blink_stats = blink::WebMemoryStatistics::Get();
1773 memory_metrics->partition_alloc_kb =
Blink Reformat1c4d759e2017-04-09 16:34:541774 blink_stats.partition_alloc_total_allocated_bytes / 1024;
1775 memory_metrics->blink_gc_kb =
1776 blink_stats.blink_gc_total_allocated_bytes / 1024;
keishi12b598b92017-06-20 10:25:261777 std::unique_ptr<base::ProcessMetrics> metric(
1778 base::ProcessMetrics::CreateCurrentProcessMetrics());
1779 size_t malloc_usage = metric->GetMallocUsage();
keishi51ed0d52017-01-12 10:04:461780 memory_metrics->malloc_mb = malloc_usage / 1024 / 1024;
1781
1782 discardable_memory::ClientDiscardableSharedMemoryManager::Statistics
1783 discardable_stats = discardable_shared_memory_manager_->GetStatistics();
1784 size_t discardable_usage =
1785 discardable_stats.total_size - discardable_stats.freelist_size;
1786 memory_metrics->discardable_kb = discardable_usage / 1024;
1787
1788 size_t v8_usage = 0;
Blink Reformat1c4d759e2017-04-09 16:34:541789 if (v8::Isolate* isolate = blink::MainThreadIsolate()) {
keishi51ed0d52017-01-12 10:04:461790 v8::HeapStatistics v8_heap_statistics;
1791 isolate->GetHeapStatistics(&v8_heap_statistics);
1792 v8_usage = v8_heap_statistics.total_heap_size();
1793 }
1794 // TODO(tasak): Currently only memory usage of mainThreadIsolate() is
1795 // reported. We should collect memory usages of all isolates using
1796 // memory-infra.
1797 memory_metrics->v8_main_thread_isolate_mb = v8_usage / 1024 / 1024;
Blink Reformat1c4d759e2017-04-09 16:34:541798 size_t total_allocated = blink_stats.partition_alloc_total_allocated_bytes +
1799 blink_stats.blink_gc_total_allocated_bytes +
keishi51ed0d52017-01-12 10:04:461800 malloc_usage + v8_usage + discardable_usage;
1801 memory_metrics->total_allocated_mb = total_allocated / 1024 / 1024;
1802 memory_metrics->non_discardable_total_allocated_mb =
1803 (total_allocated - discardable_usage) / 1024 / 1024;
1804 memory_metrics->total_allocated_per_render_view_mb =
chrisha05e94f22017-04-05 22:06:041805 total_allocated / render_view_count / 1024 / 1024;
bashia0ba0d42017-04-03 08:11:061806
1807 return true;
keishi51ed0d52017-01-12 10:04:461808}
1809
tasak335a1872017-06-14 09:50:231810static void RecordMemoryUsageAfterBackgroundedMB(const char* basename,
1811 const char* suffix,
1812 int memory_usage) {
1813 std::string histogram_name = base::StringPrintf("%s.%s", basename, suffix);
1814 base::UmaHistogramMemoryLargeMB(histogram_name, memory_usage);
1815}
1816
1817void RenderThreadImpl::RecordMemoryUsageAfterBackgrounded(
1818 const char* suffix,
1819 int foregrounded_count) {
1820 // If this renderer is resumed, we should not update UMA.
1821 if (!RendererIsHidden())
1822 return;
1823 // If this renderer was not kept backgrounded for 5/10/15 minutes,
1824 // we should not record current memory usage.
1825 if (foregrounded_count != process_foregrounded_count_)
1826 return;
1827
1828 RendererMemoryMetrics memory_metrics;
1829 if (!GetRendererMemoryMetrics(&memory_metrics))
1830 return;
1831 RecordMemoryUsageAfterBackgroundedMB(
1832 "Memory.Experimental.Renderer.PartitionAlloc.AfterBackgrounded", suffix,
1833 memory_metrics.partition_alloc_kb / 1024);
1834 RecordMemoryUsageAfterBackgroundedMB(
1835 "Memory.Experimental.Renderer.BlinkGC.AfterBackgrounded", suffix,
1836 memory_metrics.blink_gc_kb / 1024);
1837 RecordMemoryUsageAfterBackgroundedMB(
1838 "Memory.Experimental.Renderer.Malloc.AfterBackgrounded", suffix,
1839 memory_metrics.malloc_mb);
1840 RecordMemoryUsageAfterBackgroundedMB(
1841 "Memory.Experimental.Renderer.Discardable.AfterBackgrounded", suffix,
1842 memory_metrics.discardable_kb / 1024);
1843 RecordMemoryUsageAfterBackgroundedMB(
1844 "Memory.Experimental.Renderer.V8MainThreaIsolate.AfterBackgrounded",
1845 suffix, memory_metrics.v8_main_thread_isolate_mb);
1846 RecordMemoryUsageAfterBackgroundedMB(
1847 "Memory.Experimental.Renderer.TotalAllocated.AfterBackgrounded", suffix,
1848 memory_metrics.total_allocated_mb);
1849}
1850
tasak72f64042017-01-19 14:02:531851#define GET_MEMORY_GROWTH(current, previous, allocator) \
1852 (current.allocator > previous.allocator \
1853 ? current.allocator - previous.allocator \
1854 : 0)
1855
tasaka27961a2017-05-24 07:33:251856static void RecordPurgeAndSuspendMemoryGrowthKB(const char* basename,
1857 const char* suffix,
1858 int memory_usage) {
1859 std::string histogram_name = base::StringPrintf("%s.%s", basename, suffix);
1860 base::UmaHistogramMemoryKB(histogram_name, memory_usage);
1861}
tasakbb0640b2017-05-15 09:02:261862
1863void RenderThreadImpl::RecordPurgeAndSuspendMemoryGrowthMetrics(
1864 const char* suffix,
1865 int foregrounded_count_when_purged) {
tasak72f64042017-01-19 14:02:531866 // If this renderer is resumed, we should not update UMA.
1867 if (!RendererIsHidden())
1868 return;
tasakbb0640b2017-05-15 09:02:261869 if (foregrounded_count_when_purged != process_foregrounded_count_)
1870 return;
tasak72f64042017-01-19 14:02:531871
1872 RendererMemoryMetrics memory_metrics;
bashia0ba0d42017-04-03 08:11:061873 if (!GetRendererMemoryMetrics(&memory_metrics))
1874 return;
1875
tasaka27961a2017-05-24 07:33:251876 RecordPurgeAndSuspendMemoryGrowthKB(
tasakbb0640b2017-05-15 09:02:261877 "PurgeAndSuspend.Experimental.MemoryGrowth.PartitionAllocKB", suffix,
tasak72f64042017-01-19 14:02:531878 GET_MEMORY_GROWTH(memory_metrics, purge_and_suspend_memory_metrics_,
1879 partition_alloc_kb));
tasaka27961a2017-05-24 07:33:251880 RecordPurgeAndSuspendMemoryGrowthKB(
tasakbb0640b2017-05-15 09:02:261881 "PurgeAndSuspend.Experimental.MemoryGrowth.BlinkGCKB", suffix,
tasak72f64042017-01-19 14:02:531882 GET_MEMORY_GROWTH(memory_metrics, purge_and_suspend_memory_metrics_,
1883 blink_gc_kb));
tasaka27961a2017-05-24 07:33:251884 RecordPurgeAndSuspendMemoryGrowthKB(
tasakbb0640b2017-05-15 09:02:261885 "PurgeAndSuspend.Experimental.MemoryGrowth.MallocKB", suffix,
tasak72f64042017-01-19 14:02:531886 GET_MEMORY_GROWTH(memory_metrics, purge_and_suspend_memory_metrics_,
tasakbb0640b2017-05-15 09:02:261887 malloc_mb) *
1888 1024);
tasaka27961a2017-05-24 07:33:251889 RecordPurgeAndSuspendMemoryGrowthKB(
tasakbb0640b2017-05-15 09:02:261890 "PurgeAndSuspend.Experimental.MemoryGrowth.DiscardableKB", suffix,
tasak72f64042017-01-19 14:02:531891 GET_MEMORY_GROWTH(memory_metrics, purge_and_suspend_memory_metrics_,
1892 discardable_kb));
tasaka27961a2017-05-24 07:33:251893 RecordPurgeAndSuspendMemoryGrowthKB(
tasakbb0640b2017-05-15 09:02:261894 "PurgeAndSuspend.Experimental.MemoryGrowth.V8MainThreadIsolateKB", suffix,
tasak72f64042017-01-19 14:02:531895 GET_MEMORY_GROWTH(memory_metrics, purge_and_suspend_memory_metrics_,
tasakbb0640b2017-05-15 09:02:261896 v8_main_thread_isolate_mb) *
1897 1024);
tasaka27961a2017-05-24 07:33:251898 RecordPurgeAndSuspendMemoryGrowthKB(
tasakbb0640b2017-05-15 09:02:261899 "PurgeAndSuspend.Experimental.MemoryGrowth.TotalAllocatedKB", suffix,
tasak72f64042017-01-19 14:02:531900 GET_MEMORY_GROWTH(memory_metrics, purge_and_suspend_memory_metrics_,
tasakbb0640b2017-05-15 09:02:261901 total_allocated_mb) *
1902 1024);
jdduke73220f02015-09-04 17:03:511903}
1904
sadrul6d310fa2016-08-04 02:12:161905scoped_refptr<gpu::GpuChannelHost> RenderThreadImpl::EstablishGpuChannelSync() {
[email protected]d13f35d2012-05-18 02:28:151906 TRACE_EVENT0("gpu", "RenderThreadImpl::EstablishGpuChannelSync");
1907
piman9fc22f32016-05-02 22:21:221908 if (gpu_channel_) {
[email protected]1082b1d2010-03-30 00:31:221909 // Do nothing if we already have a GPU channel or are already
1910 // establishing one.
[email protected]7951bfe2013-06-13 01:43:341911 if (!gpu_channel_->IsLost())
piman9fc22f32016-05-02 22:21:221912 return gpu_channel_;
[email protected]6217d392010-03-25 22:08:351913
1914 // Recreate the channel if it has been lost.
piman765e5282015-05-08 03:43:011915 gpu_channel_->DestroyChannel();
penghuange1d86512016-07-08 18:15:001916 gpu_channel_ = nullptr;
[email protected]6217d392010-03-25 22:08:351917 }
1918
sadrul53546592016-12-17 01:44:211919 gpu_channel_ = gpu_->EstablishGpuChannelSync();
1920 if (gpu_channel_)
1921 GetContentClient()->SetGpuInfo(gpu_channel_->gpu_info());
piman9fc22f32016-05-02 22:21:221922 return gpu_channel_;
[email protected]3bf4d532010-03-27 00:23:341923}
1924
danakjc7afae52017-06-20 21:12:411925void RenderThreadImpl::RequestNewLayerTreeFrameSink(
danakj83066a32016-06-21 02:34:491926 bool use_software,
1927 int routing_id,
1928 scoped_refptr<FrameSwapMessageQueue> frame_swap_message_queue,
fsamuelcf3002e2017-03-20 23:13:471929 const GURL& url,
danakjc7afae52017-06-20 21:12:411930 const LayerTreeFrameSinkCallback& callback) {
danakj83066a32016-06-21 02:34:491931 const base::CommandLine& command_line =
1932 *base::CommandLine::ForCurrentProcess();
1933 if (command_line.HasSwitch(switches::kDisableGpuCompositing))
1934 use_software = true;
1935
samans09812d32017-03-27 19:51:501936 // In disable gpu vsync mode, also let the renderer tick as fast as it
1937 // can. The top level begin frame source will also be running as a back
1938 // to back begin frame source, but using a synthetic begin frame source
1939 // here reduces latency when in this mode (at least for frames
1940 // starting--it potentially increases it for input on the other hand.)
1941 std::unique_ptr<cc::SyntheticBeginFrameSource> synthetic_begin_frame_source;
1942 if (command_line.HasSwitch(switches::kDisableGpuVsync) &&
1943 command_line.GetSwitchValueASCII(switches::kDisableGpuVsync) != "gpu") {
1944 synthetic_begin_frame_source = CreateSyntheticBeginFrameSource();
1945 }
1946
sadrul943e3b32016-08-04 18:22:591947#if defined(USE_AURA)
fsamuel098eade2017-03-21 18:06:141948 if (!use_software && IsRunningInMash()) {
sadrulbe22c4f2017-03-14 06:59:251949 scoped_refptr<gpu::GpuChannelHost> channel = EstablishGpuChannelSync();
1950 // If the channel could not be established correctly, then return null. This
1951 // would cause the compositor to wait and try again at a later time.
fsamuelcf3002e2017-03-20 23:13:471952 if (!channel) {
1953 callback.Run(nullptr);
1954 return;
1955 }
fsamuel95c974eb2017-03-22 10:00:251956 RendererWindowTreeClient::Get(routing_id)
danakjc7afae52017-06-20 21:12:411957 ->RequestLayerTreeFrameSink(
fsamuel95c974eb2017-03-22 10:00:251958 gpu_->CreateContextProvider(std::move(channel)),
1959 GetGpuMemoryBufferManager(), callback);
fsamuelcf3002e2017-03-20 23:13:471960 return;
danakj83066a32016-06-21 02:34:491961 }
1962#endif
1963
danakj2e3aca02017-06-23 22:58:521964 cc::mojom::CompositorFrameSinkPtrInfo sink_info;
1965 cc::mojom::CompositorFrameSinkRequest sink_request =
samansa61ab212017-05-24 12:11:431966 mojo::MakeRequest(&sink_info);
danakj2e3aca02017-06-23 22:58:521967 cc::mojom::CompositorFrameSinkClientPtr client;
1968 cc::mojom::CompositorFrameSinkClientRequest client_request =
samansa61ab212017-05-24 12:11:431969 mojo::MakeRequest(&client);
1970
danakj83066a32016-06-21 02:34:491971 if (command_line.HasSwitch(switches::kEnableVulkan)) {
1972 scoped_refptr<cc::VulkanContextProvider> vulkan_context_provider =
1973 cc::VulkanInProcessContextProvider::Create();
1974 if (vulkan_context_provider) {
1975 DCHECK(!layout_test_mode());
samansa61ab212017-05-24 12:11:431976 frame_sink_provider_->CreateForWidget(routing_id, std::move(sink_request),
1977 std::move(client));
danakjc7afae52017-06-20 21:12:411978 callback.Run(base::MakeUnique<viz::ClientLayerTreeFrameSink>(
samans7e6675cc2017-06-05 20:16:081979 std::move(vulkan_context_provider),
1980 std::move(synthetic_begin_frame_source), std::move(sink_info),
1981 std::move(client_request),
1982 base::MakeUnique<RendererLocalSurfaceIdProvider>(),
1983 false /* enable_surface_synchroninzation */));
fsamuelcf3002e2017-03-20 23:13:471984 return;
danakj83066a32016-06-21 02:34:491985 }
1986 }
1987
1988 // Create a gpu process channel and verify we want to use GPU compositing
1989 // before creating any context providers.
1990 scoped_refptr<gpu::GpuChannelHost> gpu_channel_host;
1991 if (!use_software) {
sadrul6d310fa2016-08-04 02:12:161992 gpu_channel_host = EstablishGpuChannelSync();
danakj83066a32016-06-21 02:34:491993 if (!gpu_channel_host) {
1994 // Cause the compositor to wait and try again.
fsamuelcf3002e2017-03-20 23:13:471995 callback.Run(nullptr);
1996 return;
danakj83066a32016-06-21 02:34:491997 }
1998 // We may get a valid channel, but with a software renderer. In that case,
1999 // disable GPU compositing.
2000 if (gpu_channel_host->gpu_info().software_rendering)
2001 use_software = true;
2002 }
2003
2004 if (use_software) {
2005 DCHECK(!layout_test_mode());
samansa61ab212017-05-24 12:11:432006 frame_sink_provider_->CreateForWidget(routing_id, std::move(sink_request),
2007 std::move(client));
danakjc7afae52017-06-20 21:12:412008 callback.Run(base::MakeUnique<viz::ClientLayerTreeFrameSink>(
samans7e6675cc2017-06-05 20:16:082009 nullptr, nullptr, nullptr, shared_bitmap_manager(),
2010 std::move(synthetic_begin_frame_source), std::move(sink_info),
2011 std::move(client_request),
2012 base::MakeUnique<RendererLocalSurfaceIdProvider>(),
2013 false /* enable_surface_synchroninzation */));
fsamuelcf3002e2017-03-20 23:13:472014 return;
danakj83066a32016-06-21 02:34:492015 }
2016
sadrul85cc5d82016-12-20 03:37:412017 scoped_refptr<ui::ContextProviderCommandBuffer> worker_context_provider =
danakj83066a32016-06-21 02:34:492018 SharedCompositorWorkerContextProvider();
2019 if (!worker_context_provider) {
2020 // Cause the compositor to wait and try again.
fsamuelcf3002e2017-03-20 23:13:472021 callback.Run(nullptr);
2022 return;
danakj83066a32016-06-21 02:34:492023 }
2024
2025 // The renderer compositor context doesn't do a lot of stuff, so we don't
2026 // expect it to need a lot of space for commands or transfer. Raster and
2027 // uploads happen on the worker context instead.
2028 gpu::SharedMemoryLimits limits = gpu::SharedMemoryLimits::ForMailboxContext();
2029
2030 // This is for an offscreen context for the compositor. So the default
2031 // framebuffer doesn't need alpha, depth, stencil, antialiasing.
2032 gpu::gles2::ContextCreationAttribHelper attributes;
2033 attributes.alpha_size = -1;
2034 attributes.depth_size = 0;
2035 attributes.stencil_size = 0;
2036 attributes.samples = 0;
2037 attributes.sample_buffers = 0;
2038 attributes.bind_generates_resource = false;
2039 attributes.lose_context_when_out_of_memory = true;
2040
2041 constexpr bool automatic_flushes = false;
2042 constexpr bool support_locking = false;
2043
2044 // The compositor context shares resources with the worker context unless
2045 // the worker is async.
sadrul85cc5d82016-12-20 03:37:412046 ui::ContextProviderCommandBuffer* share_context =
2047 worker_context_provider.get();
danakj83066a32016-06-21 02:34:492048 if (IsAsyncWorkerContextEnabled())
2049 share_context = nullptr;
2050
sadrul85cc5d82016-12-20 03:37:412051 scoped_refptr<ui::ContextProviderCommandBuffer> context_provider(
2052 new ui::ContextProviderCommandBuffer(
sunnyps8f9139e2017-05-12 17:53:252053 gpu_channel_host, kGpuStreamIdDefault, kGpuStreamPriorityDefault,
2054 gpu::kNullSurfaceHandle, url, automatic_flushes, support_locking,
2055 limits, attributes, share_context,
sadrul85cc5d82016-12-20 03:37:412056 ui::command_buffer_metrics::RENDER_COMPOSITOR_CONTEXT));
danakj83066a32016-06-21 02:34:492057
danakj83066a32016-06-21 02:34:492058 if (layout_test_deps_) {
danakjc7afae52017-06-20 21:12:412059 callback.Run(layout_test_deps_->CreateLayerTreeFrameSink(
jbroman6ccbc7d472016-07-27 04:45:412060 routing_id, std::move(gpu_channel_host), std::move(context_provider),
fsamuelcf3002e2017-03-20 23:13:472061 std::move(worker_context_provider), GetGpuMemoryBufferManager(), this));
2062 return;
danakj83066a32016-06-21 02:34:492063 }
2064
2065#if defined(OS_ANDROID)
2066 if (sync_compositor_message_filter_) {
samans09812d32017-03-27 19:51:502067 std::unique_ptr<cc::BeginFrameSource> begin_frame_source =
2068 synthetic_begin_frame_source
2069 ? std::move(synthetic_begin_frame_source)
2070 : CreateExternalBeginFrameSource(routing_id);
danakjc7afae52017-06-20 21:12:412071 callback.Run(base::MakeUnique<SynchronousLayerTreeFrameSink>(
danakja40dd4482016-06-28 01:14:102072 std::move(context_provider), std::move(worker_context_provider),
danakje9cf5812017-02-16 22:22:552073 GetGpuMemoryBufferManager(), shared_bitmap_manager(), routing_id,
danakjc7afae52017-06-20 21:12:412074 g_next_layer_tree_frame_sink_id++, std::move(begin_frame_source),
enne077ba4862016-09-12 20:59:532075 sync_compositor_message_filter_.get(),
fsamuelcf3002e2017-03-20 23:13:472076 std::move(frame_swap_message_queue)));
2077 return;
danakj83066a32016-06-21 02:34:492078 }
2079#endif
samansa61ab212017-05-24 12:11:432080 frame_sink_provider_->CreateForWidget(routing_id, std::move(sink_request),
2081 std::move(client));
danakjc7afae52017-06-20 21:12:412082 callback.Run(base::MakeUnique<viz::ClientLayerTreeFrameSink>(
samans2040988b2017-04-11 23:58:352083 std::move(context_provider), std::move(worker_context_provider),
samans7e6675cc2017-06-05 20:16:082084 GetGpuMemoryBufferManager(), nullptr,
2085 std::move(synthetic_begin_frame_source), std::move(sink_info),
2086 std::move(client_request),
2087 base::MakeUnique<RendererLocalSurfaceIdProvider>(),
2088 false /* enable_surface_synchroninzation */));
danakj83066a32016-06-21 02:34:492089}
2090
rockot067ca55f2016-09-30 22:00:152091AssociatedInterfaceRegistry*
2092RenderThreadImpl::GetAssociatedInterfaceRegistry() {
2093 return &associated_interfaces_;
2094}
2095
jbroman6ccbc7d472016-07-27 04:45:412096std::unique_ptr<cc::SwapPromise>
2097RenderThreadImpl::RequestCopyOfOutputForLayoutTest(
2098 int32_t routing_id,
2099 std::unique_ptr<cc::CopyOutputRequest> request) {
2100 DCHECK(layout_test_deps_);
2101 return layout_test_deps_->RequestCopyOfOutput(routing_id, std::move(request));
2102}
2103
altimineb6bd1962017-05-03 14:52:382104std::unique_ptr<blink::WebMediaStreamCenter>
2105RenderThreadImpl::CreateMediaStreamCenter(
[email protected]180ef242013-11-07 06:50:462106 blink::WebMediaStreamCenterClient* client) {
altimineb6bd1962017-05-03 14:52:382107 std::unique_ptr<blink::WebMediaStreamCenter> media_stream_center;
Brett Wilson0748bf412016-11-22 17:55:462108#if BUILDFLAG(ENABLE_WEBRTC)
altimineb6bd1962017-05-03 14:52:382109 if (!media_stream_center) {
2110 media_stream_center =
2111 GetContentClient()->renderer()->OverrideCreateWebMediaStreamCenter(
2112 client);
2113 if (!media_stream_center) {
2114 media_stream_center = base::MakeUnique<MediaStreamCenter>(
2115 client, GetPeerConnectionDependencyFactory());
[email protected]68e5fee2013-02-18 10:04:222116 }
2117 }
[email protected]d8cd8372012-03-09 10:49:512118#endif
altimineb6bd1962017-05-03 14:52:382119 return media_stream_center;
[email protected]d8cd8372012-03-09 10:49:512120}
2121
Brett Wilson0748bf412016-11-22 17:55:462122#if BUILDFLAG(ENABLE_WEBRTC)
[email protected]0107d8a2014-05-16 10:20:342123PeerConnectionDependencyFactory*
2124RenderThreadImpl::GetPeerConnectionDependencyFactory() {
[email protected]83e0a482014-05-22 18:07:182125 return peer_connection_factory_.get();
[email protected]6ee10bd2012-09-13 09:01:532126}
[email protected]22fe91d2014-08-12 17:07:122127#endif
[email protected]6ee10bd2012-09-13 09:01:532128
rockot1587e332016-07-27 17:44:142129mojom::RenderFrameMessageFilter*
2130RenderThreadImpl::render_frame_message_filter() {
2131 if (!render_frame_message_filter_)
2132 GetChannel()->GetRemoteAssociatedInterface(&render_frame_message_filter_);
2133 return render_frame_message_filter_.get();
2134}
2135
rockote261d2112016-09-21 22:22:232136mojom::RenderMessageFilter* RenderThreadImpl::render_message_filter() {
2137 if (!render_message_filter_)
2138 GetChannel()->GetRemoteAssociatedInterface(&render_message_filter_);
2139 return render_message_filter_.get();
2140}
2141
penghuang346a46f92016-03-31 21:37:522142gpu::GpuChannelHost* RenderThreadImpl::GetGpuChannel() {
piman9fc22f32016-05-02 22:21:222143 if (!gpu_channel_)
danakj3873e852016-05-05 00:46:072144 return nullptr;
[email protected]7951bfe2013-06-13 01:43:342145 if (gpu_channel_->IsLost())
danakj3873e852016-05-05 00:46:072146 return nullptr;
[email protected]6217d392010-03-25 22:08:352147 return gpu_channel_.get();
2148}
2149
chiniforooshan614d70a2017-03-17 01:19:332150void RenderThreadImpl::OnFieldTrialGroupFinalized(
2151 const std::string& trial_name,
2152 const std::string& group_name) {
2153 mojom::FieldTrialRecorderPtr field_trial_recorder;
ben649b3edd2017-03-23 00:32:022154 GetConnector()->BindInterface(mojom::kBrowserServiceName,
2155 &field_trial_recorder);
chiniforooshan614d70a2017-03-17 01:19:332156 field_trial_recorder->FieldTrialActivated(trial_name);
2157}
2158
rockot067ca55f2016-09-30 22:00:152159void RenderThreadImpl::CreateView(mojom::CreateViewParamsPtr params) {
2160 CompositorDependencies* compositor_deps = this;
wjmaclean1d970622017-01-21 22:28:242161 is_scroll_animator_enabled_ = params->web_preferences.enable_scroll_animator;
rockot067ca55f2016-09-30 22:00:152162 // When bringing in render_view, also bring in webkit's glue and jsbindings.
nickf7b38222016-11-22 21:59:352163 RenderViewImpl::Create(compositor_deps, *params,
2164 RenderWidget::ShowCallback());
rockot067ca55f2016-09-30 22:00:152165}
2166
rockot53be7caf2016-10-04 20:17:082167void RenderThreadImpl::CreateFrame(mojom::CreateFrameParamsPtr params) {
2168 // Debug cases of https://crbug.com/626802.
2169 base::debug::SetCrashKeyValue("newframe_routing_id",
2170 base::IntToString(params->routing_id));
2171 base::debug::SetCrashKeyValue("newframe_proxy_id",
2172 base::IntToString(params->proxy_routing_id));
2173 base::debug::SetCrashKeyValue("newframe_opener_id",
2174 base::IntToString(params->opener_routing_id));
2175 base::debug::SetCrashKeyValue("newframe_parent_id",
2176 base::IntToString(params->parent_routing_id));
2177 base::debug::SetCrashKeyValue("newframe_widget_id",
2178 base::IntToString(
2179 params->widget_params->routing_id));
2180 base::debug::SetCrashKeyValue("newframe_widget_hidden",
2181 params->widget_params->hidden ? "yes" : "no");
2182 base::debug::SetCrashKeyValue("newframe_replicated_origin",
2183 params->replication_state.origin.Serialize());
2184 base::debug::SetCrashKeyValue("newframe_oopifs_possible",
2185 SiteIsolationPolicy::AreCrossProcessFramesPossible() ? "yes" : "no");
2186 CompositorDependencies* compositor_deps = this;
2187 RenderFrameImpl::CreateFrame(
2188 params->routing_id, params->proxy_routing_id, params->opener_routing_id,
2189 params->parent_routing_id, params->previous_sibling_routing_id,
2190 params->replication_state, compositor_deps, *params->widget_params,
2191 params->frame_owner_properties);
2192}
2193
2194void RenderThreadImpl::CreateFrameProxy(
2195 int32_t routing_id,
2196 int32_t render_view_routing_id,
2197 int32_t opener_routing_id,
2198 int32_t parent_routing_id,
2199 const FrameReplicationState& replicated_state) {
nick3b5a21f2016-11-22 23:07:112200 RenderFrameProxy::CreateFrameProxy(
2201 routing_id, render_view_routing_id,
2202 RenderFrameImpl::ResolveOpener(opener_routing_id), parent_routing_id,
2203 replicated_state);
rockot53be7caf2016-10-04 20:17:082204}
2205
rockota2db0da2016-10-18 17:39:112206void RenderThreadImpl::OnNetworkConnectionChanged(
2207 net::NetworkChangeNotifier::ConnectionType type,
2208 double max_bandwidth_mbps) {
2209 bool online = type != net::NetworkChangeNotifier::CONNECTION_NONE;
Blink Reformat1c4d759e2017-04-09 16:34:542210 WebNetworkStateNotifier::SetOnLine(online);
rockota2db0da2016-10-18 17:39:112211 for (auto& observer : observers_)
2212 observer.NetworkStateChanged(online);
Blink Reformat1c4d759e2017-04-09 16:34:542213 WebNetworkStateNotifier::SetWebConnection(
rockota2db0da2016-10-18 17:39:112214 NetConnectionTypeToWebConnectionType(type), max_bandwidth_mbps);
2215}
2216
tbansal15973c32017-05-10 18:40:442217void RenderThreadImpl::OnNetworkQualityChanged(
tbansalb612c5d2017-05-25 18:53:062218 net::EffectiveConnectionType type,
tbansal99d8aeb2017-05-22 19:12:582219 base::TimeDelta http_rtt,
2220 base::TimeDelta transport_rtt,
tbansal15973c32017-05-10 18:40:442221 double downlink_throughput_kbps) {
2222 UMA_HISTOGRAM_BOOLEAN("NQE.RenderThreadNotified", true);
tbansalb612c5d2017-05-25 18:53:062223 WebNetworkStateNotifier::SetNetworkQuality(
2224 EffectiveConnectionTypeToWebEffectiveConnectionType(type), http_rtt,
2225 transport_rtt, downlink_throughput_kbps);
tbansal15973c32017-05-10 18:40:442226}
2227
rockota2db0da2016-10-18 17:39:112228void RenderThreadImpl::SetWebKitSharedTimersSuspended(bool suspend) {
2229#if defined(OS_ANDROID)
2230 if (suspend) {
2231 renderer_scheduler_->SuspendTimerQueue();
2232 } else {
2233 renderer_scheduler_->ResumeTimerQueue();
2234 }
2235 webkit_shared_timer_suspended_ = suspend;
2236#else
2237 NOTREACHED();
2238#endif
2239}
2240
2241void RenderThreadImpl::UpdateScrollbarTheme(
2242 mojom::UpdateScrollbarThemeParamsPtr params) {
2243#if defined(OS_MACOSX)
2244 static_cast<WebScrollbarBehaviorImpl*>(
Blink Reformat1c4d759e2017-04-09 16:34:542245 blink_platform_impl_->ScrollbarBehavior())
rockota2db0da2016-10-18 17:39:112246 ->set_jump_on_track_click(params->jump_on_track_click);
2247
Blink Reformat1c4d759e2017-04-09 16:34:542248 blink::WebScrollbarTheme::UpdateScrollbarsWithNSDefaults(
rockota2db0da2016-10-18 17:39:112249 params->initial_button_delay, params->autoscroll_button_delay,
2250 params->preferred_scroller_style, params->redraw,
2251 params->button_placement);
2252#else
2253 NOTREACHED();
2254#endif
2255}
2256
2257void RenderThreadImpl::OnSystemColorsChanged(
2258 int32_t aqua_color_variant,
2259 const std::string& highlight_text_color,
2260 const std::string& highlight_color) {
2261#if defined(OS_MACOSX)
2262 SystemColorsDidChange(aqua_color_variant, highlight_text_color,
2263 highlight_color);
2264#else
2265 NOTREACHED();
2266#endif
2267}
2268
2269void RenderThreadImpl::PurgePluginListCache(bool reload_pages) {
brettw4b461082016-11-19 18:55:162270#if BUILDFLAG(ENABLE_PLUGINS)
rockota2db0da2016-10-18 17:39:112271 // The call below will cause a GetPlugins call with refresh=true, but at this
2272 // point we already know that the browser has refreshed its list, so disable
2273 // refresh temporarily to prevent each renderer process causing the list to be
2274 // regenerated.
2275 blink_platform_impl_->set_plugin_refresh_allowed(false);
Blink Reformat1c4d759e2017-04-09 16:34:542276 blink::ResetPluginCache(reload_pages);
rockota2db0da2016-10-18 17:39:112277 blink_platform_impl_->set_plugin_refresh_allowed(true);
2278
2279 for (auto& observer : observers_)
2280 observer.PluginListChanged();
2281#else
2282 NOTREACHED();
2283#endif
2284}
2285
[email protected]0ec90d522014-03-12 16:28:192286void RenderThreadImpl::OnCreateNewSharedWorker(
2287 const WorkerProcessMsg_CreateWorker_Params& params) {
2288 // EmbeddedSharedWorkerStub will self-destruct.
mkwstcfa98932016-03-09 13:06:192289 new EmbeddedSharedWorkerStub(
2290 params.url, params.name, params.content_security_policy,
2291 params.security_policy_type, params.creation_address_space,
horoed54f832017-05-21 05:25:472292 params.pause_on_start, params.route_id, params.data_saver_enabled);
[email protected]0ec90d522014-03-12 16:28:192293}
2294
[email protected]5071cb22013-07-10 02:19:062295void RenderThreadImpl::OnMemoryPressure(
2296 base::MemoryPressureListener::MemoryPressureLevel memory_pressure_level) {
hong.zhengb28b5332016-05-11 02:33:392297 TRACE_EVENT0("memory","RenderThreadImpl::OnMemoryPressure");
rmcilroy7fbb3bd52015-02-17 19:02:142298 if (blink_platform_impl_) {
Blink Reformat1c4d759e2017-04-09 16:34:542299 blink::WebMemoryCoordinator::OnMemoryPressure(
bashic577bfc2016-01-08 03:42:352300 static_cast<blink::WebMemoryPressureLevel>(memory_pressure_level));
hajimehoshi7bb39582016-10-12 04:30:572301 }
2302 if (memory_pressure_level ==
2303 base::MemoryPressureListener::MEMORY_PRESSURE_LEVEL_CRITICAL) {
2304 ReleaseFreeMemory();
2305 ClearMemory();
2306 }
2307}
rmcilroyab967c972015-02-17 23:15:002308
hajimehoshi7bb39582016-10-12 04:30:572309void RenderThreadImpl::OnMemoryStateChange(base::MemoryState state) {
hajimehoshi7bb39582016-10-12 04:30:572310 if (blink_platform_impl_) {
Blink Reformat1c4d759e2017-04-09 16:34:542311 blink::WebMemoryCoordinator::OnMemoryStateChange(
hajimehoshi7bb39582016-10-12 04:30:572312 static_cast<blink::MemoryState>(state));
2313 }
bashi233f65e2017-02-09 08:36:032314}
2315
2316void RenderThreadImpl::OnPurgeMemory() {
bashib9058f282017-03-30 01:55:242317 // Record amount of purged memory after 2 seconds. 2 seconds is arbitrary
2318 // but it works most cases.
2319 RendererMemoryMetrics metrics;
bashia0ba0d42017-04-03 08:11:062320 if (!GetRendererMemoryMetrics(&metrics))
2321 return;
2322
bashib9058f282017-03-30 01:55:242323 GetRendererScheduler()->DefaultTaskRunner()->PostDelayedTask(
2324 FROM_HERE,
2325 base::Bind(&RenderThreadImpl::RecordPurgeMemory, base::Unretained(this),
2326 std::move(metrics)),
2327 base::TimeDelta::FromSeconds(2));
2328
bashi233f65e2017-02-09 08:36:032329 OnTrimMemoryImmediately();
2330 ReleaseFreeMemory();
2331 ClearMemory();
2332 if (blink_platform_impl_)
Blink Reformat1c4d759e2017-04-09 16:34:542333 blink::WebMemoryCoordinator::OnPurgeMemory();
hajimehoshi7bb39582016-10-12 04:30:572334}
2335
bashib9058f282017-03-30 01:55:242336void RenderThreadImpl::RecordPurgeMemory(RendererMemoryMetrics before) {
2337 RendererMemoryMetrics after;
bashia0ba0d42017-04-03 08:11:062338 if (!GetRendererMemoryMetrics(&after))
2339 return;
bashib9058f282017-03-30 01:55:242340 int64_t mbytes = static_cast<int64_t>(before.total_allocated_mb) -
2341 static_cast<int64_t>(after.total_allocated_mb);
2342 if (mbytes < 0)
2343 mbytes = 0;
2344 UMA_HISTOGRAM_MEMORY_LARGE_MB("Memory.Experimental.Renderer.PurgedMemory",
2345 mbytes);
2346}
2347
hajimehoshi7bb39582016-10-12 04:30:572348void RenderThreadImpl::ClearMemory() {
2349 // Do not call into blink if it is not initialized.
2350 if (blink_platform_impl_) {
2351 // Purge Skia font cache, by setting it to 0 and then again to the
2352 // previous limit.
2353 size_t font_cache_limit = SkGraphics::SetFontCacheLimit(0);
2354 SkGraphics::SetFontCacheLimit(font_cache_limit);
rmcilroy7fbb3bd52015-02-17 19:02:142355 }
[email protected]5071cb22013-07-10 02:19:062356}
2357
skyostil2d3b5bd2015-05-27 15:40:592358scoped_refptr<base::SingleThreadTaskRunner>
thestig529ad8a2016-07-08 20:30:122359RenderThreadImpl::GetFileThreadTaskRunner() {
fdoraye94d8642016-07-07 19:19:012360 DCHECK(message_loop()->task_runner()->BelongsToCurrentThread());
[email protected]59383c782013-04-17 16:43:272361 if (!file_thread_) {
[email protected]c6a7b862010-08-20 22:19:382362 file_thread_.reset(new base::Thread("Renderer::FILE"));
2363 file_thread_->Start();
2364 }
skyostil2d3b5bd2015-05-27 15:40:592365 return file_thread_->task_runner();
[email protected]c6a7b862010-08-20 22:19:382366}
[email protected]e9ff79c2012-10-19 21:31:262367
acolwellb4034942014-08-28 15:42:432368scoped_refptr<base::SingleThreadTaskRunner>
2369RenderThreadImpl::GetMediaThreadTaskRunner() {
fdoraye94d8642016-07-07 19:19:012370 DCHECK(message_loop()->task_runner()->BelongsToCurrentThread());
[email protected]c1330c82013-06-06 02:23:252371 if (!media_thread_) {
2372 media_thread_.reset(new base::Thread("Media"));
2373 media_thread_->Start();
2374 }
skyostil2d3b5bd2015-05-27 15:40:592375 return media_thread_->task_runner();
[email protected]c1330c82013-06-06 02:23:252376}
2377
dcastagna4517a182015-08-05 19:51:032378base::TaskRunner* RenderThreadImpl::GetWorkerTaskRunner() {
prashant.nfad657e2016-06-01 07:52:172379 return categorized_worker_pool_.get();
dcastagnab880e8f2015-06-30 20:16:062380}
2381
sadrul85cc5d82016-12-20 03:37:412382scoped_refptr<ui::ContextProviderCommandBuffer>
danakj0b4b94e32016-05-10 22:33:012383RenderThreadImpl::SharedCompositorWorkerContextProvider() {
revemand180dfc32015-09-24 00:19:432384 DCHECK(IsMainThread());
2385 // Try to reuse existing shared worker context provider.
revemand180dfc32015-09-24 00:19:432386 if (shared_worker_context_provider_) {
2387 // Note: If context is lost, delete reference after releasing the lock.
boliu11afa7e2016-04-18 18:04:142388 cc::ContextProvider::ScopedContextLock lock(
2389 shared_worker_context_provider_.get());
revemand180dfc32015-09-24 00:19:432390 if (shared_worker_context_provider_->ContextGL()
danakje8ec797e2016-04-19 04:08:432391 ->GetGraphicsResetStatusKHR() == GL_NO_ERROR)
2392 return shared_worker_context_provider_;
revemand180dfc32015-09-24 00:19:432393 }
danakje8ec797e2016-04-19 04:08:432394
sadrul6d310fa2016-08-04 02:12:162395 scoped_refptr<gpu::GpuChannelHost> gpu_channel_host(
2396 EstablishGpuChannelSync());
danakje8ec797e2016-04-19 04:08:432397 if (!gpu_channel_host) {
2398 shared_worker_context_provider_ = nullptr;
2399 return shared_worker_context_provider_;
revemand180dfc32015-09-24 00:19:432400 }
danakje8ec797e2016-04-19 04:08:432401
sunnyps8f9139e2017-05-12 17:53:252402 int32_t stream_id = kGpuStreamIdDefault;
2403 gpu::SchedulingPriority stream_priority = kGpuStreamPriorityDefault;
sunnypsd8ce1c22016-05-10 18:02:402404 if (is_async_worker_context_enabled_) {
sunnyps8f9139e2017-05-12 17:53:252405 stream_id = kGpuStreamIdWorker;
2406 stream_priority = kGpuStreamPriorityWorker;
sunnypsd8ce1c22016-05-10 18:02:402407 }
2408
danakj9a04adc2016-05-16 22:45:072409 bool support_locking = true;
danakj0dd9e1e2016-05-11 22:15:092410 shared_worker_context_provider_ = CreateOffscreenContext(
danakj9a04adc2016-05-16 22:45:072411 std::move(gpu_channel_host), gpu::SharedMemoryLimits(), support_locking,
sadrul85cc5d82016-12-20 03:37:412412 ui::command_buffer_metrics::RENDER_WORKER_CONTEXT, stream_id,
danakj0dd9e1e2016-05-11 22:15:092413 stream_priority);
danakje8ec797e2016-04-19 04:08:432414 if (!shared_worker_context_provider_->BindToCurrentThread())
2415 shared_worker_context_provider_ = nullptr;
revemand180dfc32015-09-24 00:19:432416 return shared_worker_context_provider_;
2417}
2418
juncai2f298a82017-04-18 03:51:392419void RenderThreadImpl::SampleGamepads(device::Gamepads* data) {
Blink Reformat1c4d759e2017-04-09 16:34:542420 blink_platform_impl_->SampleGamepads(*data);
[email protected]0ff736562014-05-09 09:09:472421}
2422
rmcilroyaa296052015-04-14 15:35:272423bool RenderThreadImpl::RendererIsHidden() const {
2424 return widget_count_ > 0 && hidden_widget_count_ == widget_count_;
2425}
2426
[email protected]b2db9272014-01-10 17:42:002427void RenderThreadImpl::WidgetCreated() {
rmcilroyaa296052015-04-14 15:35:272428 bool renderer_was_hidden = RendererIsHidden();
[email protected]b2db9272014-01-10 17:42:002429 widget_count_++;
rmcilroyaa296052015-04-14 15:35:272430 if (renderer_was_hidden)
2431 OnRendererVisible();
[email protected]b2db9272014-01-10 17:42:002432}
2433
2434void RenderThreadImpl::WidgetDestroyed() {
rmcilroyaa296052015-04-14 15:35:272435 // TODO(rmcilroy): Remove the restriction that destroyed widgets must be
2436 // unhidden before WidgetDestroyed is called.
2437 DCHECK_GT(widget_count_, 0);
2438 DCHECK_GT(widget_count_, hidden_widget_count_);
[email protected]b2db9272014-01-10 17:42:002439 widget_count_--;
rmcilroyaa296052015-04-14 15:35:272440 if (RendererIsHidden())
2441 OnRendererHidden();
[email protected]b2db9272014-01-10 17:42:002442}
2443
2444void RenderThreadImpl::WidgetHidden() {
2445 DCHECK_LT(hidden_widget_count_, widget_count_);
2446 hidden_widget_count_++;
rmcilroyaa296052015-04-14 15:35:272447 if (RendererIsHidden())
2448 OnRendererHidden();
[email protected]b2db9272014-01-10 17:42:002449}
2450
2451void RenderThreadImpl::WidgetRestored() {
rmcilroyaa296052015-04-14 15:35:272452 bool renderer_was_hidden = RendererIsHidden();
[email protected]b2db9272014-01-10 17:42:002453 DCHECK_GT(hidden_widget_count_, 0);
2454 hidden_widget_count_--;
rmcilroyaa296052015-04-14 15:35:272455 if (renderer_was_hidden)
2456 OnRendererVisible();
2457}
[email protected]b2db9272014-01-10 17:42:002458
rmcilroyaa296052015-04-14 15:35:272459void RenderThreadImpl::OnRendererHidden() {
Blink Reformat1c4d759e2017-04-09 16:34:542460 blink::MainThreadIsolate()->IsolateInBackgroundNotification();
rmcilroyaa296052015-04-14 15:35:272461 // TODO(rmcilroy): Remove IdleHandler and replace it with an IdleTask
2462 // scheduled by the RendererScheduler - http://crbug.com/469210.
ulan4a385192015-11-11 10:59:182463 if (!GetContentClient()->renderer()->RunIdleHandlerWhenWidgetsHidden())
2464 return;
Alexander Timin771b3372017-06-15 13:26:472465 renderer_scheduler_->SetRendererHidden(true);
ulan4a385192015-11-11 10:59:182466 ScheduleIdleHandler(kInitialIdleHandlerDelayMs);
rmcilroyaa296052015-04-14 15:35:272467}
2468
2469void RenderThreadImpl::OnRendererVisible() {
Blink Reformat1c4d759e2017-04-09 16:34:542470 blink::MainThreadIsolate()->IsolateInForegroundNotification();
rmcilroyaa296052015-04-14 15:35:272471 if (!GetContentClient()->renderer()->RunIdleHandlerWhenWidgetsHidden())
[email protected]b2db9272014-01-10 17:42:002472 return;
Alexander Timin771b3372017-06-15 13:26:472473 renderer_scheduler_->SetRendererHidden(false);
[email protected]b2db9272014-01-10 17:42:002474 ScheduleIdleHandler(kLongIdleHandlerDelayMs);
2475}
2476
ssid0603ca9f2015-06-09 16:48:082477void RenderThreadImpl::ReleaseFreeMemory() {
2478 base::allocator::ReleaseFreeMemory();
penghuang342762b2016-12-02 21:04:582479 discardable_shared_memory_manager_->ReleaseFreeMemory();
ssid0603ca9f2015-06-09 16:48:082480
2481 if (blink_platform_impl_)
Blink Reformat1c4d759e2017-04-09 16:34:542482 blink::DecommitFreeableMemory();
ssid0603ca9f2015-06-09 16:48:082483}
2484
ben76f52b242016-06-18 05:42:482485RenderThreadImpl::PendingFrameCreate::PendingFrameCreate(
benf28ce882017-05-02 16:15:492486 const service_manager::BindSourceInfo& browser_info,
rockotf8fdd9b2015-12-16 22:22:352487 int routing_id,
ben76f52b242016-06-18 05:42:482488 mojom::FrameRequest frame_request,
csharrison95f01e922017-04-24 18:52:352489 mojom::FrameHostInterfaceBrokerPtr frame_host_interface_broker)
benf28ce882017-05-02 16:15:492490 : browser_info_(browser_info),
2491 routing_id_(routing_id),
ben76f52b242016-06-18 05:42:482492 frame_request_(std::move(frame_request)),
csharrison95f01e922017-04-24 18:52:352493 frame_host_interface_broker_(std::move(frame_host_interface_broker)) {
ben76f52b242016-06-18 05:42:482494 // The RenderFrame may be deleted before the CreateFrame message is received.
2495 // In that case, the RenderFrameHost should cancel the create, which is
csharrison95f01e922017-04-24 18:52:352496 // detected by setting an error handler on |frame_host_interface_broker_|.
2497 frame_host_interface_broker_.set_connection_error_handler(
2498 base::Bind(&RenderThreadImpl::PendingFrameCreate::OnConnectionError,
2499 base::Unretained(this)));
rockotf8fdd9b2015-12-16 22:22:352500}
2501
ben76f52b242016-06-18 05:42:482502RenderThreadImpl::PendingFrameCreate::~PendingFrameCreate() {
rockotf8fdd9b2015-12-16 22:22:352503}
2504
ben76f52b242016-06-18 05:42:482505void RenderThreadImpl::PendingFrameCreate::OnConnectionError() {
rockotf8fdd9b2015-12-16 22:22:352506 size_t erased =
ben76f52b242016-06-18 05:42:482507 RenderThreadImpl::current()->pending_frame_creates_.erase(routing_id_);
rockotf8fdd9b2015-12-16 22:22:352508 DCHECK_EQ(1u, erased);
2509}
2510
hong.zhengb28b5332016-05-11 02:33:392511void RenderThreadImpl::OnSyncMemoryPressure(
2512 base::MemoryPressureListener::MemoryPressureLevel memory_pressure_level) {
Blink Reformat1c4d759e2017-04-09 16:34:542513 if (!blink::MainThreadIsolate())
hong.zhengb28b5332016-05-11 02:33:392514 return;
2515
2516 v8::MemoryPressureLevel v8_memory_pressure_level =
2517 static_cast<v8::MemoryPressureLevel>(memory_pressure_level);
2518
Luke Halliwell16136de2017-07-05 21:15:562519#if !BUILDFLAG(ALLOW_CRITICAL_MEMORY_PRESSURE_HANDLING_IN_FOREGROUND)
hong.zhengb28b5332016-05-11 02:33:392520 // In order to reduce performance impact, translate critical level to
Luke Halliwell16136de2017-07-05 21:15:562521 // moderate level for foreground renderer.
hong.zhengb28b5332016-05-11 02:33:392522 if (!RendererIsHidden() &&
2523 v8_memory_pressure_level == v8::MemoryPressureLevel::kCritical)
2524 v8_memory_pressure_level = v8::MemoryPressureLevel::kModerate;
Luke Halliwell16136de2017-07-05 21:15:562525#endif // !BUILDFLAG(ALLOW_CRITICAL_MEMORY_PRESSURE_HANDLING_IN_FOREGROUND)
hong.zhengb28b5332016-05-11 02:33:392526
Blink Reformat1c4d759e2017-04-09 16:34:542527 blink::MainThreadIsolate()->MemoryPressureNotification(
hong.zhengb28b5332016-05-11 02:33:392528 v8_memory_pressure_level);
2529 blink::MemoryPressureNotificationToWorkerThreadIsolates(
2530 v8_memory_pressure_level);
2531}
2532
bashic4b4afcb2016-08-23 06:37:522533// Note that this would be called only when memory_coordinator is enabled.
2534// OnSyncMemoryPressure() is never called in that case.
2535void RenderThreadImpl::OnTrimMemoryImmediately() {
Blink Reformat1c4d759e2017-04-09 16:34:542536 if (blink::MainThreadIsolate()) {
2537 blink::MainThreadIsolate()->MemoryPressureNotification(
bashic4b4afcb2016-08-23 06:37:522538 v8::MemoryPressureLevel::kCritical);
2539 blink::MemoryPressureNotificationToWorkerThreadIsolates(
2540 v8::MemoryPressureLevel::kCritical);
2541 }
2542}
2543
rockot067ca55f2016-09-30 22:00:152544void RenderThreadImpl::OnRendererInterfaceRequest(
2545 mojom::RendererAssociatedRequest request) {
2546 DCHECK(!renderer_binding_.is_bound());
2547 renderer_binding_.Bind(std::move(request));
2548}
bashic4b4afcb2016-08-23 06:37:522549
[email protected]e9ff79c2012-10-19 21:31:262550} // namespace content