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