Remove unused WebProcessPool::requestNetworkingStatistics
[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
545     void platformInitializeNetworkProcess(NetworkProcessCreationParameters&);
546
547     void handleMessage(IPC::Connection&, const String& messageName, const UserData& messageBody);
548     void handleSynchronousMessage(IPC::Connection&, const String& messageName, const UserData& messageBody, CompletionHandler<void(UserData&&)>&&);
549
550     void didGetStatistics(const StatisticsData&, uint64_t callbackID);
551
552 #if ENABLE(GAMEPAD)
553     void startedUsingGamepads(IPC::Connection&);
554     void stoppedUsingGamepads(IPC::Connection&);
555
556     void processStoppedUsingGamepads(WebProcessProxy&);
557 #endif
558
559     void reinstateNetworkProcessAssertionState(NetworkProcessProxy&);
560     void updateProcessAssertions();
561
562     // IPC::MessageReceiver.
563     // Implemented in generated WebProcessPoolMessageReceiver.cpp
564     void didReceiveMessage(IPC::Connection&, IPC::Decoder&) override;
565     void didReceiveSyncMessage(IPC::Connection&, IPC::Decoder&, std::unique_ptr<IPC::Encoder>&) override;
566
567     static void languageChanged(void* context);
568     void languageChanged();
569
570     bool usesSingleWebProcess() const { return m_configuration->usesSingleWebProcess(); }
571
572 #if PLATFORM(IOS_FAMILY)
573     static String cookieStorageDirectory();
574     static String parentBundleDirectory();
575     static String networkingCachesDirectory();
576     static String webContentCachesDirectory();
577     static String containerTemporaryDirectory();
578 #endif
579
580 #if PLATFORM(COCOA)
581     void registerNotificationObservers();
582     void unregisterNotificationObservers();
583 #endif
584
585     void setApplicationIsActive(bool);
586
587     void resolvePathsForSandboxExtensions();
588     void platformResolvePathsForSandboxExtensions();
589
590     void addProcessToOriginCacheSet(WebProcessProxy&, const URL&);
591     void removeProcessFromOriginCacheSet(WebProcessProxy&);
592
593     void tryPrewarmWithDomainInformation(WebProcessProxy&, const WebCore::RegistrableDomain&);
594
595     void updateMaxSuspendedPageCount();
596
597 #if PLATFORM(IOS)
598     static float displayBrightness();
599     static void backlightLevelDidChangeCallback(CFNotificationCenterRef, void *observer, CFStringRef name, const void *, CFDictionaryRef userInfo);    
600 #endif
601
602     Ref<API::ProcessPoolConfiguration> m_configuration;
603
604     IPC::MessageReceiverMap m_messageReceiverMap;
605
606     Vector<RefPtr<WebProcessProxy>> m_processes;
607     WebProcessProxy* m_prewarmedProcess { nullptr };
608     WebProcessProxy* m_dummyProcessProxy { nullptr }; // A lightweight WebProcessProxy without backing process.
609
610     WebProcessProxy* m_processWithPageCache { nullptr };
611 #if ENABLE(SERVICE_WORKER)
612     using RegistrableDomainWithSessionID = std::pair<WebCore::RegistrableDomain, PAL::SessionID>;
613     HashMap<RegistrableDomainWithSessionID, WebProcessProxy*> m_serviceWorkerProcesses;
614     bool m_waitingForWorkerContextProcessConnection { false };
615     bool m_allowsAnySSLCertificateForServiceWorker { false };
616     String m_serviceWorkerUserAgent;
617     Optional<WebPreferencesStore> m_serviceWorkerPreferences;
618     HashMap<String, bool> m_mayHaveRegisteredServiceWorkers;
619 #endif
620
621     Ref<WebPageGroup> m_defaultPageGroup;
622
623     RefPtr<API::Object> m_injectedBundleInitializationUserData;
624     std::unique_ptr<API::InjectedBundleClient> m_injectedBundleClient;
625
626     WebContextClient m_client;
627     WebContextConnectionClient m_connectionClient;
628     std::unique_ptr<API::AutomationClient> m_automationClient;
629     UniqueRef<API::DownloadClient> m_downloadClient;
630     std::unique_ptr<API::LegacyContextHistoryClient> m_historyClient;
631     std::unique_ptr<API::CustomProtocolManagerClient> m_customProtocolManagerClient;
632
633     RefPtr<WebAutomationSession> m_automationSession;
634
635 #if ENABLE(NETSCAPE_PLUGIN_API)
636     PluginInfoStore m_pluginInfoStore;
637 #endif
638     Ref<VisitedLinkStore> m_visitedLinkStore;
639     bool m_visitedLinksPopulated { false };
640
641     PlugInAutoStartProvider m_plugInAutoStartProvider { this };
642         
643     HashSet<String> m_schemesToRegisterAsEmptyDocument;
644     HashSet<String> m_schemesToRegisterAsSecure;
645     HashSet<String> m_schemesToRegisterAsBypassingContentSecurityPolicy;
646     HashSet<String> m_schemesToSetDomainRelaxationForbiddenFor;
647     HashSet<String> m_schemesToRegisterAsLocal;
648     HashSet<String> m_schemesToRegisterAsNoAccess;
649     HashSet<String> m_schemesToRegisterAsDisplayIsolated;
650     HashSet<String> m_schemesToRegisterAsCORSEnabled;
651     HashSet<String> m_schemesToRegisterAsAlwaysRevalidated;
652     HashSet<String> m_schemesToRegisterAsCachePartitioned;
653     HashSet<String> m_schemesToRegisterAsCanDisplayOnlyIfCanRequest;
654
655     bool m_alwaysUsesComplexTextCodePath { false };
656     bool m_shouldUseFontSmoothing { true };
657
658     Vector<String> m_fontWhitelist;
659
660     // Messages that were posted before any pages were created.
661     // The client should use initialization messages instead, so that a restarted process would get the same state.
662     Vector<std::pair<String, RefPtr<API::Object>>> m_messagesToInjectedBundlePostedToEmptyContext;
663
664     bool m_memorySamplerEnabled { false };
665     double m_memorySamplerInterval { 1400.0 };
666
667     RefPtr<WebKit::WebsiteDataStore> m_websiteDataStore;
668
669     typedef HashMap<const char*, RefPtr<WebContextSupplement>, PtrHash<const char*>> WebContextSupplementMap;
670     WebContextSupplementMap m_supplements;
671
672 #if USE(SOUP)
673     HTTPCookieAcceptPolicy m_initialHTTPCookieAcceptPolicy { HTTPCookieAcceptPolicy::OnlyFromMainDocumentDomain };
674     WebCore::SoupNetworkProxySettings m_networkProxySettings;
675 #endif
676
677 #if PLATFORM(MAC)
678     RetainPtr<NSObject> m_enhancedAccessibilityObserver;
679     RetainPtr<NSObject> m_automaticTextReplacementNotificationObserver;
680     RetainPtr<NSObject> m_automaticSpellingCorrectionNotificationObserver;
681     RetainPtr<NSObject> m_automaticQuoteSubstitutionNotificationObserver;
682     RetainPtr<NSObject> m_automaticDashSubstitutionNotificationObserver;
683     RetainPtr<NSObject> m_accessibilityDisplayOptionsNotificationObserver;
684 #if ENABLE(WEBPROCESS_WINDOWSERVER_BLOCKING)
685     RetainPtr<NSObject> m_scrollerStyleNotificationObserver;
686 #endif
687     RetainPtr<NSObject> m_activationObserver;
688     RetainPtr<NSObject> m_deactivationObserver;
689
690     std::unique_ptr<HighPerformanceGraphicsUsageSampler> m_highPerformanceGraphicsUsageSampler;
691     std::unique_ptr<PerActivityStateCPUUsageSampler> m_perActivityStateCPUUsageSampler;
692 #endif
693
694 #if PLATFORM(IOS_FAMILY)
695     RetainPtr<NSObject> m_accessibilityEnabledObserver;
696 #endif
697
698     bool m_shouldUseTestingNetworkSession { false };
699
700     bool m_processTerminationEnabled { true };
701
702     bool m_didNetworkProcessCrash { false };
703     std::unique_ptr<NetworkProcessProxy> m_networkProcess;
704
705     HashMap<uint64_t, RefPtr<DictionaryCallback>> m_dictionaryCallbacks;
706     HashMap<uint64_t, RefPtr<StatisticsRequest>> m_statisticsRequests;
707
708 #if USE(SOUP)
709     bool m_ignoreTLSErrors { true };
710 #endif
711
712     bool m_memoryCacheDisabled { false };
713     bool m_javaScriptConfigurationFileEnabled { false };
714     String m_javaScriptConfigurationDirectory;
715     bool m_alwaysRunsAtBackgroundPriority;
716     bool m_shouldTakeUIBackgroundAssertion;
717     bool m_shouldMakeNextWebProcessLaunchFailForTesting { false };
718     bool m_shouldMakeNextNetworkProcessLaunchFailForTesting { false };
719
720     UserObservablePageCounter m_userObservablePageCounter;
721     ProcessSuppressionDisabledCounter m_processSuppressionDisabledForPageCounter;
722     HiddenPageThrottlingAutoIncreasesCounter m_hiddenPageThrottlingAutoIncreasesCounter;
723     RunLoop::Timer<WebProcessPool> m_hiddenPageThrottlingTimer;
724
725 #if PLATFORM(COCOA)
726     RetainPtr<NSMutableDictionary> m_bundleParameters;
727     ProcessSuppressionDisabledToken m_pluginProcessManagerProcessSuppressionDisabledToken;
728     mutable RetainPtr<NSSet> m_classesForParameterCoder;
729 #endif
730
731 #if ENABLE(CONTENT_EXTENSIONS)
732     HashMap<String, String> m_encodedContentExtensions;
733 #endif
734
735 #if ENABLE(NETSCAPE_PLUGIN_API)
736     HashMap<String, HashMap<String, HashMap<String, uint8_t>>> m_pluginLoadClientPolicies;
737 #endif
738
739 #if ENABLE(GAMEPAD)
740     HashSet<WebProcessProxy*> m_processesUsingGamepads;
741 #endif
742
743 #if PLATFORM(COCOA)
744     bool m_cookieStoragePartitioningEnabled { false };
745 #endif
746     bool m_storageAccessAPIEnabled { false };
747
748     struct Paths {
749         String injectedBundlePath;
750         String uiProcessBundleResourcePath;
751
752 #if PLATFORM(IOS_FAMILY)
753         String cookieStorageDirectory;
754         String containerCachesDirectory;
755         String containerTemporaryDirectory;
756 #endif
757
758         Vector<String> additionalWebProcessSandboxExtensionPaths;
759     };
760     Paths m_resolvedPaths;
761
762     HashMap<PAL::SessionID, HashSet<WebPageProxyIdentifier>> m_sessionToPageIDsMap;
763     RunLoop::Timer<WebProcessPool> m_serviceWorkerProcessesTerminationTimer;
764
765 #if PLATFORM(IOS_FAMILY)
766     ForegroundWebProcessCounter m_foregroundWebProcessCounter;
767     BackgroundWebProcessCounter m_backgroundWebProcessCounter;
768     ProcessThrottler::ForegroundActivityToken m_foregroundTokenForNetworkProcess;
769     ProcessThrottler::BackgroundActivityToken m_backgroundTokenForNetworkProcess;
770 #if ENABLE(SERVICE_WORKER)
771     HashMap<WebCore::RegistrableDomain, ProcessThrottler::ForegroundActivityToken> m_foregroundTokensForServiceWorkerProcesses;
772     HashMap<WebCore::RegistrableDomain, ProcessThrottler::BackgroundActivityToken> m_backgroundTokensForServiceWorkerProcesses;
773 #endif
774 #endif
775
776     Deque<std::unique_ptr<SuspendedPageProxy>> m_suspendedPages;
777     unsigned m_maxSuspendedPageCount { 0 };
778
779     UniqueRef<WebProcessCache> m_webProcessCache;
780     HashMap<WebCore::RegistrableDomain, RefPtr<WebProcessProxy>> m_swappedProcessesPerRegistrableDomain;
781
782     HashMap<WebCore::RegistrableDomain, std::unique_ptr<WebCore::PrewarmInformation>> m_prewarmInformationPerRegistrableDomain;
783
784 #if PLATFORM(MAC) && ENABLE(WEBPROCESS_WINDOWSERVER_BLOCKING)
785     Vector<std::unique_ptr<DisplayLink>> m_displayLinks;
786 #endif
787
788 #if PLATFORM(GTK) || PLATFORM(WPE)
789     bool m_sandboxEnabled { false };
790     HashMap<CString, SandboxPermission> m_extraSandboxPaths;
791 #endif
792
793     HashMap<WebCore::ProcessIdentifier, std::unique_ptr<ProcessAssertion>> m_processesWithUploads;
794     std::unique_ptr<ProcessAssertion> m_uiProcessUploadAssertion;
795
796     HashMap<WebCore::ProcessIdentifier, std::unique_ptr<ProcessAssertion>> m_processesPlayingAudibleMedia;
797     std::unique_ptr<ProcessAssertion> m_uiProcessMediaPlaybackAssertion;
798
799 #if PLATFORM(IOS)
800     // FIXME: Delayed process launch is currently disabled on iOS for performance reasons (rdar://problem/49074131).
801     bool m_isDelayedWebProcessLaunchDisabled { true };
802 #else
803     bool m_isDelayedWebProcessLaunchDisabled { false };
804 #endif
805 };
806
807 template<typename T>
808 void WebProcessPool::sendToNetworkingProcess(T&& message)
809 {
810     if (m_networkProcess && m_networkProcess->canSendMessage())
811         m_networkProcess->send(std::forward<T>(message), 0);
812 }
813
814 template<typename T>
815 void WebProcessPool::sendToNetworkingProcessRelaunchingIfNecessary(T&& message)
816 {
817     ensureNetworkProcess();
818     m_networkProcess->send(std::forward<T>(message), 0);
819 }
820
821 template<typename T>
822 void WebProcessPool::sendToAllProcesses(const T& message)
823 {
824     size_t processCount = m_processes.size();
825     for (size_t i = 0; i < processCount; ++i) {
826         WebProcessProxy* process = m_processes[i].get();
827         if (process->canSendMessage())
828             process->send(T(message), 0);
829     }
830 }
831
832 template<typename T>
833 void WebProcessPool::sendToAllProcessesForSession(const T& message, PAL::SessionID sessionID)
834 {
835     size_t processCount = m_processes.size();
836     for (size_t i = 0; i < processCount; ++i) {
837         WebProcessProxy* process = m_processes[i].get();
838         if (process->canSendMessage() && !process->isPrewarmed() && process->sessionID() == sessionID)
839             process->send(T(message), 0);
840     }
841 }
842
843 template<typename T>
844 void WebProcessPool::sendToAllProcessesRelaunchingThemIfNecessary(const T& message)
845 {
846     // 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.
847     sendToAllProcesses(message);
848 }
849
850 template<typename T>
851 void WebProcessPool::sendToOneProcess(T&& message)
852 {
853     bool messageSent = false;
854     size_t processCount = m_processes.size();
855     for (size_t i = 0; i < processCount; ++i) {
856         WebProcessProxy* process = m_processes[i].get();
857         if (process->canSendMessage()) {
858             process->send(std::forward<T>(message), 0);
859             messageSent = true;
860             break;
861         }
862     }
863
864     if (!messageSent) {
865         prewarmProcess();
866         RefPtr<WebProcessProxy> process = m_processes.last();
867         if (process->canSendMessage())
868             process->send(std::forward<T>(message), 0);
869     }
870 }
871
872 } // namespace WebKit