22554c4ef694e326b21bf814151f3f2613163156
[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
261     WebPageGroup& defaultPageGroup() { return m_defaultPageGroup.get(); }
262
263     void setAlwaysUsesComplexTextCodePath(bool);
264     void setShouldUseFontSmoothing(bool);
265     
266     void registerURLSchemeAsEmptyDocument(const String&);
267     void registerURLSchemeAsSecure(const String&);
268     void registerURLSchemeAsBypassingContentSecurityPolicy(const String&);
269     void setDomainRelaxationForbiddenForURLScheme(const String&);
270     void setCanHandleHTTPSServerTrustEvaluation(bool);
271     void registerURLSchemeAsLocal(const String&);
272     void registerURLSchemeAsNoAccess(const String&);
273     void registerURLSchemeAsDisplayIsolated(const String&);
274     void registerURLSchemeAsCORSEnabled(const String&);
275     void registerURLSchemeAsCachePartitioned(const String&);
276     void registerURLSchemeServiceWorkersCanHandle(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     void disableServiceWorkerProcessTerminationDelay();
321
322     void syncNetworkProcessCookies();
323     void syncLocalStorage(CompletionHandler<void()>&& callback);
324     void clearLegacyPrivateBrowsingLocalStorage(CompletionHandler<void()>&& callback);
325
326     void setShouldMakeNextWebProcessLaunchFailForTesting(bool value) { m_shouldMakeNextWebProcessLaunchFailForTesting = value; }
327     bool shouldMakeNextWebProcessLaunchFailForTesting() const { return m_shouldMakeNextWebProcessLaunchFailForTesting; }
328     void setShouldMakeNextNetworkProcessLaunchFailForTesting(bool value) { m_shouldMakeNextNetworkProcessLaunchFailForTesting = value; }
329     bool shouldMakeNextNetworkProcessLaunchFailForTesting() const { return m_shouldMakeNextNetworkProcessLaunchFailForTesting; }
330
331     void reportWebContentCPUTime(Seconds cpuTime, uint64_t activityState);
332
333     void allowSpecificHTTPSCertificateForHost(const WebCertificateInfo*, const String& host);
334
335     WebProcessProxy& processForRegistrableDomain(WebsiteDataStore&, WebPageProxy*, const WebCore::RegistrableDomain&); // Will return an existing one if limit is met or due to caching.
336
337     void prewarmProcess();
338
339     bool shouldTerminate(WebProcessProxy*);
340
341     void disableProcessTermination() { m_processTerminationEnabled = false; }
342     void enableProcessTermination();
343
344     void updateAutomationCapabilities() const;
345     void setAutomationSession(RefPtr<WebAutomationSession>&&);
346     WebAutomationSession* automationSession() const { return m_automationSession.get(); }
347
348     // Defaults to false.
349     void setHTTPPipeliningEnabled(bool);
350     bool httpPipeliningEnabled() const;
351
352     void getStatistics(uint32_t statisticsMask, Function<void (API::Dictionary*, CallbackBase::Error)>&&);
353     
354     bool javaScriptConfigurationFileEnabled() { return m_javaScriptConfigurationFileEnabled; }
355     void setJavaScriptConfigurationFileEnabled(bool flag);
356 #if PLATFORM(IOS_FAMILY)
357     void setJavaScriptConfigurationFileEnabledFromDefaults();
358 #endif
359
360     void garbageCollectJavaScriptObjects();
361     void setJavaScriptGarbageCollectorTimerEnabled(bool flag);
362
363 #if PLATFORM(COCOA)
364     static bool omitPDFSupport();
365 #endif
366
367     void fullKeyboardAccessModeChanged(bool fullKeyboardAccessEnabled);
368 #if OS(LINUX)
369     void sendMemoryPressureEvent(bool isCritical);
370 #endif
371     void textCheckerStateChanged();
372
373     Ref<API::Dictionary> plugInAutoStartOriginHashes() const;
374     void setPlugInAutoStartOriginHashes(API::Dictionary&);
375     void setPlugInAutoStartOrigins(API::Array&);
376     void setPlugInAutoStartOriginsFilteringOutEntriesAddedAfterTime(API::Dictionary&, WallTime);
377
378     // Network Process Management
379     NetworkProcessProxy& ensureNetworkProcess(WebsiteDataStore* withWebsiteDataStore = nullptr);
380     NetworkProcessProxy* networkProcess() { return m_networkProcess.get(); }
381     void networkProcessCrashed(NetworkProcessProxy&, Vector<std::pair<RefPtr<WebProcessProxy>, Messages::WebProcessProxy::GetNetworkProcessConnection::DelayedReply>>&&);
382
383     void getNetworkProcessConnection(WebProcessProxy&, Messages::WebProcessProxy::GetNetworkProcessConnection::DelayedReply&&);
384
385     bool isServiceWorkerPageID(WebPageProxyIdentifier) const;
386 #if ENABLE(SERVICE_WORKER)
387     void establishWorkerContextConnectionToNetworkProcess(NetworkProcessProxy&, WebCore::RegistrableDomain&&, PAL::SessionID);
388     size_t serviceWorkerProxiesCount() const { return m_serviceWorkerProcesses.size(); }
389     void setAllowsAnySSLCertificateForServiceWorker(bool allows) { m_allowsAnySSLCertificateForServiceWorker = allows; }
390     bool allowsAnySSLCertificateForServiceWorker() const { return m_allowsAnySSLCertificateForServiceWorker; }
391     void updateServiceWorkerUserAgent(const String& userAgent);
392     bool mayHaveRegisteredServiceWorkers(const WebsiteDataStore&);
393 #endif
394
395 #if PLATFORM(COCOA)
396     bool processSuppressionEnabled() const;
397 #endif
398
399     void windowServerConnectionStateChanged();
400
401 #if USE(SOUP)
402     void setIgnoreTLSErrors(bool);
403     bool ignoreTLSErrors() const { return m_ignoreTLSErrors; }
404 #endif
405
406     static void setInvalidMessageCallback(void (*)(WKStringRef));
407     static void didReceiveInvalidMessage(const IPC::StringReference& messageReceiverName, const IPC::StringReference& messageName);
408
409     void processDidCachePage(WebProcessProxy*);
410
411     bool isURLKnownHSTSHost(const String& urlString) const;
412     void resetHSTSHosts();
413     void resetHSTSHostsAddedAfterDate(double startDateIntervalSince1970);
414
415     void registerSchemeForCustomProtocol(const String&);
416     void unregisterSchemeForCustomProtocol(const String&);
417
418     static void registerGlobalURLSchemeAsHavingCustomProtocolHandlers(const String&);
419     static void unregisterGlobalURLSchemeAsHavingCustomProtocolHandlers(const String&);
420
421 #if PLATFORM(COCOA)
422     void updateProcessSuppressionState();
423
424     NSMutableDictionary *ensureBundleParameters();
425     NSMutableDictionary *bundleParameters() { return m_bundleParameters.get(); }
426 #else
427     void updateProcessSuppressionState() const { }
428 #endif
429
430     void updateHiddenPageThrottlingAutoIncreaseLimit();
431
432     void setMemoryCacheDisabled(bool);
433     void setFontWhitelist(API::Array*);
434
435     UserObservablePageCounter::Token userObservablePageCount()
436     {
437         return m_userObservablePageCounter.count();
438     }
439
440     ProcessSuppressionDisabledToken processSuppressionDisabledForPageCount()
441     {
442         return m_processSuppressionDisabledForPageCounter.count();
443     }
444
445     HiddenPageThrottlingAutoIncreasesCounter::Token hiddenPageThrottlingAutoIncreasesCount()
446     {
447         return m_hiddenPageThrottlingAutoIncreasesCounter.count();
448     }
449
450     void setResourceLoadStatisticsEnabled(bool);
451     void clearResourceLoadStatistics();
452
453     bool alwaysRunsAtBackgroundPriority() const { return m_alwaysRunsAtBackgroundPriority; }
454     bool shouldTakeUIBackgroundAssertion() const { return m_shouldTakeUIBackgroundAssertion; }
455
456     void synthesizeAppIsBackground(bool background);
457     
458 #if ENABLE(GAMEPAD)
459     void gamepadConnected(const UIGamepad&);
460     void gamepadDisconnected(const UIGamepad&);
461
462     void setInitialConnectedGamepads(const Vector<std::unique_ptr<UIGamepad>>&);
463 #endif
464
465 #if PLATFORM(COCOA)
466     bool cookieStoragePartitioningEnabled() const { return m_cookieStoragePartitioningEnabled; }
467     void setCookieStoragePartitioningEnabled(bool);
468
469     void clearPermanentCredentialsForProtectionSpace(WebCore::ProtectionSpace&&);
470 #endif
471     bool storageAccessAPIEnabled() const { return m_storageAccessAPIEnabled; }
472     void setStorageAccessAPIEnabled(bool);
473
474     static uint64_t registerProcessPoolCreationListener(Function<void(WebProcessPool&)>&&);
475     static void unregisterProcessPoolCreationListener(uint64_t identifier);
476
477 #if PLATFORM(IOS_FAMILY)
478     ForegroundWebProcessToken foregroundWebProcessToken() const { return ForegroundWebProcessToken(m_foregroundWebProcessCounter.count()); }
479     BackgroundWebProcessToken backgroundWebProcessToken() const { return BackgroundWebProcessToken(m_backgroundWebProcessCounter.count()); }
480 #endif
481
482     void processForNavigation(WebPageProxy&, const API::Navigation&, Ref<WebProcessProxy>&& sourceProcess, const URL& sourceURL, ProcessSwapRequestedByClient, Ref<WebsiteDataStore>&&, CompletionHandler<void(Ref<WebProcessProxy>&&, SuspendedPageProxy*, const String&)>&&);
483
484     // SuspendedPageProxy management.
485     void addSuspendedPage(std::unique_ptr<SuspendedPageProxy>&&);
486     void removeAllSuspendedPagesForPage(WebPageProxy&, WebProcessProxy* = nullptr);
487     std::unique_ptr<SuspendedPageProxy> takeSuspendedPage(SuspendedPageProxy&);
488     void removeSuspendedPage(SuspendedPageProxy&);
489     bool hasSuspendedPageFor(WebProcessProxy&, WebPageProxy&) const;
490     unsigned maxSuspendedPageCount() const { return m_maxSuspendedPageCount; }
491     RefPtr<WebProcessProxy> findReusableSuspendedPageProcess(const WebCore::RegistrableDomain&, WebPageProxy&, WebsiteDataStore&);
492
493     void clearSuspendedPages(AllowProcessCaching);
494
495     void didReachGoodTimeToPrewarm();
496
497     void didCollectPrewarmInformation(const WebCore::RegistrableDomain&, const WebCore::PrewarmInformation&);
498
499     void screenPropertiesStateChanged();
500
501     void addMockMediaDevice(const WebCore::MockMediaDevice&);
502     void clearMockMediaDevices();
503     void removeMockMediaDevice(const String& persistentId);
504     void resetMockMediaDevices();
505
506     void sendDisplayConfigurationChangedMessageForTesting();
507     void clearCurrentModifierStateForTesting();
508
509 #if ENABLE(RESOURCE_LOAD_STATISTICS)
510     void didCommitCrossSiteLoadWithDataTransfer(PAL::SessionID, const WebCore::RegistrableDomain& fromDomain, const WebCore::RegistrableDomain& toDomain, OptionSet<WebCore::CrossSiteNavigationDataTransfer::Flag>, WebPageProxyIdentifier, WebCore::PageIdentifier);
511 #endif
512
513 #if PLATFORM(GTK) || PLATFORM(WPE)
514     void setSandboxEnabled(bool enabled) { m_sandboxEnabled = enabled; };
515     void addSandboxPath(const CString& path, SandboxPermission permission) { m_extraSandboxPaths.add(path, permission); };
516     const HashMap<CString, SandboxPermission>& sandboxPaths() const { return m_extraSandboxPaths; };
517     bool sandboxEnabled() const { return m_sandboxEnabled; };
518 #endif
519     
520     void setWebProcessHasUploads(WebCore::ProcessIdentifier);
521     void clearWebProcessHasUploads(WebCore::ProcessIdentifier);
522
523     void setWebProcessIsPlayingAudibleMedia(WebCore::ProcessIdentifier);
524     void clearWebProcessIsPlayingAudibleMedia(WebCore::ProcessIdentifier);
525
526     void disableDelayedWebProcessLaunch() { m_isDelayedWebProcessLaunchDisabled = true; }
527
528     void setJavaScriptConfigurationDirectory(String&& directory) { m_javaScriptConfigurationDirectory = directory; }
529     const String& javaScriptConfigurationDirectory() const { return m_javaScriptConfigurationDirectory; }
530     
531     WebProcessDataStoreParameters webProcessDataStoreParameters(WebProcessProxy&, WebsiteDataStore&);
532     
533     PlugInAutoStartProvider& plugInAutoStartProvider() { return m_plugInAutoStartProvider; }
534
535 private:
536     void platformInitialize();
537
538     void platformInitializeWebProcess(const WebProcessProxy&, WebProcessCreationParameters&);
539     void platformInvalidateContext();
540
541     void processForNavigationInternal(WebPageProxy&, const API::Navigation&, Ref<WebProcessProxy>&& sourceProcess, const URL& sourceURL, ProcessSwapRequestedByClient, Ref<WebsiteDataStore>&&, CompletionHandler<void(Ref<WebProcessProxy>&&, SuspendedPageProxy*, const String&)>&&);
542
543     RefPtr<WebProcessProxy> tryTakePrewarmedProcess(WebsiteDataStore&);
544
545     WebProcessProxy& createNewWebProcess(WebsiteDataStore*, WebProcessProxy::IsPrewarmed = WebProcessProxy::IsPrewarmed::No);
546     void initializeNewWebProcess(WebProcessProxy&, WebsiteDataStore*, WebProcessProxy::IsPrewarmed = WebProcessProxy::IsPrewarmed::No);
547
548     void requestWebContentStatistics(StatisticsRequest&);
549     void requestNetworkingStatistics(StatisticsRequest&);
550
551     void platformInitializeNetworkProcess(NetworkProcessCreationParameters&);
552
553     void handleMessage(IPC::Connection&, const String& messageName, const UserData& messageBody);
554     void handleSynchronousMessage(IPC::Connection&, const String& messageName, const UserData& messageBody, CompletionHandler<void(UserData&&)>&&);
555
556     void didGetStatistics(const StatisticsData&, uint64_t callbackID);
557
558 #if ENABLE(GAMEPAD)
559     void startedUsingGamepads(IPC::Connection&);
560     void stoppedUsingGamepads(IPC::Connection&);
561
562     void processStoppedUsingGamepads(WebProcessProxy&);
563 #endif
564
565     void reinstateNetworkProcessAssertionState(NetworkProcessProxy&);
566     void updateProcessAssertions();
567
568     // IPC::MessageReceiver.
569     // Implemented in generated WebProcessPoolMessageReceiver.cpp
570     void didReceiveMessage(IPC::Connection&, IPC::Decoder&) override;
571     void didReceiveSyncMessage(IPC::Connection&, IPC::Decoder&, std::unique_ptr<IPC::Encoder>&) override;
572
573     static void languageChanged(void* context);
574     void languageChanged();
575
576     bool usesSingleWebProcess() const { return m_configuration->usesSingleWebProcess(); }
577
578 #if PLATFORM(IOS_FAMILY)
579     static String cookieStorageDirectory();
580     static String parentBundleDirectory();
581     static String networkingCachesDirectory();
582     static String webContentCachesDirectory();
583     static String containerTemporaryDirectory();
584 #endif
585
586 #if PLATFORM(COCOA)
587     void registerNotificationObservers();
588     void unregisterNotificationObservers();
589 #endif
590
591     void setApplicationIsActive(bool);
592
593     void resolvePathsForSandboxExtensions();
594     void platformResolvePathsForSandboxExtensions();
595
596     void addProcessToOriginCacheSet(WebProcessProxy&, const URL&);
597     void removeProcessFromOriginCacheSet(WebProcessProxy&);
598
599     void tryPrewarmWithDomainInformation(WebProcessProxy&, const WebCore::RegistrableDomain&);
600
601     void updateMaxSuspendedPageCount();
602
603 #if PLATFORM(IOS)
604     static float displayBrightness();
605     static void backlightLevelDidChangeCallback(CFNotificationCenterRef, void *observer, CFStringRef name, const void *, CFDictionaryRef userInfo);    
606 #endif
607
608     Ref<API::ProcessPoolConfiguration> m_configuration;
609
610     IPC::MessageReceiverMap m_messageReceiverMap;
611
612     Vector<RefPtr<WebProcessProxy>> m_processes;
613     WebProcessProxy* m_prewarmedProcess { nullptr };
614     WebProcessProxy* m_dummyProcessProxy { nullptr }; // A lightweight WebProcessProxy without backing process.
615
616     WebProcessProxy* m_processWithPageCache { nullptr };
617 #if ENABLE(SERVICE_WORKER)
618     using RegistrableDomainWithSessionID = std::pair<WebCore::RegistrableDomain, PAL::SessionID>;
619     HashMap<RegistrableDomainWithSessionID, WebProcessProxy*> m_serviceWorkerProcesses;
620     bool m_waitingForWorkerContextProcessConnection { false };
621     bool m_allowsAnySSLCertificateForServiceWorker { false };
622     bool m_shouldDisableServiceWorkerProcessTerminationDelay { false };
623     String m_serviceWorkerUserAgent;
624     Optional<WebPreferencesStore> m_serviceWorkerPreferences;
625     HashMap<String, bool> m_mayHaveRegisteredServiceWorkers;
626 #endif
627
628     Ref<WebPageGroup> m_defaultPageGroup;
629
630     RefPtr<API::Object> m_injectedBundleInitializationUserData;
631     std::unique_ptr<API::InjectedBundleClient> m_injectedBundleClient;
632
633     WebContextClient m_client;
634     WebContextConnectionClient m_connectionClient;
635     std::unique_ptr<API::AutomationClient> m_automationClient;
636     UniqueRef<API::DownloadClient> m_downloadClient;
637     std::unique_ptr<API::LegacyContextHistoryClient> m_historyClient;
638     std::unique_ptr<API::CustomProtocolManagerClient> m_customProtocolManagerClient;
639
640     RefPtr<WebAutomationSession> m_automationSession;
641
642 #if ENABLE(NETSCAPE_PLUGIN_API)
643     PluginInfoStore m_pluginInfoStore;
644 #endif
645     Ref<VisitedLinkStore> m_visitedLinkStore;
646     bool m_visitedLinksPopulated { false };
647
648     PlugInAutoStartProvider m_plugInAutoStartProvider { this };
649         
650     HashSet<String> m_schemesToRegisterAsEmptyDocument;
651     HashSet<String> m_schemesToRegisterAsSecure;
652     HashSet<String> m_schemesToRegisterAsBypassingContentSecurityPolicy;
653     HashSet<String> m_schemesToSetDomainRelaxationForbiddenFor;
654     HashSet<String> m_schemesToRegisterAsLocal;
655     HashSet<String> m_schemesToRegisterAsNoAccess;
656     HashSet<String> m_schemesToRegisterAsDisplayIsolated;
657     HashSet<String> m_schemesToRegisterAsCORSEnabled;
658     HashSet<String> m_schemesToRegisterAsAlwaysRevalidated;
659     HashSet<String> m_schemesToRegisterAsCachePartitioned;
660     HashSet<String> m_schemesServiceWorkersCanHandle;
661     HashSet<String> m_schemesToRegisterAsCanDisplayOnlyIfCanRequest;
662
663     bool m_alwaysUsesComplexTextCodePath { false };
664     bool m_shouldUseFontSmoothing { true };
665
666     Vector<String> m_fontWhitelist;
667
668     // Messages that were posted before any pages were created.
669     // The client should use initialization messages instead, so that a restarted process would get the same state.
670     Vector<std::pair<String, RefPtr<API::Object>>> m_messagesToInjectedBundlePostedToEmptyContext;
671
672     bool m_memorySamplerEnabled { false };
673     double m_memorySamplerInterval { 1400.0 };
674
675     RefPtr<WebKit::WebsiteDataStore> m_websiteDataStore;
676
677     typedef HashMap<const char*, RefPtr<WebContextSupplement>, PtrHash<const char*>> WebContextSupplementMap;
678     WebContextSupplementMap m_supplements;
679
680 #if USE(SOUP)
681     HTTPCookieAcceptPolicy m_initialHTTPCookieAcceptPolicy { HTTPCookieAcceptPolicy::OnlyFromMainDocumentDomain };
682     WebCore::SoupNetworkProxySettings m_networkProxySettings;
683 #endif
684     HashSet<String, ASCIICaseInsensitiveHash> m_urlSchemesRegisteredForCustomProtocols;
685
686 #if PLATFORM(MAC)
687     RetainPtr<NSObject> m_enhancedAccessibilityObserver;
688     RetainPtr<NSObject> m_automaticTextReplacementNotificationObserver;
689     RetainPtr<NSObject> m_automaticSpellingCorrectionNotificationObserver;
690     RetainPtr<NSObject> m_automaticQuoteSubstitutionNotificationObserver;
691     RetainPtr<NSObject> m_automaticDashSubstitutionNotificationObserver;
692     RetainPtr<NSObject> m_accessibilityDisplayOptionsNotificationObserver;
693 #if ENABLE(WEBPROCESS_WINDOWSERVER_BLOCKING)
694     RetainPtr<NSObject> m_scrollerStyleNotificationObserver;
695 #endif
696     RetainPtr<NSObject> m_activationObserver;
697     RetainPtr<NSObject> m_deactivationObserver;
698
699     std::unique_ptr<HighPerformanceGraphicsUsageSampler> m_highPerformanceGraphicsUsageSampler;
700     std::unique_ptr<PerActivityStateCPUUsageSampler> m_perActivityStateCPUUsageSampler;
701 #endif
702
703 #if PLATFORM(IOS_FAMILY)
704     RetainPtr<NSObject> m_accessibilityEnabledObserver;
705 #endif
706
707     bool m_shouldUseTestingNetworkSession { false };
708
709     bool m_processTerminationEnabled { true };
710
711     bool m_canHandleHTTPSServerTrustEvaluation { true };
712     bool m_didNetworkProcessCrash { false };
713     std::unique_ptr<NetworkProcessProxy> m_networkProcess;
714
715     HashMap<uint64_t, RefPtr<DictionaryCallback>> m_dictionaryCallbacks;
716     HashMap<uint64_t, RefPtr<StatisticsRequest>> m_statisticsRequests;
717
718 #if USE(SOUP)
719     bool m_ignoreTLSErrors { true };
720 #endif
721
722     bool m_memoryCacheDisabled { false };
723     bool m_javaScriptConfigurationFileEnabled { false };
724     String m_javaScriptConfigurationDirectory;
725     bool m_alwaysRunsAtBackgroundPriority;
726     bool m_shouldTakeUIBackgroundAssertion;
727     bool m_shouldMakeNextWebProcessLaunchFailForTesting { false };
728     bool m_shouldMakeNextNetworkProcessLaunchFailForTesting { false };
729     bool m_shouldEnableITPForDefaultSessions { false };
730
731     UserObservablePageCounter m_userObservablePageCounter;
732     ProcessSuppressionDisabledCounter m_processSuppressionDisabledForPageCounter;
733     HiddenPageThrottlingAutoIncreasesCounter m_hiddenPageThrottlingAutoIncreasesCounter;
734     RunLoop::Timer<WebProcessPool> m_hiddenPageThrottlingTimer;
735
736 #if PLATFORM(COCOA)
737     RetainPtr<NSMutableDictionary> m_bundleParameters;
738     ProcessSuppressionDisabledToken m_pluginProcessManagerProcessSuppressionDisabledToken;
739     mutable RetainPtr<NSSet> m_classesForParameterCoder;
740 #endif
741
742 #if ENABLE(CONTENT_EXTENSIONS)
743     HashMap<String, String> m_encodedContentExtensions;
744 #endif
745
746 #if ENABLE(NETSCAPE_PLUGIN_API)
747     HashMap<String, HashMap<String, HashMap<String, uint8_t>>> m_pluginLoadClientPolicies;
748 #endif
749
750 #if ENABLE(GAMEPAD)
751     HashSet<WebProcessProxy*> m_processesUsingGamepads;
752 #endif
753
754 #if PLATFORM(COCOA)
755     bool m_cookieStoragePartitioningEnabled { false };
756 #endif
757     bool m_storageAccessAPIEnabled { false };
758
759     struct Paths {
760         String injectedBundlePath;
761         String uiProcessBundleResourcePath;
762
763 #if PLATFORM(IOS_FAMILY)
764         String cookieStorageDirectory;
765         String containerCachesDirectory;
766         String containerTemporaryDirectory;
767 #endif
768
769         Vector<String> additionalWebProcessSandboxExtensionPaths;
770     };
771     Paths m_resolvedPaths;
772
773     HashMap<PAL::SessionID, HashSet<WebPageProxyIdentifier>> m_sessionToPageIDsMap;
774     RunLoop::Timer<WebProcessPool> m_serviceWorkerProcessesTerminationTimer;
775
776 #if PLATFORM(IOS_FAMILY)
777     ForegroundWebProcessCounter m_foregroundWebProcessCounter;
778     BackgroundWebProcessCounter m_backgroundWebProcessCounter;
779     ProcessThrottler::ForegroundActivityToken m_foregroundTokenForNetworkProcess;
780     ProcessThrottler::BackgroundActivityToken m_backgroundTokenForNetworkProcess;
781 #if ENABLE(SERVICE_WORKER)
782     HashMap<WebCore::RegistrableDomain, ProcessThrottler::ForegroundActivityToken> m_foregroundTokensForServiceWorkerProcesses;
783     HashMap<WebCore::RegistrableDomain, ProcessThrottler::BackgroundActivityToken> m_backgroundTokensForServiceWorkerProcesses;
784 #endif
785 #endif
786
787     Deque<std::unique_ptr<SuspendedPageProxy>> m_suspendedPages;
788     unsigned m_maxSuspendedPageCount { 0 };
789
790     UniqueRef<WebProcessCache> m_webProcessCache;
791     HashMap<WebCore::RegistrableDomain, RefPtr<WebProcessProxy>> m_swappedProcessesPerRegistrableDomain;
792
793     HashMap<WebCore::RegistrableDomain, std::unique_ptr<WebCore::PrewarmInformation>> m_prewarmInformationPerRegistrableDomain;
794
795 #if PLATFORM(MAC) && ENABLE(WEBPROCESS_WINDOWSERVER_BLOCKING)
796     Vector<std::unique_ptr<DisplayLink>> m_displayLinks;
797 #endif
798
799 #if PLATFORM(GTK) || PLATFORM(WPE)
800     bool m_sandboxEnabled { false };
801     HashMap<CString, SandboxPermission> m_extraSandboxPaths;
802 #endif
803
804     HashMap<WebCore::ProcessIdentifier, std::unique_ptr<ProcessAssertion>> m_processesWithUploads;
805     std::unique_ptr<ProcessAssertion> m_uiProcessUploadAssertion;
806
807     HashMap<WebCore::ProcessIdentifier, std::unique_ptr<ProcessAssertion>> m_processesPlayingAudibleMedia;
808     std::unique_ptr<ProcessAssertion> m_uiProcessMediaPlaybackAssertion;
809
810 #if PLATFORM(IOS)
811     // FIXME: Delayed process launch is currently disabled on iOS for performance reasons (rdar://problem/49074131).
812     bool m_isDelayedWebProcessLaunchDisabled { true };
813 #else
814     bool m_isDelayedWebProcessLaunchDisabled { false };
815 #endif
816 };
817
818 template<typename T>
819 void WebProcessPool::sendToNetworkingProcess(T&& message)
820 {
821     if (m_networkProcess && m_networkProcess->canSendMessage())
822         m_networkProcess->send(std::forward<T>(message), 0);
823 }
824
825 template<typename T>
826 void WebProcessPool::sendToNetworkingProcessRelaunchingIfNecessary(T&& message)
827 {
828     ensureNetworkProcess();
829     m_networkProcess->send(std::forward<T>(message), 0);
830 }
831
832 template<typename T>
833 void WebProcessPool::sendToAllProcesses(const T& message)
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())
839             process->send(T(message), 0);
840     }
841 }
842
843 template<typename T>
844 void WebProcessPool::sendToAllProcessesForSession(const T& message, PAL::SessionID sessionID)
845 {
846     size_t processCount = m_processes.size();
847     for (size_t i = 0; i < processCount; ++i) {
848         WebProcessProxy* process = m_processes[i].get();
849         if (process->canSendMessage() && !process->isPrewarmed() && process->sessionID() == sessionID)
850             process->send(T(message), 0);
851     }
852 }
853
854 template<typename T>
855 void WebProcessPool::sendToAllProcessesRelaunchingThemIfNecessary(const T& message)
856 {
857     // 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.
858     sendToAllProcesses(message);
859 }
860
861 template<typename T>
862 void WebProcessPool::sendToOneProcess(T&& message)
863 {
864     bool messageSent = false;
865     size_t processCount = m_processes.size();
866     for (size_t i = 0; i < processCount; ++i) {
867         WebProcessProxy* process = m_processes[i].get();
868         if (process->canSendMessage()) {
869             process->send(std::forward<T>(message), 0);
870             messageSent = true;
871             break;
872         }
873     }
874
875     if (!messageSent) {
876         prewarmProcess();
877         RefPtr<WebProcessProxy> process = m_processes.last();
878         if (process->canSendMessage())
879             process->send(std::forward<T>(message), 0);
880     }
881 }
882
883 } // namespace WebKit