Title: [196622] trunk
Revision
196622
Author
[email protected]
Date
2016-02-15 21:36:38 -0800 (Mon, 15 Feb 2016)

Log Message

[Mac] Gather some rudimentary statistics during resource load 
https://bugs.webkit.org/show_bug.cgi?id=153575
<rdar://problem/24075254>

Reviewed by Brady Eidson.

Source/WebCore:

Tested by: http/tests/navigation/statistics.html

* CMakeLists.txt:
* PlatformWin.cmake:
* WebCore.xcodeproj/project.pbxproj:
* dom/Document.cpp:
(WebCore::Document::updateLastHandledUserGestureTimestamp): Log user interaction
with the ResourceLoadObserver.
* loader/DocumentLoader.cpp:
(WebCore::DocumentLoader::willSendRequest): Track load statistics if the
user interacted with the document.
* loader/ResourceLoadObserver.cpp: Added.
* loader/ResourceLoadObserver.h: Added.
* loader/ResourceLoadStatistics.cpp: Added.
* loader/ResourceLoadStatistics.h: Added.
* loader/SubresourceLoader.cpp:
(WebCore::SubresourceLoader::willSendRequestInternal): Track load statistics.
* page/Settings.cpp:
(WebCore::Settings::setResourceLoadStatisticsEnabled): Added.
* page/Settings.h:
(WebCore::Settings::resourceLoadStatisticsEnabled): Added.
* platform/Logging.h:
* testing/Internals.cpp:
(WebCore::Internals::resourceLoadStatisticsForOrigin):
(WebCore::Internals::setResourceLoadStatisticsEnabled):
* testing/Internals.h:
* testing/Internals.idl:

Source/WebKit/mac:

* Misc/WebKitNSStringExtras.h:
* Misc/WebKitNSStringExtras.mm:
(+[NSString _webkit_localStorageDirectoryWithBundleIdentifier:]): Added.
* WebView/WebPreferenceKeysPrivate.h:
* WebView/WebPreferences.mm:
(+[WebPreferences initialize]):
(-[WebPreferences resourceLoadStatisticsEnabled]): Added.
(-[WebPreferences setResourceLoadStatisticsEnabled:]): Added.
* WebView/WebPreferencesPrivate.h:
* WebView/WebView.mm:
(WebKitInitializeApplicationCachePathIfNecessary):
(WebKitInitializeApplicationStatisticsStoragePathIfNecessary): Added.
(-[WebView _commonInitializationWithFrameName:groupName:]): Add call to new
initialization method.
(-[WebView _preferencesChanged:]): Track changes in the user's desire to
monitor resource load statistics.
(+[WebView _applicationWillTerminate]): Write statistics to disk (if preferences
say to do so.)

Tools:

* MiniBrowser/mac/SettingsController.h:
* MiniBrowser/mac/SettingsController.m:
(-[SettingsController _populateMenu]): Add menu item for new debug flag.
(-[SettingsController toggleResourceLoadStatisticsEnabled:]): Added.
(-[SettingsController resourceLoadStatisticsEnabled]): Added.
* MiniBrowser/mac/WK1BrowserWindowController.m:
(-[WK1BrowserWindowController didChangeSettings]): React to changes in
users's desire to track resource load statistics.

LayoutTests:

* http/tests/navigation/resources/redirect-on-reload-updates-history-item-statistics.php: Added.
* http/tests/navigation/resources/redirect-updates-history-item-done-statistics.html: Added.
* http/tests/navigation/statistics-expected.txt: Added.
* http/tests/navigation/statistics.html: Added.

Modified Paths

Added Paths

Diff

Modified: trunk/LayoutTests/ChangeLog (196621 => 196622)


--- trunk/LayoutTests/ChangeLog	2016-02-16 05:32:56 UTC (rev 196621)
+++ trunk/LayoutTests/ChangeLog	2016-02-16 05:36:38 UTC (rev 196622)
@@ -1,3 +1,16 @@
+2016-02-15  Brent Fulgham  <[email protected]>
+
+        [Mac] Gather some rudimentary statistics during resource load 
+        https://bugs.webkit.org/show_bug.cgi?id=153575
+        <rdar://problem/24075254>
+
+        Reviewed by Brady Eidson.
+
+        * http/tests/navigation/resources/redirect-on-reload-updates-history-item-statistics.php: Added.
+        * http/tests/navigation/resources/redirect-updates-history-item-done-statistics.html: Added.
+        * http/tests/navigation/statistics-expected.txt: Added.
+        * http/tests/navigation/statistics.html: Added.
+
 2016-02-15  Chris Dumez  <[email protected]>
 
         The following properties should exist on the global object: AudioTrackList, AudioTrack, VideoTrackList, VideoTrack

Added: trunk/LayoutTests/http/tests/navigation/resources/redirect-on-reload-updates-history-item-statistics.php (0 => 196622)


--- trunk/LayoutTests/http/tests/navigation/resources/redirect-on-reload-updates-history-item-statistics.php	                        (rev 0)
+++ trunk/LayoutTests/http/tests/navigation/resources/redirect-on-reload-updates-history-item-statistics.php	2016-02-16 05:36:38 UTC (rev 196622)
@@ -0,0 +1,44 @@
+<?php
+header('cache-control: no-store');
+
+$location=$_COOKIE['location'];
+if ($location!="") {
+    header('Status: 303 See Other');
+    header('Location: '.$location);
+    exit;
+}
+?>
+
+<script src=''></script>
+<script>
+_onunload_ = function() {
+  // no page cache
+}
+
+_onload_ = function() {
+    setTimeout(function() {
+        // The first time through here (sessionStorage.done is false), this
+        // code inserts a new history item using pushState, and then it
+        // triggers a reload of the history item.  However, we set the
+        // "location" cookie so that when we reload this page, we actually
+        // redirect to the value of the "location" cookie.
+        //
+        // This loads the "goback" page, which bounces us back here after
+        // setting sessionStorage.done to true.  The point of this test is to
+        // ensure that going back actually performs a real navigation as
+        // opposed to performing a "same document navigation" as would normally
+        // be done when navigating back after a pushState.
+
+        if (sessionStorage.done) {
+            location.replace("redirect-updates-history-item-done-statistics.html"); 
+        } else {
+            history.pushState(null, null, "");
+
+            setLocationCookie("redirect-on-reload-updates-history-item-goback.html");
+            location.reload();
+        }
+    }, 0);
+}
+</script>
+
+<p>redirect-on-reload-updates-history-item.php: You should not see this text!</p>

Added: trunk/LayoutTests/http/tests/navigation/resources/redirect-updates-history-item-done-statistics.html (0 => 196622)


--- trunk/LayoutTests/http/tests/navigation/resources/redirect-updates-history-item-done-statistics.html	                        (rev 0)
+++ trunk/LayoutTests/http/tests/navigation/resources/redirect-updates-history-item-done-statistics.html	2016-02-16 05:36:38 UTC (rev 196622)
@@ -0,0 +1,13 @@
+<script src=""
+<script>
+clearLocationCookie();
+
+_onload_ = function() {
+    if (window.testRunner) {
+        testRunner.notifyDone();
+        log("Dumping Resource Load Statistics:");
+        log(window.internals.resourceLoadStatisticsForOrigin("127.0.0.1"));
+    }
+}
+</script>
+<body>PASS</body>

Added: trunk/LayoutTests/http/tests/navigation/statistics-expected.txt (0 => 196622)


--- trunk/LayoutTests/http/tests/navigation/statistics-expected.txt	                        (rev 0)
+++ trunk/LayoutTests/http/tests/navigation/statistics-expected.txt	2016-02-16 05:36:38 UTC (rev 196622)
@@ -0,0 +1,12 @@
+main frame - has 1 onunload handler(s)
+main frame - has 1 onunload handler(s)
+PASS
+Dumping Resource Load Statistics:
+
+
+
+============== Back Forward List ==============
+        http://127.0.0.1:8000/navigation/statistics.html  **nav target**
+curr->  http://127.0.0.1:8000/navigation/resources/redirect-updates-history-item-done-statistics.html  **nav target**
+        http://127.0.0.1:8000/navigation/resources/redirect-on-reload-updates-history-item-goback.html  **nav target**
+===============================================

Added: trunk/LayoutTests/http/tests/navigation/statistics.html (0 => 196622)


--- trunk/LayoutTests/http/tests/navigation/statistics.html	                        (rev 0)
+++ trunk/LayoutTests/http/tests/navigation/statistics.html	2016-02-16 05:36:38 UTC (rev 196622)
@@ -0,0 +1,25 @@
+<script src=""
+<script>
+
+// Test that we properly update a history item when reloading the history item
+// results in a redirect to a different document.  We verify that the resulting
+// document is not treated as the same document as the original document in
+// history.  See redirect-on-reload-updates-history-item.php for more details.
+
+if (window.testRunner) {
+    testRunner.dumpAsText();
+    testRunner.dumpBackForwardList();
+    window.internals.setResourceLoadStatisticsEnabled(true);
+    testRunner.waitUntilDone();
+}
+_onload_ = function() {
+    setTimeout(function() {
+        // These fields are used by subsequent pages in this test.  Clear them
+        // to avoid confusing the test with old state.
+        clearLocationCookie();
+        delete sessionStorage.done;
+
+        location = 'resources/redirect-on-reload-updates-history-item-statistics.php';
+    }, 0);
+}
+</script>

Modified: trunk/Source/WebCore/CMakeLists.txt (196621 => 196622)


--- trunk/Source/WebCore/CMakeLists.txt	2016-02-16 05:32:56 UTC (rev 196621)
+++ trunk/Source/WebCore/CMakeLists.txt	2016-02-16 05:36:38 UTC (rev 196622)
@@ -1936,6 +1936,8 @@
     loader/PolicyChecker.cpp
     loader/ProgressTracker.cpp
     loader/ResourceLoadNotifier.cpp
+    loader/ResourceLoadObserver.cpp
+    loader/ResourceLoadStatistics.cpp
     loader/ResourceLoader.cpp
     loader/SinkDocument.cpp
     loader/SubframeLoader.cpp

Modified: trunk/Source/WebCore/ChangeLog (196621 => 196622)


--- trunk/Source/WebCore/ChangeLog	2016-02-16 05:32:56 UTC (rev 196621)
+++ trunk/Source/WebCore/ChangeLog	2016-02-16 05:36:38 UTC (rev 196622)
@@ -1,3 +1,39 @@
+2016-02-15  Brent Fulgham  <[email protected]>
+
+        [Mac] Gather some rudimentary statistics during resource load 
+        https://bugs.webkit.org/show_bug.cgi?id=153575
+        <rdar://problem/24075254>
+
+        Reviewed by Brady Eidson.
+
+        Tested by: http/tests/navigation/statistics.html
+
+        * CMakeLists.txt:
+        * PlatformWin.cmake:
+        * WebCore.xcodeproj/project.pbxproj:
+        * dom/Document.cpp:
+        (WebCore::Document::updateLastHandledUserGestureTimestamp): Log user interaction
+        with the ResourceLoadObserver.
+        * loader/DocumentLoader.cpp:
+        (WebCore::DocumentLoader::willSendRequest): Track load statistics if the
+        user interacted with the document.
+        * loader/ResourceLoadObserver.cpp: Added.
+        * loader/ResourceLoadObserver.h: Added.
+        * loader/ResourceLoadStatistics.cpp: Added.
+        * loader/ResourceLoadStatistics.h: Added.
+        * loader/SubresourceLoader.cpp:
+        (WebCore::SubresourceLoader::willSendRequestInternal): Track load statistics.
+        * page/Settings.cpp:
+        (WebCore::Settings::setResourceLoadStatisticsEnabled): Added.
+        * page/Settings.h:
+        (WebCore::Settings::resourceLoadStatisticsEnabled): Added.
+        * platform/Logging.h:
+        * testing/Internals.cpp:
+        (WebCore::Internals::resourceLoadStatisticsForOrigin):
+        (WebCore::Internals::setResourceLoadStatisticsEnabled):
+        * testing/Internals.h:
+        * testing/Internals.idl:
+
 2016-02-15  Chris Dumez  <[email protected]>
 
         The following properties should exist on the global object: AudioTrackList, AudioTrack, VideoTrackList, VideoTrack

Modified: trunk/Source/WebCore/PlatformWin.cmake (196621 => 196622)


--- trunk/Source/WebCore/PlatformWin.cmake	2016-02-16 05:32:56 UTC (rev 196621)
+++ trunk/Source/WebCore/PlatformWin.cmake	2016-02-16 05:36:38 UTC (rev 196622)
@@ -64,6 +64,8 @@
     platform/audio/PlatformMediaSessionManager.cpp
 
     platform/cf/FileSystemCF.cpp
+    platform/cf/KeyedDecoderCF.cpp
+    platform/cf/KeyedEncoderCF.cpp
     platform/cf/SharedBufferCF.cpp
 
     platform/cf/win/CertificateCFWin.cpp

Modified: trunk/Source/WebCore/WebCore.xcodeproj/project.pbxproj (196621 => 196622)


--- trunk/Source/WebCore/WebCore.xcodeproj/project.pbxproj	2016-02-16 05:32:56 UTC (rev 196621)
+++ trunk/Source/WebCore/WebCore.xcodeproj/project.pbxproj	2016-02-16 05:36:38 UTC (rev 196622)
@@ -2517,6 +2517,8 @@
 		65E0E9441133C89F00B4CB10 /* JSDOMWrapper.h in Headers */ = {isa = PBXBuildFile; fileRef = 65E0E9431133C89F00B4CB10 /* JSDOMWrapper.h */; settings = {ATTRIBUTES = (Private, ); }; };
 		65FEA86909833ADE00BED4AB /* Page.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 65FEA86809833ADE00BED4AB /* Page.cpp */; };
 		6B3480940EEF50D400AC1B41 /* NativeImagePtr.h in Headers */ = {isa = PBXBuildFile; fileRef = 6B3480920EEF50D400AC1B41 /* NativeImagePtr.h */; settings = {ATTRIBUTES = (Private, ); }; };
+		6B693A2E1C51A82E00B03BEF /* ResourceLoadObserver.h in Headers */ = {isa = PBXBuildFile; fileRef = 6B693A2D1C51A82E00B03BEF /* ResourceLoadObserver.h */; settings = {ATTRIBUTES = (Private, ); }; };
+		6B693A341C51A95D00B03BEF /* ResourceLoadObserver.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 6B693A331C51A95D00B03BEF /* ResourceLoadObserver.cpp */; };
 		6C4C96DE1AD4483500365A50 /* JSReadableStreamController.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 6C4C96DA1AD4483500365A50 /* JSReadableStreamController.cpp */; };
 		6C4C96DF1AD4483500365A50 /* JSReadableStreamController.h in Headers */ = {isa = PBXBuildFile; fileRef = 6C4C96DB1AD4483500365A50 /* JSReadableStreamController.h */; };
 		6C638895A96CCEE50C8C946C /* CachedResourceRequestInitiators.h in Headers */ = {isa = PBXBuildFile; fileRef = 6C638893A96CCEE50C8C946C /* CachedResourceRequestInitiators.h */; settings = {ATTRIBUTES = (Private, ); }; };
@@ -2691,6 +2693,8 @@
 		7A74ECBA101839A600BF939E /* InspectorDOMStorageAgent.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 7A74ECB8101839A500BF939E /* InspectorDOMStorageAgent.cpp */; };
 		7A74ECBB101839A600BF939E /* InspectorDOMStorageAgent.h in Headers */ = {isa = PBXBuildFile; fileRef = 7A74ECB9101839A600BF939E /* InspectorDOMStorageAgent.h */; };
 		7A74ECBD101839DA00BF939E /* JSInspectorFrontendHostCustom.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 7A74ECBC101839DA00BF939E /* JSInspectorFrontendHostCustom.cpp */; };
+		7A929CA61C598A9E004DF226 /* ResourceLoadStatistics.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 7A929CA11C598378004DF226 /* ResourceLoadStatistics.cpp */; };
+		7A929CA71C598AA9004DF226 /* ResourceLoadStatistics.h in Headers */ = {isa = PBXBuildFile; fileRef = 7A929CA21C598378004DF226 /* ResourceLoadStatistics.h */; };
 		7A93868518DCC14500B8263D /* VTTScanner.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 7A93868218DCC14500B8263D /* VTTScanner.cpp */; };
 		7A93868618DCC14500B8263D /* VTTScanner.h in Headers */ = {isa = PBXBuildFile; fileRef = 7A93868318DCC14500B8263D /* VTTScanner.h */; };
 		7AA3A699194A64E7001CBD24 /* TileController.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 7AA3A695194A64E7001CBD24 /* TileController.cpp */; };
@@ -10088,6 +10092,8 @@
 		65F80697054D9F86008BF776 /* BlockExceptions.mm */ = {isa = PBXFileReference; fileEncoding = 30; indentWidth = 4; lastKnownFileType = sourcecode.cpp.objcpp; path = BlockExceptions.mm; sourceTree = "<group>"; tabWidth = 8; usesTabs = 0; };
 		65FEA86809833ADE00BED4AB /* Page.cpp */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = Page.cpp; sourceTree = "<group>"; };
 		6B3480920EEF50D400AC1B41 /* NativeImagePtr.h */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.h; path = NativeImagePtr.h; sourceTree = "<group>"; };
+		6B693A2D1C51A82E00B03BEF /* ResourceLoadObserver.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = ResourceLoadObserver.h; sourceTree = "<group>"; };
+		6B693A331C51A95D00B03BEF /* ResourceLoadObserver.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = ResourceLoadObserver.cpp; sourceTree = "<group>"; };
 		6C4C96DA1AD4483500365A50 /* JSReadableStreamController.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = JSReadableStreamController.cpp; sourceTree = "<group>"; };
 		6C4C96DB1AD4483500365A50 /* JSReadableStreamController.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = JSReadableStreamController.h; sourceTree = "<group>"; };
 		6C638893A96CCEE50C8C946C /* CachedResourceRequestInitiators.h */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.h; path = CachedResourceRequestInitiators.h; sourceTree = "<group>"; };
@@ -10292,6 +10298,8 @@
 		7A74ECB8101839A500BF939E /* InspectorDOMStorageAgent.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = InspectorDOMStorageAgent.cpp; sourceTree = "<group>"; };
 		7A74ECB9101839A600BF939E /* InspectorDOMStorageAgent.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = InspectorDOMStorageAgent.h; sourceTree = "<group>"; };
 		7A74ECBC101839DA00BF939E /* JSInspectorFrontendHostCustom.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = JSInspectorFrontendHostCustom.cpp; sourceTree = "<group>"; };
+		7A929CA11C598378004DF226 /* ResourceLoadStatistics.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = ResourceLoadStatistics.cpp; sourceTree = "<group>"; };
+		7A929CA21C598378004DF226 /* ResourceLoadStatistics.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = ResourceLoadStatistics.h; sourceTree = "<group>"; };
 		7A93868218DCC14500B8263D /* VTTScanner.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = VTTScanner.cpp; sourceTree = "<group>"; };
 		7A93868318DCC14500B8263D /* VTTScanner.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = VTTScanner.h; sourceTree = "<group>"; };
 		7AA3A695194A64E7001CBD24 /* TileController.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = TileController.cpp; sourceTree = "<group>"; };
@@ -22689,6 +22697,10 @@
 				51EE7B371AA50B0500F92B21 /* ResourceLoadInfo.h */,
 				973E325410883B7C005BC493 /* ResourceLoadNotifier.cpp */,
 				973E325510883B7C005BC493 /* ResourceLoadNotifier.h */,
+				6B693A331C51A95D00B03BEF /* ResourceLoadObserver.cpp */,
+				6B693A2D1C51A82E00B03BEF /* ResourceLoadObserver.h */,
+				7A929CA11C598378004DF226 /* ResourceLoadStatistics.cpp */,
+				7A929CA21C598378004DF226 /* ResourceLoadStatistics.h */,
 				51327D5F11A33A2B004F9D65 /* SinkDocument.cpp */,
 				51327D5E11A33A2B004F9D65 /* SinkDocument.h */,
 				D000ED2511C1B9CD00C47726 /* SubframeLoader.cpp */,
@@ -24855,6 +24867,7 @@
 			isa = PBXHeadersBuildPhase;
 			buildActionMask = 2147483647;
 			files = (
+				6B693A2E1C51A82E00B03BEF /* ResourceLoadObserver.h in Headers */,
 				FE115FAB167988CD00249134 /* AbstractDatabaseServer.h in Headers */,
 				41E1B1D10FF5986900576B3B /* AbstractWorker.h in Headers */,
 				29A8122E0FBB9C1D00510293 /* AccessibilityARIAGridCell.h in Headers */,
@@ -25084,6 +25097,7 @@
 				99CC0B4F18BE9849006CEBCC /* CapturingInputCursor.h in Headers */,
 				CDC734151977896D0046BFC5 /* CARingBuffer.h in Headers */,
 				6550B69E099DF0270090D781 /* CDATASection.h in Headers */,
+				7A929CA71C598AA9004DF226 /* ResourceLoadStatistics.h in Headers */,
 				CDE8B5ED1A69777300B4B66A /* CDMPrivateClearKey.h in Headers */,
 				CD318623199F1E2A0030A0F7 /* CDMPrivateMediaSourceAVFObjC.h in Headers */,
 				CDDD571518B57A8200A94FCB /* CDMSession.h in Headers */,
@@ -29148,6 +29162,7 @@
 				E164FAA518315E1A00DB4E61 /* CryptoKeyRSAMac.cpp in Sources */,
 				E125F859182C1AA600D84CD9 /* CryptoKeySerializationRaw.cpp in Sources */,
 				31BC742D1AAFF45C006B4340 /* CSSAnimationTriggerScrollValue.cpp in Sources */,
+				7A929CA61C598A9E004DF226 /* ResourceLoadStatistics.cpp in Sources */,
 				CAE9F90F146441F000C245B0 /* CSSAspectRatioValue.cpp in Sources */,
 				FBD6AF8B15EF25E5008B7110 /* CSSBasicShapes.cpp in Sources */,
 				E16A84F914C85CCC002977DF /* CSSBorderImage.cpp in Sources */,
@@ -30120,6 +30135,7 @@
 				BCBFB53C0DCD29CF0019B3E5 /* JSDOMWindowShell.cpp in Sources */,
 				FD7868B9136B999200D403DF /* JSDynamicsCompressorNode.cpp in Sources */,
 				65DF31F909D1CC60000BE325 /* JSElement.cpp in Sources */,
+				6B693A341C51A95D00B03BEF /* ResourceLoadObserver.cpp in Sources */,
 				BC2ED5550C6B9BD300920BFF /* JSElementCustom.cpp in Sources */,
 				2ECF7ADC10162B3800427DE7 /* JSErrorEvent.cpp in Sources */,
 				F3D461481161D53200CA0D09 /* JSErrorHandler.cpp in Sources */,

Modified: trunk/Source/WebCore/dom/Document.cpp (196621 => 196622)


--- trunk/Source/WebCore/dom/Document.cpp	2016-02-16 05:32:56 UTC (rev 196621)
+++ trunk/Source/WebCore/dom/Document.cpp	2016-02-16 05:36:38 UTC (rev 196622)
@@ -134,6 +134,7 @@
 #include "RenderLayerCompositor.h"
 #include "RenderView.h"
 #include "RenderWidget.h"
+#include "ResourceLoadObserver.h"
 #include "RuntimeEnabledFeatures.h"
 #include "SVGDocumentExtensions.h"
 #include "SVGElement.h"
@@ -6396,6 +6397,9 @@
 
 void Document::updateLastHandledUserGestureTimestamp()
 {
+    if (!m_lastHandledUserGestureTimestamp)
+        ResourceLoadObserver::sharedObserver().logUserInteraction(*this);
+
     m_lastHandledUserGestureTimestamp = monotonicallyIncreasingTime();
 }
 

Modified: trunk/Source/WebCore/loader/DocumentLoader.cpp (196621 => 196622)


--- trunk/Source/WebCore/loader/DocumentLoader.cpp	2016-02-16 05:32:56 UTC (rev 196621)
+++ trunk/Source/WebCore/loader/DocumentLoader.cpp	2016-02-16 05:36:38 UTC (rev 196622)
@@ -59,6 +59,7 @@
 #include "PolicyChecker.h"
 #include "ProgressTracker.h"
 #include "ResourceHandle.h"
+#include "ResourceLoadObserver.h"
 #include "SchemeRegistry.h"
 #include "ScriptController.h"
 #include "SecurityPolicy.h"
@@ -524,9 +525,19 @@
         timing().addRedirect(redirectResponse.url(), newRequest.url());
     }
 
+    ASSERT(m_frame);
+
+    Frame& topFrame = m_frame->tree().top();
+
+    ASSERT(m_frame->document());
+    ASSERT(topFrame.document());
+
+    if (Settings::resourceLoadStatisticsEnabled())
+        ResourceLoadObserver::sharedObserver().logFrameNavigation(!redirectResponse.isNull(), m_frame->document()->url(), newRequest.url(), m_frame->isMainFrame(), topFrame.document()->url());
+    
     // Update cookie policy base URL as URL changes, except for subframes, which use the
     // URL of the main frame which doesn't change when we redirect.
-    if (frameLoader()->frame().isMainFrame())
+    if (m_frame->isMainFrame())
         newRequest.setFirstPartyForCookies(newRequest.url());
 
     // If we're fielding a redirect in response to a POST, force a load from origin, since
@@ -536,7 +547,6 @@
     if (newRequest.cachePolicy() == UseProtocolCachePolicy && isPostOrRedirectAfterPost(newRequest, redirectResponse))
         newRequest.setCachePolicy(ReloadIgnoringCacheData);
 
-    Frame& topFrame = m_frame->tree().top();
     if (&topFrame != m_frame) {
         if (!frameLoader()->mixedContentChecker().canDisplayInsecureContent(topFrame.document()->securityOrigin(), MixedContentChecker::ContentType::Active, newRequest.url())) {
             cancelMainResourceLoad(frameLoader()->cancelledError(newRequest));

Added: trunk/Source/WebCore/loader/ResourceLoadObserver.cpp (0 => 196622)


--- trunk/Source/WebCore/loader/ResourceLoadObserver.cpp	                        (rev 0)
+++ trunk/Source/WebCore/loader/ResourceLoadObserver.cpp	2016-02-16 05:36:38 UTC (rev 196622)
@@ -0,0 +1,373 @@
+/*
+ * Copyright (C) 2016 Apple Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS''
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
+ * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "config.h"
+#include "ResourceLoadObserver.h"
+
+#include "Document.h"
+#include "KeyedCoding.h"
+#include "Logging.h"
+#include "NetworkStorageSession.h"
+#include "PlatformStrategies.h"
+#include "ResourceLoadStatistics.h"
+#include "SecurityOrigin.h"
+#include "Settings.h"
+#include "SharedBuffer.h"
+#include "URL.h"
+#include <wtf/NeverDestroyed.h>
+#include <wtf/text/StringBuilder.h>
+
+#define LOG_STATISTICS_TO_FILE 0
+
+namespace WebCore {
+
+ResourceLoadObserver& ResourceLoadObserver::sharedObserver()
+{
+    static NeverDestroyed<ResourceLoadObserver> resourceLoadObserver;
+    return resourceLoadObserver;
+}
+    
+void ResourceLoadObserver::logFrameNavigation(bool isRedirect, const URL& sourceURL, const URL& targetURL, bool isMainFrame, const URL& mainFrameURL)
+{
+    if (!Settings::resourceLoadStatisticsEnabled())
+        return;
+
+    if (!targetURL.isValid() || !mainFrameURL.isValid())
+        return;
+
+    auto targetHost = targetURL.host();
+    auto mainFrameHost = mainFrameURL.host();
+
+    if (targetHost.isEmpty() || mainFrameHost.isEmpty() || targetHost == mainFrameHost || targetHost == sourceURL.host())
+        return;
+
+    auto targetPrimaryDomain = primaryDomain(targetURL);
+    auto mainFramePrimaryDomain = primaryDomain(mainFrameURL);
+    auto sourcePrimaryDomain = primaryDomain(sourceURL);
+    
+    if (targetPrimaryDomain == mainFramePrimaryDomain || targetPrimaryDomain == sourcePrimaryDomain)
+        return;
+    
+    auto targetOrigin = SecurityOrigin::create(targetURL);
+    auto& targetStatistics = resourceStatisticsForPrimaryDomain(targetPrimaryDomain);
+    
+    if (isMainFrame)
+        targetStatistics.topFrameHasBeenNavigatedToBefore = true;
+    else {
+        targetStatistics.subframeHasBeenLoadedBefore = true;
+
+        auto mainFrameOrigin = SecurityOrigin::create(mainFrameURL);
+        targetStatistics.subframeUnderTopFrameOrigins.add(mainFramePrimaryDomain);
+    }
+    
+    if (isRedirect) {
+        auto& redirectingOriginResourceStatistics = resourceStatisticsForPrimaryDomain(sourcePrimaryDomain);
+        
+        if (isPrevalentResource(targetPrimaryDomain))
+            redirectingOriginResourceStatistics.redirectedToOtherPrevalentResourceOrigins.add(targetPrimaryDomain);
+        
+        if (isMainFrame) {
+            ++targetStatistics.topFrameHasBeenRedirectedTo;
+            ++redirectingOriginResourceStatistics.topFrameHasBeenRedirectedFrom;
+        } else {
+            ++targetStatistics.subframeHasBeenRedirectedTo;
+            ++redirectingOriginResourceStatistics.subframeHasBeenRedirectedFrom;
+            redirectingOriginResourceStatistics.subframeUniqueRedirectsTo.add(targetPrimaryDomain);
+            
+            ++targetStatistics.subframeSubResourceCount;
+        }
+    } else {
+        if (sourcePrimaryDomain.isNull() || sourcePrimaryDomain.isEmpty() || sourcePrimaryDomain == "nullOrigin") {
+            if (isMainFrame)
+                ++targetStatistics.topFrameInitialLoadCount;
+            else
+                ++targetStatistics.subframeSubResourceCount;
+        } else {
+            auto& sourceOriginResourceStatistics = resourceStatisticsForPrimaryDomain(sourcePrimaryDomain);
+
+            if (isMainFrame) {
+                ++sourceOriginResourceStatistics.topFrameHasBeenNavigatedFrom;
+                ++targetStatistics.topFrameHasBeenNavigatedTo;
+            } else {
+                ++sourceOriginResourceStatistics.subframeHasBeenNavigatedFrom;
+                ++targetStatistics.subframeHasBeenNavigatedTo;
+            }
+        }
+    }
+
+    targetStatistics.checkAndSetAsPrevalentResourceIfNecessary(m_resourceStatisticsMap.size());
+}
+    
+void ResourceLoadObserver::logSubresourceLoading(bool isRedirect, const URL& sourceURL, const URL& targetURL, const URL& mainFrameURL)
+{
+    if (!Settings::resourceLoadStatisticsEnabled())
+        return;
+
+    auto targetHost = targetURL.host();
+    auto mainFrameHost = mainFrameURL.host();
+
+    if (targetHost.isEmpty() || mainFrameHost.isEmpty() || targetHost == mainFrameHost || targetHost == sourceURL.host())
+        return;
+
+    auto targetPrimaryDomain = primaryDomain(targetURL);
+    auto mainFramePrimaryDomain = primaryDomain(mainFrameURL);
+    auto sourcePrimaryDomain = primaryDomain(sourceURL);
+    
+    if (targetPrimaryDomain == mainFramePrimaryDomain || targetPrimaryDomain == sourcePrimaryDomain)
+        return;
+
+    auto& targetStatistics = resourceStatisticsForPrimaryDomain(targetPrimaryDomain);
+
+    auto mainFrameOrigin = SecurityOrigin::create(mainFrameURL);
+    targetStatistics.subresourceUnderTopFrameOrigins.add(mainFramePrimaryDomain);
+
+    if (isRedirect) {
+        auto& redirectingOriginStatistics = resourceStatisticsForPrimaryDomain(sourcePrimaryDomain);
+        
+        if (isPrevalentResource(targetPrimaryDomain))
+            redirectingOriginStatistics.redirectedToOtherPrevalentResourceOrigins.add(targetPrimaryDomain);
+        
+        ++redirectingOriginStatistics.subresourceHasBeenRedirectedFrom;
+        ++targetStatistics.subresourceHasBeenRedirectedTo;
+
+        redirectingOriginStatistics.subresourceUniqueRedirectsTo.add(targetPrimaryDomain);
+
+        ++targetStatistics.subresourceHasBeenSubresourceCount;
+
+        auto totalVisited = std::max(m_originsVisitedMap.size(), 1U);
+        
+        targetStatistics.subresourceHasBeenSubresourceCountDividedByTotalNumberOfOriginsVisited = static_cast<double>(targetStatistics.subresourceHasBeenSubresourceCount) / totalVisited;
+    } else {
+        ++targetStatistics.subresourceHasBeenSubresourceCount;
+
+        auto totalVisited = std::max(m_originsVisitedMap.size(), 1U);
+        
+        targetStatistics.subresourceHasBeenSubresourceCountDividedByTotalNumberOfOriginsVisited = static_cast<double>(targetStatistics.subresourceHasBeenSubresourceCount) / totalVisited;
+    }
+    
+    targetStatistics.checkAndSetAsPrevalentResourceIfNecessary(m_resourceStatisticsMap.size());
+}
+    
+void ResourceLoadObserver::logUserInteraction(const Document& document)
+{
+    if (!Settings::resourceLoadStatisticsEnabled())
+        return;
+
+    auto& statistics = resourceStatisticsForPrimaryDomain(primaryDomain(document.url()));
+    statistics.hadUserInteraction = true;
+}
+    
+bool ResourceLoadObserver::isPrevalentResource(const String& primaryDomain) const
+{
+    auto mapEntry = m_resourceStatisticsMap.find(primaryDomain);
+    if (mapEntry == m_resourceStatisticsMap.end())
+        return false;
+
+    return mapEntry->value.isPrevalentResource;
+}
+    
+ResourceLoadStatistics& ResourceLoadObserver::resourceStatisticsForPrimaryDomain(const String& primaryDomain)
+{
+    if (!m_resourceStatisticsMap.contains(primaryDomain))
+        m_resourceStatisticsMap.set(primaryDomain, ResourceLoadStatistics());
+    
+    return m_resourceStatisticsMap.find(primaryDomain)->value;
+}
+
+String ResourceLoadObserver::primaryDomain(const URL& url)
+{
+    String host = url.host();
+    Vector<String> hostSplitOnDot;
+    
+    host.split('.', false, hostSplitOnDot);
+
+    String primaryDomain;
+    if (host.isNull())
+        primaryDomain = "nullOrigin";
+    else if (hostSplitOnDot.size() < 3)
+        primaryDomain = host;
+    else {
+        // Skip TLD and then up to two domains smaller than 4 characters
+        int primaryDomainCutOffIndex = hostSplitOnDot.size() - 2;
+
+        // Start with TLD as a given part
+        size_t numberOfParts = 1;
+        for (; primaryDomainCutOffIndex >= 0; --primaryDomainCutOffIndex) {
+            ++numberOfParts;
+
+            // We have either a domain part that's 4 chars or longer, or 3 domain parts including TLD
+            if (hostSplitOnDot.at(primaryDomainCutOffIndex).length() >= 4 || numberOfParts >= 3)
+                break;
+        }
+
+        if (primaryDomainCutOffIndex < 0)
+            primaryDomain = host;
+        else {
+            StringBuilder builder;
+            builder.append(hostSplitOnDot.at(primaryDomainCutOffIndex));
+            for (size_t j = primaryDomainCutOffIndex + 1; j < hostSplitOnDot.size(); ++j) {
+                builder.append('.');
+                builder.append(hostSplitOnDot[j]);
+            }
+            primaryDomain = builder.toString();
+        }
+    }
+
+    return primaryDomain;
+}
+
+typedef HashMap<String, ResourceLoadStatistics>::KeyValuePairType StatisticsValue;
+
+void ResourceLoadObserver::writeDataToDisk()
+{
+    if (!Settings::resourceLoadStatisticsEnabled())
+        return;
+    
+    auto encoder = KeyedEncoder::encoder();
+    encoder->encodeUInt32("originsVisited", m_resourceStatisticsMap.size());
+    
+    encoder->encodeObjects("browsingStatistics", m_resourceStatisticsMap.begin(), m_resourceStatisticsMap.end(), [this](KeyedEncoder& encoderInner, const StatisticsValue& origin) {
+        origin.value.encode(encoderInner, origin.key);
+    });
+    
+    writeEncoderToDisk(*encoder.get(), "full_browsing_session");
+}
+
+void ResourceLoadObserver::writeDataToDisk(const String& origin, const ResourceLoadStatistics& resourceStatistics) const
+{
+    if (!Settings::resourceLoadStatisticsEnabled())
+        return;
+
+    auto encoder = KeyedEncoder::encoder();
+    encoder->encodeUInt32("originsVisited", 1);
+    
+    encoder->encodeObject(origin, resourceStatistics, [this, &origin](KeyedEncoder& encoder, const ResourceLoadStatistics& resourceStatistics) {
+        resourceStatistics.encode(encoder, origin);
+    });
+    
+    String label = origin;
+    label.replace('/', '_');
+    label.replace(':', '+');
+    writeEncoderToDisk(*encoder.get(), label);
+}
+
+void ResourceLoadObserver::setStatisticsStorageDirectory(const String& path)
+{
+    m_storagePath = path;
+}
+
+String ResourceLoadObserver::persistentStoragePath(const String& label) const
+{
+    if (m_storagePath.isEmpty())
+        return emptyString();
+
+    // TODO Decide what to call this file
+    return pathByAppendingComponent(m_storagePath, label + "_resourceLog.plist");
+}
+
+void ResourceLoadObserver::readDataFromDiskIfNeeded()
+{
+    if (!Settings::resourceLoadStatisticsEnabled())
+        return;
+
+    if (m_resourceStatisticsMap.size())
+        return;
+
+    auto decoder = createDecoderFromDisk("full_browsing_session");
+    if (!decoder)
+        return;
+
+    unsigned visitedOrigins = 0;
+    decoder->decodeUInt32("originsVisited", visitedOrigins);
+        
+    Vector<String> loadedOrigins;
+    decoder->decodeObjects("browsingStatistics", loadedOrigins, [this](KeyedDecoder& decoderInner, String& origin) {
+        if (!decoderInner.decodeString("PrevalentResourceOrigin", origin))
+            return false;
+
+        ResourceLoadStatistics statistics;
+        if (!statistics.decode(decoderInner, origin))
+            return false;
+
+        m_resourceStatisticsMap.set(origin, statistics);
+            
+        return true;
+    });
+        
+    ASSERT(visitedOrigins == static_cast<size_t>(loadedOrigins.size()));
+}
+
+std::unique_ptr<KeyedDecoder> ResourceLoadObserver::createDecoderFromDisk(const String& label) const
+{
+    String resourceLog = persistentStoragePath(label);
+    if (resourceLog.isEmpty())
+        return nullptr;
+    
+    RefPtr<SharedBuffer> rawData = SharedBuffer::createWithContentsOfFile(resourceLog);
+    if (!rawData)
+        return nullptr;
+    
+    return KeyedDecoder::decoder(reinterpret_cast<const uint8_t*>(rawData->data()), rawData->size());
+}
+    
+void ResourceLoadObserver::writeEncoderToDisk(KeyedEncoder& encoder, const String& label) const
+{
+#if LOG_STATISTICS_TO_FILE
+    RefPtr<SharedBuffer> rawData = encoder.finishEncoding();
+    if (!rawData)
+        return;
+    
+    String resourceLog = persistentStoragePath(label);
+    if (resourceLog.isEmpty())
+        return;
+
+    if (!m_storagePath.isEmpty())
+        makeAllDirectories(m_storagePath);
+
+    auto handle = openFile(resourceLog, OpenForWrite);
+    if (!handle)
+        return;
+    
+    int64_t writtenBytes = writeToFile(handle, rawData->data(), rawData->size());
+    closeFile(handle);
+    
+    if (writtenBytes != static_cast<int64_t>(rawData->size()))
+        WTFLogAlways("ResourceLoadStatistics: We only wrote %lld out of %d bytes to disk", writtenBytes, rawData->size());
+#else
+    UNUSED_PARAM(encoder);
+    UNUSED_PARAM(label);
+#endif
+}
+
+String ResourceLoadObserver::statisticsForOrigin(const String& origin)
+{
+    if (!m_resourceStatisticsMap.contains(origin))
+        return emptyString();
+    
+    auto& statistics = m_resourceStatisticsMap.find(origin)->value;
+    return "Statistics for " + origin + ":\n" + statistics.toString();
+}
+    
+}

Added: trunk/Source/WebCore/loader/ResourceLoadObserver.h (0 => 196622)


--- trunk/Source/WebCore/loader/ResourceLoadObserver.h	                        (rev 0)
+++ trunk/Source/WebCore/loader/ResourceLoadObserver.h	2016-02-16 05:36:38 UTC (rev 196622)
@@ -0,0 +1,77 @@
+/*
+ * Copyright (C) 2016 Apple Inc.  All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL APPLE INC. OR
+ * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
+ * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+ * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
+ * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
+ * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef ResourceLoadObserver_h
+#define ResourceLoadObserver_h
+
+#include <wtf/HashMap.h>
+#include <wtf/text/WTFString.h>
+
+namespace WebCore {
+
+class Document;
+class KeyedDecoder;
+class KeyedEncoder;
+class URL;
+
+struct ResourceLoadStatistics;
+
+class ResourceLoadObserver {
+    friend class NeverDestroyed<ResourceLoadObserver>;
+public:
+    WEBCORE_EXPORT static ResourceLoadObserver& sharedObserver();
+    
+    void logFrameNavigation(bool isRedirect, const URL& sourceURL, const URL& targetURL, bool isMainFrame, const URL& mainFrameURL);
+    void logSubresourceLoading(bool isRedirect, const URL& sourceURL, const URL& targetURL, const URL& mainFrameURL);
+    void logUserInteraction(const Document&);
+
+    WEBCORE_EXPORT void writeDataToDisk();
+    WEBCORE_EXPORT void readDataFromDiskIfNeeded();
+    WEBCORE_EXPORT void setStatisticsStorageDirectory(const String&);
+
+    WEBCORE_EXPORT String statisticsForOrigin(const String&);
+
+private:
+    ResourceLoadStatistics& resourceStatisticsForPrimaryDomain(const String&);
+    
+    static String primaryDomain(const URL&);
+
+    bool isPrevalentResource(const String&) const;
+
+    String persistentStoragePath(const String& label) const;
+
+    void writeDataToDisk(const String& origin, const ResourceLoadStatistics&) const;
+
+    std::unique_ptr<KeyedDecoder> createDecoderFromDisk(const String& label) const;
+    void writeEncoderToDisk(KeyedEncoder&, const String& label) const;
+
+    HashMap<String, size_t> m_originsVisitedMap;
+    HashMap<String, ResourceLoadStatistics> m_resourceStatisticsMap;
+    String m_storagePath;
+};
+    
+} // namespace WebCore
+
+#endif /* ResourceLoadObserver_h */

Added: trunk/Source/WebCore/loader/ResourceLoadStatistics.cpp (0 => 196622)


--- trunk/Source/WebCore/loader/ResourceLoadStatistics.cpp	                        (rev 0)
+++ trunk/Source/WebCore/loader/ResourceLoadStatistics.cpp	2016-02-16 05:36:38 UTC (rev 196622)
@@ -0,0 +1,312 @@
+/*
+ * Copyright (C) 2016 Apple Inc.  All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL APPLE INC. OR
+ * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
+ * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+ * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
+ * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
+ * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "config.h"
+#include "ResourceLoadStatistics.h"
+
+#include "KeyedCoding.h"
+#include <wtf/text/StringBuilder.h>
+#include <wtf/text/StringHash.h>
+
+namespace WebCore {
+
+static const unsigned minimumOriginsVisitedForPrevalenceClassification = 100;
+
+// Sub frame thresholds
+static const unsigned subframeUnderTopFrameOriginsThresholdAbsolute = 3;
+
+// Subresource thresholds
+static const unsigned subresourceUnderTopFrameOriginsThresholdAbsolute = 5;
+static const unsigned subresourceHasBeenRedirectedFromToUniqueDomainsThresholdAbsolute = 3;
+static const unsigned redirectedToOtherPrevalentResourceOriginsThresholdAbsolute = 2;
+
+bool ResourceLoadStatistics::checkAndSetAsPrevalentResourceIfNecessary(unsigned originsVisitedSoFar)
+{
+    if (originsVisitedSoFar < minimumOriginsVisitedForPrevalenceClassification || isPrevalentResource)
+        return false;
+
+    if (hasPrevalentResourceCharacteristics()) {
+        isPrevalentResource = true;
+        return true;
+    }
+
+    return false;
+}
+
+bool ResourceLoadStatistics::hasPrevalentResourceCharacteristics() const
+{
+    return subframeUnderTopFrameOrigins.size() > subframeUnderTopFrameOriginsThresholdAbsolute
+        || subresourceUnderTopFrameOrigins.size() > subresourceUnderTopFrameOriginsThresholdAbsolute
+        || subresourceUniqueRedirectsTo.size() > subresourceHasBeenRedirectedFromToUniqueDomainsThresholdAbsolute
+        || redirectedToOtherPrevalentResourceOrigins.size() > redirectedToOtherPrevalentResourceOriginsThresholdAbsolute;
+}
+
+typedef WTF::HashMap<String, unsigned, StringHash, HashTraits<String>, HashTraits<unsigned>>::KeyValuePairType ResourceLoadStatisticsValue;
+
+static void encodeHashCountedSet(KeyedEncoder& encoder, const String& label, const HashCountedSet<String>& hashCountedSet)
+{
+    if (hashCountedSet.isEmpty())
+        return;
+
+    encoder.encodeObjects(label, hashCountedSet.begin(), hashCountedSet.end(), [](KeyedEncoder& encoderInner, const ResourceLoadStatisticsValue& origin) {
+        encoderInner.encodeString("origin", origin.key);
+        encoderInner.encodeUInt32("count", origin.value);
+    });
+}
+
+void ResourceLoadStatistics::encode(KeyedEncoder& encoder, const String& origin) const
+{
+    encoder.encodeString("PrevalentResourceOrigin", origin);
+    
+    // User interaction
+    encoder.encodeBool("hadUserInteraction", hadUserInteraction);
+    
+    // Top frame stats
+    encoder.encodeBool("topFrameHasBeenNavigatedToBefore", topFrameHasBeenNavigatedToBefore);
+    encoder.encodeUInt32("topFrameHasBeenRedirectedTo", topFrameHasBeenRedirectedTo);
+    encoder.encodeUInt32("topFrameHasBeenRedirectedFrom", topFrameHasBeenRedirectedFrom);
+    encoder.encodeUInt32("topFrameInitialLoadCount", topFrameInitialLoadCount);
+    encoder.encodeUInt32("topFrameHasBeenNavigatedTo", topFrameHasBeenNavigatedTo);
+    encoder.encodeUInt32("topFrameHasBeenNavigatedFrom", topFrameHasBeenNavigatedFrom);
+    
+    // Subframe stats
+    encoder.encodeBool("subframeHasBeenLoadedBefore", subframeHasBeenLoadedBefore);
+    encoder.encodeUInt32("subframeHasBeenRedirectedTo", subframeHasBeenRedirectedTo);
+    encoder.encodeUInt32("subframeHasBeenRedirectedFrom", subframeHasBeenRedirectedFrom);
+    encoder.encodeUInt32("subframeSubResourceCount", subframeSubResourceCount);
+    encodeHashCountedSet(encoder, "subframeUnderTopFrameOrigins", subframeUnderTopFrameOrigins);
+    encodeHashCountedSet(encoder, "subframeUniqueRedirectsTo", subframeUniqueRedirectsTo);
+    encoder.encodeUInt32("subframeHasBeenNavigatedTo", subframeHasBeenNavigatedTo);
+    encoder.encodeUInt32("subframeHasBeenNavigatedFrom", subframeHasBeenNavigatedFrom);
+    
+    // Subresource stats
+    encoder.encodeUInt32("subresourceHasBeenRedirectedFrom", subresourceHasBeenRedirectedFrom);
+    encoder.encodeUInt32("subresourceHasBeenRedirectedTo", subresourceHasBeenRedirectedTo);
+    encoder.encodeUInt32("subresourceHasBeenSubresourceCount", subresourceHasBeenSubresourceCount);
+    encoder.encodeDouble("subresourceHasBeenSubresourceCountDividedByTotalNumberOfOriginsVisited", subresourceHasBeenSubresourceCountDividedByTotalNumberOfOriginsVisited);
+    encodeHashCountedSet(encoder, "subresourceUnderTopFrameOrigins", subresourceUnderTopFrameOrigins);
+    encodeHashCountedSet(encoder, "subresourceUniqueRedirectsTo", subresourceUniqueRedirectsTo);
+    
+    // Prevalent Resource
+    encodeHashCountedSet(encoder, "redirectedToOtherPrevalentResourceOrigins", redirectedToOtherPrevalentResourceOrigins);
+    encoder.encodeBool("isPrevalentResource", isPrevalentResource);
+}
+
+static void decodeHashCountedSet(KeyedDecoder& decoder, const String& label, HashCountedSet<String>& hashCountedSet)
+{
+    Vector<String> ignore;
+    decoder.decodeObjects(label, ignore, [&hashCountedSet](KeyedDecoder& decoderInner, String& origin) {
+        if (!decoderInner.decodeString("origin", origin))
+            return false;
+        
+        unsigned count;
+        if (!decoderInner.decodeUInt32("count", count))
+            return false;
+        
+        // FIXME: Create a HashCountedSet method to do this efficiently
+        for (unsigned i = 0; i < count; ++i)
+            hashCountedSet.add(origin);
+        return true;
+    });
+}
+
+bool ResourceLoadStatistics::decode(KeyedDecoder& decoder, const String& origin)
+{
+    String storedOrigin;
+    if (!decoder.decodeString("PrevalentResourceOrigin", storedOrigin))
+        return false;
+    
+    ASSERT_UNUSED(origin, storedOrigin == origin);
+    
+    // User interaction
+    if (!decoder.decodeBool("hadUserInteraction", hadUserInteraction))
+        return false;
+    
+    // Top frame stats
+    if (!decoder.decodeBool("topFrameHasBeenNavigatedToBefore", topFrameHasBeenNavigatedToBefore))
+        return false;
+    
+    if (!decoder.decodeUInt32("topFrameHasBeenRedirectedTo", topFrameHasBeenRedirectedTo))
+        return false;
+    
+    if (!decoder.decodeUInt32("topFrameHasBeenRedirectedFrom", topFrameHasBeenRedirectedFrom))
+        return false;
+    
+    if (!decoder.decodeUInt32("topFrameInitialLoadCount", topFrameInitialLoadCount))
+        return false;
+    
+    if (!decoder.decodeUInt32("topFrameHasBeenNavigatedTo", topFrameHasBeenNavigatedTo))
+        return false;
+    
+    if (!decoder.decodeUInt32("topFrameHasBeenNavigatedFrom", topFrameHasBeenNavigatedFrom))
+        return false;
+    
+    // Subframe stats
+    if (!decoder.decodeBool("subframeHasBeenLoadedBefore", subframeHasBeenLoadedBefore))
+        return false;
+    
+    if (!decoder.decodeUInt32("subframeHasBeenRedirectedTo", subframeHasBeenRedirectedTo))
+        return false;
+    
+    if (!decoder.decodeUInt32("subframeHasBeenRedirectedFrom", subframeHasBeenRedirectedFrom))
+        return false;
+    
+    if (!decoder.decodeUInt32("subframeSubResourceCount", subframeSubResourceCount))
+        return false;
+
+    decodeHashCountedSet(decoder, "subframeUnderTopFrameOrigins", subframeUnderTopFrameOrigins);
+    decodeHashCountedSet(decoder, "subframeUniqueRedirectsTo", subframeUniqueRedirectsTo);
+    
+    if (!decoder.decodeUInt32("subframeHasBeenNavigatedTo", subframeHasBeenNavigatedTo))
+        return false;
+    
+    if (!decoder.decodeUInt32("subframeHasBeenNavigatedFrom", subframeHasBeenNavigatedFrom))
+        return false;
+    
+    // Subresource stats
+    if (!decoder.decodeUInt32("subresourceHasBeenRedirectedFrom", subresourceHasBeenRedirectedFrom))
+        return false;
+    
+    if (!decoder.decodeUInt32("subresourceHasBeenRedirectedTo", subresourceHasBeenRedirectedTo))
+        return false;
+    
+    if (!decoder.decodeUInt32("subresourceHasBeenSubresourceCount", subresourceHasBeenSubresourceCount))
+        return false;
+    
+    if (!decoder.decodeDouble("subresourceHasBeenSubresourceCountDividedByTotalNumberOfOriginsVisited", subresourceHasBeenSubresourceCountDividedByTotalNumberOfOriginsVisited))
+        return false;
+
+    decodeHashCountedSet(decoder, "subresourceUnderTopFrameOrigins", subresourceUnderTopFrameOrigins);
+    decodeHashCountedSet(decoder, "subresourceUniqueRedirectsTo", subresourceUniqueRedirectsTo);
+    
+    // Prevalent Resource
+    decodeHashCountedSet(decoder, "redirectedToOtherPrevalentResourceOrigins", redirectedToOtherPrevalentResourceOrigins);
+    
+    if (!decoder.decodeBool("isPrevalentResource", isPrevalentResource))
+        return false;
+    
+    return true;
+}
+
+static void appendBoolean(StringBuilder& builder, const String& label, bool flag)
+{
+    builder.append("    ");
+    builder.append(label);
+    builder.append(": ");
+    builder.append(flag ? "Yes" : "No");
+}
+
+static void appendHashCountedSet(StringBuilder& builder, const String& label, const HashCountedSet<String>& hashCountedSet)
+{
+    if (hashCountedSet.isEmpty())
+        return;
+
+    builder.append("    ");
+    builder.append(label);
+    builder.append(":\n");
+
+    for (auto& entry : hashCountedSet) {
+        builder.append("        ");
+        builder.append(entry.key);
+        builder.append(": ");
+        builder.appendNumber(entry.value);
+        builder.append('\n');
+    }
+    
+}
+
+String ResourceLoadStatistics::toString() const
+{
+    StringBuilder builder;
+    
+    // User interaction
+    appendBoolean(builder, "hadUserInteraction", hadUserInteraction);
+    builder.append('\n');
+    
+    // Top frame stats
+    appendBoolean(builder, "topFrameHasBeenNavigatedToBefore", topFrameHasBeenNavigatedToBefore);
+    builder.append('\n');
+    builder.append("    topFrameHasBeenRedirectedTo: ");
+    builder.appendNumber(topFrameHasBeenRedirectedTo);
+    builder.append('\n');
+    builder.append("    topFrameHasBeenRedirectedFrom: ");
+    builder.appendNumber(topFrameHasBeenRedirectedFrom);
+    builder.append('\n');
+    builder.append("    topFrameInitialLoadCount: ");
+    builder.appendNumber(topFrameInitialLoadCount);
+    builder.append('\n');
+    builder.append("    topFrameHasBeenNavigatedTo: ");
+    builder.appendNumber(topFrameHasBeenNavigatedTo);
+    builder.append('\n');
+    builder.append("    topFrameHasBeenNavigatedFrom: ");
+    builder.appendNumber(topFrameHasBeenNavigatedFrom);
+    builder.append('\n');
+    
+    // Subframe stats
+    appendBoolean(builder, "subframeHasBeenLoadedBefore", subframeHasBeenLoadedBefore);
+    builder.append('\n');
+    builder.append("    subframeHasBeenRedirectedTo: ");
+    builder.appendNumber(subframeHasBeenRedirectedTo);
+    builder.append('\n');
+    builder.append("    subframeHasBeenRedirectedFrom: ");
+    builder.appendNumber(subframeHasBeenRedirectedFrom);
+    builder.append('\n');
+    builder.append("    subframeSubResourceCount: ");
+    builder.appendNumber(subframeSubResourceCount);
+    builder.append('\n');
+    appendHashCountedSet(builder, "subframeUnderTopFrameOrigins", subframeUnderTopFrameOrigins);
+    appendHashCountedSet(builder, "subframeUniqueRedirectsTo", subframeUniqueRedirectsTo);
+    builder.append("    subframeHasBeenNavigatedTo: ");
+    builder.appendNumber(subframeHasBeenNavigatedTo);
+    builder.append('\n');
+    builder.append("    subframeHasBeenNavigatedFrom: ");
+    builder.appendNumber(subframeHasBeenNavigatedFrom);
+    builder.append('\n');
+    
+    // Subresource stats
+    builder.append("    subresourceHasBeenRedirectedFrom: ");
+    builder.appendNumber(subresourceHasBeenRedirectedFrom);
+    builder.append('\n');
+    builder.append("    subresourceHasBeenRedirectedTo: ");
+    builder.appendNumber(subresourceHasBeenRedirectedTo);
+    builder.append('\n');
+    builder.append("    subresourceHasBeenSubresourceCount: ");
+    builder.appendNumber(subresourceHasBeenSubresourceCount);
+    builder.append('\n');
+    builder.append("    subresourceHasBeenSubresourceCountDividedByTotalNumberOfOriginsVisited: ");
+    builder.appendNumber(subresourceHasBeenSubresourceCountDividedByTotalNumberOfOriginsVisited);
+    builder.append('\n');
+    appendHashCountedSet(builder, "subresourceUnderTopFrameOrigins", subresourceUnderTopFrameOrigins);
+    appendHashCountedSet(builder, "subresourceUniqueRedirectsTo", subresourceUniqueRedirectsTo);
+    
+    // Prevalent Resource
+    appendHashCountedSet(builder, "redirectedToOtherPrevalentResourceOrigins", redirectedToOtherPrevalentResourceOrigins);
+    appendBoolean(builder, "isPrevalentResource", isPrevalentResource);
+    builder.append('\n');
+
+    return builder.toString();
+}
+
+}

Added: trunk/Source/WebCore/loader/ResourceLoadStatistics.h (0 => 196622)


--- trunk/Source/WebCore/loader/ResourceLoadStatistics.h	                        (rev 0)
+++ trunk/Source/WebCore/loader/ResourceLoadStatistics.h	2016-02-16 05:36:38 UTC (rev 196622)
@@ -0,0 +1,84 @@
+/*
+ * Copyright (C) 2016 Apple Inc.  All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL APPLE INC. OR
+ * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
+ * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+ * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
+ * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
+ * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef ResourceLoadStatistics_h
+#define ResourceLoadStatistics_h
+
+#include <wtf/HashCountedSet.h>
+#include <wtf/text/WTFString.h>
+
+namespace WebCore {
+
+class KeyedDecoder;
+class KeyedEncoder;
+
+struct ResourceLoadStatistics {
+    bool checkAndSetAsPrevalentResourceIfNecessary(unsigned originsVisitedSoFar);
+
+    bool hasPrevalentRedirection() const;
+    bool hasPrevalentResourceCharacteristics() const;
+
+    void encode(KeyedEncoder&, const String& origin) const;
+    bool decode(KeyedDecoder&, const String& origin);
+
+    String toString() const;
+
+    // User interaction
+    bool hadUserInteraction { false };
+    
+    // Top frame stats
+    unsigned topFrameHasBeenRedirectedTo { 0 };
+    unsigned topFrameHasBeenRedirectedFrom { 0 };
+    unsigned topFrameInitialLoadCount { 0 };
+    unsigned topFrameHasBeenNavigatedTo { 0 };
+    unsigned topFrameHasBeenNavigatedFrom { 0 };
+    bool topFrameHasBeenNavigatedToBefore { false };
+    
+    // Subframe stats
+    HashCountedSet<String> subframeUnderTopFrameOrigins;
+    unsigned subframeHasBeenRedirectedTo { 0 };
+    unsigned subframeHasBeenRedirectedFrom { 0 };
+    HashCountedSet<String> subframeUniqueRedirectsTo;
+    unsigned subframeSubResourceCount { 0 };
+    unsigned subframeHasBeenNavigatedTo { 0 };
+    unsigned subframeHasBeenNavigatedFrom { 0 };
+    bool subframeHasBeenLoadedBefore { false };
+    
+    // Subresource stats
+    HashCountedSet<String> subresourceUnderTopFrameOrigins;
+    unsigned subresourceHasBeenSubresourceCount { 0 };
+    double subresourceHasBeenSubresourceCountDividedByTotalNumberOfOriginsVisited { 0.0 };
+    unsigned subresourceHasBeenRedirectedFrom { 0 };
+    unsigned subresourceHasBeenRedirectedTo { 0 };
+    HashCountedSet<String> subresourceUniqueRedirectsTo;
+    
+    // Prevalent resource stats
+    HashCountedSet<String> redirectedToOtherPrevalentResourceOrigins;
+    bool isPrevalentResource { false };
+};
+
+} // namespace WebCore
+
+#endif // ResourceLoadStatistics_h

Modified: trunk/Source/WebCore/loader/SubresourceLoader.cpp (196621 => 196622)


--- trunk/Source/WebCore/loader/SubresourceLoader.cpp	2016-02-16 05:32:56 UTC (rev 196621)
+++ trunk/Source/WebCore/loader/SubresourceLoader.cpp	2016-02-16 05:36:38 UTC (rev 196622)
@@ -40,6 +40,7 @@
 #include "MainFrame.h"
 #include "MemoryCache.h"
 #include "Page.h"
+#include "ResourceLoadObserver.h"
 #include "Settings.h"
 #include <wtf/Ref.h>
 #include <wtf/RefCountedLeakCounter.h>
@@ -189,6 +190,9 @@
     ResourceLoader::willSendRequestInternal(newRequest, redirectResponse);
     if (newRequest.isNull())
         cancel();
+
+    if (Settings::resourceLoadStatisticsEnabled())
+        ResourceLoadObserver::sharedObserver().logSubresourceLoading(!redirectResponse.isNull(), redirectResponse.url(), newRequest.url(), m_frame ? m_frame->mainFrame().document()->url() : URL());
 }
 
 void SubresourceLoader::didSendData(unsigned long long bytesSent, unsigned long long totalBytesToBeSent)

Modified: trunk/Source/WebCore/page/Settings.cpp (196621 => 196622)


--- trunk/Source/WebCore/page/Settings.cpp	2016-02-16 05:32:56 UTC (rev 196621)
+++ trunk/Source/WebCore/page/Settings.cpp	2016-02-16 05:36:38 UTC (rev 196622)
@@ -96,6 +96,7 @@
 bool Settings::gShouldRewriteConstAsVar = false;
 bool Settings::gShouldRespectPriorityInCSSAttributeSetters = false;
 bool Settings::gLowPowerVideoAudioBufferSizeEnabled = false;
+bool Settings::gResourceLoadStatisticsEnabledEnabled = false;
 
 #if PLATFORM(IOS)
 bool Settings::gNetworkDataUsageTrackingEnabled = false;
@@ -699,6 +700,11 @@
     gLowPowerVideoAudioBufferSizeEnabled = flag;
 }
 
+void Settings::setResourceLoadStatisticsEnabled(bool flag)
+{
+    gResourceLoadStatisticsEnabledEnabled = flag;
+}
+
 #if PLATFORM(IOS)
 void Settings::setAudioSessionCategoryOverride(unsigned sessionCategory)
 {

Modified: trunk/Source/WebCore/page/Settings.h (196621 => 196622)


--- trunk/Source/WebCore/page/Settings.h	2016-02-16 05:32:56 UTC (rev 196621)
+++ trunk/Source/WebCore/page/Settings.h	2016-02-16 05:36:38 UTC (rev 196622)
@@ -242,6 +242,9 @@
     static bool lowPowerVideoAudioBufferSizeEnabled() { return gLowPowerVideoAudioBufferSizeEnabled; }
     WEBCORE_EXPORT static void setLowPowerVideoAudioBufferSizeEnabled(bool);
 
+    static bool resourceLoadStatisticsEnabled() { return gResourceLoadStatisticsEnabledEnabled; }
+    WEBCORE_EXPORT static void setResourceLoadStatisticsEnabled(bool);
+
 #if PLATFORM(IOS)
     WEBCORE_EXPORT static void setAudioSessionCategoryOverride(unsigned);
     static unsigned audioSessionCategoryOverride();
@@ -377,6 +380,7 @@
 #endif
 
     static bool gLowPowerVideoAudioBufferSizeEnabled;
+    static bool gResourceLoadStatisticsEnabledEnabled;
 };
 
 } // namespace WebCore

Modified: trunk/Source/WebCore/platform/Logging.h (196621 => 196622)


--- trunk/Source/WebCore/platform/Logging.h	2016-02-16 05:32:56 UTC (rev 196621)
+++ trunk/Source/WebCore/platform/Logging.h	2016-02-16 05:36:38 UTC (rev 196622)
@@ -86,6 +86,7 @@
     M(WebGL) \
     M(WebReplay) \
     M(WheelEventTestTriggers) \
+    M(ResourceLoadObserver) \
 
 #define DECLARE_LOG_CHANNEL(name) \
     WEBCORE_EXPORT extern WTFLogChannel JOIN_LOG_CHANNEL_WITH_PREFIX(LOG_CHANNEL_PREFIX, name);

Modified: trunk/Source/WebCore/testing/Internals.cpp (196621 => 196622)


--- trunk/Source/WebCore/testing/Internals.cpp	2016-02-16 05:32:56 UTC (rev 196621)
+++ trunk/Source/WebCore/testing/Internals.cpp	2016-02-16 05:36:38 UTC (rev 196622)
@@ -102,6 +102,7 @@
 #include "RenderTreeAsText.h"
 #include "RenderView.h"
 #include "RenderedDocumentMarker.h"
+#include "ResourceLoadObserver.h"
 #include "RuntimeEnabledFeatures.h"
 #include "SchemeRegistry.h"
 #include "ScriptedAnimationController.h"
@@ -3460,4 +3461,14 @@
 }
 #endif
 
+String Internals::resourceLoadStatisticsForOrigin(String origin)
+{
+    return ResourceLoadObserver::sharedObserver().statisticsForOrigin(origin);
 }
+
+void Internals::setResourceLoadStatisticsEnabled(bool enable)
+{
+    Settings::setResourceLoadStatisticsEnabled(enable);
+}
+
+}

Modified: trunk/Source/WebCore/testing/Internals.h (196621 => 196622)


--- trunk/Source/WebCore/testing/Internals.h	2016-02-16 05:32:56 UTC (rev 196621)
+++ trunk/Source/WebCore/testing/Internals.h	2016-02-16 05:36:38 UTC (rev 196622)
@@ -462,6 +462,9 @@
     String userVisibleString(const DOMURL*);
     void setShowAllPlugins(bool);
 
+    String resourceLoadStatisticsForOrigin(String origin);
+    void setResourceLoadStatisticsEnabled(bool);
+
 #if ENABLE(STREAMS_API)
     bool isReadableStreamDisturbed(ScriptState&, JSC::JSValue);
 #endif

Modified: trunk/Source/WebCore/testing/Internals.idl (196621 => 196622)


--- trunk/Source/WebCore/testing/Internals.idl	2016-02-16 05:32:56 UTC (rev 196621)
+++ trunk/Source/WebCore/testing/Internals.idl	2016-02-16 05:36:38 UTC (rev 196622)
@@ -433,4 +433,7 @@
     void setShowAllPlugins(boolean showAll);
 
     [Conditional=STREAMS_API, CallWith=ScriptState] boolean isReadableStreamDisturbed(any stream);
+
+    DOMString resourceLoadStatisticsForOrigin(DOMString domain);
+    void setResourceLoadStatisticsEnabled(boolean enable);
 };

Modified: trunk/Source/WebKit/mac/ChangeLog (196621 => 196622)


--- trunk/Source/WebKit/mac/ChangeLog	2016-02-16 05:32:56 UTC (rev 196621)
+++ trunk/Source/WebKit/mac/ChangeLog	2016-02-16 05:36:38 UTC (rev 196622)
@@ -1,3 +1,30 @@
+2016-02-15  Brent Fulgham  <[email protected]>
+
+        [Mac] Gather some rudimentary statistics during resource load 
+        https://bugs.webkit.org/show_bug.cgi?id=153575
+        <rdar://problem/24075254>
+
+        Reviewed by Brady Eidson.
+
+        * Misc/WebKitNSStringExtras.h:
+        * Misc/WebKitNSStringExtras.mm:
+        (+[NSString _webkit_localStorageDirectoryWithBundleIdentifier:]): Added.
+        * WebView/WebPreferenceKeysPrivate.h:
+        * WebView/WebPreferences.mm:
+        (+[WebPreferences initialize]):
+        (-[WebPreferences resourceLoadStatisticsEnabled]): Added.
+        (-[WebPreferences setResourceLoadStatisticsEnabled:]): Added.
+        * WebView/WebPreferencesPrivate.h:
+        * WebView/WebView.mm:
+        (WebKitInitializeApplicationCachePathIfNecessary):
+        (WebKitInitializeApplicationStatisticsStoragePathIfNecessary): Added.
+        (-[WebView _commonInitializationWithFrameName:groupName:]): Add call to new
+        initialization method.
+        (-[WebView _preferencesChanged:]): Track changes in the user's desire to
+        monitor resource load statistics.
+        (+[WebView _applicationWillTerminate]): Write statistics to disk (if preferences
+        say to do so.)
+
 2016-02-13  Mark Lam  <[email protected]>
 
         Add thread violation checks to WebView public APIs.

Modified: trunk/Source/WebKit/mac/Misc/WebKitNSStringExtras.h (196621 => 196622)


--- trunk/Source/WebKit/mac/Misc/WebKitNSStringExtras.h	2016-02-16 05:32:56 UTC (rev 196621)
+++ trunk/Source/WebKit/mac/Misc/WebKitNSStringExtras.h	2016-02-16 05:36:38 UTC (rev 196622)
@@ -33,6 +33,7 @@
 #endif
 
 extern NSString *WebKitLocalCacheDefaultsKey;
+extern NSString *WebKitResourceLoadStatisticsDirectoryDefaultsKey;
 
 @interface NSString (WebKitExtras)
 
@@ -65,5 +66,6 @@
 #endif
 
 + (NSString *)_webkit_localCacheDirectoryWithBundleIdentifier:(NSString*)bundleIdentifier;
++ (NSString *)_webkit_localStorageDirectoryWithBundleIdentifier:(NSString*)bundleIdentifier;
 
 @end

Modified: trunk/Source/WebKit/mac/Misc/WebKitNSStringExtras.mm (196621 => 196622)


--- trunk/Source/WebKit/mac/Misc/WebKitNSStringExtras.mm	2016-02-16 05:32:56 UTC (rev 196621)
+++ trunk/Source/WebKit/mac/Misc/WebKitNSStringExtras.mm	2016-02-16 05:36:38 UTC (rev 196622)
@@ -46,6 +46,7 @@
 #endif
 
 NSString *WebKitLocalCacheDefaultsKey = @"WebKitLocalCache";
+NSString *WebKitResourceLoadStatisticsDirectoryDefaultsKey = @"WebKitResourceLoadStatisticsDirectory";
 
 using namespace WebCore;
 
@@ -311,4 +312,20 @@
     return [cacheDir stringByAppendingPathComponent:bundleIdentifier];
 }
 
++ (NSString *)_webkit_localStorageDirectoryWithBundleIdentifier:(NSString*)bundleIdentifier
+{
+    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
+    NSString *storageDirectory = [defaults objectForKey:WebKitResourceLoadStatisticsDirectoryDefaultsKey];
+
+    if (!storageDirectory || ![storageDirectory isKindOfClass:[NSString class]]) {
+        NSError *error;
+        NSString *storageDirectory = [[[NSFileManager defaultManager] URLForDirectory:NSApplicationSupportDirectory inDomain:NSUserDomainMask appropriateForURL:nil create:YES error:&error] path];
+        
+        if (!storageDirectory || ![storageDirectory isKindOfClass:[NSString class]])
+            storageDirectory = [NSHomeDirectory() stringByAppendingPathComponent:@"Library/Application Support"];
+    }
+
+    return [storageDirectory stringByAppendingPathComponent:bundleIdentifier];
+}
+
 @end

Modified: trunk/Source/WebKit/mac/WebKit.exp (196621 => 196622)


--- trunk/Source/WebKit/mac/WebKit.exp	2016-02-16 05:32:56 UTC (rev 196621)
+++ trunk/Source/WebKit/mac/WebKit.exp	2016-02-16 05:36:38 UTC (rev 196622)
@@ -80,6 +80,7 @@
 _WebKitErrorPlugInNameKey
 _WebKitErrorPlugInPageURLStringKey
 _WebKitLocalCacheDefaultsKey
+_WebKitResourceLoadStatisticsDirectoryDefaultsKey
 _WebLocalizedString
 _WebPlugInAttributesKey
 _WebPlugInBaseURLKey

Modified: trunk/Source/WebKit/mac/WebView/WebPreferenceKeysPrivate.h (196621 => 196622)


--- trunk/Source/WebKit/mac/WebView/WebPreferenceKeysPrivate.h	2016-02-16 05:32:56 UTC (rev 196621)
+++ trunk/Source/WebKit/mac/WebView/WebPreferenceKeysPrivate.h	2016-02-16 05:36:38 UTC (rev 196622)
@@ -136,6 +136,7 @@
 #define WebKitNotificationsEnabledKey @"WebKitNotificationsEnabled"
 #define WebKitSuppressesIncrementalRenderingKey @"WebKitSuppressesIncrementalRendering"
 #define WebKitSubpixelCSSOMElementMetricsEnabledPreferenceKey @"WebKitSubpixelCSSOMElementMetricsEnabled"
+#define WebKitResourceLoadStatisticsEnabledPreferenceKey @"WebKitResourceLoadStatisticsEnabled"
 #if TARGET_OS_IPHONE
 #define WebKitAudioSessionCategoryOverride @"WebKitAudioSessionCategoryOverride"
 #define WebKitAVKitEnabled @"WebKitAVKitEnabled"

Modified: trunk/Source/WebKit/mac/WebView/WebPreferences.mm (196621 => 196622)


--- trunk/Source/WebKit/mac/WebView/WebPreferences.mm	2016-02-16 05:32:56 UTC (rev 196621)
+++ trunk/Source/WebKit/mac/WebView/WebPreferences.mm	2016-02-16 05:36:38 UTC (rev 196622)
@@ -505,6 +505,7 @@
         [NSNumber numberWithBool:NO],  WebKitForceSoftwareWebGLRenderingPreferenceKey,
         [NSNumber numberWithBool:NO],   WebKitAccelerated2dCanvasEnabledPreferenceKey,
         [NSNumber numberWithBool:NO],  WebKitSubpixelCSSOMElementMetricsEnabledPreferenceKey,
+        [NSNumber numberWithBool:NO],  WebKitResourceLoadStatisticsEnabledPreferenceKey,
 #if PLATFORM(IOS)
         [NSNumber numberWithBool:YES],  WebKitFrameFlatteningEnabledPreferenceKey,
 #else
@@ -1829,6 +1830,16 @@
     [self _setBoolValue:enabled forKey:WebKitDisplayListDrawingEnabledPreferenceKey];
 }
 
+- (BOOL)resourceLoadStatisticsEnabled
+{
+    return [self _boolValueForKey:WebKitResourceLoadStatisticsEnabledPreferenceKey];
+}
+
+- (void)setResourceLoadStatisticsEnabled:(BOOL)enabled
+{
+    [self _setBoolValue:enabled forKey:WebKitResourceLoadStatisticsEnabledPreferenceKey];
+}
+
 - (BOOL)canvasUsesAcceleratedDrawing
 {
     return [self _boolValueForKey:WebKitCanvasUsesAcceleratedDrawingPreferenceKey];

Modified: trunk/Source/WebKit/mac/WebView/WebPreferencesPrivate.h (196621 => 196622)


--- trunk/Source/WebKit/mac/WebView/WebPreferencesPrivate.h	2016-02-16 05:32:56 UTC (rev 196621)
+++ trunk/Source/WebKit/mac/WebView/WebPreferencesPrivate.h	2016-02-16 05:36:38 UTC (rev 196622)
@@ -203,6 +203,9 @@
 - (BOOL)displayListDrawingEnabled;
 - (void)setDisplayListDrawingEnabled:(BOOL)enabled;
 
+- (BOOL)resourceLoadStatisticsEnabled;
+- (void)setResourceLoadStatisticsEnabled:(BOOL)enabled;
+
 - (BOOL)canvasUsesAcceleratedDrawing;
 - (void)setCanvasUsesAcceleratedDrawing:(BOOL)enabled;
 

Modified: trunk/Source/WebKit/mac/WebView/WebView.mm (196621 => 196622)


--- trunk/Source/WebKit/mac/WebView/WebView.mm	2016-02-16 05:32:56 UTC (rev 196621)
+++ trunk/Source/WebKit/mac/WebView/WebView.mm	2016-02-16 05:36:38 UTC (rev 196622)
@@ -168,6 +168,7 @@
 #import <WebCore/RenderView.h>
 #import <WebCore/RenderWidget.h>
 #import <WebCore/ResourceHandle.h>
+#import <WebCore/ResourceLoadObserver.h>
 #import <WebCore/ResourceRequest.h>
 #import <WebCore/RuntimeApplicationChecks.h>
 #import <WebCore/RuntimeEnabledFeatures.h>
@@ -746,9 +747,28 @@
     NSString* cacheDir = [NSString _webkit_localCacheDirectoryWithBundleIdentifier:appName];
 
     webApplicationCacheStorage().setCacheDirectory(cacheDir);
+    
     initialized = YES;
 }
 
+static void WebKitInitializeApplicationStatisticsStoragePathIfNecessary()
+{
+    static BOOL initialized = NO;
+    if (initialized)
+        return;
+    
+    NSString *appName = [[NSBundle mainBundle] bundleIdentifier];
+    if (!appName)
+        appName = [[NSProcessInfo processInfo] processName];
+    
+    ASSERT(appName);
+    
+    NSString *supportDirectory = [NSString _webkit_localStorageDirectoryWithBundleIdentifier:appName];
+    ResourceLoadObserver::sharedObserver().setStatisticsStorageDirectory(supportDirectory);
+    
+    initialized = YES;
+}
+
 static bool shouldEnableLoadDeferring()
 {
     return !applicationIsAdobeInstaller();
@@ -943,6 +963,7 @@
 #endif
         WebKitInitializeStorageIfNecessary();
         WebKitInitializeApplicationCachePathIfNecessary();
+        WebKitInitializeApplicationStatisticsStoragePathIfNecessary();
 #if ENABLE(GAMEPAD)
         WebKitInitializeGamepadProviderIfNecessary();
 #endif
@@ -2452,6 +2473,9 @@
 
     settings.setHiddenPageCSSAnimationSuspensionEnabled([preferences hiddenPageCSSAnimationSuspensionEnabled]);
 
+    settings.setResourceLoadStatisticsEnabled([preferences resourceLoadStatisticsEnabled]);
+    ResourceLoadObserver::sharedObserver().readDataFromDiskIfNeeded();
+
 #if ENABLE(GAMEPAD)
     RuntimeEnabledFeatures::sharedFeatures().setGamepadsEnabled([preferences gamepadsEnabled]);
 #endif
@@ -4820,6 +4844,8 @@
 {   
     applicationIsTerminating = YES;
 
+    ResourceLoadObserver::sharedObserver().writeDataToDisk();
+
     if (fastDocumentTeardownEnabled())
         [self closeAllWebViews];
 

Modified: trunk/Tools/ChangeLog (196621 => 196622)


--- trunk/Tools/ChangeLog	2016-02-16 05:32:56 UTC (rev 196621)
+++ trunk/Tools/ChangeLog	2016-02-16 05:36:38 UTC (rev 196622)
@@ -1,3 +1,20 @@
+2016-02-15  Brent Fulgham  <[email protected]>
+
+        [Mac] Gather some rudimentary statistics during resource load 
+        https://bugs.webkit.org/show_bug.cgi?id=153575
+        <rdar://problem/24075254>
+
+        Reviewed by Brady Eidson.
+
+        * MiniBrowser/mac/SettingsController.h:
+        * MiniBrowser/mac/SettingsController.m:
+        (-[SettingsController _populateMenu]): Add menu item for new debug flag.
+        (-[SettingsController toggleResourceLoadStatisticsEnabled:]): Added.
+        (-[SettingsController resourceLoadStatisticsEnabled]): Added.
+        * MiniBrowser/mac/WK1BrowserWindowController.m:
+        (-[WK1BrowserWindowController didChangeSettings]): React to changes in
+        users's desire to track resource load statistics.
+
 2016-02-15  Csaba Osztrogonác  <[email protected]>
 
         [EFL] Update Tools/efl/install-dependencies

Modified: trunk/Tools/DumpRenderTree/mac/DumpRenderTree.mm (196621 => 196622)


--- trunk/Tools/DumpRenderTree/mac/DumpRenderTree.mm	2016-02-16 05:32:56 UTC (rev 196621)
+++ trunk/Tools/DumpRenderTree/mac/DumpRenderTree.mm	2016-02-16 05:36:38 UTC (rev 196622)
@@ -1053,6 +1053,7 @@
         WebDatabaseDirectoryDefaultsKey: [libraryPath stringByAppendingPathComponent:@"Databases"],
         WebStorageDirectoryDefaultsKey: [libraryPath stringByAppendingPathComponent:@"LocalStorage"],
         WebKitLocalCacheDefaultsKey: [libraryPath stringByAppendingPathComponent:@"LocalCache"],
+        WebKitResourceLoadStatisticsDirectoryDefaultsKey: [libraryPath stringByAppendingPathComponent:@"LocalStorage"],
 #if PLATFORM(MAC) && __MAC_OS_X_VERSION_MIN_REQUIRED > 101000
         // This needs to also be added to argument domain because of <rdar://problem/20210002>.
         @"AppleSystemFontOSSubversion": @(10),

Modified: trunk/Tools/MiniBrowser/mac/SettingsController.h (196621 => 196622)


--- trunk/Tools/MiniBrowser/mac/SettingsController.h	2016-02-16 05:32:56 UTC (rev 196621)
+++ trunk/Tools/MiniBrowser/mac/SettingsController.h	2016-02-16 05:36:38 UTC (rev 196622)
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2014 Apple Inc. All rights reserved.
+ * Copyright (C) 2014-2016 Apple Inc. All rights reserved.
  *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
@@ -48,6 +48,7 @@
 @property (nonatomic, readonly) BOOL subPixelCSSOMMetricsEnabled;
 @property (nonatomic, readonly) BOOL acceleratedDrawingEnabled;
 @property (nonatomic, readonly) BOOL displayListDrawingEnabled;
+@property (nonatomic, readonly) BOOL resourceLoadStatisticsEnabled;
 @property (nonatomic, readonly) NSString *defaultURL;
 
 @end

Modified: trunk/Tools/MiniBrowser/mac/SettingsController.m (196621 => 196622)


--- trunk/Tools/MiniBrowser/mac/SettingsController.m	2016-02-16 05:32:56 UTC (rev 196621)
+++ trunk/Tools/MiniBrowser/mac/SettingsController.m	2016-02-16 05:36:38 UTC (rev 196622)
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2014 Apple Inc. All rights reserved.
+ * Copyright (C) 2014-2016 Apple Inc. All rights reserved.
  *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
@@ -39,6 +39,7 @@
 static NSString * const IncrementalRenderingSuppressedPreferenceKey = @"IncrementalRenderingSuppressed";
 static NSString * const AcceleratedDrawingEnabledPreferenceKey = @"AcceleratedDrawingEnabled";
 static NSString * const DisplayListDrawingEnabledPreferenceKey = @"DisplayListDrawingEnabled";
+static NSString * const ResourceLoadStatisticsEnabledPreferenceKey = @"ResourceLoadStatisticsEnabled";
 
 static NSString * const NonFastScrollableRegionOverlayVisiblePreferenceKey = @"NonFastScrollableRegionOverlayVisible";
 static NSString * const WheelEventHandlerRegionOverlayVisiblePreferenceKey = @"WheelEventHandlerRegionOverlayVisible";
@@ -140,6 +141,7 @@
 
     [self _addHeaderWithTitle:@"WebKit1-only Settings"];
     [self _addItemWithTitle:@"Enable Subpixel CSSOM Metrics" action:@selector(toggleEnableSubPixelCSSOMMetrics:) indented:YES];
+    [self _addItemWithTitle:@"Enable Resource Load Statistics" action:@selector(toggleResourceLoadStatisticsEnabled:) indented:NO];
 }
 
 - (BOOL)validateMenuItem:(NSMenuItem *)menuItem
@@ -162,6 +164,8 @@
         [menuItem setState:[self acceleratedDrawingEnabled] ? NSOnState : NSOffState];
     else if (action == @selector(toggleDisplayListDrawingEnabled:))
         [menuItem setState:[self displayListDrawingEnabled] ? NSOnState : NSOffState];
+    else if (action == @selector(toggleResourceLoadStatisticsEnabled:))
+        [menuItem setState:[self resourceLoadStatisticsEnabled] ? NSOnState : NSOffState];
     else if (action == @selector(toggleShowTiledScrollingIndicator:))
         [menuItem setState:[self tiledScrollingIndicatorVisible] ? NSOnState : NSOffState];
     else if (action == @selector(toggleShowResourceUsageOverlay:))
@@ -316,6 +320,16 @@
     return [[NSUserDefaults standardUserDefaults] boolForKey:ResourceUsageOverlayVisiblePreferenceKey];
 }
 
+- (void)toggleResourceLoadStatisticsEnabled:(id)sender
+{
+    [self _toggleBooleanDefault:ResourceLoadStatisticsEnabledPreferenceKey];
+}
+
+- (BOOL)resourceLoadStatisticsEnabled
+{
+    return [[NSUserDefaults standardUserDefaults] boolForKey:ResourceLoadStatisticsEnabledPreferenceKey];
+}
+
 - (void)toggleEnableSubPixelCSSOMMetrics:(id)sender
 {
     [self _toggleBooleanDefault:EnableSubPixelCSSOMMetricsPreferenceKey];

Modified: trunk/Tools/MiniBrowser/mac/WK1BrowserWindowController.m (196621 => 196622)


--- trunk/Tools/MiniBrowser/mac/WK1BrowserWindowController.m	2016-02-16 05:32:56 UTC (rev 196621)
+++ trunk/Tools/MiniBrowser/mac/WK1BrowserWindowController.m	2016-02-16 05:36:38 UTC (rev 196622)
@@ -260,6 +260,7 @@
     [[WebPreferences standardPreferences] setShowRepaintCounter:settings.layerBordersVisible];
     [[WebPreferences standardPreferences] setSuppressesIncrementalRendering:settings.incrementalRenderingSuppressed];
     [[WebPreferences standardPreferences] setAcceleratedDrawingEnabled:settings.acceleratedDrawingEnabled];
+    [[WebPreferences standardPreferences] setResourceLoadStatisticsEnabled:settings.resourceLoadStatisticsEnabled];
 
     BOOL useTransparentWindows = settings.useTransparentWindows;
     if (useTransparentWindows != !self.window.isOpaque) {
_______________________________________________
webkit-changes mailing list
[email protected]
https://lists.webkit.org/mailman/listinfo/webkit-changes

Reply via email to