Unreviewed, rolling out r236368.
[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 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     // Sends the message to WebProcess or StorageProcess as approporiate for current process model.
177     template<typename T> void sendToStorageProcess(T&& message);
178     template<typename T> void sendToStorageProcessRelaunchingIfNecessary(T&& message);
179
180     void processDidFinishLaunching(WebProcessProxy*);
181
182     // Disconnect the process from the context.
183     void disconnectProcess(WebProcessProxy*);
184
185     API::WebsiteDataStore* websiteDataStore() const { return m_websiteDataStore.get(); }
186     void setPrimaryDataStore(API::WebsiteDataStore& dataStore) { m_websiteDataStore = &dataStore; }
187
188     Ref<WebPageProxy> createWebPage(PageClient&, Ref<API::PageConfiguration>&&);
189
190     void pageBeginUsingWebsiteDataStore(WebPageProxy&);
191     void pageEndUsingWebsiteDataStore(WebPageProxy&);
192
193     const String& injectedBundlePath() const { return m_configuration->injectedBundlePath(); }
194
195     DownloadProxy* download(WebPageProxy* initiatingPage, const WebCore::ResourceRequest&, const String& suggestedFilename = { });
196     DownloadProxy* resumeDownload(const API::Data* resumeData, const String& path);
197
198     void setInjectedBundleInitializationUserData(RefPtr<API::Object>&& userData) { m_injectedBundleInitializationUserData = WTFMove(userData); }
199
200     void postMessageToInjectedBundle(const String&, API::Object*);
201
202     void populateVisitedLinks();
203
204 #if ENABLE(NETSCAPE_PLUGIN_API)
205     void setAdditionalPluginsDirectory(const String&);
206     void refreshPlugins();
207
208     PluginInfoStore& pluginInfoStore() { return m_pluginInfoStore; }
209
210     void setPluginLoadClientPolicy(WebCore::PluginLoadClientPolicy, const String& host, const String& bundleIdentifier, const String& versionString);
211     void resetPluginLoadClientPolicies(HashMap<String, HashMap<String, HashMap<String, uint8_t>>>&&);
212     void clearPluginClientPolicies();
213     const HashMap<String, HashMap<String, HashMap<String, uint8_t>>>& pluginLoadClientPolicies() const { return m_pluginLoadClientPolicies; }
214 #endif
215
216     void addSupportedPlugin(String&& matchingDomain, String&& name, HashSet<String>&& mimeTypes, HashSet<String> extensions);
217     void clearSupportedPlugins();
218
219     ProcessID networkProcessIdentifier();
220     ProcessID storageProcessIdentifier();
221
222     WebPageGroup& defaultPageGroup() { return m_defaultPageGroup.get(); }
223
224     void setAlwaysUsesComplexTextCodePath(bool);
225     void setShouldUseFontSmoothing(bool);
226     
227     void registerURLSchemeAsEmptyDocument(const String&);
228     void registerURLSchemeAsSecure(const String&);
229     void registerURLSchemeAsBypassingContentSecurityPolicy(const String&);
230     void setDomainRelaxationForbiddenForURLScheme(const String&);
231     void setCanHandleHTTPSServerTrustEvaluation(bool);
232     void registerURLSchemeAsLocal(const String&);
233     void registerURLSchemeAsNoAccess(const String&);
234     void registerURLSchemeAsDisplayIsolated(const String&);
235     void registerURLSchemeAsCORSEnabled(const String&);
236     void registerURLSchemeAsCachePartitioned(const String&);
237     void registerURLSchemeServiceWorkersCanHandle(const String&);
238     void registerURLSchemeAsCanDisplayOnlyIfCanRequest(const String&);
239
240     void preconnectToServer(const WebCore::URL&);
241
242     VisitedLinkStore& visitedLinkStore() { return m_visitedLinkStore.get(); }
243
244     void setCacheModel(CacheModel);
245     CacheModel cacheModel() const { return m_configuration->cacheModel(); }
246
247     void setDefaultRequestTimeoutInterval(double);
248
249     void startMemorySampler(const double interval);
250     void stopMemorySampler();
251
252 #if USE(SOUP)
253     void setInitialHTTPCookieAcceptPolicy(HTTPCookieAcceptPolicy policy) { m_initialHTTPCookieAcceptPolicy = policy; }
254     void setNetworkProxySettings(const WebCore::SoupNetworkProxySettings&);
255 #endif
256     void setEnhancedAccessibility(bool);
257     
258     // Downloads.
259     DownloadProxy* createDownloadProxy(const WebCore::ResourceRequest&, WebPageProxy* originatingPage);
260     API::DownloadClient& downloadClient() { return *m_downloadClient; }
261
262     API::LegacyContextHistoryClient& historyClient() { return *m_historyClient; }
263     WebContextClient& client() { return m_client; }
264
265     API::CustomProtocolManagerClient& customProtocolManagerClient() const { return *m_customProtocolManagerClient; }
266
267     struct Statistics {
268         unsigned wkViewCount;
269         unsigned wkPageCount;
270         unsigned wkFrameCount;
271     };
272     static Statistics& statistics();    
273
274     void useTestingNetworkSession();
275     bool isUsingTestingNetworkSession() const { return m_shouldUseTestingNetworkSession; }
276
277     void setAllowsAnySSLCertificateForWebSocket(bool);
278
279     void clearCachedCredentials();
280     void terminateStorageProcessForTesting();
281     void terminateNetworkProcess();
282     void terminateServiceWorkerProcesses();
283     void disableServiceWorkerProcessTerminationDelay();
284
285     void syncNetworkProcessCookies();
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)
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<Messages::WebProcessProxy::GetNetworkProcessConnection::DelayedReply>&&);
342
343     void getNetworkProcessConnection(Messages::WebProcessProxy::GetNetworkProcessConnection::DelayedReply&&);
344
345     void ensureStorageProcessAndWebsiteDataStore(WebsiteDataStore* relevantDataStore);
346     StorageProcessProxy* storageProcess() { return m_storageProcess.get(); }
347     void getStorageProcessConnection(WebProcessProxy&, PAL::SessionID initialSessionID, Messages::WebProcessProxy::GetStorageProcessConnection::DelayedReply&&);
348     void storageProcessCrashed(StorageProcessProxy*);
349 #if ENABLE(SERVICE_WORKER)
350     void establishWorkerContextConnectionToStorageProcess(StorageProcessProxy&, WebCore::SecurityOriginData&&, std::optional<PAL::SessionID>);
351     ServiceWorkerProcessProxy* serviceWorkerProcessProxyFromPageID(uint64_t pageID) const;
352     const HashMap<WebCore::SecurityOriginData, ServiceWorkerProcessProxy*>& serviceWorkerProxies() const { return m_serviceWorkerProcesses; }
353     void setAllowsAnySSLCertificateForServiceWorker(bool allows) { m_allowsAnySSLCertificateForServiceWorker = allows; }
354     bool allowsAnySSLCertificateForServiceWorker() const { return m_allowsAnySSLCertificateForServiceWorker; }
355     void updateServiceWorkerUserAgent(const String& userAgent);
356     bool mayHaveRegisteredServiceWorkers(const WebsiteDataStore&);
357 #endif
358
359 #if PLATFORM(COCOA)
360     bool processSuppressionEnabled() const;
361 #endif
362
363     void windowServerConnectionStateChanged();
364
365     static void willStartUsingPrivateBrowsing();
366     static void willStopUsingPrivateBrowsing();
367
368 #if USE(SOUP)
369     void setIgnoreTLSErrors(bool);
370     bool ignoreTLSErrors() const { return m_ignoreTLSErrors; }
371 #endif
372
373     static void setInvalidMessageCallback(void (*)(WKStringRef));
374     static void didReceiveInvalidMessage(const IPC::StringReference& messageReceiverName, const IPC::StringReference& messageName);
375
376     void processDidCachePage(WebProcessProxy*);
377
378     bool isURLKnownHSTSHost(const String& urlString, bool privateBrowsingEnabled) const;
379     void resetHSTSHosts();
380     void resetHSTSHostsAddedAfterDate(double startDateIntervalSince1970);
381
382     void registerSchemeForCustomProtocol(const String&);
383     void unregisterSchemeForCustomProtocol(const String&);
384
385     static void registerGlobalURLSchemeAsHavingCustomProtocolHandlers(const String&);
386     static void unregisterGlobalURLSchemeAsHavingCustomProtocolHandlers(const String&);
387
388 #if PLATFORM(COCOA)
389     void updateProcessSuppressionState();
390
391     NSMutableDictionary *ensureBundleParameters();
392     NSMutableDictionary *bundleParameters() { return m_bundleParameters.get(); }
393 #else
394     void updateProcessSuppressionState() const { }
395 #endif
396
397     void updateHiddenPageThrottlingAutoIncreaseLimit();
398
399     void setMemoryCacheDisabled(bool);
400     void setFontWhitelist(API::Array*);
401
402     UserObservablePageCounter::Token userObservablePageCount()
403     {
404         return m_userObservablePageCounter.count();
405     }
406
407     ProcessSuppressionDisabledToken processSuppressionDisabledForPageCount()
408     {
409         return m_processSuppressionDisabledForPageCounter.count();
410     }
411
412     HiddenPageThrottlingAutoIncreasesCounter::Token hiddenPageThrottlingAutoIncreasesCount()
413     {
414         return m_hiddenPageThrottlingAutoIncreasesCounter.count();
415     }
416
417     void setResourceLoadStatisticsEnabled(bool);
418     void clearResourceLoadStatistics();
419
420     bool alwaysRunsAtBackgroundPriority() const { return m_alwaysRunsAtBackgroundPriority; }
421     bool shouldTakeUIBackgroundAssertion() const { return m_shouldTakeUIBackgroundAssertion; }
422
423 #if ENABLE(GAMEPAD)
424     void gamepadConnected(const UIGamepad&);
425     void gamepadDisconnected(const UIGamepad&);
426
427     void setInitialConnectedGamepads(const Vector<std::unique_ptr<UIGamepad>>&);
428 #endif
429
430 #if PLATFORM(COCOA)
431     bool cookieStoragePartitioningEnabled() const { return m_cookieStoragePartitioningEnabled; }
432     void setCookieStoragePartitioningEnabled(bool);
433     bool storageAccessAPIEnabled() const { return m_storageAccessAPIEnabled; }
434     void setStorageAccessAPIEnabled(bool);
435 #endif
436
437 #if ENABLE(SERVICE_WORKER)
438     void postMessageToServiceWorkerClient(const WebCore::ServiceWorkerClientIdentifier& destinationIdentifier, WebCore::MessageWithMessagePorts&&, WebCore::ServiceWorkerIdentifier sourceIdentifier, const String& sourceOrigin);
439     void postMessageToServiceWorker(WebCore::ServiceWorkerIdentifier destination, WebCore::MessageWithMessagePorts&&, const WebCore::ServiceWorkerOrClientIdentifier& source, WebCore::SWServerConnectionIdentifier);
440 #endif
441
442     static uint64_t registerProcessPoolCreationListener(Function<void(WebProcessPool&)>&&);
443     static void unregisterProcessPoolCreationListener(uint64_t identifier);
444
445 #if PLATFORM(IOS)
446     ForegroundWebProcessToken foregroundWebProcessToken() const { return ForegroundWebProcessToken(m_foregroundWebProcessCounter.count()); }
447     BackgroundWebProcessToken backgroundWebProcessToken() const { return BackgroundWebProcessToken(m_backgroundWebProcessCounter.count()); }
448 #endif
449
450     Ref<WebProcessProxy> processForNavigation(WebPageProxy&, const API::Navigation&, ProcessSwapRequestedByClient, WebCore::PolicyAction&, String& reason);
451     void registerSuspendedPageProxy(SuspendedPageProxy&);
452     void unregisterSuspendedPageProxy(SuspendedPageProxy&);
453     void didReachGoodTimeToPrewarm();
454
455     void screenPropertiesStateChanged();
456
457     void addMockMediaDevice(const WebCore::MockMediaDevice&);
458     void clearMockMediaDevices();
459     void removeMockMediaDevice(const String& persistentId);
460     void resetMockMediaDevices();
461
462     void sendDisplayConfigurationChangedMessageForTesting();
463
464 private:
465     void platformInitialize();
466
467     void platformInitializeWebProcess(WebProcessCreationParameters&);
468     void platformInvalidateContext();
469
470     Ref<WebProcessProxy> processForNavigationInternal(WebPageProxy&, const API::Navigation&, ProcessSwapRequestedByClient, WebCore::PolicyAction&, String& reason);
471
472     RefPtr<WebProcessProxy> tryTakePrewarmedProcess(WebsiteDataStore&);
473
474     WebProcessProxy& createNewWebProcess(WebsiteDataStore&, WebProcessProxy::IsPrewarmed = WebProcessProxy::IsPrewarmed::No);
475     void initializeNewWebProcess(WebProcessProxy&, WebsiteDataStore&);
476
477     void requestWebContentStatistics(StatisticsRequest*);
478     void requestNetworkingStatistics(StatisticsRequest*);
479
480     void platformInitializeNetworkProcess(NetworkProcessCreationParameters&);
481
482     void handleMessage(IPC::Connection&, const String& messageName, const UserData& messageBody);
483     void handleSynchronousMessage(IPC::Connection&, const String& messageName, const UserData& messageBody, UserData& returnUserData);
484
485     void didGetStatistics(const StatisticsData&, uint64_t callbackID);
486
487 #if ENABLE(GAMEPAD)
488     void startedUsingGamepads(IPC::Connection&);
489     void stoppedUsingGamepads(IPC::Connection&);
490
491     void processStoppedUsingGamepads(WebProcessProxy&);
492 #endif
493
494     void reinstateNetworkProcessAssertionState(NetworkProcessProxy&);
495     void updateProcessAssertions();
496
497     // IPC::MessageReceiver.
498     // Implemented in generated WebProcessPoolMessageReceiver.cpp
499     void didReceiveMessage(IPC::Connection&, IPC::Decoder&) override;
500     void didReceiveSyncMessage(IPC::Connection&, IPC::Decoder&, std::unique_ptr<IPC::Encoder>&) override;
501
502     static void languageChanged(void* context);
503     void languageChanged();
504
505 #if PLATFORM(IOS)
506     String cookieStorageDirectory() const;
507 #endif
508
509 #if PLATFORM(IOS)
510     String parentBundleDirectory() const;
511     String networkingCachesDirectory() const;
512     String webContentCachesDirectory() const;
513     String containerTemporaryDirectory() const;
514 #endif
515
516 #if PLATFORM(COCOA)
517     void registerNotificationObservers();
518     void unregisterNotificationObservers();
519 #endif
520
521     void addPlugInAutoStartOriginHash(const String& pageOrigin, unsigned plugInOriginHash, PAL::SessionID);
522     void plugInDidReceiveUserInteraction(unsigned plugInOriginHash, PAL::SessionID);
523
524     void setAnyPageGroupMightHavePrivateBrowsingEnabled(bool);
525
526     void resolvePathsForSandboxExtensions();
527     void platformResolvePathsForSandboxExtensions();
528
529     void addProcessToOriginCacheSet(WebPageProxy&);
530     void removeProcessFromOriginCacheSet(WebProcessProxy&);
531
532     Ref<API::ProcessPoolConfiguration> m_configuration;
533
534     IPC::MessageReceiverMap m_messageReceiverMap;
535
536     Vector<RefPtr<WebProcessProxy>> m_processes;
537     WebProcessProxy* m_prewarmedProcess { nullptr };
538
539     WebProcessProxy* m_processWithPageCache { nullptr };
540 #if ENABLE(SERVICE_WORKER)
541     HashMap<WebCore::SecurityOriginData, ServiceWorkerProcessProxy*> m_serviceWorkerProcesses;
542     bool m_waitingForWorkerContextProcessConnection { false };
543     bool m_allowsAnySSLCertificateForServiceWorker { false };
544     bool m_shouldDisableServiceWorkerProcessTerminationDelay { false };
545     String m_serviceWorkerUserAgent;
546     std::optional<WebPreferencesStore> m_serviceWorkerPreferences;
547     HashMap<String, bool> m_mayHaveRegisteredServiceWorkers;
548 #endif
549
550     Ref<WebPageGroup> m_defaultPageGroup;
551
552     RefPtr<API::Object> m_injectedBundleInitializationUserData;
553     std::unique_ptr<API::InjectedBundleClient> m_injectedBundleClient;
554
555     WebContextClient m_client;
556     WebContextConnectionClient m_connectionClient;
557     std::unique_ptr<API::AutomationClient> m_automationClient;
558     std::unique_ptr<API::DownloadClient> m_downloadClient;
559     std::unique_ptr<API::LegacyContextHistoryClient> m_historyClient;
560     std::unique_ptr<API::CustomProtocolManagerClient> m_customProtocolManagerClient;
561
562     RefPtr<WebAutomationSession> m_automationSession;
563
564 #if ENABLE(NETSCAPE_PLUGIN_API)
565     PluginInfoStore m_pluginInfoStore;
566 #endif
567     Ref<VisitedLinkStore> m_visitedLinkStore;
568     bool m_visitedLinksPopulated { false };
569
570     PlugInAutoStartProvider m_plugInAutoStartProvider { this };
571         
572     HashSet<String> m_schemesToRegisterAsEmptyDocument;
573     HashSet<String> m_schemesToRegisterAsSecure;
574     HashSet<String> m_schemesToRegisterAsBypassingContentSecurityPolicy;
575     HashSet<String> m_schemesToSetDomainRelaxationForbiddenFor;
576     HashSet<String> m_schemesToRegisterAsLocal;
577     HashSet<String> m_schemesToRegisterAsNoAccess;
578     HashSet<String> m_schemesToRegisterAsDisplayIsolated;
579     HashSet<String> m_schemesToRegisterAsCORSEnabled;
580     HashSet<String> m_schemesToRegisterAsAlwaysRevalidated;
581     HashSet<String> m_schemesToRegisterAsCachePartitioned;
582     HashSet<String> m_schemesServiceWorkersCanHandle;
583     HashSet<String> m_schemesToRegisterAsCanDisplayOnlyIfCanRequest;
584
585     bool m_alwaysUsesComplexTextCodePath { false };
586     bool m_shouldUseFontSmoothing { true };
587
588     Vector<String> m_fontWhitelist;
589
590     // Messages that were posted before any pages were created.
591     // The client should use initialization messages instead, so that a restarted process would get the same state.
592     Vector<std::pair<String, RefPtr<API::Object>>> m_messagesToInjectedBundlePostedToEmptyContext;
593
594     bool m_memorySamplerEnabled { false };
595     double m_memorySamplerInterval { 1400.0 };
596
597     RefPtr<API::WebsiteDataStore> m_websiteDataStore;
598
599     typedef HashMap<const char*, RefPtr<WebContextSupplement>, PtrHash<const char*>> WebContextSupplementMap;
600     WebContextSupplementMap m_supplements;
601
602 #if USE(SOUP)
603     HTTPCookieAcceptPolicy m_initialHTTPCookieAcceptPolicy { HTTPCookieAcceptPolicyOnlyFromMainDocumentDomain };
604     WebCore::SoupNetworkProxySettings m_networkProxySettings;
605 #endif
606     HashSet<String, ASCIICaseInsensitiveHash> m_urlSchemesRegisteredForCustomProtocols;
607
608 #if PLATFORM(MAC)
609     RetainPtr<NSObject> m_enhancedAccessibilityObserver;
610     RetainPtr<NSObject> m_automaticTextReplacementNotificationObserver;
611     RetainPtr<NSObject> m_automaticSpellingCorrectionNotificationObserver;
612     RetainPtr<NSObject> m_automaticQuoteSubstitutionNotificationObserver;
613     RetainPtr<NSObject> m_automaticDashSubstitutionNotificationObserver;
614     RetainPtr<NSObject> m_accessibilityDisplayOptionsNotificationObserver;
615 #if ENABLE(WEBPROCESS_WINDOWSERVER_BLOCKING)
616     RetainPtr<NSObject> m_scrollerStyleNotificationObserver;
617 #endif
618
619     std::unique_ptr<HighPerformanceGraphicsUsageSampler> m_highPerformanceGraphicsUsageSampler;
620     std::unique_ptr<PerActivityStateCPUUsageSampler> m_perActivityStateCPUUsageSampler;
621 #endif
622
623     bool m_shouldUseTestingNetworkSession { false };
624
625     bool m_processTerminationEnabled { true };
626
627     bool m_canHandleHTTPSServerTrustEvaluation { true };
628     bool m_didNetworkProcessCrash { false };
629     RefPtr<NetworkProcessProxy> m_networkProcess;
630     RefPtr<StorageProcessProxy> m_storageProcess;
631
632     HashMap<uint64_t, RefPtr<DictionaryCallback>> m_dictionaryCallbacks;
633     HashMap<uint64_t, RefPtr<StatisticsRequest>> m_statisticsRequests;
634
635 #if USE(SOUP)
636     bool m_ignoreTLSErrors { true };
637 #endif
638
639     bool m_memoryCacheDisabled { false };
640     bool m_javaScriptConfigurationFileEnabled { false };
641     bool m_alwaysRunsAtBackgroundPriority;
642     bool m_shouldTakeUIBackgroundAssertion;
643     bool m_shouldMakeNextWebProcessLaunchFailForTesting { false };
644     bool m_shouldMakeNextNetworkProcessLaunchFailForTesting { false };
645
646     UserObservablePageCounter m_userObservablePageCounter;
647     ProcessSuppressionDisabledCounter m_processSuppressionDisabledForPageCounter;
648     HiddenPageThrottlingAutoIncreasesCounter m_hiddenPageThrottlingAutoIncreasesCounter;
649     RunLoop::Timer<WebProcessPool> m_hiddenPageThrottlingTimer;
650
651 #if PLATFORM(COCOA)
652     RetainPtr<NSMutableDictionary> m_bundleParameters;
653     ProcessSuppressionDisabledToken m_pluginProcessManagerProcessSuppressionDisabledToken;
654 #endif
655
656 #if ENABLE(CONTENT_EXTENSIONS)
657     HashMap<String, String> m_encodedContentExtensions;
658 #endif
659
660 #if ENABLE(NETSCAPE_PLUGIN_API)
661     HashMap<String, HashMap<String, HashMap<String, uint8_t>>> m_pluginLoadClientPolicies;
662 #endif
663
664 #if ENABLE(GAMEPAD)
665     HashSet<WebProcessProxy*> m_processesUsingGamepads;
666 #endif
667
668 #if PLATFORM(COCOA)
669     bool m_cookieStoragePartitioningEnabled { false };
670     bool m_storageAccessAPIEnabled { false };
671 #endif
672
673     struct Paths {
674         String injectedBundlePath;
675         String applicationCacheDirectory;
676         String webSQLDatabaseDirectory;
677         String mediaCacheDirectory;
678         String mediaKeyStorageDirectory;
679         String uiProcessBundleResourcePath;
680         String indexedDatabaseDirectory;
681
682 #if PLATFORM(IOS)
683         String cookieStorageDirectory;
684         String containerCachesDirectory;
685         String containerTemporaryDirectory;
686 #endif
687
688         Vector<String> additionalWebProcessSandboxExtensionPaths;
689     };
690     Paths m_resolvedPaths;
691
692     HashMap<PAL::SessionID, HashSet<WebPageProxy*>> m_sessionToPagesMap;
693     RunLoop::Timer<WebProcessPool> m_serviceWorkerProcessesTerminationTimer;
694
695 #if PLATFORM(IOS)
696     ForegroundWebProcessCounter m_foregroundWebProcessCounter;
697     BackgroundWebProcessCounter m_backgroundWebProcessCounter;
698     ProcessThrottler::ForegroundActivityToken m_foregroundTokenForNetworkProcess;
699     ProcessThrottler::BackgroundActivityToken m_backgroundTokenForNetworkProcess;
700 #if ENABLE(SERVICE_WORKER)
701     HashMap<WebCore::SecurityOriginData, ProcessThrottler::ForegroundActivityToken> m_foregroundTokensForServiceWorkerProcesses;
702     HashMap<WebCore::SecurityOriginData, ProcessThrottler::BackgroundActivityToken> m_backgroundTokensForServiceWorkerProcesses;
703 #endif
704 #endif
705
706     HashMap<WebCore::SecurityOriginData, Vector<SuspendedPageProxy*>> m_suspendedPages;
707     HashMap<String, RefPtr<WebProcessProxy>> m_swappedProcessesPerRegistrableDomain;
708 };
709
710 template<typename T>
711 void WebProcessPool::sendToNetworkingProcess(T&& message)
712 {
713     if (m_networkProcess && m_networkProcess->canSendMessage())
714         m_networkProcess->send(std::forward<T>(message), 0);
715 }
716
717 template<typename T>
718 void WebProcessPool::sendToNetworkingProcessRelaunchingIfNecessary(T&& message)
719 {
720     ensureNetworkProcess();
721     m_networkProcess->send(std::forward<T>(message), 0);
722 }
723
724 template<typename T>
725 void WebProcessPool::sendToStorageProcess(T&& message)
726 {
727     if (m_storageProcess && m_storageProcess->canSendMessage())
728         m_storageProcess->send(std::forward<T>(message), 0);
729 }
730
731 template<typename T>
732 void WebProcessPool::sendToStorageProcessRelaunchingIfNecessary(T&& message)
733 {
734     ensureStorageProcessAndWebsiteDataStore(nullptr);
735     m_storageProcess->send(std::forward<T>(message), 0);
736 }
737
738 template<typename T>
739 void WebProcessPool::sendToAllProcesses(const T& message)
740 {
741     size_t processCount = m_processes.size();
742     for (size_t i = 0; i < processCount; ++i) {
743         WebProcessProxy* process = m_processes[i].get();
744         if (process->canSendMessage())
745             process->send(T(message), 0);
746     }
747 }
748
749 template<typename T>
750 void WebProcessPool::sendToAllProcessesRelaunchingThemIfNecessary(const T& message)
751 {
752     // 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.
753     sendToAllProcesses(message);
754 }
755
756 template<typename T>
757 void WebProcessPool::sendToOneProcess(T&& message)
758 {
759     bool messageSent = false;
760     size_t processCount = m_processes.size();
761     for (size_t i = 0; i < processCount; ++i) {
762         WebProcessProxy* process = m_processes[i].get();
763         if (process->canSendMessage()) {
764             process->send(std::forward<T>(message), 0);
765             messageSent = true;
766             break;
767         }
768     }
769
770     if (!messageSent) {
771         prewarmProcess();
772         RefPtr<WebProcessProxy> process = m_processes.last();
773         if (process->canSendMessage())
774             process->send(std::forward<T>(message), 0);
775     }
776 }
777
778 } // namespace WebKit