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