[PAL] Move HysteresisActivity into PAL
[WebKit-https.git] / Source / WebKit / WebProcess / WebProcess.h
1 /*
2  * Copyright (C) 2010-2017 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 #pragma once
27
28 #include "CacheModel.h"
29 #include "ChildProcess.h"
30 #include "PluginProcessConnectionManager.h"
31 #include "ResourceCachesToClear.h"
32 #include "SandboxExtension.h"
33 #include "TextCheckerState.h"
34 #include "ViewUpdateDispatcher.h"
35 #include "WebInspectorInterruptDispatcher.h"
36 #include <WebCore/ActivityState.h>
37 #include <WebCore/Timer.h>
38 #include <pal/HysteresisActivity.h>
39 #include <pal/SessionID.h>
40 #include <wtf/Forward.h>
41 #include <wtf/HashMap.h>
42 #include <wtf/HashSet.h>
43 #include <wtf/RefCounter.h>
44 #include <wtf/text/AtomicString.h>
45 #include <wtf/text/AtomicStringHash.h>
46
47 #if PLATFORM(COCOA)
48 #include <dispatch/dispatch.h>
49 #include <WebCore/MachSendRight.h>
50 #endif
51
52 #if PLATFORM(IOS)
53 #include "WebSQLiteDatabaseTracker.h"
54 #endif
55
56 namespace API {
57 class Object;
58 }
59
60 namespace PAL {
61 class SessionID;
62 }
63
64 namespace WebCore {
65 class ApplicationCacheStorage;
66 class CPUMonitor;
67 class CertificateInfo;
68 class PageGroup;
69 class ResourceRequest;
70 class UserGestureToken;
71 struct PluginInfo;
72 struct SecurityOriginData;
73 struct SoupNetworkProxySettings;
74 }
75
76 namespace WebKit {
77
78 class EventDispatcher;
79 class GamepadData;
80 class InjectedBundle;
81 class LibWebRTCNetwork;
82 class NetworkProcessConnection;
83 class ObjCObjectGraph;
84 class UserData;
85 class WaylandCompositorDisplay;
86 class WebAutomationSessionProxy;
87 class WebCacheStorageProvider;
88 class WebConnectionToUIProcess;
89 class WebFrame;
90 class WebLoaderStrategy;
91 class WebPage;
92 class WebPageGroupProxy;
93 class WebProcessSupplement;
94 class WebToStorageProcessConnection;
95 enum class WebsiteDataType;
96 struct WebPageCreationParameters;
97 struct WebPageGroupData;
98 struct WebPreferencesStore;
99 struct WebProcessCreationParameters;
100 struct WebsiteData;
101 struct WebsiteDataStoreParameters;
102
103 class WebProcess : public ChildProcess {
104 public:
105     static WebProcess& singleton();
106
107     template <typename T>
108     T* supplement()
109     {
110         return static_cast<T*>(m_supplements.get(T::supplementName()));
111     }
112
113     template <typename T>
114     void addSupplement()
115     {
116         m_supplements.add(T::supplementName(), std::make_unique<T>(*this));
117     }
118
119     WebConnectionToUIProcess* webConnectionToUIProcess() const { return m_webConnection.get(); }
120
121     WebPage* webPage(uint64_t pageID) const;
122     void createWebPage(uint64_t pageID, WebPageCreationParameters&&);
123     void removeWebPage(uint64_t pageID);
124     WebPage* focusedWebPage() const;
125
126     InjectedBundle* injectedBundle() const { return m_injectedBundle.get(); }
127
128 #if PLATFORM(COCOA)
129     const WebCore::MachSendRight& compositingRenderServerPort() const { return m_compositingRenderServerPort; }
130 #endif
131
132     bool shouldPlugInAutoStartFromOrigin(WebPage&, const String& pageOrigin, const String& pluginOrigin, const String& mimeType);
133     void plugInDidStartFromOrigin(const String& pageOrigin, const String& pluginOrigin, const String& mimeType, PAL::SessionID);
134     void plugInDidReceiveUserInteraction(const String& pageOrigin, const String& pluginOrigin, const String& mimeType, PAL::SessionID);
135     void setPluginLoadClientPolicy(uint8_t policy, const String& host, const String& bundleIdentifier, const String& versionString);
136     void resetPluginLoadClientPolicies(const HashMap<String, HashMap<String, HashMap<String, uint8_t>>>&);
137     void clearPluginClientPolicies();
138     void refreshPlugins();
139
140     bool fullKeyboardAccessEnabled() const { return m_fullKeyboardAccessEnabled; }
141
142     WebFrame* webFrame(uint64_t) const;
143     void addWebFrame(uint64_t, WebFrame*);
144     void removeWebFrame(uint64_t);
145
146     WebPageGroupProxy* webPageGroup(WebCore::PageGroup*);
147     WebPageGroupProxy* webPageGroup(uint64_t pageGroupID);
148     WebPageGroupProxy* webPageGroup(const WebPageGroupData&);
149
150     uint64_t userGestureTokenIdentifier(RefPtr<WebCore::UserGestureToken>);
151     void userGestureTokenDestroyed(WebCore::UserGestureToken&);
152     
153     const TextCheckerState& textCheckerState() const { return m_textCheckerState; }
154     void setTextCheckerState(const TextCheckerState&);
155
156     void clearResourceCaches(ResourceCachesToClear = AllResourceCaches);
157     
158 #if ENABLE(NETSCAPE_PLUGIN_API)
159     PluginProcessConnectionManager& pluginProcessConnectionManager();
160 #endif
161
162     EventDispatcher& eventDispatcher() { return *m_eventDispatcher; }
163
164     NetworkProcessConnection& networkConnection();
165     void networkProcessConnectionClosed(NetworkProcessConnection*);
166     WebLoaderStrategy& webLoaderStrategy();
167
168 #if USE(LIBWEBRTC)
169     LibWebRTCNetwork& libWebRTCNetwork();
170 #endif
171
172     void webToStorageProcessConnectionClosed(WebToStorageProcessConnection*);
173     WebToStorageProcessConnection* webToStorageProcessConnection();
174
175     void setCacheModel(uint32_t);
176
177     void ensurePrivateBrowsingSession(PAL::SessionID);
178     void ensureLegacyPrivateBrowsingSessionInNetworkProcess();
179     void addWebsiteDataStore(WebsiteDataStoreParameters&&);
180     void destroySession(PAL::SessionID);
181
182     void pageDidEnterWindow(uint64_t pageID);
183     void pageWillLeaveWindow(uint64_t pageID);
184
185     void nonVisibleProcessCleanupTimerFired();
186
187 #if PLATFORM(COCOA)
188     RetainPtr<CFDataRef> sourceApplicationAuditData() const;
189     void destroyRenderingResources();
190 #endif
191
192     void updateActivePages();
193     void pageActivityStateDidChange(uint64_t pageID, WebCore::ActivityState::Flags changed);
194
195     void setHiddenPageDOMTimerThrottlingIncreaseLimit(int milliseconds);
196
197     void processWillSuspendImminently(bool& handled);
198     void prepareToSuspend();
199     void cancelPrepareToSuspend();
200     void processDidResume();
201
202 #if PLATFORM(IOS)
203     void resetAllGeolocationPermissions();
204 #endif
205
206 #if PLATFORM(WAYLAND)
207     WaylandCompositorDisplay* waylandCompositorDisplay() const { return m_waylandCompositorDisplay.get(); }
208 #endif
209
210     RefPtr<API::Object> transformHandlesToObjects(API::Object*);
211     static RefPtr<API::Object> transformObjectsToHandles(API::Object*);
212
213 #if PLATFORM(COCOA)
214     RefPtr<ObjCObjectGraph> transformHandlesToObjects(ObjCObjectGraph&);
215     static RefPtr<ObjCObjectGraph> transformObjectsToHandles(ObjCObjectGraph&);
216 #endif
217
218 #if ENABLE(SERVICE_CONTROLS)
219     bool hasImageServices() const { return m_hasImageServices; }
220     bool hasSelectionServices() const { return m_hasSelectionServices; }
221     bool hasRichContentServices() const { return m_hasRichContentServices; }
222 #endif
223
224     WebCore::ApplicationCacheStorage& applicationCacheStorage() { return *m_applicationCacheStorage; }
225
226     void prefetchDNS(const String&);
227
228     WebAutomationSessionProxy* automationSessionProxy() { return m_automationSessionProxy.get(); }
229
230     WebCacheStorageProvider& cacheStorageProvider() { return m_cacheStorageProvider.get(); }
231
232 private:
233     WebProcess();
234     ~WebProcess();
235
236     void initializeWebProcess(WebProcessCreationParameters&&);
237     void platformInitializeWebProcess(WebProcessCreationParameters&&);
238
239 #if USE(OS_STATE)
240     void registerWithStateDumper();
241 #endif
242
243     void markAllLayersVolatile(WTF::Function<void()>&& completionHandler);
244     void cancelMarkAllLayersVolatile();
245     void setAllLayerTreeStatesFrozen(bool);
246     void processSuspensionCleanupTimerFired();
247
248     void clearCachedCredentials();
249
250     void platformTerminate();
251     void registerURLSchemeAsEmptyDocument(const String&);
252     void registerURLSchemeAsSecure(const String&) const;
253     void registerURLSchemeAsBypassingContentSecurityPolicy(const String&) const;
254     void setDomainRelaxationForbiddenForURLScheme(const String&) const;
255     void registerURLSchemeAsLocal(const String&) const;
256     void registerURLSchemeAsNoAccess(const String&) const;
257     void registerURLSchemeAsDisplayIsolated(const String&) const;
258     void registerURLSchemeAsCORSEnabled(const String&) const;
259     void registerURLSchemeAsAlwaysRevalidated(const String&) const;
260     void registerURLSchemeAsCachePartitioned(const String&) const;
261     void setDefaultRequestTimeoutInterval(double);
262     void setAlwaysUsesComplexTextCodePath(bool);
263     void setShouldUseFontSmoothing(bool);
264     void setResourceLoadStatisticsEnabled(bool);
265     void clearResourceLoadStatistics();
266     void userPreferredLanguagesChanged(const Vector<String>&) const;
267     void fullKeyboardAccessModeChanged(bool fullKeyboardAccessEnabled);
268
269     bool isPlugInAutoStartOriginHash(unsigned plugInOriginHash, PAL::SessionID);
270     void didAddPlugInAutoStartOriginHash(unsigned plugInOriginHash, double expirationTime, PAL::SessionID);
271     void resetPlugInAutoStartOriginDefaultHashes(const HashMap<unsigned, double>& hashes);
272     void resetPlugInAutoStartOriginHashes(const HashMap<PAL::SessionID, HashMap<unsigned, double>>& hashes);
273
274     void platformSetCacheModel(CacheModel);
275
276     void setEnhancedAccessibility(bool);
277     
278     void startMemorySampler(const SandboxExtension::Handle&, const String&, const double);
279     void stopMemorySampler();
280     
281     void getWebCoreStatistics(uint64_t callbackID);
282     void garbageCollectJavaScriptObjects();
283     void setJavaScriptGarbageCollectorTimerEnabled(bool flag);
284
285     void mainThreadPing();
286     void backgroundResponsivenessPing();
287
288 #if ENABLE(GAMEPAD)
289     void setInitialGamepads(const Vector<GamepadData>&);
290     void gamepadConnected(const GamepadData&);
291     void gamepadDisconnected(unsigned index);
292 #endif
293
294 #if USE(SOUP)
295     void setNetworkProxySettings(const WebCore::SoupNetworkProxySettings&);
296 #endif
297
298     void releasePageCache();
299
300     void fetchWebsiteData(PAL::SessionID, OptionSet<WebsiteDataType>, WebsiteData&);
301     void deleteWebsiteData(PAL::SessionID, OptionSet<WebsiteDataType>, std::chrono::system_clock::time_point modifiedSince);
302     void deleteWebsiteDataForOrigins(PAL::SessionID, OptionSet<WebsiteDataType>, const Vector<WebCore::SecurityOriginData>& origins);
303
304     void setMemoryCacheDisabled(bool);
305
306 #if ENABLE(SERVICE_CONTROLS)
307     void setEnabledServices(bool hasImageServices, bool hasSelectionServices, bool hasRichContentServices);
308 #endif
309
310     void handleInjectedBundleMessage(const String& messageName, const UserData& messageBody);
311     void setInjectedBundleParameter(const String& key, const IPC::DataReference&);
312     void setInjectedBundleParameters(const IPC::DataReference&);
313
314     enum class ShouldAcknowledgeWhenReadyToSuspend { No, Yes };
315     void actualPrepareToSuspend(ShouldAcknowledgeWhenReadyToSuspend);
316
317     void ensureAutomationSessionProxy(const String& sessionIdentifier);
318     void destroyAutomationSessionProxy();
319
320     void logDiagnosticMessageForNetworkProcessCrash();
321     bool hasVisibleWebPage() const;
322     void updateCPULimit();
323     enum class CPUMonitorUpdateReason { LimitHasChanged, VisibilityHasChanged };
324     void updateCPUMonitorState(CPUMonitorUpdateReason);
325
326     // ChildProcess
327     void initializeProcess(const ChildProcessInitializationParameters&) override;
328     void initializeProcessName(const ChildProcessInitializationParameters&) override;
329     void initializeSandbox(const ChildProcessInitializationParameters&, SandboxInitializationParameters&) override;
330     void initializeConnection(IPC::Connection*) override;
331     bool shouldTerminate() override;
332     void terminate() override;
333
334 #if USE(APPKIT)
335     void stopRunLoop() override;
336 #endif
337
338     void platformInitializeProcess(const ChildProcessInitializationParameters&);
339
340     // IPC::Connection::Client
341     friend class WebConnectionToUIProcess;
342     void didReceiveMessage(IPC::Connection&, IPC::Decoder&) override;
343     void didReceiveSyncMessage(IPC::Connection&, IPC::Decoder&, std::unique_ptr<IPC::Encoder>&) override;
344     void didClose(IPC::Connection&) override;
345
346     // Implemented in generated WebProcessMessageReceiver.cpp
347     void didReceiveWebProcessMessage(IPC::Connection&, IPC::Decoder&);
348     void didReceiveSyncWebProcessMessage(IPC::Connection&, IPC::Decoder&, std::unique_ptr<IPC::Encoder>&);
349
350     RefPtr<WebConnectionToUIProcess> m_webConnection;
351
352     HashMap<uint64_t, RefPtr<WebPage>> m_pageMap;
353     HashMap<uint64_t, RefPtr<WebPageGroupProxy>> m_pageGroupMap;
354     RefPtr<InjectedBundle> m_injectedBundle;
355
356     RefPtr<EventDispatcher> m_eventDispatcher;
357 #if PLATFORM(IOS)
358     RefPtr<ViewUpdateDispatcher> m_viewUpdateDispatcher;
359 #endif
360     RefPtr<WebInspectorInterruptDispatcher> m_webInspectorInterruptDispatcher;
361
362     HashMap<PAL::SessionID, HashMap<unsigned, double>> m_plugInAutoStartOriginHashes;
363     HashSet<String> m_plugInAutoStartOrigins;
364
365     bool m_hasSetCacheModel { false };
366     CacheModel m_cacheModel { CacheModelDocumentViewer };
367
368 #if PLATFORM(COCOA)
369     WebCore::MachSendRight m_compositingRenderServerPort;
370 #endif
371
372     bool m_fullKeyboardAccessEnabled { false };
373
374     HashMap<uint64_t, WebFrame*> m_frameMap;
375
376     typedef HashMap<const char*, std::unique_ptr<WebProcessSupplement>, PtrHash<const char*>> WebProcessSupplementMap;
377     WebProcessSupplementMap m_supplements;
378
379     TextCheckerState m_textCheckerState;
380
381     void ensureNetworkProcessConnection();
382     RefPtr<NetworkProcessConnection> m_networkProcessConnection;
383     WebLoaderStrategy& m_webLoaderStrategy;
384
385     Ref<WebCacheStorageProvider> m_cacheStorageProvider;
386
387 #if USE(LIBWEBRTC)
388     std::unique_ptr<LibWebRTCNetwork> m_libWebRTCNetwork;
389 #endif
390
391     HashSet<String> m_dnsPrefetchedHosts;
392     PAL::HysteresisActivity m_dnsPrefetchHystereris;
393
394     std::unique_ptr<WebAutomationSessionProxy> m_automationSessionProxy;
395
396     void ensureWebToStorageProcessConnection();
397     RefPtr<WebToStorageProcessConnection> m_webToStorageProcessConnection;
398
399 #if ENABLE(NETSCAPE_PLUGIN_API)
400     RefPtr<PluginProcessConnectionManager> m_pluginProcessConnectionManager;
401 #endif
402
403 #if ENABLE(SERVICE_CONTROLS)
404     bool m_hasImageServices { false };
405     bool m_hasSelectionServices { false };
406     bool m_hasRichContentServices { false };
407 #endif
408
409     HashSet<uint64_t> m_pagesInWindows;
410     WebCore::Timer m_nonVisibleProcessCleanupTimer;
411
412     RefPtr<WebCore::ApplicationCacheStorage> m_applicationCacheStorage;
413
414 #if PLATFORM(IOS)
415     WebSQLiteDatabaseTracker m_webSQLiteDatabaseTracker;
416 #endif
417
418     enum PageMarkingLayersAsVolatileCounterType { };
419     using PageMarkingLayersAsVolatileCounter = RefCounter<PageMarkingLayersAsVolatileCounterType>;
420     std::unique_ptr<PageMarkingLayersAsVolatileCounter> m_pageMarkingLayersAsVolatileCounter;
421
422     bool m_suppressMemoryPressureHandler { false };
423 #if PLATFORM(MAC)
424     std::unique_ptr<WebCore::CPUMonitor> m_cpuMonitor;
425     std::optional<double> m_cpuLimit;
426 #endif
427
428     HashMap<WebCore::UserGestureToken *, uint64_t> m_userGestureTokens;
429
430 #if PLATFORM(WAYLAND)
431     std::unique_ptr<WaylandCompositorDisplay> m_waylandCompositorDisplay;
432 #endif
433 };
434
435 } // namespace WebKit