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