Make synchronous IPC introduced in r237267 asynchronous
[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     void activePagesOriginsInWebProcessForTesting(ProcessID, CompletionHandler<void(Vector<String>&&)>&&);
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
298     enum class MayCreateDefaultDataStore { No, Yes };
299     void prewarmProcess(MayCreateDefaultDataStore);
300
301     bool shouldTerminate(WebProcessProxy*);
302
303     void disableProcessTermination() { m_processTerminationEnabled = false; }
304     void enableProcessTermination();
305
306     void updateAutomationCapabilities() const;
307     void setAutomationSession(RefPtr<WebAutomationSession>&&);
308     WebAutomationSession* automationSession() const { return m_automationSession.get(); }
309
310     // Defaults to false.
311     void setHTTPPipeliningEnabled(bool);
312     bool httpPipeliningEnabled() const;
313
314     void getStatistics(uint32_t statisticsMask, Function<void (API::Dictionary*, CallbackBase::Error)>&&);
315     
316     bool javaScriptConfigurationFileEnabled() { return m_javaScriptConfigurationFileEnabled; }
317     void setJavaScriptConfigurationFileEnabled(bool flag);
318 #if PLATFORM(IOS_FAMILY)
319     void setJavaScriptConfigurationFileEnabledFromDefaults();
320 #endif
321
322     void garbageCollectJavaScriptObjects();
323     void setJavaScriptGarbageCollectorTimerEnabled(bool flag);
324
325 #if PLATFORM(COCOA)
326     static bool omitPDFSupport();
327 #endif
328
329     void fullKeyboardAccessModeChanged(bool fullKeyboardAccessEnabled);
330 #if OS(LINUX)
331     void sendMemoryPressureEvent(bool isCritical);
332 #endif
333     void textCheckerStateChanged();
334
335     Ref<API::Dictionary> plugInAutoStartOriginHashes() const;
336     void setPlugInAutoStartOriginHashes(API::Dictionary&);
337     void setPlugInAutoStartOrigins(API::Array&);
338     void setPlugInAutoStartOriginsFilteringOutEntriesAddedAfterTime(API::Dictionary&, WallTime);
339
340     // Network Process Management
341     NetworkProcessProxy& ensureNetworkProcess(WebsiteDataStore* withWebsiteDataStore = nullptr);
342     NetworkProcessProxy* networkProcess() { return m_networkProcess.get(); }
343     void networkProcessCrashed(NetworkProcessProxy&, Vector<std::pair<RefPtr<WebProcessProxy>, Messages::WebProcessProxy::GetNetworkProcessConnection::DelayedReply>>&&);
344
345     void getNetworkProcessConnection(WebProcessProxy&, Messages::WebProcessProxy::GetNetworkProcessConnection::DelayedReply&&);
346
347 #if ENABLE(SERVICE_WORKER)
348     void establishWorkerContextConnectionToNetworkProcess(NetworkProcessProxy&, WebCore::SecurityOriginData&&, std::optional<PAL::SessionID>);
349     ServiceWorkerProcessProxy* serviceWorkerProcessProxyFromPageID(uint64_t pageID) const;
350     const HashMap<WebCore::SecurityOriginData, ServiceWorkerProcessProxy*>& serviceWorkerProxies() const { return m_serviceWorkerProcesses; }
351     void setAllowsAnySSLCertificateForServiceWorker(bool allows) { m_allowsAnySSLCertificateForServiceWorker = allows; }
352     bool allowsAnySSLCertificateForServiceWorker() const { return m_allowsAnySSLCertificateForServiceWorker; }
353     void updateServiceWorkerUserAgent(const String& userAgent);
354     bool mayHaveRegisteredServiceWorkers(const WebsiteDataStore&);
355 #endif
356
357 #if PLATFORM(COCOA)
358     bool processSuppressionEnabled() const;
359 #endif
360
361     void windowServerConnectionStateChanged();
362
363     static void willStartUsingPrivateBrowsing();
364     static void willStopUsingPrivateBrowsing();
365
366 #if USE(SOUP)
367     void setIgnoreTLSErrors(bool);
368     bool ignoreTLSErrors() const { return m_ignoreTLSErrors; }
369 #endif
370
371     static void setInvalidMessageCallback(void (*)(WKStringRef));
372     static void didReceiveInvalidMessage(const IPC::StringReference& messageReceiverName, const IPC::StringReference& messageName);
373
374     void processDidCachePage(WebProcessProxy*);
375
376     bool isURLKnownHSTSHost(const String& urlString, bool privateBrowsingEnabled) const;
377     void resetHSTSHosts();
378     void resetHSTSHostsAddedAfterDate(double startDateIntervalSince1970);
379
380     void registerSchemeForCustomProtocol(const String&);
381     void unregisterSchemeForCustomProtocol(const String&);
382
383     static void registerGlobalURLSchemeAsHavingCustomProtocolHandlers(const String&);
384     static void unregisterGlobalURLSchemeAsHavingCustomProtocolHandlers(const String&);
385
386 #if PLATFORM(COCOA)
387     void updateProcessSuppressionState();
388
389     NSMutableDictionary *ensureBundleParameters();
390     NSMutableDictionary *bundleParameters() { return m_bundleParameters.get(); }
391 #else
392     void updateProcessSuppressionState() const { }
393 #endif
394
395     void updateHiddenPageThrottlingAutoIncreaseLimit();
396
397     void setMemoryCacheDisabled(bool);
398     void setFontWhitelist(API::Array*);
399
400     UserObservablePageCounter::Token userObservablePageCount()
401     {
402         return m_userObservablePageCounter.count();
403     }
404
405     ProcessSuppressionDisabledToken processSuppressionDisabledForPageCount()
406     {
407         return m_processSuppressionDisabledForPageCounter.count();
408     }
409
410     HiddenPageThrottlingAutoIncreasesCounter::Token hiddenPageThrottlingAutoIncreasesCount()
411     {
412         return m_hiddenPageThrottlingAutoIncreasesCounter.count();
413     }
414
415     void setResourceLoadStatisticsEnabled(bool);
416     void clearResourceLoadStatistics();
417
418     bool alwaysRunsAtBackgroundPriority() const { return m_alwaysRunsAtBackgroundPriority; }
419     bool shouldTakeUIBackgroundAssertion() const { return m_shouldTakeUIBackgroundAssertion; }
420
421 #if ENABLE(GAMEPAD)
422     void gamepadConnected(const UIGamepad&);
423     void gamepadDisconnected(const UIGamepad&);
424
425     void setInitialConnectedGamepads(const Vector<std::unique_ptr<UIGamepad>>&);
426 #endif
427
428 #if PLATFORM(COCOA)
429     bool cookieStoragePartitioningEnabled() const { return m_cookieStoragePartitioningEnabled; }
430     void setCookieStoragePartitioningEnabled(bool);
431     bool storageAccessAPIEnabled() const { return m_storageAccessAPIEnabled; }
432     void setStorageAccessAPIEnabled(bool);
433 #endif
434
435 #if ENABLE(SERVICE_WORKER)
436     void postMessageToServiceWorkerClient(const WebCore::ServiceWorkerClientIdentifier& destinationIdentifier, WebCore::MessageWithMessagePorts&&, WebCore::ServiceWorkerIdentifier sourceIdentifier, const String& sourceOrigin);
437     void postMessageToServiceWorker(WebCore::ServiceWorkerIdentifier destination, WebCore::MessageWithMessagePorts&&, const WebCore::ServiceWorkerOrClientIdentifier& source, WebCore::SWServerConnectionIdentifier);
438 #endif
439
440     static uint64_t registerProcessPoolCreationListener(Function<void(WebProcessPool&)>&&);
441     static void unregisterProcessPoolCreationListener(uint64_t identifier);
442
443 #if PLATFORM(IOS_FAMILY)
444     ForegroundWebProcessToken foregroundWebProcessToken() const { return ForegroundWebProcessToken(m_foregroundWebProcessCounter.count()); }
445     BackgroundWebProcessToken backgroundWebProcessToken() const { return BackgroundWebProcessToken(m_backgroundWebProcessCounter.count()); }
446 #endif
447
448     Ref<WebProcessProxy> processForNavigation(WebPageProxy&, const API::Navigation&, ProcessSwapRequestedByClient, String& reason);
449
450     // SuspendedPageProxy management.
451     void addSuspendedPage(std::unique_ptr<SuspendedPageProxy>&&);
452     void removeAllSuspendedPagesForPage(WebPageProxy&);
453     std::unique_ptr<SuspendedPageProxy> takeSuspendedPage(SuspendedPageProxy&);
454     void removeSuspendedPage(SuspendedPageProxy&);
455     bool hasSuspendedPageFor(WebProcessProxy&) const;
456     unsigned maxSuspendedPageCount() const { return m_maxSuspendedPageCount; }
457
458     void didReachGoodTimeToPrewarm();
459
460     void didCollectPrewarmInformation(const String& registrableDomain, const WebCore::PrewarmInformation&);
461
462     void screenPropertiesStateChanged();
463
464     void addMockMediaDevice(const WebCore::MockMediaDevice&);
465     void clearMockMediaDevices();
466     void removeMockMediaDevice(const String& persistentId);
467     void resetMockMediaDevices();
468
469     void sendDisplayConfigurationChangedMessageForTesting();
470
471 #if PLATFORM(GTK) || PLATFORM(WPE)
472     void setSandboxEnabled(bool enabled) { m_sandboxEnabled = enabled; };
473     bool sandboxEnabled() const { return m_sandboxEnabled; };
474 #endif
475
476 private:
477     void platformInitialize();
478
479     void platformInitializeWebProcess(WebProcessCreationParameters&);
480     void platformInvalidateContext();
481
482     Ref<WebProcessProxy> processForNavigationInternal(WebPageProxy&, const API::Navigation&, ProcessSwapRequestedByClient, String& reason);
483
484     RefPtr<WebProcessProxy> tryTakePrewarmedProcess(WebsiteDataStore&);
485
486     WebProcessProxy& createNewWebProcess(WebsiteDataStore&, WebProcessProxy::IsPrewarmed = WebProcessProxy::IsPrewarmed::No);
487     void initializeNewWebProcess(WebProcessProxy&, WebsiteDataStore&);
488
489     void requestWebContentStatistics(StatisticsRequest*);
490     void requestNetworkingStatistics(StatisticsRequest*);
491
492     void platformInitializeNetworkProcess(NetworkProcessCreationParameters&);
493
494     void handleMessage(IPC::Connection&, const String& messageName, const UserData& messageBody);
495     void handleSynchronousMessage(IPC::Connection&, const String& messageName, const UserData& messageBody, UserData& returnUserData);
496
497     void didGetStatistics(const StatisticsData&, uint64_t callbackID);
498
499 #if ENABLE(GAMEPAD)
500     void startedUsingGamepads(IPC::Connection&);
501     void stoppedUsingGamepads(IPC::Connection&);
502
503     void processStoppedUsingGamepads(WebProcessProxy&);
504 #endif
505
506     void reinstateNetworkProcessAssertionState(NetworkProcessProxy&);
507     void updateProcessAssertions();
508
509     // IPC::MessageReceiver.
510     // Implemented in generated WebProcessPoolMessageReceiver.cpp
511     void didReceiveMessage(IPC::Connection&, IPC::Decoder&) override;
512     void didReceiveSyncMessage(IPC::Connection&, IPC::Decoder&, std::unique_ptr<IPC::Encoder>&) override;
513
514     static void languageChanged(void* context);
515     void languageChanged();
516
517 #if PLATFORM(IOS_FAMILY)
518     String cookieStorageDirectory() const;
519 #endif
520
521 #if PLATFORM(IOS_FAMILY)
522     String parentBundleDirectory() const;
523     String networkingCachesDirectory() const;
524     String webContentCachesDirectory() const;
525     String containerTemporaryDirectory() const;
526 #endif
527
528 #if PLATFORM(COCOA)
529     void registerNotificationObservers();
530     void unregisterNotificationObservers();
531 #endif
532
533     void addPlugInAutoStartOriginHash(const String& pageOrigin, unsigned plugInOriginHash, PAL::SessionID);
534     void plugInDidReceiveUserInteraction(unsigned plugInOriginHash, PAL::SessionID);
535
536     void setAnyPageGroupMightHavePrivateBrowsingEnabled(bool);
537
538     void resolvePathsForSandboxExtensions();
539     void platformResolvePathsForSandboxExtensions();
540
541     void addProcessToOriginCacheSet(WebPageProxy&);
542     void removeProcessFromOriginCacheSet(WebProcessProxy&);
543
544     void tryPrewarmWithDomainInformation(WebProcessProxy&, const WebCore::URL&);
545
546     void updateMaxSuspendedPageCount();
547
548     Ref<API::ProcessPoolConfiguration> m_configuration;
549
550     IPC::MessageReceiverMap m_messageReceiverMap;
551
552     Vector<RefPtr<WebProcessProxy>> m_processes;
553     WebProcessProxy* m_prewarmedProcess { nullptr };
554
555     WebProcessProxy* m_processWithPageCache { nullptr };
556 #if ENABLE(SERVICE_WORKER)
557     HashMap<WebCore::SecurityOriginData, ServiceWorkerProcessProxy*> m_serviceWorkerProcesses;
558     bool m_waitingForWorkerContextProcessConnection { false };
559     bool m_allowsAnySSLCertificateForServiceWorker { false };
560     bool m_shouldDisableServiceWorkerProcessTerminationDelay { false };
561     String m_serviceWorkerUserAgent;
562     std::optional<WebPreferencesStore> m_serviceWorkerPreferences;
563     HashMap<String, bool> m_mayHaveRegisteredServiceWorkers;
564 #endif
565
566     Ref<WebPageGroup> m_defaultPageGroup;
567
568     RefPtr<API::Object> m_injectedBundleInitializationUserData;
569     std::unique_ptr<API::InjectedBundleClient> m_injectedBundleClient;
570
571     WebContextClient m_client;
572     WebContextConnectionClient m_connectionClient;
573     std::unique_ptr<API::AutomationClient> m_automationClient;
574     std::unique_ptr<API::DownloadClient> m_downloadClient;
575     std::unique_ptr<API::LegacyContextHistoryClient> m_historyClient;
576     std::unique_ptr<API::CustomProtocolManagerClient> m_customProtocolManagerClient;
577
578     RefPtr<WebAutomationSession> m_automationSession;
579
580 #if ENABLE(NETSCAPE_PLUGIN_API)
581     PluginInfoStore m_pluginInfoStore;
582 #endif
583     Ref<VisitedLinkStore> m_visitedLinkStore;
584     bool m_visitedLinksPopulated { false };
585
586     PlugInAutoStartProvider m_plugInAutoStartProvider { this };
587         
588     HashSet<String> m_schemesToRegisterAsEmptyDocument;
589     HashSet<String> m_schemesToRegisterAsSecure;
590     HashSet<String> m_schemesToRegisterAsBypassingContentSecurityPolicy;
591     HashSet<String> m_schemesToSetDomainRelaxationForbiddenFor;
592     HashSet<String> m_schemesToRegisterAsLocal;
593     HashSet<String> m_schemesToRegisterAsNoAccess;
594     HashSet<String> m_schemesToRegisterAsDisplayIsolated;
595     HashSet<String> m_schemesToRegisterAsCORSEnabled;
596     HashSet<String> m_schemesToRegisterAsAlwaysRevalidated;
597     HashSet<String> m_schemesToRegisterAsCachePartitioned;
598     HashSet<String> m_schemesServiceWorkersCanHandle;
599     HashSet<String> m_schemesToRegisterAsCanDisplayOnlyIfCanRequest;
600
601     bool m_alwaysUsesComplexTextCodePath { false };
602     bool m_shouldUseFontSmoothing { true };
603
604     Vector<String> m_fontWhitelist;
605
606     // Messages that were posted before any pages were created.
607     // The client should use initialization messages instead, so that a restarted process would get the same state.
608     Vector<std::pair<String, RefPtr<API::Object>>> m_messagesToInjectedBundlePostedToEmptyContext;
609
610     bool m_memorySamplerEnabled { false };
611     double m_memorySamplerInterval { 1400.0 };
612
613     RefPtr<API::WebsiteDataStore> m_websiteDataStore;
614
615     typedef HashMap<const char*, RefPtr<WebContextSupplement>, PtrHash<const char*>> WebContextSupplementMap;
616     WebContextSupplementMap m_supplements;
617
618 #if USE(SOUP)
619     HTTPCookieAcceptPolicy m_initialHTTPCookieAcceptPolicy { HTTPCookieAcceptPolicyOnlyFromMainDocumentDomain };
620     WebCore::SoupNetworkProxySettings m_networkProxySettings;
621 #endif
622     HashSet<String, ASCIICaseInsensitiveHash> m_urlSchemesRegisteredForCustomProtocols;
623
624 #if PLATFORM(MAC)
625     RetainPtr<NSObject> m_enhancedAccessibilityObserver;
626     RetainPtr<NSObject> m_automaticTextReplacementNotificationObserver;
627     RetainPtr<NSObject> m_automaticSpellingCorrectionNotificationObserver;
628     RetainPtr<NSObject> m_automaticQuoteSubstitutionNotificationObserver;
629     RetainPtr<NSObject> m_automaticDashSubstitutionNotificationObserver;
630     RetainPtr<NSObject> m_accessibilityDisplayOptionsNotificationObserver;
631 #if ENABLE(WEBPROCESS_WINDOWSERVER_BLOCKING)
632     RetainPtr<NSObject> m_scrollerStyleNotificationObserver;
633 #endif
634
635     std::unique_ptr<HighPerformanceGraphicsUsageSampler> m_highPerformanceGraphicsUsageSampler;
636     std::unique_ptr<PerActivityStateCPUUsageSampler> m_perActivityStateCPUUsageSampler;
637 #endif
638
639     bool m_shouldUseTestingNetworkSession { false };
640
641     bool m_processTerminationEnabled { true };
642
643     bool m_canHandleHTTPSServerTrustEvaluation { true };
644     bool m_didNetworkProcessCrash { false };
645     std::unique_ptr<NetworkProcessProxy> m_networkProcess;
646
647     HashMap<uint64_t, RefPtr<DictionaryCallback>> m_dictionaryCallbacks;
648     HashMap<uint64_t, RefPtr<StatisticsRequest>> m_statisticsRequests;
649
650 #if USE(SOUP)
651     bool m_ignoreTLSErrors { true };
652 #endif
653
654     bool m_memoryCacheDisabled { false };
655     bool m_javaScriptConfigurationFileEnabled { false };
656     bool m_alwaysRunsAtBackgroundPriority;
657     bool m_shouldTakeUIBackgroundAssertion;
658     bool m_shouldMakeNextWebProcessLaunchFailForTesting { false };
659     bool m_shouldMakeNextNetworkProcessLaunchFailForTesting { false };
660
661     UserObservablePageCounter m_userObservablePageCounter;
662     ProcessSuppressionDisabledCounter m_processSuppressionDisabledForPageCounter;
663     HiddenPageThrottlingAutoIncreasesCounter m_hiddenPageThrottlingAutoIncreasesCounter;
664     RunLoop::Timer<WebProcessPool> m_hiddenPageThrottlingTimer;
665
666 #if PLATFORM(COCOA)
667     RetainPtr<NSMutableDictionary> m_bundleParameters;
668     ProcessSuppressionDisabledToken m_pluginProcessManagerProcessSuppressionDisabledToken;
669 #endif
670
671 #if ENABLE(CONTENT_EXTENSIONS)
672     HashMap<String, String> m_encodedContentExtensions;
673 #endif
674
675 #if ENABLE(NETSCAPE_PLUGIN_API)
676     HashMap<String, HashMap<String, HashMap<String, uint8_t>>> m_pluginLoadClientPolicies;
677 #endif
678
679 #if ENABLE(GAMEPAD)
680     HashSet<WebProcessProxy*> m_processesUsingGamepads;
681 #endif
682
683 #if PLATFORM(COCOA)
684     bool m_cookieStoragePartitioningEnabled { false };
685     bool m_storageAccessAPIEnabled { false };
686 #endif
687
688     struct Paths {
689         String injectedBundlePath;
690         String applicationCacheDirectory;
691         String webSQLDatabaseDirectory;
692         String mediaCacheDirectory;
693         String mediaKeyStorageDirectory;
694         String uiProcessBundleResourcePath;
695         String indexedDatabaseDirectory;
696
697 #if PLATFORM(IOS_FAMILY)
698         String cookieStorageDirectory;
699         String containerCachesDirectory;
700         String containerTemporaryDirectory;
701 #endif
702
703         Vector<String> additionalWebProcessSandboxExtensionPaths;
704     };
705     Paths m_resolvedPaths;
706
707     HashMap<PAL::SessionID, HashSet<WebPageProxy*>> m_sessionToPagesMap;
708     RunLoop::Timer<WebProcessPool> m_serviceWorkerProcessesTerminationTimer;
709
710 #if PLATFORM(IOS_FAMILY)
711     ForegroundWebProcessCounter m_foregroundWebProcessCounter;
712     BackgroundWebProcessCounter m_backgroundWebProcessCounter;
713     ProcessThrottler::ForegroundActivityToken m_foregroundTokenForNetworkProcess;
714     ProcessThrottler::BackgroundActivityToken m_backgroundTokenForNetworkProcess;
715 #if ENABLE(SERVICE_WORKER)
716     HashMap<WebCore::SecurityOriginData, ProcessThrottler::ForegroundActivityToken> m_foregroundTokensForServiceWorkerProcesses;
717     HashMap<WebCore::SecurityOriginData, ProcessThrottler::BackgroundActivityToken> m_backgroundTokensForServiceWorkerProcesses;
718 #endif
719 #endif
720
721     Deque<std::unique_ptr<SuspendedPageProxy>> m_suspendedPages;
722     unsigned m_maxSuspendedPageCount { 0 };
723
724     HashMap<String, RefPtr<WebProcessProxy>> m_swappedProcessesPerRegistrableDomain;
725
726     HashMap<String, std::unique_ptr<WebCore::PrewarmInformation>> m_prewarmInformationPerRegistrableDomain;
727
728 #if PLATFORM(GTK) || PLATFORM(WPE)
729     bool m_sandboxEnabled { false };
730 #endif
731 };
732
733 template<typename T>
734 void WebProcessPool::sendToNetworkingProcess(T&& message)
735 {
736     if (m_networkProcess && m_networkProcess->canSendMessage())
737         m_networkProcess->send(std::forward<T>(message), 0);
738 }
739
740 template<typename T>
741 void WebProcessPool::sendToNetworkingProcessRelaunchingIfNecessary(T&& message)
742 {
743     ensureNetworkProcess();
744     m_networkProcess->send(std::forward<T>(message), 0);
745 }
746
747 template<typename T>
748 void WebProcessPool::sendToAllProcesses(const T& message)
749 {
750     size_t processCount = m_processes.size();
751     for (size_t i = 0; i < processCount; ++i) {
752         WebProcessProxy* process = m_processes[i].get();
753         if (process->canSendMessage())
754             process->send(T(message), 0);
755     }
756 }
757
758 template<typename T>
759 void WebProcessPool::sendToAllProcessesRelaunchingThemIfNecessary(const T& message)
760 {
761     // 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.
762     sendToAllProcesses(message);
763 }
764
765 template<typename T>
766 void WebProcessPool::sendToOneProcess(T&& message)
767 {
768     bool messageSent = false;
769     size_t processCount = m_processes.size();
770     for (size_t i = 0; i < processCount; ++i) {
771         WebProcessProxy* process = m_processes[i].get();
772         if (process->canSendMessage()) {
773             process->send(std::forward<T>(message), 0);
774             messageSent = true;
775             break;
776         }
777     }
778
779     if (!messageSent) {
780         prewarmProcess(MayCreateDefaultDataStore::No);
781         RefPtr<WebProcessProxy> process = m_processes.last();
782         if (process->canSendMessage())
783             process->send(std::forward<T>(message), 0);
784     }
785 }
786
787 } // namespace WebKit