Optimize content extensions interpreting speed.
[WebKit-https.git] / Source / WebCore / contentextensions / ContentExtensionsBackend.cpp
1 /*
2  * Copyright (C) 2014 Apple Inc. All rights reserved.
3  *
4  * Redistribution and use in source and binary forms, with or without
5  * modification, are permitted provided that the following conditions
6  * are met:
7  * 1. Redistributions of source code must retain the above copyright
8  *    notice, this list of conditions and the following disclaimer.
9  * 2. Redistributions in binary form must reproduce the above copyright
10  *    notice, this list of conditions and the following disclaimer in the
11  *    documentation and/or other materials provided with the distribution.
12  *
13  * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS''
14  * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
15  * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
16  * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS
17  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
18  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
19  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
20  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
21  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
22  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
23  * THE POSSIBILITY OF SUCH DAMAGE.
24  */
25
26 #include "config.h"
27 #include "ContentExtensionsBackend.h"
28
29 #if ENABLE(CONTENT_EXTENSIONS)
30
31 #include "CompiledContentExtension.h"
32 #include "ContentExtension.h"
33 #include "ContentExtensionsDebugging.h"
34 #include "DFABytecodeInterpreter.h"
35 #include "Document.h"
36 #include "DocumentLoader.h"
37 #include "Frame.h"
38 #include "MainFrame.h"
39 #include "ResourceLoadInfo.h"
40 #include "URL.h"
41 #include "UserContentController.h"
42 #include <wtf/NeverDestroyed.h>
43 #include <wtf/text/CString.h>
44
45 namespace WebCore {
46
47 namespace ContentExtensions {
48     
49 void ContentExtensionsBackend::addContentExtension(const String& identifier, RefPtr<CompiledContentExtension> compiledContentExtension)
50 {
51     ASSERT(!identifier.isEmpty());
52     if (identifier.isEmpty())
53         return;
54
55     if (!compiledContentExtension) {
56         removeContentExtension(identifier);
57         return;
58     }
59
60     RefPtr<ContentExtension> extension = ContentExtension::create(identifier, adoptRef(*compiledContentExtension.leakRef()));
61     m_contentExtensions.set(identifier, WTF::move(extension));
62 }
63
64 void ContentExtensionsBackend::removeContentExtension(const String& identifier)
65 {
66     m_contentExtensions.remove(identifier);
67 }
68
69 void ContentExtensionsBackend::removeAllContentExtensions()
70 {
71     m_contentExtensions.clear();
72 }
73
74 Vector<Action> ContentExtensionsBackend::actionsForResourceLoad(const ResourceLoadInfo& resourceLoadInfo) const
75 {
76 #if CONTENT_EXTENSIONS_PERFORMANCE_REPORTING
77     double addedTimeStart = monotonicallyIncreasingTime();
78 #endif
79     if (resourceLoadInfo.resourceURL.protocolIsData()
80         || resourceLoadInfo.resourceURL.protocolIsJavaScript())
81         return Vector<Action>();
82
83     const String& urlString = resourceLoadInfo.resourceURL.string();
84     ASSERT_WITH_MESSAGE(urlString.containsOnlyASCII(), "A decoded URL should only contain ASCII characters. The matching algorithm assumes the input is ASCII.");
85     const CString& urlCString = urlString.utf8();
86
87     Vector<Action> finalActions;
88     ResourceFlags flags = resourceLoadInfo.getResourceFlags();
89     for (auto& contentExtension : m_contentExtensions.values()) {
90         RELEASE_ASSERT(contentExtension);
91         const CompiledContentExtension& compiledExtension = contentExtension->compiledExtension();
92         DFABytecodeInterpreter interpreter(compiledExtension.bytecode(), compiledExtension.bytecodeLength(), contentExtension->m_pagesUsed);
93         DFABytecodeInterpreter::Actions triggeredActions = interpreter.interpret(urlCString, flags);
94         
95         const SerializedActionByte* actions = compiledExtension.actions();
96         const unsigned actionsLength = compiledExtension.actionsLength();
97         
98         bool sawIgnorePreviousRules = false;
99         if (!triggeredActions.isEmpty()) {
100             Vector<unsigned> actionLocations;
101             actionLocations.reserveInitialCapacity(triggeredActions.size());
102             for (auto actionLocation : triggeredActions)
103                 actionLocations.append(static_cast<unsigned>(actionLocation));
104             std::sort(actionLocations.begin(), actionLocations.end());
105
106             // Add actions in reverse order to properly deal with IgnorePreviousRules.
107             for (unsigned i = actionLocations.size(); i; i--) {
108                 Action action = Action::deserialize(actions, actionsLength, actionLocations[i - 1]);
109                 if (action.type() == ActionType::IgnorePreviousRules) {
110                     sawIgnorePreviousRules = true;
111                     break;
112                 }
113                 finalActions.append(action);
114             }
115         }
116         if (!sawIgnorePreviousRules) {
117             DFABytecodeInterpreter::Actions universalActions = interpreter.actionsFromDFARoot();
118             for (auto actionLocation : universalActions) {
119                 Action action = Action::deserialize(actions, actionsLength, static_cast<unsigned>(actionLocation));
120                 
121                 // CSS selectors were already compiled into a stylesheet using globalDisplayNoneSelectors.
122                 if (action.type() != ActionType::CSSDisplayNoneSelector)
123                     finalActions.append(action);
124             }
125             finalActions.append(Action(ActionType::CSSDisplayNoneStyleSheet, contentExtension->identifier()));
126         }
127     }
128 #if CONTENT_EXTENSIONS_PERFORMANCE_REPORTING
129     double addedTimeEnd = monotonicallyIncreasingTime();
130     WTFLogAlways("Time added: %f microseconds %s", (addedTimeEnd - addedTimeStart) * 1.0e6, resourceLoadInfo.resourceURL.string().utf8().data());
131 #endif
132     return finalActions;
133 }
134
135 StyleSheetContents* ContentExtensionsBackend::globalDisplayNoneStyleSheet(const String& identifier) const
136 {
137     const auto& contentExtension = m_contentExtensions.get(identifier);
138     return contentExtension ? contentExtension->globalDisplayNoneStyleSheet() : nullptr;
139 }
140
141 void ContentExtensionsBackend::processContentExtensionRulesForLoad(ResourceRequest& request, ResourceType resourceType, DocumentLoader& initiatingDocumentLoader)
142 {
143     Document* currentDocument = nullptr;
144     URL mainDocumentURL;
145
146     if (initiatingDocumentLoader.frame()) {
147         currentDocument = initiatingDocumentLoader.frame()->document();
148
149         if (Document* mainDocument = initiatingDocumentLoader.frame()->mainFrame().document())
150             mainDocumentURL = mainDocument->url();
151     }
152
153     ResourceLoadInfo resourceLoadInfo = { request.url(), mainDocumentURL, resourceType };
154     Vector<ContentExtensions::Action> actions = actionsForResourceLoad(resourceLoadInfo);
155
156     StringBuilder css;
157     bool willBlockLoad = false;
158     for (const auto& action : actions) {
159         switch (action.type()) {
160         case ContentExtensions::ActionType::BlockLoad:
161             willBlockLoad = true;
162             break;
163         case ContentExtensions::ActionType::BlockCookies:
164             request.setAllowCookies(false);
165             break;
166         case ContentExtensions::ActionType::CSSDisplayNoneSelector:
167             css.append(action.stringArgument());
168             css.append(displayNoneCSSRule());
169             break;
170         case ContentExtensions::ActionType::CSSDisplayNoneStyleSheet: {
171             StyleSheetContents* styleSheetContents = globalDisplayNoneStyleSheet(action.stringArgument());
172             if (styleSheetContents) {
173                 if (resourceType == ResourceType::Document)
174                     initiatingDocumentLoader.addPendingContentExtensionSheet(action.stringArgument(), *styleSheetContents);
175                 else if (currentDocument)
176                     currentDocument->styleSheetCollection().maybeAddContentExtensionSheet(action.stringArgument(), *styleSheetContents);
177             }
178             break;
179         }
180         case ContentExtensions::ActionType::IgnorePreviousRules:
181         case ContentExtensions::ActionType::InvalidAction:
182             RELEASE_ASSERT_NOT_REACHED();
183         }
184     }
185
186     if (css.length()) {
187         Ref<StyleSheetContents> styleSheet = StyleSheetContents::create();
188         styleSheet->setIsUserStyleSheet(true);
189
190         if (styleSheet->parseString(css.toString())) {
191             if (resourceType == ResourceType::Document)
192                 initiatingDocumentLoader.addPendingContentExtensionSheet(styleSheet);
193             else if (currentDocument)
194                 currentDocument->styleSheetCollection().addUserSheet(WTF::move(styleSheet));
195         }
196     }
197
198     if (willBlockLoad)
199         request = ResourceRequest();
200 }
201
202 const String& ContentExtensionsBackend::displayNoneCSSRule()
203 {
204     static NeverDestroyed<const String> rule(ASCIILiteral("{display:none !important;}\n"));
205     return rule;
206 }
207
208 } // namespace ContentExtensions
209
210 } // namespace WebCore
211
212 #endif // ENABLE(CONTENT_EXTENSIONS)