blob: 8ea4bb12aade5984c278edfbd451a37fde8103f0 [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"
[email protected]06533c0b2009-03-05 21:39:1114#include "base/command_line.h"
creis9f7248b2016-01-27 20:27:3915#include "base/debug/crash_logging.h"
[email protected]94f9a0f682009-06-15 18:30:3016#include "base/lazy_instance.h"
[email protected]bee16aab2009-08-26 15:55:0317#include "base/logging.h"
avi1023d012015-12-25 02:39:1418#include "base/macros.h"
reveman1af05cb32015-03-17 23:18:1619#include "base/memory/discardable_memory_allocator.h"
hajimehoshi7bb39582016-10-12 04:30:5720#include "base/memory/memory_coordinator_client_registry.h"
dchengcedca5612016-04-09 01:40:1521#include "base/memory/ptr_util.h"
[email protected]8bac37b2013-07-18 19:13:5622#include "base/memory/shared_memory.h"
[email protected]835d7c82010-10-14 04:38:3823#include "base/metrics/field_trial.h"
asvitkine8d51e9d2016-09-02 23:55:4324#include "base/metrics/histogram_macros.h"
[email protected]433df472012-03-07 20:33:3925#include "base/path_service.h"
tasakb46626a2016-10-18 05:54:4426#include "base/process/process_metrics.h"
fdoray2df4a9e2016-07-18 23:47:1627#include "base/run_loop.h"
[email protected]21aa99682013-06-11 07:17:0128#include "base/strings/string16.h"
[email protected]1e1d1e12014-01-17 16:14:2929#include "base/strings/string_number_conversions.h"
hablichd6a4f122015-10-28 11:34:4930#include "base/strings/string_split.h"
ccameron6728bae32015-01-09 20:18:0631#include "base/strings/sys_string_conversions.h"
[email protected]74ebfb12013-06-07 20:48:0032#include "base/strings/utf_string_conversions.h"
reveman34b7a1522015-03-23 20:27:4733#include "base/threading/simple_thread.h"
[email protected]1357c322010-12-30 22:18:5634#include "base/threading/thread_local.h"
[email protected]d293572a2013-05-23 18:50:4535#include "base/threading/thread_restrictions.h"
gab30f26df2016-05-11 19:37:5536#include "base/threading/thread_task_runner_handle.h"
ccameron9c48d1d42016-09-22 01:46:0137#include "base/trace_event/memory_dump_manager.h"
primiano9e38d552015-01-28 04:18:0138#include "base/trace_event/trace_event.h"
[email protected]7a4de7a62010-08-17 18:38:2439#include "base/values.h"
avi1023d012015-12-25 02:39:1440#include "build/build_config.h"
jbroman0d302162015-09-05 05:46:2341#include "cc/base/histograms.h"
[email protected]d72493152014-01-08 17:37:4542#include "cc/base/switches.h"
[email protected]38564622014-08-19 02:47:1843#include "cc/blink/web_layer_impl.h"
ericrk9151705c2016-07-26 19:53:1644#include "cc/output/buffer_to_texture_target_map.h"
danakj1120f4c2016-09-15 02:05:3245#include "cc/output/compositor_frame_sink.h"
jbroman6ccbc7d472016-07-27 04:45:4146#include "cc/output/copy_output_request.h"
danakj83066a32016-06-21 02:34:4947#include "cc/output/vulkan_in_process_context_provider.h"
danakj920156852015-05-18 20:22:2948#include "cc/raster/task_graph_runner.h"
vollick1050cc62015-12-03 07:04:5449#include "cc/trees/layer_tree_host_common.h"
loysoa6edaaff2015-05-25 03:26:4450#include "cc/trees/layer_tree_settings.h"
[email protected]a8cb3b73b2013-08-12 05:50:5051#include "content/child/appcache/appcache_dispatcher.h"
52#include "content/child/appcache/appcache_frontend_impl.h"
dmurph1fb98482016-03-30 21:14:2653#include "content/child/blob_storage/blob_message_filter.h"
revemancb5a66af2014-10-25 00:34:3954#include "content/child/child_discardable_shared_memory_manager.h"
reveman22dd9292014-10-13 20:52:0555#include "content/child/child_gpu_memory_buffer_manager.h"
[email protected]10208ea2013-06-06 20:08:0356#include "content/child/child_histogram_message_filter.h"
alexclarke0bc36e8d32014-12-17 17:29:2057#include "content/child/child_resource_message_filter.h"
jbauman2f5c1942014-12-06 03:28:2458#include "content/child/child_shared_bitmap_manager.h"
[email protected]fdeac262014-07-10 12:52:5159#include "content/child/content_child_helpers.h"
[email protected]89c36f82013-07-17 06:23:2760#include "content/child/db_message_filter.h"
[email protected]c7199a6e2013-06-04 12:56:0161#include "content/child/indexed_db/indexed_db_dispatcher.h"
62#include "content/child/indexed_db/indexed_db_message_filter.h"
bashia6264042016-09-15 04:49:5163#include "content/child/memory/child_memory_coordinator_impl.h"
[email protected]10208ea2013-06-06 20:08:0364#include "content/child/resource_dispatcher.h"
alexclarke0bc36e8d32014-12-17 17:29:2065#include "content/child/resource_scheduling_filter.h"
[email protected]643255da2013-06-12 20:55:1366#include "content/child/runtime_features.h"
[email protected]57cf97882013-06-26 20:39:0167#include "content/child/thread_safe_sender.h"
[email protected]c7199a6e2013-06-04 12:56:0168#include "content/child/web_database_observer_impl.h"
kinukoef647412015-12-23 06:10:4369#include "content/child/worker_thread_registry.h"
[email protected]bdae9812011-10-15 00:33:0370#include "content/common/child_process_messages.h"
[email protected]89c36f82013-07-17 06:23:2771#include "content/common/content_constants_internal.h"
[email protected]5f2aa722013-08-07 16:59:4172#include "content/common/dom_storage/dom_storage_messages.h"
[email protected]82307f6b2014-08-07 03:30:1273#include "content/common/frame_messages.h"
raymesbba82b32016-07-19 00:41:3874#include "content/common/frame_owner_properties.h"
[email protected]c29b7ff2013-03-06 03:51:0475#include "content/common/gpu/client/context_provider_command_buffer.h"
avia7c3f51c2015-09-16 00:30:3176#include "content/common/render_process_messages.h"
[email protected]94dc971d2011-03-05 19:08:3277#include "content/common/resource_messages.h"
mek27c9d742015-07-16 18:30:1878#include "content/common/service_worker/embedded_worker_setup.mojom.h"
alexmos68734212016-08-27 00:06:3179#include "content/common/site_isolation_policy.h"
[email protected]778574e2011-03-21 22:03:5080#include "content/common/view_messages.h"
[email protected]0ec90d522014-03-12 16:28:1981#include "content/common/worker_messages.h"
[email protected]a458504b2012-07-23 19:57:0682#include "content/public/common/content_constants.h"
bashia6264042016-09-15 04:49:5183#include "content/public/common/content_features.h"
[email protected]433df472012-03-07 20:33:3984#include "content/public/common/content_paths.h"
[email protected]c08950d22011-10-13 22:20:2985#include "content/public/common/content_switches.h"
[email protected]daf82f82011-10-31 22:35:3186#include "content/public/common/renderer_preferences.h"
[email protected]58436a12012-03-21 17:10:2687#include "content/public/common/url_constants.h"
[email protected]d344114c2011-10-01 01:24:3488#include "content/public/renderer/content_renderer_client.h"
tyoshino832a58a2016-04-18 08:14:0889#include "content/public/renderer/render_thread_observer.h"
[email protected]64ffa0442011-10-03 22:08:3690#include "content/public/renderer/render_view_visitor.h"
fsamuel6c1dfeb2014-12-18 19:21:3391#include "content/renderer/browser_plugin/browser_plugin_manager.h"
jsbell279efb42015-03-31 17:02:4692#include "content/renderer/cache_storage/cache_storage_dispatcher.h"
93#include "content/renderer/cache_storage/cache_storage_message_filter.h"
prashant.nfad657e2016-06-01 07:52:1794#include "content/renderer/categorized_worker_pool.h"
[email protected]70019152012-12-19 11:44:1995#include "content/renderer/devtools/devtools_agent_filter.h"
[email protected]1910fe82012-05-10 00:04:1096#include "content/renderer/dom_storage/dom_storage_dispatcher.h"
97#include "content/renderer/dom_storage/webstoragearea_impl.h"
98#include "content/renderer/dom_storage/webstoragenamespace_impl.h"
simonhonga7e3ac42014-11-11 20:50:2299#include "content/renderer/gpu/compositor_external_begin_frame_source.h"
100#include "content/renderer/gpu/compositor_forwarding_message_filter.h"
danakj83066a32016-06-21 02:34:49101#include "content/renderer/gpu/frame_swap_message_queue.h"
danakj1120f4c2016-09-15 02:05:32102#include "content/renderer/gpu/renderer_compositor_frame_sink.h"
[email protected]7a72d452013-12-13 10:01:13103#include "content/renderer/input/input_event_filter.h"
104#include "content/renderer/input/input_handler_manager.h"
jdduke691dd572014-12-02 20:47:52105#include "content/renderer/input/main_thread_input_event_filter.h"
[email protected]f7eb0a392011-07-12 10:19:51106#include "content/renderer/media/audio_input_message_filter.h"
107#include "content/renderer/media/audio_message_filter.h"
[email protected]3958e972012-07-17 00:25:41108#include "content/renderer/media/audio_renderer_mixer_manager.h"
[email protected]d8cd8372012-03-09 10:49:51109#include "content/renderer/media/media_stream_center.h"
[email protected]a9875152013-06-22 04:03:03110#include "content/renderer/media/midi_message_filter.h"
xhwang194acae2014-11-12 22:46:33111#include "content/renderer/media/render_media_client.h"
[email protected]2329bfc72014-02-28 02:03:21112#include "content/renderer/media/renderer_gpu_video_accelerator_factories.h"
[email protected]80b161a2011-06-27 17:42:11113#include "content/renderer/media/video_capture_impl_manager.h"
[email protected]d7ff5fb2014-05-29 19:50:25114#include "content/renderer/net_info_helper.h"
[email protected]4761cf12012-09-12 10:37:55115#include "content/renderer/p2p/socket_dispatcher.h"
[email protected]82307f6b2014-08-07 03:30:12116#include "content/renderer/render_frame_proxy.h"
[email protected]8704f89b2011-04-15 00:30:05117#include "content/renderer/render_process_impl.h"
[email protected]310ebd6302011-10-10 19:06:28118#include "content/renderer/render_view_impl.h"
tfarina556a7232014-10-05 01:02:09119#include "content/renderer/renderer_blink_platform_impl.h"
jdduke94ae1f32015-02-05 06:27:13120#include "content/renderer/scheduler/resource_dispatch_throttler.h"
[email protected]7670d4332013-11-29 04:35:00121#include "content/renderer/service_worker/embedded_worker_dispatcher.h"
shimazu5de409e42016-09-29 08:45:28122#include "content/renderer/service_worker/embedded_worker_instance_client_impl.h"
mek27c9d742015-07-16 18:30:18123#include "content/renderer/service_worker/service_worker_context_client.h"
kinuko5af4ffe2015-06-09 03:38:46124#include "content/renderer/service_worker/service_worker_context_message_filter.h"
[email protected]0ec90d522014-03-12 16:28:19125#include "content/renderer/shared_worker/embedded_shared_worker_stub.h"
chunyang.daibe874c52014-11-14 06:45:05126#include "gin/public/debug.h"
dongseong.hwang72183b02014-12-08 10:41:55127#include "gpu/GLES2/gl2extchromium.h"
danakj6f4e1e22016-04-20 03:27:34128#include "gpu/command_buffer/client/shared_memory_limits.h"
danakj870925d42016-05-03 20:07:38129#include "gpu/ipc/client/command_buffer_proxy_impl.h"
penghuang346a46f92016-03-31 21:37:52130#include "gpu/ipc/client/gpu_channel_host.h"
[email protected]46f36a492010-07-28 19:36:41131#include "ipc/ipc_channel_handle.h"
amistryd4aa70d2016-06-23 07:52:37132#include "ipc/ipc_channel_mojo.h"
[email protected]cb6037d2009-11-16 22:55:17133#include "ipc/ipc_platform_file.h"
[email protected]433df472012-03-07 20:33:39134#include "media/base/media.h"
servolk8b3b39b2015-03-03 19:08:18135#include "media/renderers/gpu_video_accelerator_factories.h"
[email protected]f68c1462014-04-24 18:17:53136#include "mojo/common/common_type_converters.h"
rockot85dce0862015-11-13 01:33:59137#include "mojo/public/cpp/bindings/strong_binding.h"
[email protected]620161e2011-03-07 18:05:26138#include "net/base/net_errors.h"
eroman9ab64842015-07-21 05:07:52139#include "net/base/port_util.h"
hablichd6a4f122015-10-28 11:34:49140#include "net/base/registry_controlled_domains/registry_controlled_domain.h"
tfarina7a4a7fd2016-01-20 14:23:44141#include "net/base/url_util.h"
rockot734fb662016-10-15 16:41:30142#include "services/service_manager/public/cpp/interface_provider.h"
143#include "services/service_manager/public/cpp/interface_registry.h"
[email protected]b48c53ad2014-02-05 21:59:18144#include "skia/ext/event_tracer_impl.h"
ssid59c969162015-07-28 13:02:58145#include "skia/ext/skia_memory_dump_provider.h"
reed6e5a72222015-08-06 20:37:16146#include "third_party/WebKit/public/platform/WebImageGenerator.h"
bashi5f4c78922016-08-18 23:06:08147#include "third_party/WebKit/public/platform/WebMemoryCoordinator.h"
[email protected]89c36f82013-07-17 06:23:27148#include "third_party/WebKit/public/platform/WebString.h"
skyostil457b0a12014-09-09 10:12:07149#include "third_party/WebKit/public/platform/WebThread.h"
skyostil529caa292016-08-10 17:44:51150#include "third_party/WebKit/public/platform/scheduler/child/compositor_worker_scheduler.h"
151#include "third_party/WebKit/public/platform/scheduler/child/webthread_impl_for_worker_scheduler.h"
152#include "third_party/WebKit/public/platform/scheduler/renderer/renderer_scheduler.h"
hong.zhenga35a480d2014-12-25 17:11:09153#include "third_party/WebKit/public/web/WebCache.h"
[email protected]2255a9332013-06-17 05:12:31154#include "third_party/WebKit/public/web/WebDatabase.h"
155#include "third_party/WebKit/public/web/WebDocument.h"
156#include "third_party/WebKit/public/web/WebFrame.h"
157#include "third_party/WebKit/public/web/WebKit.h"
158#include "third_party/WebKit/public/web/WebNetworkStateNotifier.h"
[email protected]2255a9332013-06-17 05:12:31159#include "third_party/WebKit/public/web/WebRuntimeFeatures.h"
160#include "third_party/WebKit/public/web/WebScriptController.h"
161#include "third_party/WebKit/public/web/WebSecurityPolicy.h"
[email protected]2255a9332013-06-17 05:12:31162#include "third_party/WebKit/public/web/WebView.h"
jshin0a9aa632015-04-29 18:35:29163#include "third_party/icu/source/i18n/unicode/timezone.h"
[email protected]ddbb53342014-01-06 10:59:47164#include "third_party/skia/include/core/SkGraphics.h"
[email protected]c49201a2012-05-24 11:04:57165#include "ui/base/layout.h"
[email protected]18ad6772011-09-20 21:51:32166#include "ui/base/ui_base_switches.h"
ennee292bdc2016-09-15 19:57:15167#include "ui/gl/gl_switches.h"
[email protected]2c62b562009-01-27 19:04:50168
[email protected]33b02992014-03-01 01:06:29169#if defined(OS_ANDROID)
170#include <cpu-features.h>
boliubee541f42015-11-05 00:52:53171#include "content/renderer/android/synchronous_compositor_filter.h"
danakj1120f4c2016-09-15 02:05:32172#include "content/renderer/android/synchronous_compositor_frame_sink.h"
boliue81d16132016-04-26 00:54:41173#include "content/renderer/media/android/stream_texture_factory.h"
dalecurtis88af3932016-02-20 00:12:20174#include "media/base/android/media_codec_util.h"
[email protected]33b02992014-03-01 01:06:29175#endif
176
177#if defined(OS_MACOSX)
ccamerona7644752014-12-30 01:16:31178#include "base/mac/mac_util.h"
rsesek1efb3c32015-09-29 15:39:50179#include "content/renderer/theme_helper_mac.h"
[email protected]33b02992014-03-01 01:06:29180#include "content/renderer/webscrollbarbehavior_impl_mac.h"
181#endif
182
183#if defined(OS_POSIX)
184#include "ipc/ipc_channel_posix.h"
185#endif
186
[email protected]da00a2882009-03-09 17:51:19187#if defined(OS_WIN)
188#include <windows.h>
189#include <objbase.h>
190#endif
191
[email protected]22fe91d2014-08-12 17:07:12192#if defined(ENABLE_WEBRTC)
liushouqun517b1292016-09-14 05:58:59193#include "content/renderer/media/aec_dump_message_filter.h"
[email protected]22fe91d2014-08-12 17:07:12194#include "content/renderer/media/peer_connection_tracker.h"
195#include "content/renderer/media/rtc_peer_connection_handler.h"
196#include "content/renderer/media/webrtc/peer_connection_dependency_factory.h"
[email protected]22fe91d2014-08-12 17:07:12197#endif
198
chunyang.daibe874c52014-11-14 06:45:05199#ifdef ENABLE_VTUNE_JIT_INTERFACE
200#include "v8/src/third_party/vtune/v8-vtune.h"
201#endif
202
sadrul943e3b32016-08-04 18:22:59203#if defined(USE_AURA)
bend32292b2016-10-07 00:21:58204#include "content/public/common/service_manager_connection.h"
danakj83066a32016-06-21 02:34:49205#include "content/renderer/mus/render_widget_mus_connection.h"
fsamuel2545ecc2015-12-05 00:44:46206#include "content/renderer/mus/render_widget_window_tree_client_factory.h"
sadrul99097442016-08-11 16:10:12207#include "services/ui/public/cpp/gpu_service.h"
fsamuel6c6da0232015-11-26 05:13:46208#endif
209
ochangdd89a1e2016-06-08 16:39:01210#if defined(ENABLE_IPC_FUZZER)
211#include "content/common/external_ipc_dumper.h"
212#endif
213
tasakb46626a2016-10-18 05:54:44214#if defined(OS_MACOSX)
215#include <malloc/malloc.h>
216#else
217#include <malloc.h>
218#endif
219
[email protected]d293572a2013-05-23 18:50:45220using base::ThreadRestrictions;
[email protected]180ef242013-11-07 06:50:46221using blink::WebDocument;
222using blink::WebFrame;
223using blink::WebNetworkStateNotifier;
224using blink::WebRuntimeFeatures;
225using blink::WebScriptController;
226using blink::WebSecurityPolicy;
227using blink::WebString;
228using blink::WebView;
skyostil529caa292016-08-10 17:44:51229using blink::scheduler::WebThreadImplForWorkerScheduler;
[email protected]e9ff79c2012-10-19 21:31:26230
231namespace content {
initial.commit09911bf2008-07-26 23:55:29232
[email protected]42f1d7822009-07-23 18:17:55233namespace {
[email protected]da9ccfb2012-01-28 00:34:40234
avi1023d012015-12-25 02:39:14235const int64_t kInitialIdleHandlerDelayMs = 1000;
236const int64_t kLongIdleHandlerDelayMs = 30 * 1000;
[email protected]bee16aab2009-08-26 15:55:03237
jdduke94ae1f32015-02-05 06:27:13238#if defined(OS_ANDROID)
239// On Android, resource messages can each take ~1.5ms to dispatch on the browser
240// IO thread. Limiting the message rate to 3/frame at 60hz ensures that the
241// induced work takes but a fraction (~1/4) of the overall frame budget.
242const int kMaxResourceRequestsPerFlushWhenThrottled = 3;
243#else
244const int kMaxResourceRequestsPerFlushWhenThrottled = 8;
245#endif
246const double kThrottledResourceRequestFlushPeriodS = 1. / 60.;
247
[email protected]dd2c1022014-07-22 23:13:57248// Maximum allocation size allowed for image scaling filters that
249// require pre-scaling. Skia will fallback to a filter that doesn't
250// require pre-scaling if the default filter would require an
251// allocation that exceeds this limit.
252const size_t kImageCacheSingleAllocationByteLimit = 64 * 1024 * 1024;
253
danakj83066a32016-06-21 02:34:49254// Unique identifier for each output surface created.
danakj1120f4c2016-09-15 02:05:32255uint32_t g_next_compositor_frame_sink_id = 1;
danakj83066a32016-06-21 02:34:49256
rockot5c478a72016-09-28 23:14:18257// An implementation of mojom::RenderMessageFilter which can be mocked out
258// for tests which may indirectly send messages over this interface.
259mojom::RenderMessageFilter* g_render_message_filter_for_testing;
260
[email protected]f1a29a02011-10-06 23:08:44261// Keep the global RenderThreadImpl in a TLS slot so it is impossible to access
[email protected]f3ede412010-06-21 22:52:16262// incorrectly from the wrong thread.
[email protected]da9ccfb2012-01-28 00:34:40263base::LazyInstance<base::ThreadLocalPointer<RenderThreadImpl> >
[email protected]6de0fd1d2011-11-15 13:31:49264 lazy_tls = LAZY_INSTANCE_INITIALIZER;
[email protected]1edc16b82009-04-07 17:45:54265
hong.zhengb28b5332016-05-11 02:33:39266// v8::MemoryPressureLevel should correspond to base::MemoryPressureListener.
267static_assert(static_cast<v8::MemoryPressureLevel>(
268 base::MemoryPressureListener::MEMORY_PRESSURE_LEVEL_NONE) ==
269 v8::MemoryPressureLevel::kNone, "none level not align");
270static_assert(static_cast<v8::MemoryPressureLevel>(
271 base::MemoryPressureListener::MEMORY_PRESSURE_LEVEL_MODERATE) ==
272 v8::MemoryPressureLevel::kModerate, "moderate level not align");
273static_assert(static_cast<v8::MemoryPressureLevel>(
274 base::MemoryPressureListener::MEMORY_PRESSURE_LEVEL_CRITICAL) ==
275 v8::MemoryPressureLevel::kCritical, "critical level not align");
276
hong.zheng2e296f822016-06-29 02:47:44277// WebMemoryPressureLevel should correspond to base::MemoryPressureListener.
278static_assert(static_cast<blink::WebMemoryPressureLevel>(
279 base::MemoryPressureListener::MEMORY_PRESSURE_LEVEL_NONE) ==
280 blink::WebMemoryPressureLevelNone,
281 "blink::WebMemoryPressureLevelNone not align");
282static_assert(static_cast<blink::WebMemoryPressureLevel>(
283 base::MemoryPressureListener::MEMORY_PRESSURE_LEVEL_MODERATE) ==
284 blink::WebMemoryPressureLevelModerate,
285 "blink::WebMemoryPressureLevelModerate not align");
286static_assert(static_cast<blink::WebMemoryPressureLevel>(
287 base::MemoryPressureListener::MEMORY_PRESSURE_LEVEL_CRITICAL) ==
288 blink::WebMemoryPressureLevelCritical,
289 "blink::WebMemoryPressureLevelCritical not align");
290
sadrulff12c002016-01-14 20:52:20291class WebThreadForCompositor : public WebThreadImplForWorkerScheduler {
292 public:
293 explicit WebThreadForCompositor(base::Thread::Options options)
294 : WebThreadImplForWorkerScheduler("Compositor", options) {
295 Init();
296 }
297 ~WebThreadForCompositor() override {}
298
299 private:
300 // WebThreadImplForWorkerScheduler:
skyostil529caa292016-08-10 17:44:51301 std::unique_ptr<blink::scheduler::WorkerScheduler> CreateWorkerScheduler()
302 override {
ricea29649b92016-08-31 09:30:21303 return base::MakeUnique<blink::scheduler::CompositorWorkerScheduler>(
304 thread());
sadrulff12c002016-01-14 20:52:20305 }
306
307 DISALLOW_COPY_AND_ASSIGN(WebThreadForCompositor);
308};
309
[email protected]b2d98762012-09-03 17:04:06310void* CreateHistogram(
[email protected]d1b8fccc2011-08-03 01:20:13311 const char *name, int min, int max, size_t buckets) {
312 if (min <= 0)
313 min = 1;
[email protected]b2d98762012-09-03 17:04:06314 std::string histogram_name;
315 RenderThreadImpl* render_thread_impl = RenderThreadImpl::current();
316 if (render_thread_impl) { // Can be null in tests.
317 histogram_name = render_thread_impl->
318 histogram_customizer()->ConvertToCustomHistogramName(name);
319 } else {
320 histogram_name = std::string(name);
321 }
[email protected]de415552013-01-23 04:12:17322 base::HistogramBase* histogram = base::Histogram::FactoryGet(
[email protected]b2d98762012-09-03 17:04:06323 histogram_name, min, max, buckets,
324 base::Histogram::kUmaTargetedHistogramFlag);
[email protected]d1b8fccc2011-08-03 01:20:13325 return histogram;
326}
327
[email protected]b2d98762012-09-03 17:04:06328void AddHistogramSample(void* hist, int sample) {
[email protected]d1b8fccc2011-08-03 01:20:13329 base::Histogram* histogram = static_cast<base::Histogram*>(hist);
330 histogram->Add(sample);
331}
332
[email protected]df9accd2014-03-13 18:18:30333void NotifyTimezoneChangeOnThisThread() {
334 v8::Isolate* isolate = v8::Isolate::GetCurrent();
335 if (!isolate)
336 return;
337 v8::Date::DateTimeConfigurationChangeNotification(isolate);
338}
339
ben76f52b242016-06-18 05:42:48340class FrameFactoryImpl : public mojom::FrameFactory {
rockotf8fdd9b2015-12-16 22:22:35341 public:
rockot8e66a08d2016-09-13 00:48:21342 FrameFactoryImpl() : routing_id_highmark_(-1) {}
rockotf8fdd9b2015-12-16 22:22:35343
ben76f52b242016-06-18 05:42:48344 private:
345 // mojom::FrameFactory:
346 void CreateFrame(int32_t frame_routing_id,
347 mojom::FrameRequest frame_request,
348 mojom::FrameHostPtr frame_host) override {
rockotf8fdd9b2015-12-16 22:22:35349 // TODO(morrita): This is for investigating http://crbug.com/415059 and
350 // should be removed once it is fixed.
351 CHECK_LT(routing_id_highmark_, frame_routing_id);
352 routing_id_highmark_ = frame_routing_id;
353
354 RenderFrameImpl* frame = RenderFrameImpl::FromRoutingID(frame_routing_id);
355 // We can receive a GetServiceProviderForFrame message for a frame not yet
rockot067ca55f2016-09-30 22:00:15356 // created due to a race between the message and a
357 // mojom::Renderer::CreateView IPC that triggers creation of the RenderFrame
358 // we want.
rockotf8fdd9b2015-12-16 22:22:35359 if (!frame) {
ben76f52b242016-06-18 05:42:48360 RenderThreadImpl::current()->RegisterPendingFrameCreate(
361 frame_routing_id, std::move(frame_request), std::move(frame_host));
rockotf8fdd9b2015-12-16 22:22:35362 return;
363 }
364
ben76f52b242016-06-18 05:42:48365 frame->Bind(std::move(frame_request), std::move(frame_host));
rockotf8fdd9b2015-12-16 22:22:35366 }
367
368 private:
369 int32_t routing_id_highmark_;
rockotf8fdd9b2015-12-16 22:22:35370};
371
ben76f52b242016-06-18 05:42:48372void CreateFrameFactory(mojom::FrameFactoryRequest request) {
rockot8e66a08d2016-09-13 00:48:21373 mojo::MakeStrongBinding(base::MakeUnique<FrameFactoryImpl>(),
374 std::move(request));
rockotf8fdd9b2015-12-16 22:22:35375}
376
mek27c9d742015-07-16 18:30:18377void SetupEmbeddedWorkerOnWorkerThread(
rockot400ea35b2016-10-15 19:15:32378 service_manager::mojom::InterfaceProviderRequest request,
379 service_manager::mojom::InterfaceProviderPtrInfo remote_interfaces) {
mek27c9d742015-07-16 18:30:18380 ServiceWorkerContextClient* client =
381 ServiceWorkerContextClient::ThreadSpecificInstance();
382 // It is possible for client to be null if for some reason the worker died
383 // before this call made it to the worker thread. In that case just do
384 // nothing and let mojo close the connection.
385 if (!client)
386 return;
ben13be6082016-06-29 15:08:58387 client->BindInterfaceProviders(std::move(request),
388 mojo::MakeProxy(std::move(remote_interfaces)));
mek27c9d742015-07-16 18:30:18389}
390
leon.hanbe782c42016-03-22 05:05:22391class EmbeddedWorkerSetupImpl : public mojom::EmbeddedWorkerSetup {
mek27c9d742015-07-16 18:30:18392 public:
rockot8e66a08d2016-09-13 00:48:21393 EmbeddedWorkerSetupImpl() = default;
mek27c9d742015-07-16 18:30:18394
ben95787952016-02-10 07:46:20395 void ExchangeInterfaceProviders(
mek27c9d742015-07-16 18:30:18396 int32_t thread_id,
rockot400ea35b2016-10-15 19:15:32397 service_manager::mojom::InterfaceProviderRequest request,
398 service_manager::mojom::InterfaceProviderPtr remote_interfaces) override {
kinukoef647412015-12-23 06:10:43399 WorkerThreadRegistry::Instance()->GetTaskRunnerFor(thread_id)->PostTask(
mek27c9d742015-07-16 18:30:18400 FROM_HERE,
ben13be6082016-06-29 15:08:58401 base::Bind(&SetupEmbeddedWorkerOnWorkerThread, base::Passed(&request),
402 base::Passed(remote_interfaces.PassInterface())));
mek27c9d742015-07-16 18:30:18403 }
mek27c9d742015-07-16 18:30:18404};
405
rockot8e66a08d2016-09-13 00:48:21406void CreateEmbeddedWorkerSetup(mojom::EmbeddedWorkerSetupRequest request) {
407 mojo::MakeStrongBinding(base::MakeUnique<EmbeddedWorkerSetupImpl>(),
408 std::move(request));
mek27c9d742015-07-16 18:30:18409}
410
danakjc3983552016-05-03 00:04:35411scoped_refptr<ContextProviderCommandBuffer> CreateOffscreenContext(
412 scoped_refptr<gpu::GpuChannelHost> gpu_channel_host,
danakj0dd9e1e2016-05-11 22:15:09413 const gpu::SharedMemoryLimits& limits,
danakj9a04adc2016-05-16 22:45:07414 bool support_locking,
sunnypsd8ce1c22016-05-10 18:02:40415 command_buffer_metrics::ContextType type,
416 int32_t stream_id,
417 gpu::GpuStreamPriority stream_priority) {
danakje8ec797e2016-04-19 04:08:43418 DCHECK(gpu_channel_host);
419 // This is used to create a few different offscreen contexts:
420 // - The shared main thread context (offscreen) used by blink for canvas.
421 // - The worker context (offscreen) used for GPU raster and video decoding.
422 // This is for an offscreen context, so the default framebuffer doesn't need
423 // alpha, depth, stencil, antialiasing.
424 gpu::gles2::ContextCreationAttribHelper attributes;
425 attributes.alpha_size = -1;
426 attributes.depth_size = 0;
427 attributes.stencil_size = 0;
428 attributes.samples = 0;
429 attributes.sample_buffers = 0;
430 attributes.bind_generates_resource = false;
431 attributes.lose_context_when_out_of_memory = true;
sunnypsd8ce1c22016-05-10 18:02:40432 const bool automatic_flushes = false;
danakjc3983552016-05-03 00:04:35433 return make_scoped_refptr(new ContextProviderCommandBuffer(
sunnypsd8ce1c22016-05-10 18:02:40434 std::move(gpu_channel_host), stream_id, stream_priority,
435 gpu::kNullSurfaceHandle,
danakjba37f812016-05-03 03:58:03436 GURL("chrome://gpu/RenderThreadImpl::CreateOffscreenContext"),
pimand488e8b42016-06-30 19:06:59437 automatic_flushes, support_locking, limits, attributes, nullptr, type));
danakje8ec797e2016-04-19 04:08:43438}
439
penghuange1d86512016-07-08 18:15:00440bool IsRunningInMash() {
441 const base::CommandLine* cmdline = base::CommandLine::ForCurrentProcess();
442 return cmdline->HasSwitch(switches::kIsRunningInMash);
443}
444
[email protected]b2d98762012-09-03 17:04:06445} // namespace
446
[email protected]fdeac262014-07-10 12:52:51447// For measuring memory usage after each task. Behind a command line flag.
448class MemoryObserver : public base::MessageLoop::TaskObserver {
449 public:
450 MemoryObserver() {}
dcheng6d18e402014-10-21 12:32:52451 ~MemoryObserver() override {}
[email protected]fdeac262014-07-10 12:52:51452
dcheng6d18e402014-10-21 12:32:52453 void WillProcessTask(const base::PendingTask& pending_task) override {}
[email protected]fdeac262014-07-10 12:52:51454
dcheng6d18e402014-10-21 12:32:52455 void DidProcessTask(const base::PendingTask& pending_task) override {
asvitkinec0fb8022014-08-26 04:39:35456 LOCAL_HISTOGRAM_MEMORY_KB("Memory.RendererUsed", GetMemoryUsageKB());
[email protected]fdeac262014-07-10 12:52:51457 }
458
459 private:
460 DISALLOW_COPY_AND_ASSIGN(MemoryObserver);
461};
462
[email protected]b2d98762012-09-03 17:04:06463RenderThreadImpl::HistogramCustomizer::HistogramCustomizer() {
464 custom_histograms_.insert("V8.MemoryExternalFragmentationTotal");
465 custom_histograms_.insert("V8.MemoryHeapSampleTotalCommitted");
466 custom_histograms_.insert("V8.MemoryHeapSampleTotalUsed");
hablich4598ddc2015-11-07 18:37:28467 custom_histograms_.insert("V8.MemoryHeapUsed");
468 custom_histograms_.insert("V8.MemoryHeapCommitted");
[email protected]b2d98762012-09-03 17:04:06469}
470
471RenderThreadImpl::HistogramCustomizer::~HistogramCustomizer() {}
472
473void RenderThreadImpl::HistogramCustomizer::RenderViewNavigatedToHost(
474 const std::string& host, size_t view_count) {
avi83883c82014-12-23 00:08:49475 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
476 switches::kDisableHistogramCustomizer)) {
[email protected]9baee832012-12-10 11:07:15477 return;
478 }
[email protected]b2d98762012-09-03 17:04:06479 // Check if all RenderViews are displaying a page from the same host. If there
480 // is only one RenderView, the common host is this view's host. If there are
481 // many, check if this one shares the common host of the other
482 // RenderViews. It's ok to not detect some cases where the RenderViews share a
483 // common host. This information is only used for producing custom histograms.
484 if (view_count == 1)
485 SetCommonHost(host);
486 else if (host != common_host_)
487 SetCommonHost(std::string());
488}
489
490std::string RenderThreadImpl::HistogramCustomizer::ConvertToCustomHistogramName(
491 const char* histogram_name) const {
492 std::string name(histogram_name);
493 if (!common_host_histogram_suffix_.empty() &&
494 custom_histograms_.find(name) != custom_histograms_.end())
495 name += common_host_histogram_suffix_;
496 return name;
497}
498
499void RenderThreadImpl::HistogramCustomizer::SetCommonHost(
500 const std::string& host) {
501 if (host != common_host_) {
502 common_host_ = host;
503 common_host_histogram_suffix_ = HostToCustomHistogramSuffix(host);
[email protected]4b5340282014-07-08 11:37:34504 blink::mainThreadIsolate()->SetCreateHistogramFunction(CreateHistogram);
[email protected]b2d98762012-09-03 17:04:06505 }
506}
507
hablichd6a4f122015-10-28 11:34:49508std::string RenderThreadImpl::HistogramCustomizer::HostToCustomHistogramSuffix(
509 const std::string& host) {
510 if (host == "mail.google.com")
511 return ".gmail";
512 if (host == "docs.google.com" || host == "drive.google.com")
513 return ".docs";
514 if (host == "plus.google.com")
515 return ".plus";
516 if (host == "inbox.google.com")
517 return ".inbox";
hpayerdd4def052016-02-06 19:06:10518 if (host == "calendar.google.com")
519 return ".calendar";
hablichd6a4f122015-10-28 11:34:49520 if (host == "www.youtube.com")
521 return ".youtube";
522 if (IsAlexaTop10NonGoogleSite(host))
523 return ".top10";
524
525 return std::string();
526}
527
528bool RenderThreadImpl::HistogramCustomizer::IsAlexaTop10NonGoogleSite(
529 const std::string& host) {
530 // The Top10 sites have different TLD and/or subdomains depending on the
531 // localization.
532 if (host == "sina.com.cn")
533 return true;
534
535 std::string sanitized_host =
536 net::registry_controlled_domains::GetDomainAndRegistry(
537 host, net::registry_controlled_domains::INCLUDE_PRIVATE_REGISTRIES);
538
539 if (sanitized_host == "facebook.com")
540 return true;
541 if (sanitized_host == "baidu.com")
542 return true;
543 if (sanitized_host == "qq.com")
544 return true;
545 if (sanitized_host == "twitter.com")
546 return true;
547 if (sanitized_host == "taobao.com")
548 return true;
549 if (sanitized_host == "live.com")
550 return true;
551
552 if (!sanitized_host.empty()) {
553 std::vector<base::StringPiece> host_tokens = base::SplitStringPiece(
554 sanitized_host, ".", base::TRIM_WHITESPACE, base::SPLIT_WANT_NONEMPTY);
555
556 if (host_tokens.size() >= 2) {
557 if ((host_tokens[0] == "yahoo") || (host_tokens[0] == "amazon") ||
558 (host_tokens[0] == "wikipedia")) {
559 return true;
560 }
561 }
562 }
563 return false;
564}
565
leon.han2c0f9f12015-07-11 02:01:19566// static
567RenderThreadImpl* RenderThreadImpl::Create(
568 const InProcessChildThreadParams& params) {
skyostil529caa292016-08-10 17:44:51569 std::unique_ptr<blink::scheduler::RendererScheduler> renderer_scheduler =
570 blink::scheduler::RendererScheduler::Create();
jam75c44222016-03-23 05:34:24571 scoped_refptr<base::SingleThreadTaskRunner> test_task_counter;
572 return new RenderThreadImpl(
573 params, std::move(renderer_scheduler), test_task_counter);
leon.han2c0f9f12015-07-11 02:01:19574}
575
576// static
577RenderThreadImpl* RenderThreadImpl::Create(
dchengcedca5612016-04-09 01:40:15578 std::unique_ptr<base::MessageLoop> main_message_loop,
skyostil529caa292016-08-10 17:44:51579 std::unique_ptr<blink::scheduler::RendererScheduler> renderer_scheduler) {
dcheng07945f632015-12-26 07:59:32580 return new RenderThreadImpl(std::move(main_message_loop),
581 std::move(renderer_scheduler));
leon.han2c0f9f12015-07-11 02:01:19582}
583
rockot5c478a72016-09-28 23:14:18584// static
[email protected]f1a29a02011-10-06 23:08:44585RenderThreadImpl* RenderThreadImpl::current() {
[email protected]526476902011-10-06 20:34:06586 return lazy_tls.Pointer()->Get();
587}
588
rockot5c478a72016-09-28 23:14:18589// static
590mojom::RenderMessageFilter* RenderThreadImpl::current_render_message_filter() {
591 if (g_render_message_filter_for_testing)
592 return g_render_message_filter_for_testing;
593 DCHECK(current());
594 return current()->render_message_filter();
595}
596
597// static
598void RenderThreadImpl::SetRenderMessageFilterForTesting(
599 mojom::RenderMessageFilter* render_message_filter) {
600 g_render_message_filter_for_testing = render_message_filter;
601}
602
leon.han2c0f9f12015-07-11 02:01:19603RenderThreadImpl::RenderThreadImpl(
604 const InProcessChildThreadParams& params,
skyostil529caa292016-08-10 17:44:51605 std::unique_ptr<blink::scheduler::RendererScheduler> scheduler,
jam75c44222016-03-23 05:34:24606 scoped_refptr<base::SingleThreadTaskRunner>& resource_task_queue)
morritac6238ab2015-03-18 01:48:29607 : ChildThreadImpl(Options::Builder()
prashant.nfad657e2016-06-01 07:52:17608 .InBrowserProcess(params)
bend32292b2016-10-07 00:21:58609 .AutoStartServiceManagerConnection(false)
ben5be0b9132016-08-03 00:17:18610 .ConnectToBrowser(true)
prashant.nfad657e2016-06-01 07:52:17611 .Build()),
dcheng07945f632015-12-26 07:59:32612 renderer_scheduler_(std::move(scheduler)),
blundellc00adf442016-09-16 10:43:41613 time_zone_monitor_binding_(this),
rockot067ca55f2016-09-30 22:00:15614 categorized_worker_pool_(new CategorizedWorkerPool()),
615 renderer_binding_(this) {
jam75c44222016-03-23 05:34:24616 Init(resource_task_queue);
morritac6238ab2015-03-18 01:48:29617}
618
[email protected]42f1d7822009-07-23 18:17:55619// When we run plugins in process, we actually run them on the render thread,
620// which means that we need to make the render thread pump UI events.
haraken53f081d2014-11-11 01:03:40621RenderThreadImpl::RenderThreadImpl(
dchengcedca5612016-04-09 01:40:15622 std::unique_ptr<base::MessageLoop> main_message_loop,
skyostil529caa292016-08-10 17:44:51623 std::unique_ptr<blink::scheduler::RendererScheduler> scheduler)
rockotcef38272016-07-15 22:47:47624 : ChildThreadImpl(Options::Builder()
bend32292b2016-10-07 00:21:58625 .AutoStartServiceManagerConnection(false)
ben5be0b9132016-08-03 00:17:18626 .ConnectToBrowser(true)
rockotcef38272016-07-15 22:47:47627 .Build()),
dcheng07945f632015-12-26 07:59:32628 renderer_scheduler_(std::move(scheduler)),
blundellc00adf442016-09-16 10:43:41629 time_zone_monitor_binding_(this),
dcheng07945f632015-12-26 07:59:32630 main_message_loop_(std::move(main_message_loop)),
rockot067ca55f2016-09-30 22:00:15631 categorized_worker_pool_(new CategorizedWorkerPool()),
632 renderer_binding_(this) {
jam75c44222016-03-23 05:34:24633 scoped_refptr<base::SingleThreadTaskRunner> test_task_counter;
634 Init(test_task_counter);
haraken53f081d2014-11-11 01:03:40635}
636
jam75c44222016-03-23 05:34:24637void RenderThreadImpl::Init(
638 scoped_refptr<base::SingleThreadTaskRunner>& resource_task_queue) {
fdorayf6d86242015-10-08 16:49:53639 TRACE_EVENT0("startup", "RenderThreadImpl::Init");
[email protected]a872ea1f2010-08-11 04:45:33640
ssidb2e3ece2015-02-09 16:02:20641 base::trace_event::TraceLog::GetInstance()->SetThreadSortIndex(
[email protected]91a2aea2013-07-08 23:14:39642 base::PlatformThread::CurrentId(),
643 kTraceEventRendererMainThreadSortIndex);
644
haibinluc643d33c2016-06-03 02:22:34645#if defined(USE_EXTERNAL_POPUP_MENU)
sievers9dff72052015-11-16 18:35:57646 // On Mac and Android Java UI, the select popups are rendered by the browser.
[email protected]180ef242013-11-07 06:50:46647 blink::WebView::setUseExternalPopupMenus(true);
[email protected]53c607c2011-03-21 23:19:04648#endif
649
[email protected]94f9a0f682009-06-15 18:30:30650 lazy_tls.Pointer()->Set(this);
[email protected]b3e83de2012-02-07 03:33:28651
[email protected]06c694d2012-02-01 22:26:16652 // Register this object as the main thread.
653 ChildProcess::current()->set_main_thread(this);
654
sadrul943e3b32016-08-04 18:22:59655#if defined(USE_AURA)
sadrul62c31132016-08-11 04:13:17656 if (IsRunningInMash()) {
sadrul9e0bb1d2016-08-04 20:18:39657 gpu_service_ =
bend32292b2016-10-07 00:21:58658 ui::GpuService::Create(GetServiceManagerConnection()->GetConnector(),
sadrul75f7dde2016-08-22 23:37:24659 ChildProcess::current()->io_task_runner());
sadrul62c31132016-08-11 04:13:17660 }
penghuange1d86512016-07-08 18:15:00661#endif
sadrulb9ff6c92016-10-04 02:40:04662 gpu_memory_buffer_manager_ =
663 base::MakeUnique<ChildGpuMemoryBufferManager>(thread_safe_sender());
penghuange1d86512016-07-08 18:15:00664
jam75c44222016-03-23 05:34:24665 InitializeWebKit(resource_task_queue);
666
[email protected]31f87132010-04-21 23:36:21667 // In single process the single process is all there is.
[email protected]26e82322014-01-20 14:18:22668 webkit_shared_timer_suspended_ = false;
[email protected]bee16aab2009-08-26 15:55:03669 widget_count_ = 0;
670 hidden_widget_count_ = 0;
[email protected]6593ae12011-11-14 12:09:44671 idle_notification_delay_in_ms_ = kInitialIdleHandlerDelayMs;
[email protected]1784b2f2011-11-24 10:53:48672 idle_notifications_to_skip_ = 0;
[email protected]8d86fce2009-02-26 23:37:55673
[email protected]d5b2fdf2013-06-05 09:36:55674 appcache_dispatcher_.reset(
[email protected]a8cb3b73b2013-08-12 05:50:50675 new AppCacheDispatcher(Get(), new AppCacheFrontendImpl()));
[email protected]1910fe82012-05-10 00:04:10676 dom_storage_dispatcher_.reset(new DomStorageDispatcher());
[email protected]1e8d91e2013-06-27 00:12:43677 main_thread_indexed_db_dispatcher_.reset(new IndexedDBDispatcher(
678 thread_safe_sender()));
jsbellabadb9b2015-03-23 21:03:44679 main_thread_cache_storage_dispatcher_.reset(
jsbell279efb42015-03-31 17:02:46680 new CacheStorageDispatcher(thread_safe_sender()));
[email protected]7670d4332013-11-29 04:35:00681 embedded_worker_dispatcher_.reset(new EmbeddedWorkerDispatcher());
[email protected]dd9241932010-02-24 19:23:13682
jdduke94ae1f32015-02-05 06:27:13683 // Note: This may reorder messages from the ResourceDispatcher with respect to
684 // other subsystems.
685 resource_dispatch_throttler_.reset(new ResourceDispatchThrottler(
686 static_cast<RenderThread*>(this), renderer_scheduler_.get(),
687 base::TimeDelta::FromSecondsD(kThrottledResourceRequestFlushPeriodS),
688 kMaxResourceRequestsPerFlushWhenThrottled));
689 resource_dispatcher()->set_message_sender(resource_dispatch_throttler_.get());
690
penghuange1d86512016-07-08 18:15:00691 media_stream_center_ = nullptr;
[email protected]d8cd8372012-03-09 10:49:51692
thestig529ad8a2016-07-08 20:30:12693 blob_message_filter_ = new BlobMessageFilter(GetFileThreadTaskRunner());
dmurph1fb98482016-03-30 21:14:26694 AddFilter(blob_message_filter_.get());
[email protected]017022b2009-07-27 23:06:34695 db_message_filter_ = new DBMessageFilter();
696 AddFilter(db_message_filter_.get());
[email protected]dd9241932010-02-24 19:23:13697
[email protected]45048072014-01-14 13:51:29698 vc_manager_.reset(new VideoCaptureImplManager());
[email protected]c9c43a02013-12-17 08:59:54699
fsamuel6c1dfeb2014-12-18 19:21:33700 browser_plugin_manager_.reset(new BrowserPluginManager());
701 AddObserver(browser_plugin_manager_.get());
702
[email protected]4761cf12012-09-12 10:37:55703#if defined(ENABLE_WEBRTC)
[email protected]af089972013-01-10 04:04:40704 peer_connection_tracker_.reset(new PeerConnectionTracker());
705 AddObserver(peer_connection_tracker_.get());
706
thestig529ad8a2016-07-08 20:30:12707 p2p_socket_dispatcher_ = new P2PSocketDispatcher(GetIOTaskRunner().get());
[email protected]fc72bb12013-06-02 21:13:46708 AddFilter(p2p_socket_dispatcher_.get());
[email protected]921480f62013-07-20 03:42:57709
ivocadd54f0d2015-12-18 23:17:05710 peer_connection_factory_.reset(
711 new PeerConnectionDependencyFactory(p2p_socket_dispatcher_.get()));
712
skyostil2d3b5bd2015-05-27 15:40:59713 aec_dump_message_filter_ = new AecDumpMessageFilter(
thestig529ad8a2016-07-08 20:30:12714 GetIOTaskRunner(), message_loop()->task_runner());
ivocadd54f0d2015-12-18 23:17:05715
[email protected]da9f30a2014-06-18 19:39:04716 AddFilter(aec_dump_message_filter_.get());
717
[email protected]4761cf12012-09-12 10:37:55718#endif // defined(ENABLE_WEBRTC)
[email protected]e25f4d72011-06-08 20:58:46719
thestig529ad8a2016-07-08 20:30:12720 audio_input_message_filter_ = new AudioInputMessageFilter(GetIOTaskRunner());
[email protected]f7eb0a392011-07-12 10:19:51721 AddFilter(audio_input_message_filter_.get());
722
thestig529ad8a2016-07-08 20:30:12723 audio_message_filter_ = new AudioMessageFilter(GetIOTaskRunner());
[email protected]f7eb0a392011-07-12 10:19:51724 AddFilter(audio_message_filter_.get());
725
thestig529ad8a2016-07-08 20:30:12726 midi_message_filter_ = new MidiMessageFilter(GetIOTaskRunner());
[email protected]a9875152013-06-22 04:03:03727 AddFilter(midi_message_filter_.get());
728
[email protected]ce944c62013-11-19 16:34:36729 AddFilter((new IndexedDBMessageFilter(thread_safe_sender()))->GetFilter());
[email protected]31bfae72011-12-16 02:04:38730
jsbellabadb9b2015-03-23 21:03:44731 AddFilter((new CacheStorageMessageFilter(thread_safe_sender()))->GetFilter());
732
kinuko5af4ffe2015-06-09 03:38:46733 AddFilter((new ServiceWorkerContextMessageFilter())->GetFilter());
[email protected]ddbb53342014-01-06 10:59:47734
sadrul943e3b32016-08-04 18:22:59735#if defined(USE_AURA)
rockotcef38272016-07-15 22:47:47736 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
737 switches::kUseMusInRenderer)) {
bend32292b2016-10-07 00:21:58738 CreateRenderWidgetWindowTreeClientFactory(GetServiceManagerConnection());
rockotcef38272016-07-15 22:47:47739 }
740#endif
741
742 // Must be called before RenderThreadStarted() below.
bend32292b2016-10-07 00:21:58743 StartServiceManagerConnection();
rockotcef38272016-07-15 22:47:47744
[email protected]e9ff79c2012-10-19 21:31:26745 GetContentClient()->renderer()->RenderThreadStarted();
[email protected]6779aa12011-03-29 17:32:24746
rockot067ca55f2016-09-30 22:00:15747 GetAssociatedInterfaceRegistry()->AddInterface(
748 base::Bind(&RenderThreadImpl::OnRendererInterfaceRequest,
749 base::Unretained(this)));
750
[email protected]b48c53ad2014-02-05 21:59:18751 InitSkiaEventTracer();
ssid59c969162015-07-28 13:02:58752 base::trace_event::MemoryDumpManager::GetInstance()->RegisterDumpProvider(
primiano186d6bfe2015-10-30 13:21:40753 skia::SkiaMemoryDumpProvider::GetInstance(), "Skia", nullptr);
[email protected]b48c53ad2014-02-05 21:59:18754
avi83883c82014-12-23 00:08:49755 const base::CommandLine& command_line =
756 *base::CommandLine::ForCurrentProcess();
[email protected]e54ab492012-06-12 19:40:01757
ochangdd89a1e2016-06-08 16:39:01758#if defined(ENABLE_IPC_FUZZER)
759 if (command_line.HasSwitch(switches::kIpcDumpDirectory)) {
760 base::FilePath dump_directory =
761 command_line.GetSwitchValuePath(switches::kIpcDumpDirectory);
762 IPC::ChannelProxy::OutgoingMessageFilter* filter =
763 LoadExternalIPCDumper(dump_directory);
764 GetChannel()->set_outgoing_message_filter(filter);
765 }
766#endif
767
jbroman0d302162015-09-05 05:46:23768 cc::SetClientNameForMetrics("Renderer");
loysoa6edaaff2015-05-25 03:26:44769
loyso65c93c602015-08-11 05:15:57770 is_threaded_animation_enabled_ =
771 !command_line.HasSwitch(cc::switches::kDisableThreadedAnimation);
772
reveman91a0a872014-11-04 03:40:32773 is_zero_copy_enabled_ = command_line.HasSwitch(switches::kEnableZeroCopy);
ericrk1d17f752015-10-20 03:03:07774 is_partial_raster_enabled_ =
dongseong.hwang23db47f2016-03-08 07:50:02775 !command_line.HasSwitch(switches::kDisablePartialRaster);
ccameronc7fcd132015-11-03 20:14:31776 is_gpu_memory_buffer_compositor_resources_enabled_ = command_line.HasSwitch(
777 switches::kEnableGpuMemoryBufferCompositorResources);
[email protected]a23530d2014-03-11 06:04:14778
jame1f453c2016-03-21 15:51:34779#if defined(OS_MACOSX)
thakis114a1ef2016-04-26 16:02:59780 base::ScopedCFTypeRef<CFStringRef> key(
781 base::SysUTF8ToCFStringRef("NSScrollViewRubberbanding"));
782 Boolean key_exists = false;
783 Boolean value = CFPreferencesGetAppBooleanValue(
784 key, kCFPreferencesCurrentApplication, &key_exists);
785 is_elastic_overscroll_enabled_ = !key_exists || value;
ccamerona7644752014-12-30 01:16:31786#else
787 is_elastic_overscroll_enabled_ = false;
788#endif
789
danakje6eb185c2015-02-27 23:52:05790 std::string image_texture_target_string =
dcastagna7f2f7192015-06-16 18:44:35791 command_line.GetSwitchValueASCII(switches::kContentImageTextureTarget);
ericrk9151705c2016-07-26 19:53:16792 buffer_to_texture_target_map_ =
793 cc::StringToBufferToTextureTargetMap(image_texture_target_string);
reveman44b807f12014-11-26 02:44:50794
[email protected]a23530d2014-03-11 06:04:14795 if (command_line.HasSwitch(switches::kDisableLCDText)) {
796 is_lcd_text_enabled_ = false;
797 } else if (command_line.HasSwitch(switches::kEnableLCDText)) {
798 is_lcd_text_enabled_ = true;
799 } else {
800#if defined(OS_ANDROID)
801 is_lcd_text_enabled_ = false;
802#else
803 is_lcd_text_enabled_ = true;
804#endif
805 }
806
[email protected]b8d82c22014-03-31 20:12:46807 is_gpu_rasterization_enabled_ =
808 command_line.HasSwitch(switches::kEnableGpuRasterization);
809 is_gpu_rasterization_forced_ =
810 command_line.HasSwitch(switches::kForceGpuRasterization);
sunnypsd8ce1c22016-05-10 18:02:40811 is_async_worker_context_enabled_ =
812 command_line.HasSwitch(switches::kEnableGpuAsyncWorkerContext);
[email protected]a23530d2014-03-11 06:04:14813
senorblancob60ba952015-01-27 19:12:36814 if (command_line.HasSwitch(switches::kGpuRasterizationMSAASampleCount)) {
815 std::string string_value = command_line.GetSwitchValueASCII(
816 switches::kGpuRasterizationMSAASampleCount);
817 bool parsed_msaa_sample_count =
818 base::StringToInt(string_value, &gpu_rasterization_msaa_sample_count_);
819 DCHECK(parsed_msaa_sample_count) << string_value;
820 DCHECK_GE(gpu_rasterization_msaa_sample_count_, 0);
821 } else {
senorblanco2a5b0e12015-08-14 21:55:37822 gpu_rasterization_msaa_sample_count_ = -1;
senorblancob60ba952015-01-27 19:12:36823 }
824
[email protected]b242b142014-05-07 14:48:49825 if (command_line.HasSwitch(switches::kDisableDistanceFieldText)) {
826 is_distance_field_text_enabled_ = false;
827 } else if (command_line.HasSwitch(switches::kEnableDistanceFieldText)) {
828 is_distance_field_text_enabled_ = true;
829 } else {
830 is_distance_field_text_enabled_ = false;
831 }
832
[email protected]433df472012-03-07 20:33:39833 // Note that under Linux, the media library will normally already have
834 // been initialized by the Zygote before this instance became a Renderer.
chcunninghamfd11b3c2015-06-09 02:09:42835 media::InitializeMediaLibrary();
[email protected]433df472012-03-07 20:33:39836
dalecurtis88af3932016-02-20 00:12:20837#if defined(OS_ANDROID)
838 if (!command_line.HasSwitch(switches::kDisableAcceleratedVideoDecode) &&
839 media::MediaCodecUtil::IsMediaCodecAvailable()) {
840 media::EnablePlatformDecoderSupport();
841 }
842#endif
843
[email protected]5071cb22013-07-10 02:19:06844 memory_pressure_listener_.reset(new base::MemoryPressureListener(
hong.zhengb28b5332016-05-11 02:33:39845 base::Bind(&RenderThreadImpl::OnMemoryPressure, base::Unretained(this)),
846 base::Bind(&RenderThreadImpl::OnSyncMemoryPressure,
847 base::Unretained(this))));
[email protected]5071cb22013-07-10 02:19:06848
bashia6264042016-09-15 04:49:51849 if (base::FeatureList::IsEnabled(features::kMemoryCoordinator)) {
bashi58dd2fa2016-10-17 00:01:07850 // Disable MemoryPressureListener when memory coordinator is enabled.
851 base::MemoryPressureListener::SetNotificationsSuppressed(true);
852
bashi77f19b32016-07-19 11:19:43853 // TODO(bashi): Revisit how to manage the lifetime of
854 // ChildMemoryCoordinatorImpl.
855 // https://codereview.chromium.org/2094583002/#msg52
bashia6264042016-09-15 04:49:51856 mojom::MemoryCoordinatorHandlePtr parent_coordinator;
bashi77f19b32016-07-19 11:19:43857 GetRemoteInterfaces()->GetInterface(mojo::GetProxy(&parent_coordinator));
bashia6264042016-09-15 04:49:51858 memory_coordinator_ = CreateChildMemoryCoordinator(
bashic4b4afcb2016-08-23 06:37:52859 std::move(parent_coordinator), this);
bashi77f19b32016-07-19 11:19:43860 }
861
danakj16275d4c2015-06-11 19:23:51862 int num_raster_threads = 0;
863 std::string string_value =
864 command_line.GetSwitchValueASCII(switches::kNumRasterThreads);
865 bool parsed_num_raster_threads =
866 base::StringToInt(string_value, &num_raster_threads);
867 DCHECK(parsed_num_raster_threads) << string_value;
868 DCHECK_GT(num_raster_threads, 0);
vmiura78b69282015-02-14 00:01:17869
vmpstr6c0b5112016-04-25 22:12:14870 // TODO(vmpstr): If the flag sticks, we should clean it up and always have
871 // image decode tasks.
vmpstr9dd810a2016-01-19 21:16:10872 are_image_decode_tasks_enabled_ = true;
halliwell4b3deee2014-12-19 19:57:49873
prashant.nfad657e2016-06-01 07:52:17874 categorized_worker_pool_->Start(num_raster_threads);
[email protected]1e1d1e12014-01-17 16:14:29875
boliu9760e212015-06-23 22:49:06876 // TODO(boliu): In single process, browser main loop should set up the
877 // discardable memory manager, and should skip this if kSingleProcess.
878 // See crbug.com/503724.
879 base::DiscardableMemoryAllocator::SetInstance(
880 ChildThreadImpl::discardable_shared_memory_manager());
revemancb5a66af2014-10-25 00:34:39881
bend1dd50f52016-06-26 22:10:48882 GetContentClient()->renderer()->ExposeInterfacesToBrowser(
883 GetInterfaceRegistry());
rockot229fb28e2016-06-16 04:46:16884
shimazu5de409e42016-09-29 08:45:28885 GetInterfaceRegistry()->AddInterface(base::Bind(&CreateFrameFactory));
886 GetInterfaceRegistry()->AddInterface(base::Bind(&CreateEmbeddedWorkerSetup));
887 GetInterfaceRegistry()->AddInterface(
888 base::Bind(&EmbeddedWorkerInstanceClientImpl::Create,
889 base::Unretained(embedded_worker_dispatcher_.get())));
fsamuel6c6da0232015-11-26 05:13:46890
bend1dd50f52016-06-26 22:10:48891 GetRemoteInterfaces()->GetInterface(
jamc912ca32016-02-24 20:17:31892 mojo::GetProxy(&storage_partition_service_));
hajimehoshi69093272016-05-13 08:30:58893
blundellc00adf442016-09-16 10:43:41894 device::mojom::TimeZoneMonitorPtr time_zone_monitor;
895 GetRemoteInterfaces()->GetInterface(mojo::GetProxy(&time_zone_monitor));
896 time_zone_monitor->AddClient(
897 time_zone_monitor_binding_.CreateInterfacePtrAndBind());
898
reveman7b97c322016-09-20 02:10:58899#if defined(OS_LINUX)
900 ChildProcess::current()->SetIOThreadPriority(base::ThreadPriority::DISPLAY);
901 ChildThreadImpl::current()->SetThreadPriority(
902 categorized_worker_pool_->background_worker_thread_id(),
903 base::ThreadPriority::BACKGROUND);
904#endif
905
tasakb46626a2016-10-18 05:54:44906 record_purge_suspend_metric_closure_.Reset(base::Bind(
907 &RenderThreadImpl::RecordPurgeAndSuspendMetrics, base::Unretained(this)));
hajimehoshi69093272016-05-13 08:30:58908 is_renderer_suspended_ = false;
hajimehoshi7bb39582016-10-12 04:30:57909
910 base::MemoryCoordinatorClientRegistry::GetInstance()->Register(this);
initial.commit09911bf2008-07-26 23:55:29911}
912
[email protected]f1a29a02011-10-06 23:08:44913RenderThreadImpl::~RenderThreadImpl() {
[email protected]ce79d8512013-04-22 22:44:41914}
915
916void RenderThreadImpl::Shutdown() {
ericwilligers88e69742016-10-17 19:29:55917 for (auto& observer : observers_)
918 observer.OnRenderProcessShutdown();
[email protected]1223d6ef2011-03-28 16:47:50919
[email protected]fdeac262014-07-10 12:52:51920 if (memory_observer_) {
921 message_loop()->RemoveTaskObserver(memory_observer_.get());
922 memory_observer_.reset();
923 }
924
[email protected]12cbfda32010-01-30 01:04:25925 // Wait for all databases to be closed.
tfarina556a7232014-10-05 01:02:09926 if (blink_platform_impl_) {
michaelnb15028542015-10-29 03:33:24927 // Crash the process if they fail to close after a generous amount of time.
928 bool all_closed = blink_platform_impl_->web_database_observer_impl()
929 ->WaitForAllDatabasesToClose(base::TimeDelta::FromSeconds(60));
930 CHECK(all_closed);
[email protected]1406f892013-11-12 19:38:19931 }
[email protected]12cbfda32010-01-30 01:04:25932
[email protected]8d86fce2009-02-26 23:37:55933 // Shutdown in reverse of the initialization order.
[email protected]fc72bb12013-06-02 21:13:46934 if (devtools_agent_message_filter_.get()) {
[email protected]b146d6d2012-09-11 10:20:05935 RemoveFilter(devtools_agent_message_filter_.get());
penghuange1d86512016-07-08 18:15:00936 devtools_agent_message_filter_ = nullptr;
[email protected]b146d6d2012-09-11 10:20:05937 }
[email protected]82622452011-07-22 09:57:20938
[email protected]f7eb0a392011-07-12 10:19:51939 RemoveFilter(audio_input_message_filter_.get());
penghuange1d86512016-07-08 18:15:00940 audio_input_message_filter_ = nullptr;
[email protected]f7eb0a392011-07-12 10:19:51941
[email protected]45048072014-01-14 13:51:29942#if defined(ENABLE_WEBRTC)
[email protected]51c7985e2014-05-23 22:00:08943 RTCPeerConnectionHandler::DestructAllHandlers();
tommi6c33f252014-11-24 12:29:51944 // |peer_connection_factory_| cannot be deleted until after the main message
945 // loop has been destroyed. This is because there may be pending tasks that
946 // hold on to objects produced by the PC factory that depend on threads owned
947 // by the PC factory. Once those tasks have been freed, the factory can be
948 // deleted.
[email protected]45048072014-01-14 13:51:29949#endif
[email protected]45048072014-01-14 13:51:29950 vc_manager_.reset();
[email protected]80b161a2011-06-27 17:42:11951
[email protected]017022b2009-07-27 23:06:34952 RemoveFilter(db_message_filter_.get());
penghuange1d86512016-07-08 18:15:00953 db_message_filter_ = nullptr;
[email protected]12cbfda32010-01-30 01:04:25954
[email protected]c6a7b862010-08-20 22:19:38955 // Shutdown the file thread if it's running.
[email protected]59383c782013-04-17 16:43:27956 if (file_thread_)
[email protected]c6a7b862010-08-20 22:19:38957 file_thread_->Stop();
958
simonhonga7e3ac42014-11-11 20:50:22959 if (compositor_message_filter_.get()) {
960 RemoveFilter(compositor_message_filter_.get());
penghuange1d86512016-07-08 18:15:00961 compositor_message_filter_ = nullptr;
[email protected]23d2b7e2012-08-14 00:34:09962 }
[email protected]1842fe22012-08-13 23:24:35963
boliubee541f42015-11-05 00:52:53964#if defined(OS_ANDROID)
965 if (sync_compositor_message_filter_) {
966 RemoveFilter(sync_compositor_message_filter_.get());
967 sync_compositor_message_filter_ = nullptr;
968 }
siva.gunturi5d4feb052015-11-15 16:15:31969 stream_texture_factory_ = nullptr;
boliubee541f42015-11-05 00:52:53970#endif
971
[email protected]b4ef7742014-03-19 06:12:56972 media_thread_.reset();
dalecurtis3ba0480e2014-09-09 20:21:30973
sadrulff12c002016-01-14 20:52:20974 blink_platform_impl_->SetCompositorThread(nullptr);
vollick1050cc62015-12-03 07:04:54975
dcastagna7f45dada2015-10-19 20:17:35976 compositor_thread_.reset();
977
dalecurtis3ba0480e2014-09-09 20:21:30978 // AudioMessageFilter may be accessed on |media_thread_|, so shutdown after.
979 RemoveFilter(audio_message_filter_.get());
penghuange1d86512016-07-08 18:15:00980 audio_message_filter_ = nullptr;
dalecurtis3ba0480e2014-09-09 20:21:30981
prashant.nfad657e2016-06-01 07:52:17982 categorized_worker_pool_->Shutdown();
reveman34b7a1522015-03-23 20:27:47983
jdduke691dd572014-12-02 20:47:52984 main_input_callback_.Cancel();
[email protected]b0255682013-06-07 21:24:08985 input_handler_manager_.reset();
[email protected]cadac622013-06-11 16:46:36986 if (input_event_filter_.get()) {
[email protected]b0255682013-06-07 21:24:08987 RemoveFilter(input_event_filter_.get());
penghuange1d86512016-07-08 18:15:00988 input_event_filter_ = nullptr;
[email protected]a9fb30aa2011-10-06 06:58:46989 }
990
[email protected]51f82b02014-05-27 00:02:57991 // RemoveEmbeddedWorkerRoute may be called while deleting
992 // EmbeddedWorkerDispatcher. So it must be deleted before deleting
993 // RenderThreadImpl.
994 embedded_worker_dispatcher_.reset();
995
[email protected]c5739b9e2013-11-07 06:30:22996 // Ramp down IDB before we ramp down WebKit (and V8), since IDB classes might
997 // hold pointers to V8 objects (e.g., via pending requests).
998 main_thread_indexed_db_dispatcher_.reset();
999
penghuange1d86512016-07-08 18:15:001000 main_thread_compositor_task_runner_ = nullptr;
skyostil457b0a12014-09-09 10:12:071001
dcastagna09bd6b32016-02-01 21:54:281002 gpu_factories_.clear();
dcastagna7f45dada2015-10-19 20:17:351003
vmiuraeeb91772015-04-15 01:00:511004 // Context providers must be released prior to destroying the GPU channel.
revemand180dfc32015-09-24 00:19:431005 shared_worker_context_provider_ = nullptr;
piman765e5282015-05-08 03:43:011006 shared_main_thread_contexts_ = nullptr;
vmiuraeeb91772015-04-15 01:00:511007
haraken53f081d2014-11-11 01:03:401008 if (gpu_channel_.get())
1009 gpu_channel_->DestroyChannel();
[email protected]8fd8de92008-08-12 23:50:301010
reveman413413fb2016-01-14 00:43:071011 ChildThreadImpl::Shutdown();
1012
fdoray2df4a9e2016-07-18 23:47:161013 // Shut down the message loop (if provided when the RenderThreadImpl was
1014 // constructed) and the renderer scheduler before shutting down Blink. This
1015 // prevents a scenario where a pending task in the message loop accesses Blink
1016 // objects after Blink shuts down.
skyostila37c2a72016-06-29 17:30:071017 renderer_scheduler_->SetRAILModeObserver(nullptr);
rmcilroy168f3dc2015-03-17 13:09:151018 renderer_scheduler_->Shutdown();
haraken6e79a752016-09-05 01:33:501019 if (main_message_loop_)
1020 base::RunLoop().RunUntilIdle();
1021
haraken19a7c51a2016-09-05 04:19:501022 if (blink_platform_impl_) {
1023 blink_platform_impl_->Shutdown();
1024 // This must be at the very end of the shutdown sequence.
1025 // blink::shutdown() must be called after all strong references from
1026 // Chromium to Blink are cleared.
1027 blink::shutdown();
1028 }
1029
1030 // Delay shutting down DiscardableSharedMemoryManager until blink::shutdown
1031 // is complete, because blink::shutdown destructs Blink Resources and they
1032 // may try to unlock their underlying discardable memory.
1033 ChildThreadImpl::ShutdownDiscardableSharedMemoryManager();
1034
1035 // The message loop must be cleared after shutting down
1036 // the DiscardableSharedMemoryManager, which needs to send messages
1037 // to the browser process.
haraken6e79a752016-09-05 01:33:501038 main_message_loop_.reset();
1039
penghuange1d86512016-07-08 18:15:001040 lazy_tls.Pointer()->Set(nullptr);
hajimehoshi7bb39582016-10-12 04:30:571041
1042 base::MemoryCoordinatorClientRegistry::GetInstance()->Unregister(this);
initial.commit09911bf2008-07-26 23:55:291043}
1044
[email protected]f1a29a02011-10-06 23:08:441045bool RenderThreadImpl::Send(IPC::Message* msg) {
changwan6ed4d432016-05-19 22:03:541046 // There are cases where we want to pump asynchronous messages while waiting
1047 // synchronously for the replies to the message to be sent here. However, this
1048 // may create an opportunity for re-entrancy into WebKit and other subsystems,
1049 // so we need to take care to disable callbacks, timers, and pending network
1050 // loads that could trigger such callbacks.
[email protected]38b592902011-04-16 02:08:421051 bool pumping_events = false;
[email protected]80fc08c52010-03-09 07:43:501052 if (msg->is_sync()) {
1053 if (msg->is_caller_pumping_messages()) {
1054 pumping_events = true;
[email protected]80fc08c52010-03-09 07:43:501055 }
[email protected]c1f50aa2010-02-18 03:46:571056 }
1057
[email protected]c1f50aa2010-02-18 03:46:571058 if (pumping_events) {
jdduked73ae5412015-05-11 20:07:161059 renderer_scheduler_->SuspendTimerQueue();
changwan6ed4d432016-05-19 22:03:541060 WebView::willEnterModalLoop();
[email protected]c1f50aa2010-02-18 03:46:571061 }
1062
jam8a021512a2015-02-03 18:16:081063 bool rv = ChildThreadImpl::Send(msg);
[email protected]c1f50aa2010-02-18 03:46:571064
1065 if (pumping_events) {
changwan6ed4d432016-05-19 22:03:541066 WebView::didExitModalLoop();
jdduked73ae5412015-05-11 20:07:161067 renderer_scheduler_->ResumeTimerQueue();
[email protected]c1f50aa2010-02-18 03:46:571068 }
1069
1070 return rv;
1071}
1072
[email protected]f1a29a02011-10-06 23:08:441073IPC::SyncChannel* RenderThreadImpl::GetChannel() {
[email protected]526476902011-10-06 20:34:061074 return channel();
1075}
1076
[email protected]f1a29a02011-10-06 23:08:441077std::string RenderThreadImpl::GetLocale() {
[email protected]526476902011-10-06 20:34:061078 // The browser process should have passed the locale to the renderer via the
[email protected]dfd53652012-10-25 00:20:021079 // --lang command line flag.
avi83883c82014-12-23 00:08:491080 const base::CommandLine& parsed_command_line =
1081 *base::CommandLine::ForCurrentProcess();
[email protected]526476902011-10-06 20:34:061082 const std::string& lang =
1083 parsed_command_line.GetSwitchValueASCII(switches::kLang);
[email protected]dfd53652012-10-25 00:20:021084 DCHECK(!lang.empty());
[email protected]526476902011-10-06 20:34:061085 return lang;
1086}
1087
[email protected]07bb6332012-01-21 01:07:571088IPC::SyncMessageFilter* RenderThreadImpl::GetSyncMessageFilter() {
1089 return sync_message_filter();
1090}
1091
skyostil12262cf2015-05-21 14:49:311092scoped_refptr<base::SingleThreadTaskRunner>
thestig529ad8a2016-07-08 20:30:121093RenderThreadImpl::GetIOTaskRunner() {
skyostil12262cf2015-05-21 14:49:311094 return ChildProcess::current()->io_task_runner();
[email protected]96191d52012-05-17 01:37:111095}
1096
avi1023d012015-12-25 02:39:141097void RenderThreadImpl::AddRoute(int32_t routing_id, IPC::Listener* listener) {
jam8a021512a2015-02-03 18:16:081098 ChildThreadImpl::GetRouter()->AddRoute(routing_id, listener);
ben76f52b242016-06-18 05:42:481099 auto it = pending_frame_creates_.find(routing_id);
1100 if (it == pending_frame_creates_.end())
rockotf8fdd9b2015-12-16 22:22:351101 return;
1102
1103 RenderFrameImpl* frame = RenderFrameImpl::FromRoutingID(routing_id);
1104 if (!frame)
1105 return;
1106
ben76f52b242016-06-18 05:42:481107 scoped_refptr<PendingFrameCreate> create(it->second);
1108 frame->Bind(it->second->TakeFrameRequest(), it->second->TakeFrameHost());
1109 pending_frame_creates_.erase(it);
[email protected]c1f50aa2010-02-18 03:46:571110}
1111
avi1023d012015-12-25 02:39:141112void RenderThreadImpl::RemoveRoute(int32_t routing_id) {
jam8a021512a2015-02-03 18:16:081113 ChildThreadImpl::GetRouter()->RemoveRoute(routing_id);
[email protected]c1f50aa2010-02-18 03:46:571114}
[email protected]0ec90d522014-03-12 16:28:191115
avi1023d012015-12-25 02:39:141116void RenderThreadImpl::AddEmbeddedWorkerRoute(int32_t routing_id,
[email protected]a620b132014-04-30 22:39:171117 IPC::Listener* listener) {
[email protected]48e52e42014-03-20 06:58:071118 AddRoute(routing_id, listener);
1119 if (devtools_agent_message_filter_.get()) {
[email protected]a620b132014-04-30 22:39:171120 devtools_agent_message_filter_->AddEmbeddedWorkerRouteOnMainThread(
[email protected]48e52e42014-03-20 06:58:071121 routing_id);
1122 }
1123}
1124
avi1023d012015-12-25 02:39:141125void RenderThreadImpl::RemoveEmbeddedWorkerRoute(int32_t routing_id) {
[email protected]48e52e42014-03-20 06:58:071126 RemoveRoute(routing_id);
1127 if (devtools_agent_message_filter_.get()) {
[email protected]a620b132014-04-30 22:39:171128 devtools_agent_message_filter_->RemoveEmbeddedWorkerRouteOnMainThread(
[email protected]48e52e42014-03-20 06:58:071129 routing_id);
1130 }
1131}
1132
ben76f52b242016-06-18 05:42:481133void RenderThreadImpl::RegisterPendingFrameCreate(
rockotf8fdd9b2015-12-16 22:22:351134 int routing_id,
ben76f52b242016-06-18 05:42:481135 mojom::FrameRequest frame_request,
1136 mojom::FrameHostPtr frame_host) {
1137 std::pair<PendingFrameCreateMap::iterator, bool> result =
1138 pending_frame_creates_.insert(std::make_pair(
rockotf8fdd9b2015-12-16 22:22:351139 routing_id,
ben76f52b242016-06-18 05:42:481140 make_scoped_refptr(new PendingFrameCreate(
1141 routing_id, std::move(frame_request), std::move(frame_host)))));
rockotf8fdd9b2015-12-16 22:22:351142 CHECK(result.second) << "Inserting a duplicate item.";
1143}
1144
leon.han06e55662016-03-26 17:19:421145mojom::StoragePartitionService* RenderThreadImpl::GetStoragePartitionService() {
jamc912ca32016-02-24 20:17:311146 return storage_partition_service_.get();
1147}
1148
[email protected]77fc9b92011-10-15 16:20:371149int RenderThreadImpl::GenerateRoutingID() {
rockote261d2112016-09-21 22:22:231150 int32_t routing_id = MSG_ROUTING_NONE;
1151 render_message_filter()->GenerateRoutingID(&routing_id);
[email protected]77fc9b92011-10-15 16:20:371152 return routing_id;
1153}
1154
[email protected]74122042014-04-25 00:07:301155void RenderThreadImpl::AddFilter(IPC::MessageFilter* filter) {
[email protected]42f1d7822009-07-23 18:17:551156 channel()->AddFilter(filter);
1157}
1158
[email protected]74122042014-04-25 00:07:301159void RenderThreadImpl::RemoveFilter(IPC::MessageFilter* filter) {
[email protected]42f1d7822009-07-23 18:17:551160 channel()->RemoveFilter(filter);
1161}
1162
tyoshino832a58a2016-04-18 08:14:081163void RenderThreadImpl::AddObserver(RenderThreadObserver* observer) {
[email protected]526476902011-10-06 20:34:061164 observers_.AddObserver(observer);
1165}
1166
tyoshino832a58a2016-04-18 08:14:081167void RenderThreadImpl::RemoveObserver(RenderThreadObserver* observer) {
[email protected]526476902011-10-06 20:34:061168 observers_.RemoveObserver(observer);
1169}
1170
[email protected]359dfa32011-10-12 01:10:151171void RenderThreadImpl::SetResourceDispatcherDelegate(
[email protected]e9ff79c2012-10-19 21:31:261172 ResourceDispatcherDelegate* delegate) {
[email protected]359dfa32011-10-12 01:10:151173 resource_dispatcher()->set_delegate(delegate);
1174}
1175
vollick1050cc62015-12-03 07:04:541176void RenderThreadImpl::InitializeCompositorThread() {
boliu66024c62016-04-20 04:00:411177 base::Thread::Options options;
vollick1050cc62015-12-03 07:04:541178#if defined(OS_ANDROID)
boliu66024c62016-04-20 04:00:411179 options.priority = base::ThreadPriority::DISPLAY;
vollick1050cc62015-12-03 07:04:541180#endif
boliu66024c62016-04-20 04:00:411181 compositor_thread_.reset(new WebThreadForCompositor(options));
1182 blink_platform_impl_->SetCompositorThread(compositor_thread_.get());
1183 compositor_task_runner_ = compositor_thread_->GetTaskRunner();
1184 compositor_task_runner_->PostTask(
1185 FROM_HERE,
1186 base::Bind(base::IgnoreResult(&ThreadRestrictions::SetIOAllowed), false));
reveman7b97c322016-09-20 02:10:581187#if defined(OS_LINUX)
1188 ChildThreadImpl::current()->SetThreadPriority(compositor_thread_->threadId(),
1189 base::ThreadPriority::DISPLAY);
1190#endif
vollick1050cc62015-12-03 07:04:541191
boliude5b75b2016-03-11 07:02:141192 SynchronousInputHandlerProxyClient* synchronous_input_handler_proxy_client =
1193 nullptr;
vollick1050cc62015-12-03 07:04:541194#if defined(OS_ANDROID)
boliu66024c62016-04-20 04:00:411195 if (GetContentClient()->UsingSynchronousCompositing()) {
vollick1050cc62015-12-03 07:04:541196 sync_compositor_message_filter_ =
1197 new SynchronousCompositorFilter(compositor_task_runner_);
1198 AddFilter(sync_compositor_message_filter_.get());
boliude5b75b2016-03-11 07:02:141199 synchronous_input_handler_proxy_client =
1200 sync_compositor_message_filter_.get();
vollick1050cc62015-12-03 07:04:541201 }
1202#endif
boliub2768db2016-06-03 23:35:161203 scoped_refptr<InputEventFilter> compositor_input_event_filter(
1204 new InputEventFilter(main_input_callback_.callback(),
1205 main_thread_compositor_task_runner_,
1206 compositor_task_runner_));
1207 InputHandlerManagerClient* input_handler_manager_client =
1208 compositor_input_event_filter.get();
1209 input_event_filter_ = compositor_input_event_filter;
vollick1050cc62015-12-03 07:04:541210 input_handler_manager_.reset(new InputHandlerManager(
1211 compositor_task_runner_, input_handler_manager_client,
boliude5b75b2016-03-11 07:02:141212 synchronous_input_handler_proxy_client, renderer_scheduler_.get()));
vollick1050cc62015-12-03 07:04:541213}
1214
jam75c44222016-03-23 05:34:241215void RenderThreadImpl::InitializeWebKit(
1216 scoped_refptr<base::SingleThreadTaskRunner>& resource_task_queue) {
1217 DCHECK(!blink_platform_impl_);
[email protected]d1b8fccc2011-08-03 01:20:131218
avi83883c82014-12-23 00:08:491219 const base::CommandLine& command_line =
1220 *base::CommandLine::ForCurrentProcess();
chunyang.daibe874c52014-11-14 06:45:051221
1222#ifdef ENABLE_VTUNE_JIT_INTERFACE
1223 if (command_line.HasSwitch(switches::kEnableVtune))
1224 gin::Debug::SetJitCodeEventHandler(vTune::GetVtuneCodeEventHandler());
1225#endif
1226
rmcilroy4073ae12015-01-08 13:08:101227 SetRuntimeFeaturesDefaultsAndUpdateFromArgs(command_line);
hlopko852ffcf2016-09-16 16:50:591228 GetContentClient()
1229 ->renderer()
1230 ->SetRuntimeFeaturesDefaultsBeforeBlinkInitialization();
rmcilroy4073ae12015-01-08 13:08:101231
sammcbebeb602016-04-06 06:42:551232 blink_platform_impl_.reset(new RendererBlinkPlatformImpl(
1233 renderer_scheduler_.get(),
bend1dd50f52016-06-26 22:10:481234 GetRemoteInterfaces()->GetWeakPtr()));
tfarina556a7232014-10-05 01:02:091235 blink::initialize(blink_platform_impl_.get());
[email protected]d1b8fccc2011-08-03 01:20:131236
[email protected]4b5340282014-07-08 11:37:341237 v8::Isolate* isolate = blink::mainThreadIsolate();
[email protected]4b5340282014-07-08 11:37:341238 isolate->SetCreateHistogramFunction(CreateHistogram);
1239 isolate->SetAddHistogramSampleFunction(AddHistogramSample);
skyostila37c2a72016-06-29 17:30:071240 renderer_scheduler_->SetRAILModeObserver(this);
[email protected]4b5340282014-07-08 11:37:341241
rmcilroy321f924d2014-11-06 00:56:001242 main_thread_compositor_task_runner_ =
danakj6e3bf8012014-12-16 18:27:531243 renderer_scheduler_->CompositorTaskRunner();
skyostilc30aa402014-10-10 13:49:091244
jdduke691dd572014-12-02 20:47:521245 main_input_callback_.Reset(
1246 base::Bind(base::IgnoreResult(&RenderThreadImpl::OnMessageReceived),
1247 base::Unretained(this)));
1248
jam75c44222016-03-23 05:34:241249 scoped_refptr<base::SingleThreadTaskRunner> resource_task_queue2;
1250 if (resource_task_queue) {
1251 resource_task_queue2 = resource_task_queue;
1252 } else {
1253 resource_task_queue2 = renderer_scheduler_->LoadingTaskRunner();
1254 }
1255 // Add a filter that forces resource messages to be dispatched via a
1256 // particular task runner.
1257 scoped_refptr<ResourceSchedulingFilter> filter(
1258 new ResourceSchedulingFilter(
1259 resource_task_queue2, resource_dispatcher()));
1260 channel()->AddFilter(filter.get());
1261 resource_dispatcher()->SetResourceSchedulingFilter(filter);
1262
1263 // The ChildResourceMessageFilter and the ResourceDispatcher need to use the
1264 // same queue to ensure tasks are executed in the expected order.
1265 child_resource_message_filter()->SetMainThreadTaskRunner(
1266 resource_task_queue2);
1267 resource_dispatcher()->SetMainThreadTaskRunner(resource_task_queue2);
1268
khushalsagara5b15d72016-01-07 06:15:401269 if (!command_line.HasSwitch(switches::kDisableThreadedCompositing) &&
1270 !command_line.HasSwitch(switches::kUseRemoteCompositing))
vollick1050cc62015-12-03 07:04:541271 InitializeCompositorThread();
[email protected]a9fb30aa2011-10-06 06:58:461272
jdduke691dd572014-12-02 20:47:521273 if (!input_event_filter_.get()) {
1274 // Always provide an input event filter implementation to ensure consistent
1275 // input event scheduling and prioritization.
1276 // TODO(jdduke): Merge InputEventFilter, InputHandlerManager and
1277 // MainThreadInputEventFilter, crbug.com/436057.
1278 input_event_filter_ = new MainThreadInputEventFilter(
1279 main_input_callback_.callback(), main_thread_compositor_task_runner_);
1280 }
1281 AddFilter(input_event_filter_.get());
1282
skyostil2d3b5bd2015-05-27 15:40:591283 scoped_refptr<base::SingleThreadTaskRunner> compositor_impl_side_task_runner;
vollick1050cc62015-12-03 07:04:541284 if (compositor_task_runner_)
skyostil2d3b5bd2015-05-27 15:40:591285 compositor_impl_side_task_runner = compositor_task_runner_;
[email protected]7f1f63f2013-03-07 06:07:291286 else
skyostil2d3b5bd2015-05-27 15:40:591287 compositor_impl_side_task_runner = base::ThreadTaskRunnerHandle::Get();
[email protected]1842fe22012-08-13 23:24:351288
simonhonga7e3ac42014-11-11 20:50:221289 compositor_message_filter_ = new CompositorForwardingMessageFilter(
skyostil2d3b5bd2015-05-27 15:40:591290 compositor_impl_side_task_runner.get());
simonhonga7e3ac42014-11-11 20:50:221291 AddFilter(compositor_message_filter_.get());
[email protected]1842fe22012-08-13 23:24:351292
[email protected]58436a12012-03-21 17:10:261293 RenderThreadImpl::RegisterSchemes();
1294
xhwang194acae2014-11-12 22:46:331295 RenderMediaClient::Initialize();
1296
[email protected]b146d6d2012-09-11 10:20:051297 devtools_agent_message_filter_ = new DevToolsAgentFilter();
1298 AddFilter(devtools_agent_message_filter_.get());
1299
ulan4a385192015-11-11 10:59:181300 if (GetContentClient()->renderer()->RunIdleHandlerWhenWidgetsHidden()) {
[email protected]1784b2f2011-11-24 10:53:481301 ScheduleIdleHandler(kLongIdleHandlerDelayMs);
ulan4a385192015-11-11 10:59:181302 } else {
1303 // If we do not track widget visibility, then assume conservatively that
1304 // the isolate is in background. This reduces memory usage.
1305 isolate->IsolateInBackgroundNotification();
1306 }
[email protected]2541d1a2013-07-10 07:33:271307
jdduke73220f02015-09-04 17:03:511308 renderer_scheduler_->SetTimerQueueSuspensionWhenBackgroundedEnabled(
1309 GetContentClient()
1310 ->renderer()
1311 ->AllowTimerSuspensionWhenProcessBackgrounded());
1312
reedccf98c52014-10-03 16:40:381313 SkGraphics::SetResourceCacheSingleAllocationByteLimit(
[email protected]dd2c1022014-07-22 23:13:571314 kImageCacheSingleAllocationByteLimit);
1315
reed6e5a72222015-08-06 20:37:161316 // Hook up blink's codecs so skia can call them
1317 SkGraphics::SetImageGeneratorFromEncodedFactory(
1318 blink::WebImageGenerator::create);
1319
[email protected]fdeac262014-07-10 12:52:511320 if (command_line.HasSwitch(switches::kMemoryMetrics)) {
1321 memory_observer_.reset(new MemoryObserver());
1322 message_loop()->AddTaskObserver(memory_observer_.get());
1323 }
paritosh.in7e30c902015-04-15 17:04:071324
1325 if (command_line.HasSwitch(switches::kExplicitlyAllowedPorts)) {
1326 std::string allowed_ports =
1327 command_line.GetSwitchValueASCII(switches::kExplicitlyAllowedPorts);
1328 net::SetExplicitlyAllowedPorts(allowed_ports);
1329 }
[email protected]d1b8fccc2011-08-03 01:20:131330}
1331
[email protected]58436a12012-03-21 17:10:261332void RenderThreadImpl::RegisterSchemes() {
mkwst8e94fb32015-05-20 05:05:141333 // chrome:
1334 WebString chrome_scheme(base::ASCIIToUTF16(kChromeUIScheme));
1335 WebSecurityPolicy::registerURLSchemeAsDisplayIsolated(chrome_scheme);
1336 WebSecurityPolicy::registerURLSchemeAsNotAllowingJavascriptURLs(
1337 chrome_scheme);
1338 WebSecurityPolicy::registerURLSchemeAsSecure(chrome_scheme);
1339 WebSecurityPolicy::registerURLSchemeAsCORSEnabled(chrome_scheme);
1340
1341 // chrome-devtools:
1342 WebString devtools_scheme(base::ASCIIToUTF16(kChromeDevToolsScheme));
1343 WebSecurityPolicy::registerURLSchemeAsDisplayIsolated(devtools_scheme);
meacerce6b66032016-06-02 20:56:051344
1345 // view-source:
1346 WebString view_source_scheme(base::ASCIIToUTF16(kViewSourceScheme));
1347 WebSecurityPolicy::registerURLSchemeAsDisplayIsolated(view_source_scheme);
[email protected]58436a12012-03-21 17:10:261348}
1349
[email protected]df9accd2014-03-13 18:18:301350void RenderThreadImpl::NotifyTimezoneChange() {
1351 NotifyTimezoneChangeOnThisThread();
1352 RenderThread::Get()->PostTaskToAllWebWorkers(
1353 base::Bind(&NotifyTimezoneChangeOnThisThread));
1354}
1355
[email protected]e6e30ac2014-01-13 21:24:391356void RenderThreadImpl::RecordAction(const base::UserMetricsAction& action) {
[email protected]97880c82013-12-04 07:09:211357 Send(new ViewHostMsg_UserMetricsRecordAction(action.str_));
1358}
1359
1360void RenderThreadImpl::RecordComputedAction(const std::string& action) {
[email protected]526476902011-10-06 20:34:061361 Send(new ViewHostMsg_UserMetricsRecordAction(action));
1362}
1363
dchengcedca5612016-04-09 01:40:151364std::unique_ptr<base::SharedMemory>
1365RenderThreadImpl::HostAllocateSharedMemoryBuffer(size_t size) {
erikchen4e01cbe2016-05-25 22:00:051366 return ChildThreadImpl::AllocateSharedMemory(size, thread_safe_sender(),
1367 nullptr);
[email protected]00614a82011-10-07 22:39:311368}
1369
jbauman2f5c1942014-12-06 03:28:241370cc::SharedBitmapManager* RenderThreadImpl::GetSharedBitmapManager() {
1371 return shared_bitmap_manager();
1372}
1373
[email protected]f1a29a02011-10-06 23:08:441374void RenderThreadImpl::RegisterExtension(v8::Extension* extension) {
[email protected]526476902011-10-06 20:34:061375 WebScriptController::registerExtension(extension);
[email protected]526476902011-10-06 20:34:061376}
1377
avi1023d012015-12-25 02:39:141378void RenderThreadImpl::ScheduleIdleHandler(int64_t initial_delay_ms) {
[email protected]6593ae12011-11-14 12:09:441379 idle_notification_delay_in_ms_ = initial_delay_ms;
[email protected]526476902011-10-06 20:34:061380 idle_timer_.Stop();
1381 idle_timer_.Start(FROM_HERE,
[email protected]6593ae12011-11-14 12:09:441382 base::TimeDelta::FromMilliseconds(initial_delay_ms),
[email protected]f1a29a02011-10-06 23:08:441383 this, &RenderThreadImpl::IdleHandler);
[email protected]526476902011-10-06 20:34:061384}
1385
[email protected]f1a29a02011-10-06 23:08:441386void RenderThreadImpl::IdleHandler() {
[email protected]1784b2f2011-11-24 10:53:481387 bool run_in_foreground_tab = (widget_count_ > hidden_widget_count_) &&
[email protected]e9ff79c2012-10-19 21:31:261388 GetContentClient()->renderer()->
[email protected]1784b2f2011-11-24 10:53:481389 RunIdleHandlerWhenWidgetsHidden();
1390 if (run_in_foreground_tab) {
jochen5a32aaf2014-09-26 20:37:431391 if (idle_notifications_to_skip_ > 0) {
1392 --idle_notifications_to_skip_;
1393 } else {
ssid0603ca9f2015-06-09 16:48:081394 ReleaseFreeMemory();
jochen5a32aaf2014-09-26 20:37:431395 }
1396 ScheduleIdleHandler(kLongIdleHandlerDelayMs);
[email protected]1784b2f2011-11-24 10:53:481397 return;
1398 }
[email protected]237a14852012-04-28 02:56:381399
ssid0603ca9f2015-06-09 16:48:081400 ReleaseFreeMemory();
[email protected]526476902011-10-06 20:34:061401
[email protected]26e82322014-01-20 14:18:221402 // Continue the idle timer if the webkit shared timer is not suspended or
1403 // something is left to do.
1404 bool continue_timer = !webkit_shared_timer_suspended_;
1405
sullivancd45a3e2014-09-19 14:39:181406 // Schedule next invocation. When the tab is originally hidden, an invocation
1407 // is scheduled for kInitialIdleHandlerDelayMs in
1408 // RenderThreadImpl::WidgetHidden in order to race to a minimal heap.
1409 // After that, idle calls can be much less frequent, so run at a maximum of
1410 // once every kLongIdleHandlerDelayMs.
[email protected]6593ae12011-11-14 12:09:441411 // Dampen the delay using the algorithm (if delay is in seconds):
[email protected]526476902011-10-06 20:34:061412 // delay = delay + 1 / (delay + 2)
1413 // Using floor(delay) has a dampening effect such as:
sullivancd45a3e2014-09-19 14:39:181414 // 30s, 30, 30, 31, 31, 31, 31, 32, 32, ...
[email protected]6593ae12011-11-14 12:09:441415 // If the delay is in milliseconds, the above formula is equivalent to:
1416 // delay_ms / 1000 = delay_ms / 1000 + 1 / (delay_ms / 1000 + 2)
1417 // which is equivalent to
1418 // delay_ms = delay_ms + 1000*1000 / (delay_ms + 2000).
[email protected]26e82322014-01-20 14:18:221419 if (continue_timer) {
sullivancd45a3e2014-09-19 14:39:181420 ScheduleIdleHandler(
1421 std::max(kLongIdleHandlerDelayMs,
1422 idle_notification_delay_in_ms_ +
1423 1000000 / (idle_notification_delay_in_ms_ + 2000)));
[email protected]26e82322014-01-20 14:18:221424
1425 } else {
1426 idle_timer_.Stop();
1427 }
[email protected]526476902011-10-06 20:34:061428
ericwilligers88e69742016-10-17 19:29:551429 for (auto& observer : observers_)
1430 observer.IdleNotification();
[email protected]526476902011-10-06 20:34:061431}
1432
avi1023d012015-12-25 02:39:141433int64_t RenderThreadImpl::GetIdleNotificationDelayInMs() const {
[email protected]6593ae12011-11-14 12:09:441434 return idle_notification_delay_in_ms_;
[email protected]526476902011-10-06 20:34:061435}
1436
[email protected]6593ae12011-11-14 12:09:441437void RenderThreadImpl::SetIdleNotificationDelayInMs(
avi1023d012015-12-25 02:39:141438 int64_t idle_notification_delay_in_ms) {
[email protected]6593ae12011-11-14 12:09:441439 idle_notification_delay_in_ms_ = idle_notification_delay_in_ms;
[email protected]4a7d6392011-09-19 20:55:081440}
1441
[email protected]a1a7ff32012-07-19 14:03:511442void RenderThreadImpl::UpdateHistograms(int sequence_number) {
1443 child_histogram_message_filter()->SendHistograms(sequence_number);
1444}
1445
[email protected]5b18406362013-06-18 18:46:431446int RenderThreadImpl::PostTaskToAllWebWorkers(const base::Closure& closure) {
kinukoef647412015-12-23 06:10:431447 return WorkerThreadRegistry::Instance()->PostTaskToAllThreads(closure);
[email protected]a9bd323d2013-06-17 20:27:561448}
1449
[email protected]b02f5902012-12-19 07:33:001450bool RenderThreadImpl::ResolveProxy(const GURL& url, std::string* proxy_list) {
1451 bool result = false;
1452 Send(new ViewHostMsg_ResolveProxy(url, &result, proxy_list));
1453 return result;
1454}
1455
[email protected]1784b2f2011-11-24 10:53:481456void RenderThreadImpl::PostponeIdleNotification() {
1457 idle_notifications_to_skip_ = 2;
1458}
1459
dcastagna7f45dada2015-10-19 20:17:351460media::GpuVideoAcceleratorFactories* RenderThreadImpl::GetGpuFactories() {
[email protected]3bb8bb32013-07-11 13:13:031461 DCHECK(IsMainThread());
1462
dcastagna09bd6b32016-02-01 21:54:281463 if (!gpu_factories_.empty()) {
1464 scoped_refptr<ContextProviderCommandBuffer> shared_context_provider =
1465 gpu_factories_.back()->ContextProviderMainThread();
1466 if (shared_context_provider) {
1467 cc::ContextProvider::ScopedContextLock lock(
1468 shared_context_provider.get());
1469 if (lock.ContextGL()->GetGraphicsResetStatusKHR() == GL_NO_ERROR) {
1470 return gpu_factories_.back();
1471 } else {
1472 scoped_refptr<base::SingleThreadTaskRunner> media_task_runner =
1473 GetMediaThreadTaskRunner();
1474 media_task_runner->PostTask(
1475 FROM_HERE,
1476 base::Bind(
1477 base::IgnoreResult(
1478 &RendererGpuVideoAcceleratorFactories::CheckContextLost),
1479 base::Unretained(gpu_factories_.back())));
1480 }
1481 }
1482 }
dcastagna7f45dada2015-10-19 20:17:351483
tobiasjsca238b3b2015-06-24 22:53:541484 const base::CommandLine* cmd_line = base::CommandLine::ForCurrentProcess();
1485
danakj0b4b94e32016-05-10 22:33:011486 scoped_refptr<gpu::GpuChannelHost> gpu_channel_host =
sadrul6d310fa2016-08-04 02:12:161487 EstablishGpuChannelSync();
danakj0b4b94e32016-05-10 22:33:011488 if (!gpu_channel_host)
1489 return nullptr;
danakj0dd9e1e2016-05-11 22:15:091490 // This context is only used to create textures and mailbox them, so
1491 // use lower limits than the default.
1492 gpu::SharedMemoryLimits limits = gpu::SharedMemoryLimits::ForMailboxContext();
danakj9a04adc2016-05-16 22:45:071493 bool support_locking = true;
danakj0b4b94e32016-05-10 22:33:011494 scoped_refptr<ContextProviderCommandBuffer> media_context_provider =
danakj9a04adc2016-05-16 22:45:071495 CreateOffscreenContext(gpu_channel_host, limits, support_locking,
danakj0dd9e1e2016-05-11 22:15:091496 command_buffer_metrics::RENDER_WORKER_CONTEXT,
1497 gpu::GPU_STREAM_DEFAULT,
1498 gpu::GpuStreamPriority::NORMAL);
danakj0b4b94e32016-05-10 22:33:011499 if (!media_context_provider->BindToCurrentThread())
1500 return nullptr;
danakj0b4b94e32016-05-10 22:33:011501
acolwellb4034942014-08-28 15:42:431502 scoped_refptr<base::SingleThreadTaskRunner> media_task_runner =
1503 GetMediaThreadTaskRunner();
danakj0b4b94e32016-05-10 22:33:011504 const bool enable_video_accelerator =
1505 !cmd_line->HasSwitch(switches::kDisableAcceleratedVideoDecode);
1506 const bool enable_gpu_memory_buffer_video_frames =
dcastagna43c3a86a2016-02-02 21:16:381507#if defined(OS_MACOSX) || defined(OS_LINUX)
dcastagnaa82ed96a2016-05-12 02:52:471508 !cmd_line->HasSwitch(switches::kDisableGpuMemoryBufferVideoFrames) &&
1509 !cmd_line->HasSwitch(switches::kDisableGpuCompositing) &&
1510 !gpu_channel_host->gpu_info().software_rendering;
dcastagnab65e6072015-09-05 07:18:421511#else
danakj0b4b94e32016-05-10 22:33:011512 cmd_line->HasSwitch(switches::kEnableGpuMemoryBufferVideoFrames);
dcastagnab65e6072015-09-05 07:18:421513#endif
dcastagna5077d6d2016-01-27 00:07:051514
danakj0b4b94e32016-05-10 22:33:011515 gpu_factories_.push_back(RendererGpuVideoAcceleratorFactories::Create(
1516 std::move(gpu_channel_host), base::ThreadTaskRunnerHandle::Get(),
1517 media_task_runner, std::move(media_context_provider),
ericrk9151705c2016-07-26 19:53:161518 enable_gpu_memory_buffer_video_frames, buffer_to_texture_target_map_,
danakj0b4b94e32016-05-10 22:33:011519 enable_video_accelerator));
1520 return gpu_factories_.back();
[email protected]3bb8bb32013-07-11 13:13:031521}
1522
danakj615aac22016-04-29 21:28:161523scoped_refptr<ContextProviderCommandBuffer>
[email protected]f10dc472013-09-27 03:31:591524RenderThreadImpl::SharedMainThreadContextProvider() {
[email protected]e06e1122013-03-15 17:12:381525 DCHECK(IsMainThread());
danakje8ec797e2016-04-19 04:08:431526 if (shared_main_thread_contexts_ &&
1527 shared_main_thread_contexts_->ContextGL()->GetGraphicsResetStatusKHR() ==
1528 GL_NO_ERROR)
1529 return shared_main_thread_contexts_;
1530
sadrul6d310fa2016-08-04 02:12:161531 scoped_refptr<gpu::GpuChannelHost> gpu_channel_host(
1532 EstablishGpuChannelSync());
danakje8ec797e2016-04-19 04:08:431533 if (!gpu_channel_host) {
1534 shared_main_thread_contexts_ = nullptr;
1535 return nullptr;
[email protected]c29b7ff2013-03-06 03:51:041536 }
danakje8ec797e2016-04-19 04:08:431537
danakj9a04adc2016-05-16 22:45:071538 bool support_locking = false;
danakjc3983552016-05-03 00:04:351539 shared_main_thread_contexts_ = CreateOffscreenContext(
danakj9a04adc2016-05-16 22:45:071540 std::move(gpu_channel_host), gpu::SharedMemoryLimits(), support_locking,
sunnypsd8ce1c22016-05-10 18:02:401541 command_buffer_metrics::RENDERER_MAINTHREAD_CONTEXT,
1542 gpu::GPU_STREAM_DEFAULT, gpu::GpuStreamPriority::NORMAL);
danakje8ec797e2016-04-19 04:08:431543 if (!shared_main_thread_contexts_->BindToCurrentThread())
1544 shared_main_thread_contexts_ = nullptr;
[email protected]f10dc472013-09-27 03:31:591545 return shared_main_thread_contexts_;
[email protected]c29b7ff2013-03-06 03:51:041546}
1547
siva.gunturi5d4feb052015-11-15 16:15:311548#if defined(OS_ANDROID)
boliuf8753bf62016-02-11 20:09:421549
siva.gunturi5d4feb052015-11-15 16:15:311550scoped_refptr<StreamTextureFactory> RenderThreadImpl::GetStreamTexureFactory() {
1551 DCHECK(IsMainThread());
boliu30f1b262016-04-19 00:12:331552 if (!stream_texture_factory_.get() ||
1553 stream_texture_factory_->ContextGL()->GetGraphicsResetStatusKHR() !=
1554 GL_NO_ERROR) {
piman9fc22f32016-05-02 22:21:221555 scoped_refptr<ContextProviderCommandBuffer> shared_context_provider =
1556 SharedMainThreadContextProvider();
1557 if (!shared_context_provider) {
penghuange1d86512016-07-08 18:15:001558 stream_texture_factory_ = nullptr;
1559 return nullptr;
siva.gunturi5d4feb052015-11-15 16:15:311560 }
piman9fc22f32016-05-02 22:21:221561 DCHECK(shared_context_provider->GetCommandBufferProxy());
1562 DCHECK(shared_context_provider->GetCommandBufferProxy()->channel());
1563 stream_texture_factory_ =
1564 StreamTextureFactory::Create(std::move(shared_context_provider));
siva.gunturi5d4feb052015-11-15 16:15:311565 }
1566 return stream_texture_factory_;
1567}
boliuf8753bf62016-02-11 20:09:421568
1569bool RenderThreadImpl::EnableStreamTextureCopy() {
boliu30f1b262016-04-19 00:12:331570 return sync_compositor_message_filter_.get();
boliuf8753bf62016-02-11 20:09:421571}
1572
siva.gunturi5d4feb052015-11-15 16:15:311573#endif
1574
[email protected]e9ff79c2012-10-19 21:31:261575AudioRendererMixerManager* RenderThreadImpl::GetAudioRendererMixerManager() {
[email protected]59383c782013-04-17 16:43:271576 if (!audio_renderer_mixer_manager_) {
olka7a4679392016-05-27 15:32:581577 audio_renderer_mixer_manager_ = AudioRendererMixerManager::Create();
[email protected]3958e972012-07-17 00:25:411578 }
1579
1580 return audio_renderer_mixer_manager_.get();
1581}
1582
[email protected]73429ca2014-03-06 06:07:471583base::WaitableEvent* RenderThreadImpl::GetShutdownEvent() {
1584 return ChildProcess::current()->GetShutDownEvent();
1585}
1586
rockot067ca55f2016-09-30 22:00:151587void RenderThreadImpl::OnAssociatedInterfaceRequest(
1588 const std::string& name,
1589 mojo::ScopedInterfaceEndpointHandle handle) {
1590 associated_interfaces_.BindRequest(name, std::move(handle));
1591}
1592
danakj6e3bf8012014-12-16 18:27:531593bool RenderThreadImpl::IsGpuRasterizationForced() {
1594 return is_gpu_rasterization_forced_;
1595}
1596
1597bool RenderThreadImpl::IsGpuRasterizationEnabled() {
1598 return is_gpu_rasterization_enabled_;
1599}
1600
sunnypsd8ce1c22016-05-10 18:02:401601bool RenderThreadImpl::IsAsyncWorkerContextEnabled() {
1602 return is_async_worker_context_enabled_;
1603}
1604
senorblancob60ba952015-01-27 19:12:361605int RenderThreadImpl::GetGpuRasterizationMSAASampleCount() {
1606 return gpu_rasterization_msaa_sample_count_;
1607}
1608
danakj6e3bf8012014-12-16 18:27:531609bool RenderThreadImpl::IsLcdTextEnabled() {
1610 return is_lcd_text_enabled_;
1611}
1612
1613bool RenderThreadImpl::IsDistanceFieldTextEnabled() {
1614 return is_distance_field_text_enabled_;
1615}
1616
1617bool RenderThreadImpl::IsZeroCopyEnabled() {
1618 return is_zero_copy_enabled_;
1619}
1620
ericrk1d17f752015-10-20 03:03:071621bool RenderThreadImpl::IsPartialRasterEnabled() {
1622 return is_partial_raster_enabled_;
jbroman5f7f71932015-08-18 16:24:461623}
1624
ccameronc7fcd132015-11-03 20:14:311625bool RenderThreadImpl::IsGpuMemoryBufferCompositorResourcesEnabled() {
1626 return is_gpu_memory_buffer_compositor_resources_enabled_;
1627}
1628
ccamerona7644752014-12-30 01:16:311629bool RenderThreadImpl::IsElasticOverscrollEnabled() {
1630 return is_elastic_overscroll_enabled_;
1631}
1632
ericrk9151705c2016-07-26 19:53:161633const cc::BufferToTextureTargetMap&
1634RenderThreadImpl::GetBufferToTextureTargetMap() {
1635 return buffer_to_texture_target_map_;
danakj6e3bf8012014-12-16 18:27:531636}
vmiura9084b342015-02-03 22:19:571637
danakj6e3bf8012014-12-16 18:27:531638scoped_refptr<base::SingleThreadTaskRunner>
1639RenderThreadImpl::GetCompositorMainThreadTaskRunner() {
1640 return main_thread_compositor_task_runner_;
1641}
1642
1643scoped_refptr<base::SingleThreadTaskRunner>
1644RenderThreadImpl::GetCompositorImplThreadTaskRunner() {
skyostil2d3b5bd2015-05-27 15:40:591645 return compositor_task_runner_;
danakj6e3bf8012014-12-16 18:27:531646}
1647
1648gpu::GpuMemoryBufferManager* RenderThreadImpl::GetGpuMemoryBufferManager() {
sadrula78e33d2016-08-16 20:11:211649#if defined(USE_AURA)
1650 if (gpu_service_)
1651 return gpu_service_->gpu_memory_buffer_manager();
1652#endif
sadrulb9ff6c92016-10-04 02:40:041653 return gpu_memory_buffer_manager_.get();
danakj6e3bf8012014-12-16 18:27:531654}
1655
skyostil529caa292016-08-10 17:44:511656blink::scheduler::RendererScheduler* RenderThreadImpl::GetRendererScheduler() {
danakj6e3bf8012014-12-16 18:27:531657 return renderer_scheduler_.get();
1658}
1659
dchengcedca5612016-04-09 01:40:151660std::unique_ptr<cc::BeginFrameSource>
danakj6e3bf8012014-12-16 18:27:531661RenderThreadImpl::CreateExternalBeginFrameSource(int routing_id) {
ennee292bdc2016-09-15 19:57:151662 const base::CommandLine* cmd = base::CommandLine::ForCurrentProcess();
1663 if (cmd->HasSwitch(switches::kDisableGpuVsync)) {
1664 std::string display_vsync_string =
1665 cmd->GetSwitchValueASCII(switches::kDisableGpuVsync);
1666 if (display_vsync_string != "gpu") {
1667 // In disable gpu vsync mode, also let the renderer tick as fast as it
1668 // can. The top level begin frame source will also be running as a back
1669 // to back begin frame source, but using a synthetic begin frame source
1670 // here reduces latency when in this mode (at least for frames
1671 // starting--it potentially increases it for input on the other hand.)
1672 base::SingleThreadTaskRunner* compositor_impl_side_task_runner =
1673 compositor_task_runner_ ? compositor_task_runner_.get()
1674 : base::ThreadTaskRunnerHandle::Get().get();
1675 return base::MakeUnique<cc::BackToBackBeginFrameSource>(
1676 base::MakeUnique<cc::DelayBasedTimeSource>(
1677 compositor_impl_side_task_runner));
1678 }
1679 }
1680
ricea29649b92016-08-31 09:30:211681 return base::MakeUnique<CompositorExternalBeginFrameSource>(
1682 compositor_message_filter_.get(), sync_message_filter(), routing_id);
danakj6e3bf8012014-12-16 18:27:531683}
1684
nyquist16febb42016-02-12 00:15:041685cc::ImageSerializationProcessor*
1686RenderThreadImpl::GetImageSerializationProcessor() {
1687 return GetContentClient()->renderer()->GetImageSerializationProcessor();
1688}
1689
reveman34b7a1522015-03-23 20:27:471690cc::TaskGraphRunner* RenderThreadImpl::GetTaskGraphRunner() {
prashant.nfad657e2016-06-01 07:52:171691 return categorized_worker_pool_->GetTaskGraphRunner();
reveman34b7a1522015-03-23 20:27:471692}
1693
vmpstrdfd22862015-09-25 17:42:411694bool RenderThreadImpl::AreImageDecodeTasksEnabled() {
1695 return are_image_decode_tasks_enabled_;
reveman34b7a1522015-03-23 20:27:471696}
1697
loyso65c93c602015-08-11 05:15:571698bool RenderThreadImpl::IsThreadedAnimationEnabled() {
1699 return is_threaded_animation_enabled_;
1700}
1701
skyostila37c2a72016-06-29 17:30:071702void RenderThreadImpl::OnRAILModeChanged(v8::RAILMode rail_mode) {
1703 blink::mainThreadIsolate()->SetRAILMode(rail_mode);
1704 blink::setRAILModeOnWorkerThreadIsolates(rail_mode);
1705}
1706
[email protected]b3e83de2012-02-07 03:33:281707bool RenderThreadImpl::IsMainThread() {
1708 return !!current();
1709}
1710
skyostild4452912015-05-14 14:41:531711scoped_refptr<base::SingleThreadTaskRunner>
1712RenderThreadImpl::GetIOThreadTaskRunner() {
1713 return io_thread_task_runner_;
[email protected]b3e83de2012-02-07 03:33:281714}
1715
dchengcedca5612016-04-09 01:40:151716std::unique_ptr<base::SharedMemory> RenderThreadImpl::AllocateSharedMemory(
[email protected]3f892832013-01-11 03:23:591717 size_t size) {
piman08f75532015-10-05 18:58:011718 return HostAllocateSharedMemoryBuffer(size);
[email protected]b3e83de2012-02-07 03:33:281719}
1720
torne88b66452016-05-03 13:22:141721void RenderThreadImpl::OnChannelError() {
1722 // In single-process mode, the renderer can't be restarted after shutdown.
1723 // So, if we get a channel error, crash the whole process right now to get a
1724 // more informative stack, since we will otherwise just crash later when we
1725 // try to restart it.
1726 CHECK(!base::CommandLine::ForCurrentProcess()->HasSwitch(
1727 switches::kSingleProcess));
1728 ChildThreadImpl::OnChannelError();
1729}
1730
[email protected]f1a29a02011-10-06 23:08:441731bool RenderThreadImpl::OnControlMessageReceived(const IPC::Message& msg) {
dchenga2d442c22016-10-13 15:39:211732 for (auto& observer : observers_) {
1733 if (observer.OnControlMessageReceived(msg))
[email protected]1223d6ef2011-03-28 16:47:501734 return true;
1735 }
1736
[email protected]70c19a932010-05-14 12:59:111737 // Some messages are handled by delegates.
[email protected]1910fe82012-05-10 00:04:101738 if (appcache_dispatcher_->OnMessageReceived(msg) ||
[email protected]7670d4332013-11-29 04:35:001739 dom_storage_dispatcher_->OnMessageReceived(msg) ||
1740 embedded_worker_dispatcher_->OnMessageReceived(msg)) {
[email protected]a95986a82010-12-24 06:19:281741 return true;
[email protected]1910fe82012-05-10 00:04:101742 }
[email protected]1edc16b82009-04-07 17:45:541743
[email protected]a95986a82010-12-24 06:19:281744 bool handled = true;
[email protected]f1a29a02011-10-06 23:08:441745 IPC_BEGIN_MESSAGE_MAP(RenderThreadImpl, msg)
[email protected]0ec90d522014-03-12 16:28:191746 IPC_MESSAGE_HANDLER(WorkerProcessMsg_CreateWorker, OnCreateNewSharedWorker)
[email protected]a95986a82010-12-24 06:19:281747 IPC_MESSAGE_UNHANDLED(handled = false)
[email protected]8930d472009-02-21 08:05:281748 IPC_END_MESSAGE_MAP()
[email protected]a95986a82010-12-24 06:19:281749 return handled;
initial.commit09911bf2008-07-26 23:55:291750}
1751
jdduke73220f02015-09-04 17:03:511752void RenderThreadImpl::OnProcessBackgrounded(bool backgrounded) {
1753 ChildThreadImpl::OnProcessBackgrounded(backgrounded);
1754
hajimehoshi69093272016-05-13 08:30:581755 if (backgrounded) {
jdduke73220f02015-09-04 17:03:511756 renderer_scheduler_->OnRendererBackgrounded();
hajimehoshi69093272016-05-13 08:30:581757 } else {
jdduke73220f02015-09-04 17:03:511758 renderer_scheduler_->OnRendererForegrounded();
tasakb46626a2016-10-18 05:54:441759 record_purge_suspend_metric_closure_.Cancel();
tasak07465a72016-10-21 06:38:521760 record_purge_suspend_metric_closure_.Reset(
1761 base::Bind(&RenderThreadImpl::RecordPurgeAndSuspendMetrics,
1762 base::Unretained(this)));
hajimehoshi69093272016-05-13 08:30:581763 is_renderer_suspended_ = false;
1764 }
1765}
1766
1767void RenderThreadImpl::OnProcessPurgeAndSuspend() {
1768 ChildThreadImpl::OnProcessPurgeAndSuspend();
tasaka079ac42016-10-28 03:10:191769 if (is_renderer_suspended_ || !RendererIsHidden())
hajimehoshi69093272016-05-13 08:30:581770 return;
1771 // TODO(hajimehoshi): Implement purging e.g. cache (crbug/607077)
1772 is_renderer_suspended_ = true;
1773 renderer_scheduler_->SuspendRenderer();
tasakb46626a2016-10-18 05:54:441774
1775 // Since purging is not a synchronous task (e.g. v8 GC, oilpan GC, ...),
1776 // we need to wait until the task is finished. So wait 15 seconds and
1777 // update purge+suspend UMA histogram.
1778 // TODO(tasak): use MemoryCoordinator's callback to report purge+suspend
1779 // UMA when MemoryCoordinator is available.
1780 GetRendererScheduler()->DefaultTaskRunner()->PostDelayedTask(
1781 FROM_HERE, record_purge_suspend_metric_closure_.callback(),
1782 base::TimeDelta::FromSeconds(15));
1783}
1784
1785// TODO(tasak): Replace the following GetMallocUsage() with memory-infra
1786// when it is possible to run memory-infra without tracing.
1787#if defined(OS_WIN)
1788namespace {
1789
1790static size_t GetMallocUsage() {
1791 DWORD number_of_heaps = ::GetProcessHeaps(0, NULL);
1792 if (number_of_heaps <= 0)
1793 return 0;
1794
1795 size_t malloc_usage = 0;
1796 std::unique_ptr<HANDLE[]> heaps(new HANDLE[number_of_heaps]);
1797 ::GetProcessHeaps(number_of_heaps, heaps.get());
1798 for (size_t i = 0; i < number_of_heaps; i++) {
1799 PROCESS_HEAP_ENTRY heap_entry;
1800 ::HeapLock(heaps[i]);
1801 heap_entry.lpData = NULL;
1802 while (::HeapWalk(heaps[i], &heap_entry) != 0) {
1803 if (heap_entry.lpData == heaps.get())
1804 continue;
1805 if ((heap_entry.wFlags & PROCESS_HEAP_ENTRY_BUSY) != 0)
1806 malloc_usage += heap_entry.cbData;
1807 }
1808 ::HeapUnlock(heaps[i]);
1809 }
1810 return malloc_usage;
1811}
1812
1813} // namespace
1814#elif defined(OS_MACOSX) || defined(OS_IOS)
1815namespace {
1816
1817static size_t GetMallocUsage() {
1818 malloc_statistics_t stats = {0};
1819 malloc_zone_statistics(nullptr, &stats);
1820 return stats.size_in_use;
1821}
1822
1823} // namespace
1824#endif
1825
1826// TODO(tasak): Once it is possible to use memory-infra without tracing,
1827// we should collect the metrics using memory-infra.
1828// TODO(tasak): We should also report a difference between the memory usages
1829// before and after purging by using memory-infra.
1830void RenderThreadImpl::RecordPurgeAndSuspendMetrics() const {
1831 // If this renderer is resumed, we should not update UMA.
1832 if (!is_renderer_suspended_)
1833 return;
1834
1835 // TODO(tasak): Compare memory metrics between purge-enabled renderers and
1836 // purge-disabled renderers (A/B testing).
1837 blink::WebMemoryStatistics blink_stats = blink::WebMemoryStatistics::Get();
1838 UMA_HISTOGRAM_MEMORY_KB("PurgeAndSuspend.Memory.PartitionAllocKB",
1839 blink_stats.partitionAllocTotalAllocatedBytes / 1024);
1840 UMA_HISTOGRAM_MEMORY_KB("PurgeAndSuspend.Memory.BlinkGCKB",
1841 blink_stats.blinkGCTotalAllocatedBytes / 1024);
1842#if defined(OS_LINUX) || defined(OS_ANDROID)
1843 struct mallinfo minfo = mallinfo();
1844#if defined(USE_TCMALLOC)
1845 size_t malloc_usage = minfo.uordblks;
1846#else
1847 size_t malloc_usage = minfo.hblkhd + minfo.arena;
1848#endif
1849#else
1850 size_t malloc_usage = GetMallocUsage();
1851#endif
1852 UMA_HISTOGRAM_MEMORY_MB("PurgeAndSuspend.Memory.MallocMB",
1853 malloc_usage / 1024 / 1024);
1854
1855 ChildDiscardableSharedMemoryManager::Statistics discardable_stats =
1856 ChildThreadImpl::discardable_shared_memory_manager()->GetStatistics();
1857 size_t discardable_usage =
1858 discardable_stats.total_size - discardable_stats.freelist_size;
1859 UMA_HISTOGRAM_MEMORY_KB("PurgeAndSuspend.Memory.DiscardableKB",
1860 discardable_usage / 1024);
1861
1862 size_t v8_usage = 0;
1863 if (v8::Isolate* isolate = blink::mainThreadIsolate()) {
1864 v8::HeapStatistics v8_heap_statistics;
1865 isolate->GetHeapStatistics(&v8_heap_statistics);
1866 v8_usage = v8_heap_statistics.total_heap_size();
1867 }
1868 // TODO(tasak): Currently only memory usage of mainThreadIsolate() is
1869 // reported. We should collect memory usages of all isolates using
1870 // memory-infra.
1871 UMA_HISTOGRAM_MEMORY_MB("PurgeAndSuspend.Memory.V8MainThreadIsolateMB",
1872 v8_usage / 1024 / 1024);
1873 UMA_HISTOGRAM_MEMORY_MB("PurgeAndSuspend.Memory.TotalAllocatedMB",
1874 (blink_stats.partitionAllocTotalAllocatedBytes +
1875 blink_stats.blinkGCTotalAllocatedBytes +
1876 malloc_usage + v8_usage + discardable_usage) /
1877 1024 / 1024);
jdduke73220f02015-09-04 17:03:511878}
1879
tasaka079ac42016-10-28 03:10:191880void RenderThreadImpl::OnProcessResume() {
1881 ChildThreadImpl::OnProcessResume();
1882
1883 DCHECK(is_renderer_suspended_);
1884 is_renderer_suspended_ = false;
1885 renderer_scheduler_->ResumeRenderer();
1886}
1887
sadrul6d310fa2016-08-04 02:12:161888scoped_refptr<gpu::GpuChannelHost> RenderThreadImpl::EstablishGpuChannelSync() {
[email protected]d13f35d2012-05-18 02:28:151889 TRACE_EVENT0("gpu", "RenderThreadImpl::EstablishGpuChannelSync");
1890
piman9fc22f32016-05-02 22:21:221891 if (gpu_channel_) {
[email protected]1082b1d2010-03-30 00:31:221892 // Do nothing if we already have a GPU channel or are already
1893 // establishing one.
[email protected]7951bfe2013-06-13 01:43:341894 if (!gpu_channel_->IsLost())
piman9fc22f32016-05-02 22:21:221895 return gpu_channel_;
[email protected]6217d392010-03-25 22:08:351896
1897 // Recreate the channel if it has been lost.
piman765e5282015-05-08 03:43:011898 gpu_channel_->DestroyChannel();
penghuange1d86512016-07-08 18:15:001899 gpu_channel_ = nullptr;
[email protected]6217d392010-03-25 22:08:351900 }
1901
penghuange1d86512016-07-08 18:15:001902 if (!IsRunningInMash()) {
1903 int client_id = 0;
1904 IPC::ChannelHandle channel_handle;
1905 gpu::GPUInfo gpu_info;
1906 // Ask the browser for the channel name.
1907 if (!Send(new ChildProcessHostMsg_EstablishGpuChannel(
sadrul6d310fa2016-08-04 02:12:161908 &client_id, &channel_handle, &gpu_info)) ||
amistrycef5cfa2016-07-21 00:09:321909 !channel_handle.mojo_handle.is_valid()) {
penghuange1d86512016-07-08 18:15:001910 // Otherwise cancel the connection.
1911 return nullptr;
1912 }
1913 GetContentClient()->SetGpuInfo(gpu_info);
1914
1915 // Cache some variables that are needed on the compositor thread for our
1916 // implementation of GpuChannelHostFactory.
1917 io_thread_task_runner_ = ChildProcess::current()->io_task_runner();
1918
1919 gpu_channel_ =
1920 gpu::GpuChannelHost::Create(this, client_id, gpu_info, channel_handle,
1921 ChildProcess::current()->GetShutDownEvent(),
sadrulb9ff6c92016-10-04 02:40:041922 GetGpuMemoryBufferManager());
penghuange1d86512016-07-08 18:15:001923 } else {
sadrul943e3b32016-08-04 18:22:591924#if defined(USE_AURA)
sadrul9e0bb1d2016-08-04 20:18:391925 gpu_channel_ = gpu_service_->EstablishGpuChannelSync();
penghuange1d86512016-07-08 18:15:001926#else
1927 NOTREACHED();
1928#endif
[email protected]b42a9f62011-06-08 20:36:041929 }
piman9fc22f32016-05-02 22:21:221930 return gpu_channel_;
[email protected]3bf4d532010-03-27 00:23:341931}
1932
danakj1120f4c2016-09-15 02:05:321933std::unique_ptr<cc::CompositorFrameSink>
1934RenderThreadImpl::CreateCompositorFrameSink(
danakj83066a32016-06-21 02:34:491935 bool use_software,
1936 int routing_id,
1937 scoped_refptr<FrameSwapMessageQueue> frame_swap_message_queue,
1938 const GURL& url) {
1939 const base::CommandLine& command_line =
1940 *base::CommandLine::ForCurrentProcess();
1941 if (command_line.HasSwitch(switches::kDisableGpuCompositing))
1942 use_software = true;
1943
sadrul943e3b32016-08-04 18:22:591944#if defined(USE_AURA)
bend32292b2016-10-07 00:21:581945 if (GetServiceManagerConnection() && !use_software &&
danakj83066a32016-06-21 02:34:491946 command_line.HasSwitch(switches::kUseMusInRenderer)) {
1947 RenderWidgetMusConnection* connection =
1948 RenderWidgetMusConnection::GetOrCreate(routing_id);
sadrul12e259d2016-08-19 01:36:581949 scoped_refptr<gpu::GpuChannelHost> gpu_channel_host =
1950 EstablishGpuChannelSync();
pimanc44437a22016-10-29 00:09:221951 return connection->CreateCompositorFrameSink(std::move(gpu_channel_host),
1952 GetGpuMemoryBufferManager());
danakj83066a32016-06-21 02:34:491953 }
1954#endif
1955
danakj1120f4c2016-09-15 02:05:321956 uint32_t compositor_frame_sink_id = g_next_compositor_frame_sink_id++;
danakj83066a32016-06-21 02:34:491957
1958 if (command_line.HasSwitch(switches::kEnableVulkan)) {
1959 scoped_refptr<cc::VulkanContextProvider> vulkan_context_provider =
1960 cc::VulkanInProcessContextProvider::Create();
1961 if (vulkan_context_provider) {
1962 DCHECK(!layout_test_mode());
danakj1120f4c2016-09-15 02:05:321963 return base::MakeUnique<RendererCompositorFrameSink>(
1964 routing_id, compositor_frame_sink_id,
enne077ba4862016-09-12 20:59:531965 CreateExternalBeginFrameSource(routing_id),
1966 std::move(vulkan_context_provider),
ricea29649b92016-08-31 09:30:211967 std::move(frame_swap_message_queue));
danakj83066a32016-06-21 02:34:491968 }
1969 }
1970
1971 // Create a gpu process channel and verify we want to use GPU compositing
1972 // before creating any context providers.
1973 scoped_refptr<gpu::GpuChannelHost> gpu_channel_host;
1974 if (!use_software) {
sadrul6d310fa2016-08-04 02:12:161975 gpu_channel_host = EstablishGpuChannelSync();
danakj83066a32016-06-21 02:34:491976 if (!gpu_channel_host) {
1977 // Cause the compositor to wait and try again.
1978 return nullptr;
1979 }
1980 // We may get a valid channel, but with a software renderer. In that case,
1981 // disable GPU compositing.
1982 if (gpu_channel_host->gpu_info().software_rendering)
1983 use_software = true;
1984 }
1985
1986 if (use_software) {
1987 DCHECK(!layout_test_mode());
danakj1120f4c2016-09-15 02:05:321988 return base::MakeUnique<RendererCompositorFrameSink>(
1989 routing_id, compositor_frame_sink_id,
pimanc44437a22016-10-29 00:09:221990 CreateExternalBeginFrameSource(routing_id), nullptr, nullptr, nullptr,
1991 shared_bitmap_manager(), std::move(frame_swap_message_queue));
danakj83066a32016-06-21 02:34:491992 }
1993
1994 scoped_refptr<ContextProviderCommandBuffer> worker_context_provider =
1995 SharedCompositorWorkerContextProvider();
1996 if (!worker_context_provider) {
1997 // Cause the compositor to wait and try again.
1998 return nullptr;
1999 }
2000
2001 // The renderer compositor context doesn't do a lot of stuff, so we don't
2002 // expect it to need a lot of space for commands or transfer. Raster and
2003 // uploads happen on the worker context instead.
2004 gpu::SharedMemoryLimits limits = gpu::SharedMemoryLimits::ForMailboxContext();
2005
2006 // This is for an offscreen context for the compositor. So the default
2007 // framebuffer doesn't need alpha, depth, stencil, antialiasing.
2008 gpu::gles2::ContextCreationAttribHelper attributes;
2009 attributes.alpha_size = -1;
2010 attributes.depth_size = 0;
2011 attributes.stencil_size = 0;
2012 attributes.samples = 0;
2013 attributes.sample_buffers = 0;
2014 attributes.bind_generates_resource = false;
2015 attributes.lose_context_when_out_of_memory = true;
2016
2017 constexpr bool automatic_flushes = false;
2018 constexpr bool support_locking = false;
2019
2020 // The compositor context shares resources with the worker context unless
2021 // the worker is async.
2022 ContextProviderCommandBuffer* share_context = worker_context_provider.get();
2023 if (IsAsyncWorkerContextEnabled())
2024 share_context = nullptr;
2025
2026 scoped_refptr<ContextProviderCommandBuffer> context_provider(
2027 new ContextProviderCommandBuffer(
danakja40dd4482016-06-28 01:14:102028 gpu_channel_host, gpu::GPU_STREAM_DEFAULT,
danakj83066a32016-06-21 02:34:492029 gpu::GpuStreamPriority::NORMAL, gpu::kNullSurfaceHandle, url,
pimand488e8b42016-06-30 19:06:592030 automatic_flushes, support_locking, limits, attributes, share_context,
danakj83066a32016-06-21 02:34:492031 command_buffer_metrics::RENDER_COMPOSITOR_CONTEXT));
2032
danakj83066a32016-06-21 02:34:492033 if (layout_test_deps_) {
danakj1120f4c2016-09-15 02:05:322034 return layout_test_deps_->CreateCompositorFrameSink(
jbroman6ccbc7d472016-07-27 04:45:412035 routing_id, std::move(gpu_channel_host), std::move(context_provider),
pimanc44437a22016-10-29 00:09:222036 std::move(worker_context_provider), GetGpuMemoryBufferManager(),
2037 this);
danakj83066a32016-06-21 02:34:492038 }
2039
2040#if defined(OS_ANDROID)
2041 if (sync_compositor_message_filter_) {
danakj1120f4c2016-09-15 02:05:322042 return base::MakeUnique<SynchronousCompositorFrameSink>(
danakja40dd4482016-06-28 01:14:102043 std::move(context_provider), std::move(worker_context_provider),
pimanc44437a22016-10-29 00:09:222044 GetGpuMemoryBufferManager(), routing_id, compositor_frame_sink_id,
enne077ba4862016-09-12 20:59:532045 CreateExternalBeginFrameSource(routing_id),
2046 sync_compositor_message_filter_.get(),
ricea29649b92016-08-31 09:30:212047 std::move(frame_swap_message_queue));
danakj83066a32016-06-21 02:34:492048 }
2049#endif
danakj1120f4c2016-09-15 02:05:322050 return base::WrapUnique(new RendererCompositorFrameSink(
2051 routing_id, compositor_frame_sink_id,
2052 CreateExternalBeginFrameSource(routing_id), std::move(context_provider),
pimanc44437a22016-10-29 00:09:222053 std::move(worker_context_provider), GetGpuMemoryBufferManager(),
2054 nullptr, std::move(frame_swap_message_queue)));
danakj83066a32016-06-21 02:34:492055}
2056
rockot067ca55f2016-09-30 22:00:152057AssociatedInterfaceRegistry*
2058RenderThreadImpl::GetAssociatedInterfaceRegistry() {
2059 return &associated_interfaces_;
2060}
2061
jbroman6ccbc7d472016-07-27 04:45:412062std::unique_ptr<cc::SwapPromise>
2063RenderThreadImpl::RequestCopyOfOutputForLayoutTest(
2064 int32_t routing_id,
2065 std::unique_ptr<cc::CopyOutputRequest> request) {
2066 DCHECK(layout_test_deps_);
2067 return layout_test_deps_->RequestCopyOfOutput(routing_id, std::move(request));
2068}
2069
[email protected]180ef242013-11-07 06:50:462070blink::WebMediaStreamCenter* RenderThreadImpl::CreateMediaStreamCenter(
2071 blink::WebMediaStreamCenterClient* client) {
[email protected]d8cd8372012-03-09 10:49:512072#if defined(ENABLE_WEBRTC)
[email protected]68e5fee2013-02-18 10:04:222073 if (!media_stream_center_) {
2074 media_stream_center_ = GetContentClient()->renderer()
2075 ->OverrideCreateWebMediaStreamCenter(client);
2076 if (!media_stream_center_) {
dchengcedca5612016-04-09 01:40:152077 std::unique_ptr<MediaStreamCenter> media_stream_center(
[email protected]0107d8a2014-05-16 10:20:342078 new MediaStreamCenter(client, GetPeerConnectionDependencyFactory()));
[email protected]c1298742013-07-17 04:06:322079 media_stream_center_ = media_stream_center.release();
[email protected]68e5fee2013-02-18 10:04:222080 }
2081 }
[email protected]d8cd8372012-03-09 10:49:512082#endif
2083 return media_stream_center_;
2084}
2085
[email protected]22fe91d2014-08-12 17:07:122086#if defined(ENABLE_WEBRTC)
[email protected]0107d8a2014-05-16 10:20:342087PeerConnectionDependencyFactory*
2088RenderThreadImpl::GetPeerConnectionDependencyFactory() {
[email protected]83e0a482014-05-22 18:07:182089 return peer_connection_factory_.get();
[email protected]6ee10bd2012-09-13 09:01:532090}
[email protected]22fe91d2014-08-12 17:07:122091#endif
[email protected]6ee10bd2012-09-13 09:01:532092
rockot1587e332016-07-27 17:44:142093mojom::RenderFrameMessageFilter*
2094RenderThreadImpl::render_frame_message_filter() {
2095 if (!render_frame_message_filter_)
2096 GetChannel()->GetRemoteAssociatedInterface(&render_frame_message_filter_);
2097 return render_frame_message_filter_.get();
2098}
2099
rockote261d2112016-09-21 22:22:232100mojom::RenderMessageFilter* RenderThreadImpl::render_message_filter() {
2101 if (!render_message_filter_)
2102 GetChannel()->GetRemoteAssociatedInterface(&render_message_filter_);
2103 return render_message_filter_.get();
2104}
2105
penghuang346a46f92016-03-31 21:37:522106gpu::GpuChannelHost* RenderThreadImpl::GetGpuChannel() {
piman9fc22f32016-05-02 22:21:222107 if (!gpu_channel_)
danakj3873e852016-05-05 00:46:072108 return nullptr;
[email protected]7951bfe2013-06-13 01:43:342109 if (gpu_channel_->IsLost())
danakj3873e852016-05-05 00:46:072110 return nullptr;
[email protected]6217d392010-03-25 22:08:352111 return gpu_channel_.get();
2112}
2113
rockot067ca55f2016-09-30 22:00:152114void RenderThreadImpl::CreateView(mojom::CreateViewParamsPtr params) {
2115 CompositorDependencies* compositor_deps = this;
2116 // When bringing in render_view, also bring in webkit's glue and jsbindings.
2117 RenderViewImpl::Create(compositor_deps, *params, false);
2118}
2119
rockot53be7caf2016-10-04 20:17:082120void RenderThreadImpl::CreateFrame(mojom::CreateFrameParamsPtr params) {
2121 // Debug cases of https://crbug.com/626802.
2122 base::debug::SetCrashKeyValue("newframe_routing_id",
2123 base::IntToString(params->routing_id));
2124 base::debug::SetCrashKeyValue("newframe_proxy_id",
2125 base::IntToString(params->proxy_routing_id));
2126 base::debug::SetCrashKeyValue("newframe_opener_id",
2127 base::IntToString(params->opener_routing_id));
2128 base::debug::SetCrashKeyValue("newframe_parent_id",
2129 base::IntToString(params->parent_routing_id));
2130 base::debug::SetCrashKeyValue("newframe_widget_id",
2131 base::IntToString(
2132 params->widget_params->routing_id));
2133 base::debug::SetCrashKeyValue("newframe_widget_hidden",
2134 params->widget_params->hidden ? "yes" : "no");
2135 base::debug::SetCrashKeyValue("newframe_replicated_origin",
2136 params->replication_state.origin.Serialize());
2137 base::debug::SetCrashKeyValue("newframe_oopifs_possible",
2138 SiteIsolationPolicy::AreCrossProcessFramesPossible() ? "yes" : "no");
2139 CompositorDependencies* compositor_deps = this;
2140 RenderFrameImpl::CreateFrame(
2141 params->routing_id, params->proxy_routing_id, params->opener_routing_id,
2142 params->parent_routing_id, params->previous_sibling_routing_id,
2143 params->replication_state, compositor_deps, *params->widget_params,
2144 params->frame_owner_properties);
2145}
2146
2147void RenderThreadImpl::CreateFrameProxy(
2148 int32_t routing_id,
2149 int32_t render_view_routing_id,
2150 int32_t opener_routing_id,
2151 int32_t parent_routing_id,
2152 const FrameReplicationState& replicated_state) {
2153 // Debug cases of https://crbug.com/575245.
2154 base::debug::SetCrashKeyValue("newproxy_proxy_id",
2155 base::IntToString(routing_id));
2156 base::debug::SetCrashKeyValue("newproxy_view_id",
2157 base::IntToString(render_view_routing_id));
2158 base::debug::SetCrashKeyValue("newproxy_opener_id",
2159 base::IntToString(opener_routing_id));
2160 base::debug::SetCrashKeyValue("newproxy_parent_id",
2161 base::IntToString(parent_routing_id));
2162 RenderFrameProxy::CreateFrameProxy(routing_id, render_view_routing_id,
2163 opener_routing_id, parent_routing_id,
2164 replicated_state);
2165}
2166
rockota2db0da2016-10-18 17:39:112167void RenderThreadImpl::OnNetworkConnectionChanged(
2168 net::NetworkChangeNotifier::ConnectionType type,
2169 double max_bandwidth_mbps) {
2170 bool online = type != net::NetworkChangeNotifier::CONNECTION_NONE;
2171 WebNetworkStateNotifier::setOnLine(online);
2172 for (auto& observer : observers_)
2173 observer.NetworkStateChanged(online);
2174 WebNetworkStateNotifier::setWebConnection(
2175 NetConnectionTypeToWebConnectionType(type), max_bandwidth_mbps);
2176}
2177
2178void RenderThreadImpl::SetWebKitSharedTimersSuspended(bool suspend) {
2179#if defined(OS_ANDROID)
2180 if (suspend) {
2181 renderer_scheduler_->SuspendTimerQueue();
2182 } else {
2183 renderer_scheduler_->ResumeTimerQueue();
2184 }
2185 webkit_shared_timer_suspended_ = suspend;
2186#else
2187 NOTREACHED();
2188#endif
2189}
2190
2191void RenderThreadImpl::UpdateScrollbarTheme(
2192 mojom::UpdateScrollbarThemeParamsPtr params) {
2193#if defined(OS_MACOSX)
2194 static_cast<WebScrollbarBehaviorImpl*>(
2195 blink_platform_impl_->scrollbarBehavior())
2196 ->set_jump_on_track_click(params->jump_on_track_click);
2197
2198 blink::WebScrollbarTheme::updateScrollbarsWithNSDefaults(
2199 params->initial_button_delay, params->autoscroll_button_delay,
2200 params->preferred_scroller_style, params->redraw,
2201 params->button_placement);
2202#else
2203 NOTREACHED();
2204#endif
2205}
2206
2207void RenderThreadImpl::OnSystemColorsChanged(
2208 int32_t aqua_color_variant,
2209 const std::string& highlight_text_color,
2210 const std::string& highlight_color) {
2211#if defined(OS_MACOSX)
2212 SystemColorsDidChange(aqua_color_variant, highlight_text_color,
2213 highlight_color);
2214#else
2215 NOTREACHED();
2216#endif
2217}
2218
2219void RenderThreadImpl::PurgePluginListCache(bool reload_pages) {
2220#if defined(ENABLE_PLUGINS)
2221 // The call below will cause a GetPlugins call with refresh=true, but at this
2222 // point we already know that the browser has refreshed its list, so disable
2223 // refresh temporarily to prevent each renderer process causing the list to be
2224 // regenerated.
2225 blink_platform_impl_->set_plugin_refresh_allowed(false);
2226 blink::resetPluginCache(reload_pages);
2227 blink_platform_impl_->set_plugin_refresh_allowed(true);
2228
2229 for (auto& observer : observers_)
2230 observer.PluginListChanged();
2231#else
2232 NOTREACHED();
2233#endif
2234}
2235
blundellc00adf442016-09-16 10:43:412236void RenderThreadImpl::OnTimeZoneChange(const std::string& zone_id) {
jochen22b6f9a2014-11-26 11:30:562237 if (!blink_platform_impl_)
2238 return;
jshin0a9aa632015-04-29 18:35:292239 if (!zone_id.empty()) {
2240 icu::TimeZone *new_zone = icu::TimeZone::createTimeZone(
2241 icu::UnicodeString::fromUTF8(zone_id));
2242 icu::TimeZone::adoptDefault(new_zone);
2243 VLOG(1) << "ICU default timezone is set to " << zone_id;
2244 }
[email protected]df9accd2014-03-13 18:18:302245 NotifyTimezoneChange();
2246}
2247
[email protected]0ec90d522014-03-12 16:28:192248void RenderThreadImpl::OnCreateNewSharedWorker(
2249 const WorkerProcessMsg_CreateWorker_Params& params) {
2250 // EmbeddedSharedWorkerStub will self-destruct.
mkwstcfa98932016-03-09 13:06:192251 new EmbeddedSharedWorkerStub(
2252 params.url, params.name, params.content_security_policy,
2253 params.security_policy_type, params.creation_address_space,
2254 params.pause_on_start, params.route_id);
[email protected]0ec90d522014-03-12 16:28:192255}
2256
[email protected]5071cb22013-07-10 02:19:062257void RenderThreadImpl::OnMemoryPressure(
2258 base::MemoryPressureListener::MemoryPressureLevel memory_pressure_level) {
hong.zhengb28b5332016-05-11 02:33:392259 TRACE_EVENT0("memory","RenderThreadImpl::OnMemoryPressure");
rmcilroy7fbb3bd52015-02-17 19:02:142260 if (blink_platform_impl_) {
bashi5e843ac2016-06-17 07:44:352261 blink::WebMemoryCoordinator::onMemoryPressure(
bashic577bfc2016-01-08 03:42:352262 static_cast<blink::WebMemoryPressureLevel>(memory_pressure_level));
hajimehoshi7bb39582016-10-12 04:30:572263 }
2264 if (memory_pressure_level ==
2265 base::MemoryPressureListener::MEMORY_PRESSURE_LEVEL_CRITICAL) {
2266 ReleaseFreeMemory();
2267 ClearMemory();
2268 }
2269}
rmcilroyab967c972015-02-17 23:15:002270
hajimehoshi7bb39582016-10-12 04:30:572271void RenderThreadImpl::OnMemoryStateChange(base::MemoryState state) {
2272 // TODO(hajimehoshi): Adjust the size of this memory usage according to
2273 // |state|. RenderThreadImpl doesn't have a feature to limit memory usage at
2274 // present.
2275 if (blink_platform_impl_) {
2276 blink::WebMemoryCoordinator::onMemoryStateChange(
2277 static_cast<blink::MemoryState>(state));
2278 }
2279 switch (state) {
2280 case base::MemoryState::NORMAL:
2281 break;
2282 case base::MemoryState::THROTTLED:
2283 ReleaseFreeMemory();
2284 break;
2285 case base::MemoryState::SUSPENDED:
2286 ReleaseFreeMemory();
2287 ClearMemory();
2288 break;
2289 case base::MemoryState::UNKNOWN:
2290 NOTREACHED();
2291 break;
2292 }
2293}
2294
2295void RenderThreadImpl::ClearMemory() {
2296 // Do not call into blink if it is not initialized.
2297 if (blink_platform_impl_) {
2298 // Purge Skia font cache, by setting it to 0 and then again to the
2299 // previous limit.
2300 size_t font_cache_limit = SkGraphics::SetFontCacheLimit(0);
2301 SkGraphics::SetFontCacheLimit(font_cache_limit);
rmcilroy7fbb3bd52015-02-17 19:02:142302 }
[email protected]5071cb22013-07-10 02:19:062303}
2304
skyostil2d3b5bd2015-05-27 15:40:592305scoped_refptr<base::SingleThreadTaskRunner>
thestig529ad8a2016-07-08 20:30:122306RenderThreadImpl::GetFileThreadTaskRunner() {
fdoraye94d8642016-07-07 19:19:012307 DCHECK(message_loop()->task_runner()->BelongsToCurrentThread());
[email protected]59383c782013-04-17 16:43:272308 if (!file_thread_) {
[email protected]c6a7b862010-08-20 22:19:382309 file_thread_.reset(new base::Thread("Renderer::FILE"));
2310 file_thread_->Start();
2311 }
skyostil2d3b5bd2015-05-27 15:40:592312 return file_thread_->task_runner();
[email protected]c6a7b862010-08-20 22:19:382313}
[email protected]e9ff79c2012-10-19 21:31:262314
acolwellb4034942014-08-28 15:42:432315scoped_refptr<base::SingleThreadTaskRunner>
2316RenderThreadImpl::GetMediaThreadTaskRunner() {
fdoraye94d8642016-07-07 19:19:012317 DCHECK(message_loop()->task_runner()->BelongsToCurrentThread());
[email protected]c1330c82013-06-06 02:23:252318 if (!media_thread_) {
2319 media_thread_.reset(new base::Thread("Media"));
2320 media_thread_->Start();
2321 }
skyostil2d3b5bd2015-05-27 15:40:592322 return media_thread_->task_runner();
[email protected]c1330c82013-06-06 02:23:252323}
2324
dcastagna4517a182015-08-05 19:51:032325base::TaskRunner* RenderThreadImpl::GetWorkerTaskRunner() {
prashant.nfad657e2016-06-01 07:52:172326 return categorized_worker_pool_.get();
dcastagnab880e8f2015-06-30 20:16:062327}
2328
revemand180dfc32015-09-24 00:19:432329scoped_refptr<ContextProviderCommandBuffer>
danakj0b4b94e32016-05-10 22:33:012330RenderThreadImpl::SharedCompositorWorkerContextProvider() {
revemand180dfc32015-09-24 00:19:432331 DCHECK(IsMainThread());
2332 // Try to reuse existing shared worker context provider.
revemand180dfc32015-09-24 00:19:432333 if (shared_worker_context_provider_) {
2334 // Note: If context is lost, delete reference after releasing the lock.
boliu11afa7e2016-04-18 18:04:142335 cc::ContextProvider::ScopedContextLock lock(
2336 shared_worker_context_provider_.get());
revemand180dfc32015-09-24 00:19:432337 if (shared_worker_context_provider_->ContextGL()
danakje8ec797e2016-04-19 04:08:432338 ->GetGraphicsResetStatusKHR() == GL_NO_ERROR)
2339 return shared_worker_context_provider_;
revemand180dfc32015-09-24 00:19:432340 }
danakje8ec797e2016-04-19 04:08:432341
sadrul6d310fa2016-08-04 02:12:162342 scoped_refptr<gpu::GpuChannelHost> gpu_channel_host(
2343 EstablishGpuChannelSync());
danakje8ec797e2016-04-19 04:08:432344 if (!gpu_channel_host) {
2345 shared_worker_context_provider_ = nullptr;
2346 return shared_worker_context_provider_;
revemand180dfc32015-09-24 00:19:432347 }
danakje8ec797e2016-04-19 04:08:432348
sunnypsd8ce1c22016-05-10 18:02:402349 int32_t stream_id = gpu::GPU_STREAM_DEFAULT;
2350 gpu::GpuStreamPriority stream_priority = gpu::GpuStreamPriority::NORMAL;
2351 if (is_async_worker_context_enabled_) {
2352 stream_id = gpu_channel_host->GenerateStreamID();
2353 stream_priority = gpu::GpuStreamPriority::LOW;
2354 }
2355
danakj9a04adc2016-05-16 22:45:072356 bool support_locking = true;
danakj0dd9e1e2016-05-11 22:15:092357 shared_worker_context_provider_ = CreateOffscreenContext(
danakj9a04adc2016-05-16 22:45:072358 std::move(gpu_channel_host), gpu::SharedMemoryLimits(), support_locking,
danakj0dd9e1e2016-05-11 22:15:092359 command_buffer_metrics::RENDER_WORKER_CONTEXT, stream_id,
2360 stream_priority);
danakje8ec797e2016-04-19 04:08:432361 if (!shared_worker_context_provider_->BindToCurrentThread())
2362 shared_worker_context_provider_ = nullptr;
revemand180dfc32015-09-24 00:19:432363 return shared_worker_context_provider_;
2364}
2365
[email protected]180ef242013-11-07 06:50:462366void RenderThreadImpl::SampleGamepads(blink::WebGamepads* data) {
tfarina556a7232014-10-05 01:02:092367 blink_platform_impl_->sampleGamepads(*data);
[email protected]0ff736562014-05-09 09:09:472368}
2369
rmcilroyaa296052015-04-14 15:35:272370bool RenderThreadImpl::RendererIsHidden() const {
2371 return widget_count_ > 0 && hidden_widget_count_ == widget_count_;
2372}
2373
[email protected]b2db9272014-01-10 17:42:002374void RenderThreadImpl::WidgetCreated() {
rmcilroyaa296052015-04-14 15:35:272375 bool renderer_was_hidden = RendererIsHidden();
[email protected]b2db9272014-01-10 17:42:002376 widget_count_++;
rmcilroyaa296052015-04-14 15:35:272377 if (renderer_was_hidden)
2378 OnRendererVisible();
[email protected]b2db9272014-01-10 17:42:002379}
2380
2381void RenderThreadImpl::WidgetDestroyed() {
rmcilroyaa296052015-04-14 15:35:272382 // TODO(rmcilroy): Remove the restriction that destroyed widgets must be
2383 // unhidden before WidgetDestroyed is called.
2384 DCHECK_GT(widget_count_, 0);
2385 DCHECK_GT(widget_count_, hidden_widget_count_);
[email protected]b2db9272014-01-10 17:42:002386 widget_count_--;
rmcilroyaa296052015-04-14 15:35:272387 if (RendererIsHidden())
2388 OnRendererHidden();
[email protected]b2db9272014-01-10 17:42:002389}
2390
2391void RenderThreadImpl::WidgetHidden() {
2392 DCHECK_LT(hidden_widget_count_, widget_count_);
2393 hidden_widget_count_++;
rmcilroyaa296052015-04-14 15:35:272394 if (RendererIsHidden())
2395 OnRendererHidden();
[email protected]b2db9272014-01-10 17:42:002396}
2397
2398void RenderThreadImpl::WidgetRestored() {
rmcilroyaa296052015-04-14 15:35:272399 bool renderer_was_hidden = RendererIsHidden();
[email protected]b2db9272014-01-10 17:42:002400 DCHECK_GT(hidden_widget_count_, 0);
2401 hidden_widget_count_--;
rmcilroyaa296052015-04-14 15:35:272402 if (renderer_was_hidden)
2403 OnRendererVisible();
2404}
[email protected]b2db9272014-01-10 17:42:002405
rmcilroyaa296052015-04-14 15:35:272406void RenderThreadImpl::OnRendererHidden() {
ulan432cd6e42016-03-01 15:59:142407 blink::mainThreadIsolate()->IsolateInBackgroundNotification();
rmcilroyaa296052015-04-14 15:35:272408 // TODO(rmcilroy): Remove IdleHandler and replace it with an IdleTask
2409 // scheduled by the RendererScheduler - http://crbug.com/469210.
ulan4a385192015-11-11 10:59:182410 if (!GetContentClient()->renderer()->RunIdleHandlerWhenWidgetsHidden())
2411 return;
2412 ScheduleIdleHandler(kInitialIdleHandlerDelayMs);
rmcilroyaa296052015-04-14 15:35:272413}
2414
2415void RenderThreadImpl::OnRendererVisible() {
ulan432cd6e42016-03-01 15:59:142416 blink::mainThreadIsolate()->IsolateInForegroundNotification();
rmcilroyaa296052015-04-14 15:35:272417 if (!GetContentClient()->renderer()->RunIdleHandlerWhenWidgetsHidden())
[email protected]b2db9272014-01-10 17:42:002418 return;
[email protected]b2db9272014-01-10 17:42:002419 ScheduleIdleHandler(kLongIdleHandlerDelayMs);
2420}
2421
ssid0603ca9f2015-06-09 16:48:082422void RenderThreadImpl::ReleaseFreeMemory() {
2423 base::allocator::ReleaseFreeMemory();
2424 discardable_shared_memory_manager()->ReleaseFreeMemory();
2425
2426 if (blink_platform_impl_)
2427 blink::decommitFreeableMemory();
2428}
2429
ben76f52b242016-06-18 05:42:482430RenderThreadImpl::PendingFrameCreate::PendingFrameCreate(
rockotf8fdd9b2015-12-16 22:22:352431 int routing_id,
ben76f52b242016-06-18 05:42:482432 mojom::FrameRequest frame_request,
2433 mojom::FrameHostPtr frame_host)
rockotf8fdd9b2015-12-16 22:22:352434 : routing_id_(routing_id),
ben76f52b242016-06-18 05:42:482435 frame_request_(std::move(frame_request)),
2436 frame_host_(std::move(frame_host)) {
2437 // The RenderFrame may be deleted before the CreateFrame message is received.
2438 // In that case, the RenderFrameHost should cancel the create, which is
2439 // detected by setting an error handler on |frame_host_|.
2440 frame_host_.set_connection_error_handler(base::Bind(
2441 &RenderThreadImpl::PendingFrameCreate::OnConnectionError,
rockotf8fdd9b2015-12-16 22:22:352442 base::Unretained(this)));
2443}
2444
ben76f52b242016-06-18 05:42:482445RenderThreadImpl::PendingFrameCreate::~PendingFrameCreate() {
rockotf8fdd9b2015-12-16 22:22:352446}
2447
ben76f52b242016-06-18 05:42:482448void RenderThreadImpl::PendingFrameCreate::OnConnectionError() {
rockotf8fdd9b2015-12-16 22:22:352449 size_t erased =
ben76f52b242016-06-18 05:42:482450 RenderThreadImpl::current()->pending_frame_creates_.erase(routing_id_);
rockotf8fdd9b2015-12-16 22:22:352451 DCHECK_EQ(1u, erased);
2452}
2453
hong.zhengb28b5332016-05-11 02:33:392454void RenderThreadImpl::OnSyncMemoryPressure(
2455 base::MemoryPressureListener::MemoryPressureLevel memory_pressure_level) {
2456 if (!blink::mainThreadIsolate())
2457 return;
2458
2459 v8::MemoryPressureLevel v8_memory_pressure_level =
2460 static_cast<v8::MemoryPressureLevel>(memory_pressure_level);
2461
2462 // In order to reduce performance impact, translate critical level to
2463 // moderate level for foregroud renderer.
2464 if (!RendererIsHidden() &&
2465 v8_memory_pressure_level == v8::MemoryPressureLevel::kCritical)
2466 v8_memory_pressure_level = v8::MemoryPressureLevel::kModerate;
2467
2468 blink::mainThreadIsolate()->MemoryPressureNotification(
2469 v8_memory_pressure_level);
2470 blink::MemoryPressureNotificationToWorkerThreadIsolates(
2471 v8_memory_pressure_level);
2472}
2473
bashic4b4afcb2016-08-23 06:37:522474// Note that this would be called only when memory_coordinator is enabled.
2475// OnSyncMemoryPressure() is never called in that case.
2476void RenderThreadImpl::OnTrimMemoryImmediately() {
2477 if (blink::mainThreadIsolate()) {
2478 blink::mainThreadIsolate()->MemoryPressureNotification(
2479 v8::MemoryPressureLevel::kCritical);
2480 blink::MemoryPressureNotificationToWorkerThreadIsolates(
2481 v8::MemoryPressureLevel::kCritical);
2482 }
2483}
2484
rockot067ca55f2016-09-30 22:00:152485void RenderThreadImpl::OnRendererInterfaceRequest(
2486 mojom::RendererAssociatedRequest request) {
2487 DCHECK(!renderer_binding_.is_bound());
2488 renderer_binding_.Bind(std::move(request));
2489}
bashic4b4afcb2016-08-23 06:37:522490
[email protected]e9ff79c2012-10-19 21:31:262491} // namespace content