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