Suspended page persists even after back/forward list item is gone
[WebKit-https.git] / Source / WebKit / UIProcess / WebProcessPool.h
1 /*
2  * Copyright (C) 2010-2016 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 "APIDictionary.h"
29 #include "APIObject.h"
30 #include "APIProcessPoolConfiguration.h"
31 #include "APIWebsiteDataStore.h"
32 #include "DownloadProxyMap.h"
33 #include "GenericCallback.h"
34 #include "HiddenPageThrottlingAutoIncreasesCounter.h"
35 #include "MessageReceiver.h"
36 #include "MessageReceiverMap.h"
37 #include "NetworkProcessProxy.h"
38 #include "PlugInAutoStartProvider.h"
39 #include "PluginInfoStore.h"
40 #include "ProcessThrottler.h"
41 #include "ServiceWorkerProcessProxy.h"
42 #include "StatisticsRequest.h"
43 #include "VisitedLinkStore.h"
44 #include "WebContextClient.h"
45 #include "WebContextConnectionClient.h"
46 #include "WebProcessProxy.h"
47 #include <WebCore/SecurityOriginHash.h>
48 #include <WebCore/SharedStringHash.h>
49 #include <pal/SessionID.h>
50 #include <wtf/Forward.h>
51 #include <wtf/HashMap.h>
52 #include <wtf/HashSet.h>
53 #include <wtf/MemoryPressureHandler.h>
54 #include <wtf/ProcessID.h>
55 #include <wtf/RefCounter.h>
56 #include <wtf/RefPtr.h>
57 #include <wtf/text/StringHash.h>
58 #include <wtf/text/WTFString.h>
59
60 #if ENABLE(MEDIA_SESSION)
61 #include "WebMediaSessionFocusManager.h"
62 #endif
63
64 #if USE(SOUP)
65 #include <WebCore/SoupNetworkProxySettings.h>
66 #endif
67
68 #if PLATFORM(COCOA)
69 OBJC_CLASS NSMutableDictionary;
70 OBJC_CLASS NSObject;
71 OBJC_CLASS NSString;
72 #endif
73
74 namespace API {
75 class AutomationClient;
76 class CustomProtocolManagerClient;
77 class DownloadClient;
78 class HTTPCookieStore;
79 class InjectedBundleClient;
80 class LegacyContextHistoryClient;
81 class Navigation;
82 class PageConfiguration;
83 }
84
85 namespace WebCore {
86 struct MockMediaDevice;
87 }
88
89 namespace WebKit {
90
91 class DownloadProxy;
92 class HighPerformanceGraphicsUsageSampler;
93 class UIGamepad;
94 class PerActivityStateCPUUsageSampler;
95 class ServiceWorkerProcessProxy;
96 class WebAutomationSession;
97 class WebContextSupplement;
98 class WebPageGroup;
99 class WebPageProxy;
100 struct NetworkProcessCreationParameters;
101 struct StatisticsData;
102 struct WebProcessCreationParameters;
103     
104 typedef GenericCallback<API::Dictionary*> DictionaryCallback;
105
106 #if PLATFORM(COCOA)
107 int networkProcessLatencyQOS();
108 int networkProcessThroughputQOS();
109 int webProcessLatencyQOS();
110 int webProcessThroughputQOS();
111 #endif
112
113 enum class ProcessSwapRequestedByClient;
114
115 class WebProcessPool final : public API::ObjectImpl<API::Object::Type::ProcessPool>, public CanMakeWeakPtr<WebProcessPool>, private IPC::MessageReceiver {
116 public:
117     static Ref<WebProcessPool> create(API::ProcessPoolConfiguration&);
118
119     explicit WebProcessPool(API::ProcessPoolConfiguration&);        
120     virtual ~WebProcessPool();
121
122     void notifyThisWebProcessPoolWasCreated();
123
124     API::ProcessPoolConfiguration& configuration() { return m_configuration.get(); }
125
126     static const Vector<WebProcessPool*>& allProcessPools();
127
128     template <typename T>
129     T* supplement()
130     {
131         return static_cast<T*>(m_supplements.get(T::supplementName()));
132     }
133
134     template <typename T>
135     void addSupplement()
136     {
137         m_supplements.add(T::supplementName(), T::create(this));
138     }
139
140     void addMessageReceiver(IPC::StringReference messageReceiverName, IPC::MessageReceiver&);
141     void addMessageReceiver(IPC::StringReference messageReceiverName, uint64_t destinationID, IPC::MessageReceiver&);
142     void removeMessageReceiver(IPC::StringReference messageReceiverName);
143     void removeMessageReceiver(IPC::StringReference messageReceiverName, uint64_t destinationID);
144
145     bool dispatchMessage(IPC::Connection&, IPC::Decoder&);
146     bool dispatchSyncMessage(IPC::Connection&, IPC::Decoder&, std::unique_ptr<IPC::Encoder>&);
147
148     void initializeClient(const WKContextClientBase*);
149     void setInjectedBundleClient(std::unique_ptr<API::InjectedBundleClient>&&);
150     void initializeConnectionClient(const WKContextConnectionClientBase*);
151     void setHistoryClient(std::unique_ptr<API::LegacyContextHistoryClient>&&);
152     void setDownloadClient(std::unique_ptr<API::DownloadClient>&&);
153     void setAutomationClient(std::unique_ptr<API::AutomationClient>&&);
154     void setLegacyCustomProtocolManagerClient(std::unique_ptr<API::CustomProtocolManagerClient>&&);
155
156     void setMaximumNumberOfProcesses(unsigned); // Can only be called when there are no processes running.
157     unsigned maximumNumberOfProcesses() const { return !m_configuration->maximumProcessCount() ? UINT_MAX : m_configuration->maximumProcessCount(); }
158
159     void setCustomWebContentServiceBundleIdentifier(const String&);
160     const String& customWebContentServiceBundleIdentifier() { return m_configuration->customWebContentServiceBundleIdentifier(); }
161
162     const Vector<RefPtr<WebProcessProxy>>& processes() const { return m_processes; }
163
164     // WebProcess or NetworkProcess as approporiate for current process model. The connection must be non-null.
165     IPC::Connection* networkingProcessConnection();
166
167     template<typename T> void sendToAllProcesses(const T& message);
168     template<typename T> void sendToAllProcessesRelaunchingThemIfNecessary(const T& message);
169     template<typename T> void sendToOneProcess(T&& message);
170
171     // Sends the message to WebProcess or NetworkProcess as approporiate for current process model.
172     template<typename T> void sendToNetworkingProcess(T&& message);
173     template<typename T, typename U> void sendSyncToNetworkingProcess(T&& message, U&& reply);
174     template<typename T> void sendToNetworkingProcessRelaunchingIfNecessary(T&& message);
175
176     void processDidFinishLaunching(WebProcessProxy*);
177
178     // Disconnect the process from the context.
179     void disconnectProcess(WebProcessProxy*);
180
181     API::WebsiteDataStore* websiteDataStore() const { return m_websiteDataStore.get(); }
182     void setPrimaryDataStore(API::WebsiteDataStore& dataStore) { m_websiteDataStore = &dataStore; }
183
184     Ref<WebPageProxy> createWebPage(PageClient&, Ref<API::PageConfiguration>&&);
185
186     void pageBeginUsingWebsiteDataStore(WebPageProxy&);
187     void pageEndUsingWebsiteDataStore(WebPageProxy&);
188
189     const String& injectedBundlePath() const { return m_configuration->injectedBundlePath(); }
190
191     DownloadProxy* download(WebPageProxy* initiatingPage, const WebCore::ResourceRequest&, const String& suggestedFilename = { });
192     DownloadProxy* resumeDownload(const API::Data* resumeData, const String& path);
193
194     void setInjectedBundleInitializationUserData(RefPtr<API::Object>&& userData) { m_injectedBundleInitializationUserData = WTFMove(userData); }
195
196     void postMessageToInjectedBundle(const String&, API::Object*);
197
198     void populateVisitedLinks();
199
200     void handleMemoryPressureWarning(Critical);
201
202 #if ENABLE(NETSCAPE_PLUGIN_API)
203     void setAdditionalPluginsDirectory(const String&);
204     void refreshPlugins();
205
206     PluginInfoStore& pluginInfoStore() { return m_pluginInfoStore; }
207
208     void setPluginLoadClientPolicy(WebCore::PluginLoadClientPolicy, const String& host, const String& bundleIdentifier, const String& versionString);
209     void resetPluginLoadClientPolicies(HashMap<String, HashMap<String, HashMap<String, uint8_t>>>&&);
210     void clearPluginClientPolicies();
211     const HashMap<String, HashMap<String, HashMap<String, uint8_t>>>& pluginLoadClientPolicies() const { return m_pluginLoadClientPolicies; }
212 #endif
213
214     void addSupportedPlugin(String&& matchingDomain, String&& name, HashSet<String>&& mimeTypes, HashSet<String> extensions);
215     void clearSupportedPlugins();
216
217     ProcessID networkProcessIdentifier();
218     Vector<String> activePagesOriginsInWebProcessForTesting(ProcessID);
219     bool networkProcessHasEntitlementForTesting(const String&);
220
221     WebPageGroup& defaultPageGroup() { return m_defaultPageGroup.get(); }
222
223     void setAlwaysUsesComplexTextCodePath(bool);
224     void setShouldUseFontSmoothing(bool);
225     
226     void registerURLSchemeAsEmptyDocument(const String&);
227     void registerURLSchemeAsSecure(const String&);
228     void registerURLSchemeAsBypassingContentSecurityPolicy(const String&);
229     void setDomainRelaxationForbiddenForURLScheme(const String&);
230     void setCanHandleHTTPSServerTrustEvaluation(bool);
231     void registerURLSchemeAsLocal(const String&);
232     void registerURLSchemeAsNoAccess(const String&);
233     void registerURLSchemeAsDisplayIsolated(const String&);
234     void registerURLSchemeAsCORSEnabled(const String&);
235     void registerURLSchemeAsCachePartitioned(const String&);
236     void registerURLSchemeServiceWorkersCanHandle(const String&);
237     void registerURLSchemeAsCanDisplayOnlyIfCanRequest(const String&);
238
239     void preconnectToServer(const WebCore::URL&);
240
241     VisitedLinkStore& visitedLinkStore() { return m_visitedLinkStore.get(); }
242
243     void setCacheModel(CacheModel);
244     CacheModel cacheModel() const { return m_configuration->cacheModel(); }
245
246     void setDefaultRequestTimeoutInterval(double);
247
248     void startMemorySampler(const double interval);
249     void stopMemorySampler();
250
251 #if USE(SOUP)
252     void setInitialHTTPCookieAcceptPolicy(HTTPCookieAcceptPolicy policy) { m_initialHTTPCookieAcceptPolicy = policy; }
253     void setNetworkProxySettings(const WebCore::SoupNetworkProxySettings&);
254 #endif
255     void setEnhancedAccessibility(bool);
256     
257     // Downloads.
258     DownloadProxy* createDownloadProxy(const WebCore::ResourceRequest&, WebPageProxy* originatingPage);
259     API::DownloadClient& downloadClient() { return *m_downloadClient; }
260
261     API::LegacyContextHistoryClient& historyClient() { return *m_historyClient; }
262     WebContextClient& client() { return m_client; }
263
264     API::CustomProtocolManagerClient& customProtocolManagerClient() const { return *m_customProtocolManagerClient; }
265
266     struct Statistics {
267         unsigned wkViewCount;
268         unsigned wkPageCount;
269         unsigned wkFrameCount;
270     };
271     static Statistics& statistics();    
272
273     void useTestingNetworkSession();
274     bool isUsingTestingNetworkSession() const { return m_shouldUseTestingNetworkSession; }
275
276     void setAllowsAnySSLCertificateForWebSocket(bool);
277
278     void clearCachedCredentials();
279     void terminateNetworkProcess();
280     void terminateServiceWorkerProcesses();
281     void disableServiceWorkerProcessTerminationDelay();
282
283     void syncNetworkProcessCookies();
284
285     void setIDBPerOriginQuota(uint64_t);
286
287     void setShouldMakeNextWebProcessLaunchFailForTesting(bool value) { m_shouldMakeNextWebProcessLaunchFailForTesting = value; }
288     bool shouldMakeNextWebProcessLaunchFailForTesting() const { return m_shouldMakeNextWebProcessLaunchFailForTesting; }
289     void setShouldMakeNextNetworkProcessLaunchFailForTesting(bool value) { m_shouldMakeNextNetworkProcessLaunchFailForTesting = value; }
290     bool shouldMakeNextNetworkProcessLaunchFailForTesting() const { return m_shouldMakeNextNetworkProcessLaunchFailForTesting; }
291
292     void reportWebContentCPUTime(Seconds cpuTime, uint64_t activityState);
293
294     void allowSpecificHTTPSCertificateForHost(const WebCertificateInfo*, const String& host);
295
296     WebProcessProxy& createNewWebProcessRespectingProcessCountLimit(WebsiteDataStore&); // Will return an existing one if limit is met.
297     void prewarmProcess();
298
299     bool shouldTerminate(WebProcessProxy*);
300
301     void disableProcessTermination() { m_processTerminationEnabled = false; }
302     void enableProcessTermination();
303
304     void updateAutomationCapabilities() const;
305     void setAutomationSession(RefPtr<WebAutomationSession>&&);
306     WebAutomationSession* automationSession() const { return m_automationSession.get(); }
307
308     // Defaults to false.
309     void setHTTPPipeliningEnabled(bool);
310     bool httpPipeliningEnabled() const;
311
312     void getStatistics(uint32_t statisticsMask, Function<void (API::Dictionary*, CallbackBase::Error)>&&);
313     
314     bool javaScriptConfigurationFileEnabled() { return m_javaScriptConfigurationFileEnabled; }
315     void setJavaScriptConfigurationFileEnabled(bool flag);
316 #if PLATFORM(IOS_FAMILY)
317     void setJavaScriptConfigurationFileEnabledFromDefaults();
318 #endif
319
320     void garbageCollectJavaScriptObjects();
321     void setJavaScriptGarbageCollectorTimerEnabled(bool flag);
322
323 #if PLATFORM(COCOA)
324     static bool omitPDFSupport();
325 #endif
326
327     void fullKeyboardAccessModeChanged(bool fullKeyboardAccessEnabled);
328 #if OS(LINUX)
329     void sendMemoryPressureEvent(bool isCritical);
330 #endif
331     void textCheckerStateChanged();
332
333     Ref<API::Dictionary> plugInAutoStartOriginHashes() const;
334     void setPlugInAutoStartOriginHashes(API::Dictionary&);
335     void setPlugInAutoStartOrigins(API::Array&);
336     void setPlugInAutoStartOriginsFilteringOutEntriesAddedAfterTime(API::Dictionary&, WallTime);
337
338     // Network Process Management
339     NetworkProcessProxy& ensureNetworkProcess(WebsiteDataStore* withWebsiteDataStore = nullptr);
340     NetworkProcessProxy* networkProcess() { return m_networkProcess.get(); }
341     void networkProcessCrashed(NetworkProcessProxy&, Vector<std::pair<RefPtr<WebProcessProxy>, Messages::WebProcessProxy::GetNetworkProcessConnection::DelayedReply>>&&);
342
343     void getNetworkProcessConnection(WebProcessProxy&, Messages::WebProcessProxy::GetNetworkProcessConnection::DelayedReply&&);
344
345 #if ENABLE(SERVICE_WORKER)
346     void establishWorkerContextConnectionToNetworkProcess(NetworkProcessProxy&, WebCore::SecurityOriginData&&, std::optional<PAL::SessionID>);
347     ServiceWorkerProcessProxy* serviceWorkerProcessProxyFromPageID(uint64_t pageID) const;
348     const HashMap<WebCore::SecurityOriginData, ServiceWorkerProcessProxy*>& serviceWorkerProxies() const { return m_serviceWorkerProcesses; }
349     void setAllowsAnySSLCertificateForServiceWorker(bool allows) { m_allowsAnySSLCertificateForServiceWorker = allows; }
350     bool allowsAnySSLCertificateForServiceWorker() const { return m_allowsAnySSLCertificateForServiceWorker; }
351     void updateServiceWorkerUserAgent(const String& userAgent);
352     bool mayHaveRegisteredServiceWorkers(const WebsiteDataStore&);
353 #endif
354
355 #if PLATFORM(COCOA)
356     bool processSuppressionEnabled() const;
357 #endif
358
359     void windowServerConnectionStateChanged();
360
361     static void willStartUsingPrivateBrowsing();
362     static void willStopUsingPrivateBrowsing();
363
364 #if USE(SOUP)
365     void setIgnoreTLSErrors(bool);
366     bool ignoreTLSErrors() const { return m_ignoreTLSErrors; }
367 #endif
368
369     static void setInvalidMessageCallback(void (*)(WKStringRef));
370     static void didReceiveInvalidMessage(const IPC::StringReference& messageReceiverName, const IPC::StringReference& messageName);
371
372     void processDidCachePage(WebProcessProxy*);
373
374     bool isURLKnownHSTSHost(const String& urlString, bool privateBrowsingEnabled) const;
375     void resetHSTSHosts();
376     void resetHSTSHostsAddedAfterDate(double startDateIntervalSince1970);
377
378     void registerSchemeForCustomProtocol(const String&);
379     void unregisterSchemeForCustomProtocol(const String&);
380
381     static void registerGlobalURLSchemeAsHavingCustomProtocolHandlers(const String&);
382     static void unregisterGlobalURLSchemeAsHavingCustomProtocolHandlers(const String&);
383
384 #if PLATFORM(COCOA)
385     void updateProcessSuppressionState();
386
387     NSMutableDictionary *ensureBundleParameters();
388     NSMutableDictionary *bundleParameters() { return m_bundleParameters.get(); }
389 #else
390     void updateProcessSuppressionState() const { }
391 #endif
392
393     void updateHiddenPageThrottlingAutoIncreaseLimit();
394
395     void setMemoryCacheDisabled(bool);
396     void setFontWhitelist(API::Array*);
397
398     UserObservablePageCounter::Token userObservablePageCount()
399     {
400         return m_userObservablePageCounter.count();
401     }
402
403     ProcessSuppressionDisabledToken processSuppressionDisabledForPageCount()
404     {
405         return m_processSuppressionDisabledForPageCounter.count();
406     }
407
408     HiddenPageThrottlingAutoIncreasesCounter::Token hiddenPageThrottlingAutoIncreasesCount()
409     {
410         return m_hiddenPageThrottlingAutoIncreasesCounter.count();
411     }
412
413     void setResourceLoadStatisticsEnabled(bool);
414     void clearResourceLoadStatistics();
415
416     bool alwaysRunsAtBackgroundPriority() const { return m_alwaysRunsAtBackgroundPriority; }
417     bool shouldTakeUIBackgroundAssertion() const { return m_shouldTakeUIBackgroundAssertion; }
418
419 #if ENABLE(GAMEPAD)
420     void gamepadConnected(const UIGamepad&);
421     void gamepadDisconnected(const UIGamepad&);
422
423     void setInitialConnectedGamepads(const Vector<std::unique_ptr<UIGamepad>>&);
424 #endif
425
426 #if PLATFORM(COCOA)
427     bool cookieStoragePartitioningEnabled() const { return m_cookieStoragePartitioningEnabled; }
428     void setCookieStoragePartitioningEnabled(bool);
429     bool storageAccessAPIEnabled() const { return m_storageAccessAPIEnabled; }
430     void setStorageAccessAPIEnabled(bool);
431 #endif
432
433 #if ENABLE(SERVICE_WORKER)
434     void postMessageToServiceWorkerClient(const WebCore::ServiceWorkerClientIdentifier& destinationIdentifier, WebCore::MessageWithMessagePorts&&, WebCore::ServiceWorkerIdentifier sourceIdentifier, const String& sourceOrigin);
435     void postMessageToServiceWorker(WebCore::ServiceWorkerIdentifier destination, WebCore::MessageWithMessagePorts&&, const WebCore::ServiceWorkerOrClientIdentifier& source, WebCore::SWServerConnectionIdentifier);
436 #endif
437
438     static uint64_t registerProcessPoolCreationListener(Function<void(WebProcessPool&)>&&);
439     static void unregisterProcessPoolCreationListener(uint64_t identifier);
440
441 #if PLATFORM(IOS_FAMILY)
442     ForegroundWebProcessToken foregroundWebProcessToken() const { return ForegroundWebProcessToken(m_foregroundWebProcessCounter.count()); }
443     BackgroundWebProcessToken backgroundWebProcessToken() const { return BackgroundWebProcessToken(m_backgroundWebProcessCounter.count()); }
444 #endif
445
446     Ref<WebProcessProxy> processForNavigation(WebPageProxy&, const API::Navigation&, ProcessSwapRequestedByClient, String& reason);
447
448     // SuspendedPageProxy management.
449     void addSuspendedPage(std::unique_ptr<SuspendedPageProxy>&&);
450     void removeAllSuspendedPagesForPage(WebPageProxy&);
451     std::unique_ptr<SuspendedPageProxy> takeSuspendedPage(SuspendedPageProxy&);
452     void removeSuspendedPage(SuspendedPageProxy&);
453     bool hasSuspendedPageFor(WebProcessProxy&) const;
454     unsigned maxSuspendedPageCount() const { return m_maxSuspendedPageCount; }
455
456     void didReachGoodTimeToPrewarm();
457
458     void didCollectPrewarmInformation(const String& registrableDomain, const WebCore::PrewarmInformation&);
459
460     void screenPropertiesStateChanged();
461
462     void addMockMediaDevice(const WebCore::MockMediaDevice&);
463     void clearMockMediaDevices();
464     void removeMockMediaDevice(const String& persistentId);
465     void resetMockMediaDevices();
466
467     void sendDisplayConfigurationChangedMessageForTesting();
468
469 #if PLATFORM(GTK) || PLATFORM(WPE)
470     void setSandboxEnabled(bool enabled) { m_sandboxEnabled = enabled; };
471     bool sandboxEnabled() const { return m_sandboxEnabled; };
472 #endif
473
474 private:
475     void platformInitialize();
476
477     void platformInitializeWebProcess(WebProcessCreationParameters&);
478     void platformInvalidateContext();
479
480     Ref<WebProcessProxy> processForNavigationInternal(WebPageProxy&, const API::Navigation&, ProcessSwapRequestedByClient, String& reason);
481
482     RefPtr<WebProcessProxy> tryTakePrewarmedProcess(WebsiteDataStore&);
483
484     WebProcessProxy& createNewWebProcess(WebsiteDataStore&, WebProcessProxy::IsPrewarmed = WebProcessProxy::IsPrewarmed::No);
485     void initializeNewWebProcess(WebProcessProxy&, WebsiteDataStore&);
486
487     void requestWebContentStatistics(StatisticsRequest*);
488     void requestNetworkingStatistics(StatisticsRequest*);
489
490     void platformInitializeNetworkProcess(NetworkProcessCreationParameters&);
491
492     void handleMessage(IPC::Connection&, const String& messageName, const UserData& messageBody);
493     void handleSynchronousMessage(IPC::Connection&, const String& messageName, const UserData& messageBody, UserData& returnUserData);
494
495     void didGetStatistics(const StatisticsData&, uint64_t callbackID);
496
497 #if ENABLE(GAMEPAD)
498     void startedUsingGamepads(IPC::Connection&);
499     void stoppedUsingGamepads(IPC::Connection&);
500
501     void processStoppedUsingGamepads(WebProcessProxy&);
502 #endif
503
504     void reinstateNetworkProcessAssertionState(NetworkProcessProxy&);
505     void updateProcessAssertions();
506
507     // IPC::MessageReceiver.
508     // Implemented in generated WebProcessPoolMessageReceiver.cpp
509     void didReceiveMessage(IPC::Connection&, IPC::Decoder&) override;
510     void didReceiveSyncMessage(IPC::Connection&, IPC::Decoder&, std::unique_ptr<IPC::Encoder>&) override;
511
512     static void languageChanged(void* context);
513     void languageChanged();
514
515 #if PLATFORM(IOS_FAMILY)
516     String cookieStorageDirectory() const;
517 #endif
518
519 #if PLATFORM(IOS_FAMILY)
520     String parentBundleDirectory() const;
521     String networkingCachesDirectory() const;
522     String webContentCachesDirectory() const;
523     String containerTemporaryDirectory() const;
524 #endif
525
526 #if PLATFORM(COCOA)
527     void registerNotificationObservers();
528     void unregisterNotificationObservers();
529 #endif
530
531     void addPlugInAutoStartOriginHash(const String& pageOrigin, unsigned plugInOriginHash, PAL::SessionID);
532     void plugInDidReceiveUserInteraction(unsigned plugInOriginHash, PAL::SessionID);
533
534     void setAnyPageGroupMightHavePrivateBrowsingEnabled(bool);
535
536     void resolvePathsForSandboxExtensions();
537     void platformResolvePathsForSandboxExtensions();
538
539     void addProcessToOriginCacheSet(WebPageProxy&);
540     void removeProcessFromOriginCacheSet(WebProcessProxy&);
541
542     void tryPrewarmWithDomainInformation(WebProcessProxy&, const WebCore::URL&);
543
544     void updateMaxSuspendedPageCount();
545
546     Ref<API::ProcessPoolConfiguration> m_configuration;
547
548     IPC::MessageReceiverMap m_messageReceiverMap;
549
550     Vector<RefPtr<WebProcessProxy>> m_processes;
551     WebProcessProxy* m_prewarmedProcess { nullptr };
552
553     WebProcessProxy* m_processWithPageCache { nullptr };
554 #if ENABLE(SERVICE_WORKER)
555     HashMap<WebCore::SecurityOriginData, ServiceWorkerProcessProxy*> m_serviceWorkerProcesses;
556     bool m_waitingForWorkerContextProcessConnection { false };
557     bool m_allowsAnySSLCertificateForServiceWorker { false };
558     bool m_shouldDisableServiceWorkerProcessTerminationDelay { false };
559     String m_serviceWorkerUserAgent;
560     std::optional<WebPreferencesStore> m_serviceWorkerPreferences;
561     HashMap<String, bool> m_mayHaveRegisteredServiceWorkers;
562 #endif
563
564     Ref<WebPageGroup> m_defaultPageGroup;
565
566     RefPtr<API::Object> m_injectedBundleInitializationUserData;
567     std::unique_ptr<API::InjectedBundleClient> m_injectedBundleClient;
568
569     WebContextClient m_client;
570     WebContextConnectionClient m_connectionClient;
571     std::unique_ptr<API::AutomationClient> m_automationClient;
572     std::unique_ptr<API::DownloadClient> m_downloadClient;
573     std::unique_ptr<API::LegacyContextHistoryClient> m_historyClient;
574     std::unique_ptr<API::CustomProtocolManagerClient> m_customProtocolManagerClient;
575
576     RefPtr<WebAutomationSession> m_automationSession;
577
578 #if ENABLE(NETSCAPE_PLUGIN_API)
579     PluginInfoStore m_pluginInfoStore;
580 #endif
581     Ref<VisitedLinkStore> m_visitedLinkStore;
582     bool m_visitedLinksPopulated { false };
583
584     PlugInAutoStartProvider m_plugInAutoStartProvider { this };
585         
586     HashSet<String> m_schemesToRegisterAsEmptyDocument;
587     HashSet<String> m_schemesToRegisterAsSecure;
588     HashSet<String> m_schemesToRegisterAsBypassingContentSecurityPolicy;
589     HashSet<String> m_schemesToSetDomainRelaxationForbiddenFor;
590     HashSet<String> m_schemesToRegisterAsLocal;
591     HashSet<String> m_schemesToRegisterAsNoAccess;
592     HashSet<String> m_schemesToRegisterAsDisplayIsolated;
593     HashSet<String> m_schemesToRegisterAsCORSEnabled;
594     HashSet<String> m_schemesToRegisterAsAlwaysRevalidated;
595     HashSet<String> m_schemesToRegisterAsCachePartitioned;
596     HashSet<String> m_schemesServiceWorkersCanHandle;
597     HashSet<String> m_schemesToRegisterAsCanDisplayOnlyIfCanRequest;
598
599     bool m_alwaysUsesComplexTextCodePath { false };
600     bool m_shouldUseFontSmoothing { true };
601
602     Vector<String> m_fontWhitelist;
603
604     // Messages that were posted before any pages were created.
605     // The client should use initialization messages instead, so that a restarted process would get the same state.
606     Vector<std::pair<String, RefPtr<API::Object>>> m_messagesToInjectedBundlePostedToEmptyContext;
607
608     bool m_memorySamplerEnabled { false };
609     double m_memorySamplerInterval { 1400.0 };
610
611     RefPtr<API::WebsiteDataStore> m_websiteDataStore;
612
613     typedef HashMap<const char*, RefPtr<WebContextSupplement>, PtrHash<const char*>> WebContextSupplementMap;
614     WebContextSupplementMap m_supplements;
615
616 #if USE(SOUP)
617     HTTPCookieAcceptPolicy m_initialHTTPCookieAcceptPolicy { HTTPCookieAcceptPolicyOnlyFromMainDocumentDomain };
618     WebCore::SoupNetworkProxySettings m_networkProxySettings;
619 #endif
620     HashSet<String, ASCIICaseInsensitiveHash> m_urlSchemesRegisteredForCustomProtocols;
621
622 #if PLATFORM(MAC)
623     RetainPtr<NSObject> m_enhancedAccessibilityObserver;
624     RetainPtr<NSObject> m_automaticTextReplacementNotificationObserver;
625     RetainPtr<NSObject> m_automaticSpellingCorrectionNotificationObserver;
626     RetainPtr<NSObject> m_automaticQuoteSubstitutionNotificationObserver;
627     RetainPtr<NSObject> m_automaticDashSubstitutionNotificationObserver;
628     RetainPtr<NSObject> m_accessibilityDisplayOptionsNotificationObserver;
629 #if ENABLE(WEBPROCESS_WINDOWSERVER_BLOCKING)
630     RetainPtr<NSObject> m_scrollerStyleNotificationObserver;
631 #endif
632
633     std::unique_ptr<HighPerformanceGraphicsUsageSampler> m_highPerformanceGraphicsUsageSampler;
634     std::unique_ptr<PerActivityStateCPUUsageSampler> m_perActivityStateCPUUsageSampler;
635 #endif
636
637     bool m_shouldUseTestingNetworkSession { false };
638
639     bool m_processTerminationEnabled { true };
640
641     bool m_canHandleHTTPSServerTrustEvaluation { true };
642     bool m_didNetworkProcessCrash { false };
643     std::unique_ptr<NetworkProcessProxy> m_networkProcess;
644
645     HashMap<uint64_t, RefPtr<DictionaryCallback>> m_dictionaryCallbacks;
646     HashMap<uint64_t, RefPtr<StatisticsRequest>> m_statisticsRequests;
647
648 #if USE(SOUP)
649     bool m_ignoreTLSErrors { true };
650 #endif
651
652     bool m_memoryCacheDisabled { false };
653     bool m_javaScriptConfigurationFileEnabled { false };
654     bool m_alwaysRunsAtBackgroundPriority;
655     bool m_shouldTakeUIBackgroundAssertion;
656     bool m_shouldMakeNextWebProcessLaunchFailForTesting { false };
657     bool m_shouldMakeNextNetworkProcessLaunchFailForTesting { false };
658
659     UserObservablePageCounter m_userObservablePageCounter;
660     ProcessSuppressionDisabledCounter m_processSuppressionDisabledForPageCounter;
661     HiddenPageThrottlingAutoIncreasesCounter m_hiddenPageThrottlingAutoIncreasesCounter;
662     RunLoop::Timer<WebProcessPool> m_hiddenPageThrottlingTimer;
663
664 #if PLATFORM(COCOA)
665     RetainPtr<NSMutableDictionary> m_bundleParameters;
666     ProcessSuppressionDisabledToken m_pluginProcessManagerProcessSuppressionDisabledToken;
667 #endif
668
669 #if ENABLE(CONTENT_EXTENSIONS)
670     HashMap<String, String> m_encodedContentExtensions;
671 #endif
672
673 #if ENABLE(NETSCAPE_PLUGIN_API)
674     HashMap<String, HashMap<String, HashMap<String, uint8_t>>> m_pluginLoadClientPolicies;
675 #endif
676
677 #if ENABLE(GAMEPAD)
678     HashSet<WebProcessProxy*> m_processesUsingGamepads;
679 #endif
680
681 #if PLATFORM(COCOA)
682     bool m_cookieStoragePartitioningEnabled { false };
683     bool m_storageAccessAPIEnabled { false };
684 #endif
685
686     struct Paths {
687         String injectedBundlePath;
688         String applicationCacheDirectory;
689         String webSQLDatabaseDirectory;
690         String mediaCacheDirectory;
691         String mediaKeyStorageDirectory;
692         String uiProcessBundleResourcePath;
693         String indexedDatabaseDirectory;
694
695 #if PLATFORM(IOS_FAMILY)
696         String cookieStorageDirectory;
697         String containerCachesDirectory;
698         String containerTemporaryDirectory;
699 #endif
700
701         Vector<String> additionalWebProcessSandboxExtensionPaths;
702     };
703     Paths m_resolvedPaths;
704
705     HashMap<PAL::SessionID, HashSet<WebPageProxy*>> m_sessionToPagesMap;
706     RunLoop::Timer<WebProcessPool> m_serviceWorkerProcessesTerminationTimer;
707
708 #if PLATFORM(IOS_FAMILY)
709     ForegroundWebProcessCounter m_foregroundWebProcessCounter;
710     BackgroundWebProcessCounter m_backgroundWebProcessCounter;
711     ProcessThrottler::ForegroundActivityToken m_foregroundTokenForNetworkProcess;
712     ProcessThrottler::BackgroundActivityToken m_backgroundTokenForNetworkProcess;
713 #if ENABLE(SERVICE_WORKER)
714     HashMap<WebCore::SecurityOriginData, ProcessThrottler::ForegroundActivityToken> m_foregroundTokensForServiceWorkerProcesses;
715     HashMap<WebCore::SecurityOriginData, ProcessThrottler::BackgroundActivityToken> m_backgroundTokensForServiceWorkerProcesses;
716 #endif
717 #endif
718
719     Deque<std::unique_ptr<SuspendedPageProxy>> m_suspendedPages;
720     unsigned m_maxSuspendedPageCount { 0 };
721
722     HashMap<String, RefPtr<WebProcessProxy>> m_swappedProcessesPerRegistrableDomain;
723
724     HashMap<String, std::unique_ptr<WebCore::PrewarmInformation>> m_prewarmInformationPerRegistrableDomain;
725
726 #if PLATFORM(GTK) || PLATFORM(WPE)
727     bool m_sandboxEnabled { false };
728 #endif
729 };
730
731 template<typename T>
732 void WebProcessPool::sendToNetworkingProcess(T&& message)
733 {
734     if (m_networkProcess && m_networkProcess->canSendMessage())
735         m_networkProcess->send(std::forward<T>(message), 0);
736 }
737
738 template<typename T>
739 void WebProcessPool::sendToNetworkingProcessRelaunchingIfNecessary(T&& message)
740 {
741     ensureNetworkProcess();
742     m_networkProcess->send(std::forward<T>(message), 0);
743 }
744
745 template<typename T>
746 void WebProcessPool::sendToAllProcesses(const T& message)
747 {
748     size_t processCount = m_processes.size();
749     for (size_t i = 0; i < processCount; ++i) {
750         WebProcessProxy* process = m_processes[i].get();
751         if (process->canSendMessage())
752             process->send(T(message), 0);
753     }
754 }
755
756 template<typename T>
757 void WebProcessPool::sendToAllProcessesRelaunchingThemIfNecessary(const T& message)
758 {
759     // FIXME (Multi-WebProcess): WebProcessPool doesn't track processes that have exited, so it cannot relaunch these. Perhaps this functionality won't be needed in this mode.
760     sendToAllProcesses(message);
761 }
762
763 template<typename T>
764 void WebProcessPool::sendToOneProcess(T&& message)
765 {
766     bool messageSent = false;
767     size_t processCount = m_processes.size();
768     for (size_t i = 0; i < processCount; ++i) {
769         WebProcessProxy* process = m_processes[i].get();
770         if (process->canSendMessage()) {
771             process->send(std::forward<T>(message), 0);
772             messageSent = true;
773             break;
774         }
775     }
776
777     if (!messageSent) {
778         prewarmProcess();
779         RefPtr<WebProcessProxy> process = m_processes.last();
780         if (process->canSendMessage())
781             process->send(std::forward<T>(message), 0);
782     }
783 }
784
785 } // namespace WebKit