1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "chrome/renderer/chrome_render_process_observer.h"
10 #include "base/allocator/allocator_extension.h"
11 #include "base/bind.h"
12 #include "base/command_line.h"
13 #include "base/files/file_util.h"
14 #include "base/memory/weak_ptr.h"
15 #include "base/message_loop/message_loop.h"
16 #include "base/metrics/field_trial.h"
17 #include "base/metrics/histogram.h"
18 #include "base/metrics/statistics_recorder.h"
19 #include "base/native_library.h"
20 #include "base/path_service.h"
21 #include "base/strings/utf_string_conversions.h"
22 #include "base/threading/platform_thread.h"
23 #include "chrome/common/child_process_logging.h"
24 #include "chrome/common/chrome_paths.h"
25 #include "chrome/common/chrome_switches.h"
26 #include "chrome/common/net/net_resource_provider.h"
27 #include "chrome/common/render_messages.h"
28 #include "chrome/common/url_constants.h"
29 #include "chrome/common/variations/variations_util.h"
30 #include "chrome/renderer/content_settings_observer.h"
31 #include "chrome/renderer/security_filter_peer.h"
32 #include "content/public/child/resource_dispatcher_delegate.h"
33 #include "content/public/renderer/render_thread.h"
34 #include "content/public/renderer/render_view.h"
35 #include "content/public/renderer/render_view_visitor.h"
36 #include "crypto/nss_util.h"
37 #include "net/base/net_errors.h"
38 #include "net/base/net_module.h"
39 #include "third_party/WebKit/public/web/WebCache.h"
40 #include "third_party/WebKit/public/web/WebDocument.h"
41 #include "third_party/WebKit/public/web/WebFrame.h"
42 #include "third_party/WebKit/public/web/WebRuntimeFeatures.h"
43 #include "third_party/WebKit/public/web/WebSecurityPolicy.h"
44 #include "third_party/WebKit/public/web/WebView.h"
47 #include "base/win/iat_patch_function.h"
50 #if defined(ENABLE_EXTENSIONS)
51 #include "chrome/renderer/extensions/extension_localization_peer.h"
54 using blink::WebCache
;
55 using blink::WebRuntimeFeatures
;
56 using blink::WebSecurityPolicy
;
57 using blink::WebString
;
58 using content::RenderThread
;
62 const int kCacheStatsDelayMS
= 2000;
64 class RendererResourceDelegate
: public content::ResourceDispatcherDelegate
{
66 RendererResourceDelegate()
67 : weak_factory_(this) {
70 content::RequestPeer
* OnRequestComplete(content::RequestPeer
* current_peer
,
71 content::ResourceType resource_type
,
72 int error_code
) override
{
73 // Update the browser about our cache.
74 // Rate limit informing the host of our cache stats.
75 if (!weak_factory_
.HasWeakPtrs()) {
76 base::MessageLoop::current()->PostDelayedTask(
78 base::Bind(&RendererResourceDelegate::InformHostOfCacheStats
,
79 weak_factory_
.GetWeakPtr()),
80 base::TimeDelta::FromMilliseconds(kCacheStatsDelayMS
));
83 if (error_code
== net::ERR_ABORTED
) {
87 // Resource canceled with a specific error are filtered.
88 return SecurityFilterPeer::CreateSecurityFilterPeerForDeniedRequest(
89 resource_type
, current_peer
, error_code
);
92 content::RequestPeer
* OnReceivedResponse(content::RequestPeer
* current_peer
,
93 const std::string
& mime_type
,
94 const GURL
& url
) override
{
95 #if defined(ENABLE_EXTENSIONS)
96 return ExtensionLocalizationPeer::CreateExtensionLocalizationPeer(
97 current_peer
, RenderThread::Get(), mime_type
, url
);
104 void InformHostOfCacheStats() {
105 WebCache::UsageStats stats
;
106 WebCache::getUsageStats(&stats
);
107 RenderThread::Get()->Send(new ChromeViewHostMsg_UpdatedCacheStats(stats
));
110 base::WeakPtrFactory
<RendererResourceDelegate
> weak_factory_
;
112 DISALLOW_COPY_AND_ASSIGN(RendererResourceDelegate
);
116 static base::win::IATPatchFunction g_iat_patch_createdca
;
117 HDC WINAPI
CreateDCAPatch(LPCSTR driver_name
,
120 const void* init_data
) {
121 DCHECK(std::string("DISPLAY") == std::string(driver_name
));
122 DCHECK(!device_name
);
126 // CreateDC fails behind the sandbox, but not CreateCompatibleDC.
127 return CreateCompatibleDC(NULL
);
130 static base::win::IATPatchFunction g_iat_patch_get_font_data
;
131 DWORD WINAPI
GetFontDataPatch(HDC hdc
,
136 int rv
= GetFontData(hdc
, table
, offset
, buffer
, length
);
137 if (rv
== GDI_ERROR
&& hdc
) {
138 HFONT font
= static_cast<HFONT
>(GetCurrentObject(hdc
, OBJ_FONT
));
141 if (GetObject(font
, sizeof(LOGFONT
), &logfont
)) {
142 std::vector
<char> font_data
;
143 RenderThread::Get()->PreCacheFont(logfont
);
144 rv
= GetFontData(hdc
, table
, offset
, buffer
, length
);
145 RenderThread::Get()->ReleaseCachedFonts();
152 static const int kWaitForWorkersStatsTimeoutMS
= 20;
154 class HeapStatisticsCollector
{
156 HeapStatisticsCollector() : round_id_(0) {}
158 void InitiateCollection();
159 static HeapStatisticsCollector
* Instance();
162 void CollectOnWorkerThread(scoped_refptr
<base::TaskRunner
> master
,
164 void ReceiveStats(int round_id
, size_t total_size
, size_t used_size
);
165 void SendStatsToBrowser(int round_id
);
173 HeapStatisticsCollector
* HeapStatisticsCollector::Instance() {
174 CR_DEFINE_STATIC_LOCAL(HeapStatisticsCollector
, instance
, ());
178 void HeapStatisticsCollector::InitiateCollection() {
179 v8::HeapStatistics heap_stats
;
180 v8::Isolate::GetCurrent()->GetHeapStatistics(&heap_stats
);
181 total_bytes_
= heap_stats
.total_heap_size();
182 used_bytes_
= heap_stats
.used_heap_size();
183 base::Closure collect
= base::Bind(
184 &HeapStatisticsCollector::CollectOnWorkerThread
,
185 base::Unretained(this),
186 base::MessageLoopProxy::current(),
188 workers_to_go_
= RenderThread::Get()->PostTaskToAllWebWorkers(collect
);
189 if (workers_to_go_
) {
190 // The guard task to send out partial stats
191 // in case some workers are not responsive.
192 base::MessageLoopProxy::current()->PostDelayedTask(
194 base::Bind(&HeapStatisticsCollector::SendStatsToBrowser
,
195 base::Unretained(this),
197 base::TimeDelta::FromMilliseconds(kWaitForWorkersStatsTimeoutMS
));
199 // No worker threads so just send out the main thread data right away.
200 SendStatsToBrowser(round_id_
);
204 void HeapStatisticsCollector::CollectOnWorkerThread(
205 scoped_refptr
<base::TaskRunner
> master
,
208 size_t total_bytes
= 0;
209 size_t used_bytes
= 0;
210 v8::Isolate
* isolate
= v8::Isolate::GetCurrent();
212 v8::HeapStatistics heap_stats
;
213 isolate
->GetHeapStatistics(&heap_stats
);
214 total_bytes
= heap_stats
.total_heap_size();
215 used_bytes
= heap_stats
.used_heap_size();
219 base::Bind(&HeapStatisticsCollector::ReceiveStats
,
220 base::Unretained(this),
226 void HeapStatisticsCollector::ReceiveStats(int round_id
,
229 if (round_id
!= round_id_
)
231 total_bytes_
+= total_bytes
;
232 used_bytes_
+= used_bytes
;
233 if (!--workers_to_go_
)
234 SendStatsToBrowser(round_id
);
237 void HeapStatisticsCollector::SendStatsToBrowser(int round_id
) {
238 if (round_id
!= round_id_
)
240 // TODO(alph): Do caching heap stats and use the cache if we haven't got
241 // reply from a worker.
242 // Currently a busy worker stats are not counted.
243 RenderThread::Get()->Send(new ChromeViewHostMsg_V8HeapStats(
244 total_bytes_
, used_bytes_
));
250 bool ChromeRenderProcessObserver::is_incognito_process_
= false;
252 ChromeRenderProcessObserver::ChromeRenderProcessObserver(
253 ChromeContentRendererClient
* client
)
255 webkit_initialized_(false) {
256 const base::CommandLine
& command_line
=
257 *base::CommandLine::ForCurrentProcess();
259 #if defined(ENABLE_AUTOFILL_DIALOG)
260 WebRuntimeFeatures::enableRequestAutocomplete(true);
263 if (command_line
.HasSwitch(switches::kEnableShowModalDialog
))
264 WebRuntimeFeatures::enableShowModalDialog(true);
266 if (command_line
.HasSwitch(switches::kDisableJavaScriptHarmonyShipping
)) {
267 std::string
flag("--noharmony-shipping");
268 v8::V8::SetFlagsFromString(flag
.c_str(), static_cast<int>(flag
.size()));
271 if (command_line
.HasSwitch(switches::kJavaScriptHarmony
)) {
272 std::string
flag("--harmony");
273 v8::V8::SetFlagsFromString(flag
.c_str(), static_cast<int>(flag
.size()));
276 RenderThread
* thread
= RenderThread::Get();
277 resource_delegate_
.reset(new RendererResourceDelegate());
278 thread
->SetResourceDispatcherDelegate(resource_delegate_
.get());
280 // Configure modules that need access to resources.
281 net::NetModule::SetResourceProvider(chrome_common_net::NetResourceProvider
);
284 // Need to patch a few functions for font loading to work correctly.
286 if (PathService::Get(chrome::FILE_PDF_PLUGIN
, &pdf
) &&
287 base::PathExists(pdf
)) {
288 g_iat_patch_createdca
.Patch(
289 pdf
.value().c_str(), "gdi32.dll", "CreateDCA", CreateDCAPatch
);
290 g_iat_patch_get_font_data
.Patch(
291 pdf
.value().c_str(), "gdi32.dll", "GetFontData", GetFontDataPatch
);
295 #if defined(OS_POSIX) && !defined(OS_MACOSX) && defined(USE_NSS)
296 // On platforms where we use system NSS shared libraries,
297 // initialize NSS now because it won't be able to load the .so's
298 // after we engage the sandbox.
299 if (!command_line
.HasSwitch(switches::kSingleProcess
))
300 crypto::InitNSSSafely();
301 #elif defined(OS_WIN)
302 // crypt32.dll is used to decode X509 certificates for Chromoting.
303 // Only load this library when the feature is enabled.
304 base::LoadNativeLibrary(base::FilePath(L
"crypt32.dll"), NULL
);
306 // Setup initial set of crash dump data for Field Trials in this renderer.
307 chrome_variations::SetChildProcessLoggingVariationList();
308 // Listen for field trial activations to report them to the browser.
309 base::FieldTrialList::AddObserver(this);
312 ChromeRenderProcessObserver::~ChromeRenderProcessObserver() {
315 bool ChromeRenderProcessObserver::OnControlMessageReceived(
316 const IPC::Message
& message
) {
318 IPC_BEGIN_MESSAGE_MAP(ChromeRenderProcessObserver
, message
)
319 IPC_MESSAGE_HANDLER(ChromeViewMsg_SetIsIncognitoProcess
,
320 OnSetIsIncognitoProcess
)
321 IPC_MESSAGE_HANDLER(ChromeViewMsg_SetFieldTrialGroup
, OnSetFieldTrialGroup
)
322 IPC_MESSAGE_HANDLER(ChromeViewMsg_GetV8HeapStats
, OnGetV8HeapStats
)
323 IPC_MESSAGE_HANDLER(ChromeViewMsg_GetCacheResourceStats
,
324 OnGetCacheResourceStats
)
325 IPC_MESSAGE_HANDLER(ChromeViewMsg_SetContentSettingRules
,
326 OnSetContentSettingRules
)
327 IPC_MESSAGE_UNHANDLED(handled
= false)
328 IPC_END_MESSAGE_MAP()
332 void ChromeRenderProcessObserver::WebKitInitialized() {
333 webkit_initialized_
= true;
334 // chrome-native: is a scheme used for placeholder navigations that allow
335 // UIs to be drawn with platform native widgets instead of HTML. These pages
336 // should not be accessible, and should also be treated as empty documents
337 // that can commit synchronously. No code should be runnable in these pages,
338 // so it should not need to access anything nor should it allow javascript
339 // URLs since it should never be visible to the user.
340 WebString
native_scheme(base::ASCIIToUTF16(chrome::kChromeNativeScheme
));
341 WebSecurityPolicy::registerURLSchemeAsDisplayIsolated(native_scheme
);
342 WebSecurityPolicy::registerURLSchemeAsEmptyDocument(native_scheme
);
343 WebSecurityPolicy::registerURLSchemeAsNoAccess(native_scheme
);
344 WebSecurityPolicy::registerURLSchemeAsNotAllowingJavascriptURLs(
348 void ChromeRenderProcessObserver::OnRenderProcessShutdown() {
349 webkit_initialized_
= false;
352 void ChromeRenderProcessObserver::OnSetIsIncognitoProcess(
353 bool is_incognito_process
) {
354 is_incognito_process_
= is_incognito_process
;
357 void ChromeRenderProcessObserver::OnSetContentSettingRules(
358 const RendererContentSettingRules
& rules
) {
359 content_setting_rules_
= rules
;
362 void ChromeRenderProcessObserver::OnGetCacheResourceStats() {
363 WebCache::ResourceTypeStats stats
;
364 if (webkit_initialized_
)
365 WebCache::getResourceTypeStats(&stats
);
366 RenderThread::Get()->Send(new ChromeViewHostMsg_ResourceTypeStats(stats
));
369 void ChromeRenderProcessObserver::OnSetFieldTrialGroup(
370 const std::string
& field_trial_name
,
371 const std::string
& group_name
) {
372 base::FieldTrial
* trial
=
373 base::FieldTrialList::CreateFieldTrial(field_trial_name
, group_name
);
374 // TODO(mef): Remove this check after the investigation of 359406 is complete.
375 CHECK(trial
) << field_trial_name
<< ":" << group_name
;
376 // Ensure the trial is marked as "used" by calling group() on it if it is
377 // marked as activated.
379 chrome_variations::SetChildProcessLoggingVariationList();
382 void ChromeRenderProcessObserver::OnGetV8HeapStats() {
383 HeapStatisticsCollector::Instance()->InitiateCollection();
386 const RendererContentSettingRules
*
387 ChromeRenderProcessObserver::content_setting_rules() const {
388 return &content_setting_rules_
;
391 void ChromeRenderProcessObserver::OnFieldTrialGroupFinalized(
392 const std::string
& trial_name
,
393 const std::string
& group_name
) {
394 content::RenderThread::Get()->Send(
395 new ChromeViewHostMsg_FieldTrialActivated(trial_name
));