[PSON] Add mechanism to clear suspended pages while bypassing the WebProcess cache
[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(WebPageProxy&);
191     void pageEndUsingWebsiteDataStore(WebPageProxy&);
192
193     const String& injectedBundlePath() const { return m_configuration->injectedBundlePath(); }
194
195     DownloadProxy* download(WebPageProxy* initiatingPage, const WebCore::ResourceRequest&, const String& suggestedFilename = { });
196     DownloadProxy* resumeDownload(WebPageProxy* initiatingPage, const API::Data* resumeData, const String& path);
197
198     void setInjectedBundleInitializationUserData(RefPtr<API::Object>&& userData) { m_injectedBundleInitializationUserData = WTFMove(userData); }
199
200     void postMessageToInjectedBundle(const String&, API::Object*);
201
202     void populateVisitedLinks();
203
204     void handleMemoryPressureWarning(Critical);
205
206 #if ENABLE(NETSCAPE_PLUGIN_API)
207     void setAdditionalPluginsDirectory(const String&);
208     void refreshPlugins();
209
210     PluginInfoStore& pluginInfoStore() { return m_pluginInfoStore; }
211
212     void setPluginLoadClientPolicy(WebCore::PluginLoadClientPolicy, const String& host, const String& bundleIdentifier, const String& versionString);
213     void resetPluginLoadClientPolicies(HashMap<String, HashMap<String, HashMap<String, uint8_t>>>&&);
214     void clearPluginClientPolicies();
215     const HashMap<String, HashMap<String, HashMap<String, uint8_t>>>& pluginLoadClientPolicies() const { return m_pluginLoadClientPolicies; }
216 #endif
217
218 #if PLATFORM(MAC) && ENABLE(WEBPROCESS_WINDOWSERVER_BLOCKING)
219     void startDisplayLink(IPC::Connection&, unsigned observerID, uint32_t displayID);
220     void stopDisplayLink(IPC::Connection&, unsigned observerID, uint32_t displayID);
221     void stopDisplayLinks(IPC::Connection&);
222 #endif
223
224     void addSupportedPlugin(String&& matchingDomain, String&& name, HashSet<String>&& mimeTypes, HashSet<String> extensions);
225     void clearSupportedPlugins();
226
227     ProcessID networkProcessIdentifier();
228     void activePagesOriginsInWebProcessForTesting(ProcessID, CompletionHandler<void(Vector<String>&&)>&&);
229     bool networkProcessHasEntitlementForTesting(const String&);
230
231     WebPageGroup& defaultPageGroup() { return m_defaultPageGroup.get(); }
232
233     void setAlwaysUsesComplexTextCodePath(bool);
234     void setShouldUseFontSmoothing(bool);
235     
236     void registerURLSchemeAsEmptyDocument(const String&);
237     void registerURLSchemeAsSecure(const String&);
238     void registerURLSchemeAsBypassingContentSecurityPolicy(const String&);
239     void setDomainRelaxationForbiddenForURLScheme(const String&);
240     void setCanHandleHTTPSServerTrustEvaluation(bool);
241     void registerURLSchemeAsLocal(const String&);
242     void registerURLSchemeAsNoAccess(const String&);
243     void registerURLSchemeAsDisplayIsolated(const String&);
244     void registerURLSchemeAsCORSEnabled(const String&);
245     void registerURLSchemeAsCachePartitioned(const String&);
246     void registerURLSchemeServiceWorkersCanHandle(const String&);
247     void registerURLSchemeAsCanDisplayOnlyIfCanRequest(const String&);
248
249     void preconnectToServer(const URL&);
250
251     VisitedLinkStore& visitedLinkStore() { return m_visitedLinkStore.get(); }
252
253     void setCacheModel(CacheModel);
254     CacheModel cacheModel() const { return m_configuration->cacheModel(); }
255
256     void setDefaultRequestTimeoutInterval(double);
257
258     void startMemorySampler(const double interval);
259     void stopMemorySampler();
260
261 #if USE(SOUP)
262     void setInitialHTTPCookieAcceptPolicy(HTTPCookieAcceptPolicy policy) { m_initialHTTPCookieAcceptPolicy = policy; }
263     void setNetworkProxySettings(const WebCore::SoupNetworkProxySettings&);
264 #endif
265     void setEnhancedAccessibility(bool);
266     
267     // Downloads.
268     DownloadProxy* createDownloadProxy(const WebCore::ResourceRequest&, WebPageProxy* originatingPage);
269     API::DownloadClient& downloadClient() { return *m_downloadClient; }
270
271     bool usesNetworkingDaemon() const;
272     
273     API::LegacyContextHistoryClient& historyClient() { return *m_historyClient; }
274     WebContextClient& client() { return m_client; }
275
276     API::CustomProtocolManagerClient& customProtocolManagerClient() const { return *m_customProtocolManagerClient; }
277
278     struct Statistics {
279         unsigned wkViewCount;
280         unsigned wkPageCount;
281         unsigned wkFrameCount;
282     };
283     static Statistics& statistics();    
284
285     void useTestingNetworkSession();
286     bool isUsingTestingNetworkSession() const { return m_shouldUseTestingNetworkSession; }
287
288     void setAllowsAnySSLCertificateForWebSocket(bool);
289
290     void clearCachedCredentials();
291     void terminateNetworkProcess();
292     void terminateServiceWorkerProcesses();
293     void disableServiceWorkerProcessTerminationDelay();
294
295     void syncNetworkProcessCookies();
296
297     void setIDBPerOriginQuota(uint64_t);
298
299     void setShouldMakeNextWebProcessLaunchFailForTesting(bool value) { m_shouldMakeNextWebProcessLaunchFailForTesting = value; }
300     bool shouldMakeNextWebProcessLaunchFailForTesting() const { return m_shouldMakeNextWebProcessLaunchFailForTesting; }
301     void setShouldMakeNextNetworkProcessLaunchFailForTesting(bool value) { m_shouldMakeNextNetworkProcessLaunchFailForTesting = value; }
302     bool shouldMakeNextNetworkProcessLaunchFailForTesting() const { return m_shouldMakeNextNetworkProcessLaunchFailForTesting; }
303
304     void reportWebContentCPUTime(Seconds cpuTime, uint64_t activityState);
305
306     void allowSpecificHTTPSCertificateForHost(const WebCertificateInfo*, const String& host);
307
308     WebProcessProxy& createNewWebProcessRespectingProcessCountLimit(WebsiteDataStore&); // Will return an existing one if limit is met.
309
310     enum class MayCreateDefaultDataStore { No, Yes };
311     void prewarmProcess(MayCreateDefaultDataStore);
312
313     bool shouldTerminate(WebProcessProxy*);
314
315     void disableProcessTermination() { m_processTerminationEnabled = false; }
316     void enableProcessTermination();
317
318     void updateAutomationCapabilities() const;
319     void setAutomationSession(RefPtr<WebAutomationSession>&&);
320     WebAutomationSession* automationSession() const { return m_automationSession.get(); }
321
322     // Defaults to false.
323     void setHTTPPipeliningEnabled(bool);
324     bool httpPipeliningEnabled() const;
325
326     void getStatistics(uint32_t statisticsMask, Function<void (API::Dictionary*, CallbackBase::Error)>&&);
327     
328     bool javaScriptConfigurationFileEnabled() { return m_javaScriptConfigurationFileEnabled; }
329     void setJavaScriptConfigurationFileEnabled(bool flag);
330 #if PLATFORM(IOS_FAMILY)
331     void setJavaScriptConfigurationFileEnabledFromDefaults();
332 #endif
333
334     void garbageCollectJavaScriptObjects();
335     void setJavaScriptGarbageCollectorTimerEnabled(bool flag);
336
337 #if PLATFORM(COCOA)
338     static bool omitPDFSupport();
339 #endif
340
341     void fullKeyboardAccessModeChanged(bool fullKeyboardAccessEnabled);
342 #if OS(LINUX)
343     void sendMemoryPressureEvent(bool isCritical);
344 #endif
345     void textCheckerStateChanged();
346
347     Ref<API::Dictionary> plugInAutoStartOriginHashes() const;
348     void setPlugInAutoStartOriginHashes(API::Dictionary&);
349     void setPlugInAutoStartOrigins(API::Array&);
350     void setPlugInAutoStartOriginsFilteringOutEntriesAddedAfterTime(API::Dictionary&, WallTime);
351
352     // Network Process Management
353     NetworkProcessProxy& ensureNetworkProcess(WebsiteDataStore* withWebsiteDataStore = nullptr);
354     NetworkProcessProxy* networkProcess() { return m_networkProcess.get(); }
355     void networkProcessCrashed(NetworkProcessProxy&, Vector<std::pair<RefPtr<WebProcessProxy>, Messages::WebProcessProxy::GetNetworkProcessConnection::DelayedReply>>&&);
356
357     void getNetworkProcessConnection(WebProcessProxy&, Messages::WebProcessProxy::GetNetworkProcessConnection::DelayedReply&&);
358
359 #if ENABLE(SERVICE_WORKER)
360     void establishWorkerContextConnectionToNetworkProcess(NetworkProcessProxy&, WebCore::SecurityOriginData&&, Optional<PAL::SessionID>);
361     ServiceWorkerProcessProxy* serviceWorkerProcessProxyFromPageID(uint64_t pageID) const;
362     const HashMap<WebCore::SecurityOriginData, ServiceWorkerProcessProxy*>& serviceWorkerProxies() const { return m_serviceWorkerProcesses; }
363     void setAllowsAnySSLCertificateForServiceWorker(bool allows) { m_allowsAnySSLCertificateForServiceWorker = allows; }
364     bool allowsAnySSLCertificateForServiceWorker() const { return m_allowsAnySSLCertificateForServiceWorker; }
365     void updateServiceWorkerUserAgent(const String& userAgent);
366     bool mayHaveRegisteredServiceWorkers(const WebsiteDataStore&);
367 #endif
368
369 #if PLATFORM(COCOA)
370     bool processSuppressionEnabled() const;
371 #endif
372
373     void windowServerConnectionStateChanged();
374
375     static void willStartUsingPrivateBrowsing();
376     static void willStopUsingPrivateBrowsing();
377
378 #if USE(SOUP)
379     void setIgnoreTLSErrors(bool);
380     bool ignoreTLSErrors() const { return m_ignoreTLSErrors; }
381 #endif
382
383     static void setInvalidMessageCallback(void (*)(WKStringRef));
384     static void didReceiveInvalidMessage(const IPC::StringReference& messageReceiverName, const IPC::StringReference& messageName);
385
386     void processDidCachePage(WebProcessProxy*);
387
388     bool isURLKnownHSTSHost(const String& urlString, bool privateBrowsingEnabled) const;
389     void resetHSTSHosts();
390     void resetHSTSHostsAddedAfterDate(double startDateIntervalSince1970);
391
392     void registerSchemeForCustomProtocol(const String&);
393     void unregisterSchemeForCustomProtocol(const String&);
394
395     static void registerGlobalURLSchemeAsHavingCustomProtocolHandlers(const String&);
396     static void unregisterGlobalURLSchemeAsHavingCustomProtocolHandlers(const String&);
397
398 #if PLATFORM(COCOA)
399     void updateProcessSuppressionState();
400
401     NSMutableDictionary *ensureBundleParameters();
402     NSMutableDictionary *bundleParameters() { return m_bundleParameters.get(); }
403 #else
404     void updateProcessSuppressionState() const { }
405 #endif
406
407     void updateHiddenPageThrottlingAutoIncreaseLimit();
408
409     void setMemoryCacheDisabled(bool);
410     void setFontWhitelist(API::Array*);
411
412     UserObservablePageCounter::Token userObservablePageCount()
413     {
414         return m_userObservablePageCounter.count();
415     }
416
417     ProcessSuppressionDisabledToken processSuppressionDisabledForPageCount()
418     {
419         return m_processSuppressionDisabledForPageCounter.count();
420     }
421
422     HiddenPageThrottlingAutoIncreasesCounter::Token hiddenPageThrottlingAutoIncreasesCount()
423     {
424         return m_hiddenPageThrottlingAutoIncreasesCounter.count();
425     }
426
427     void setResourceLoadStatisticsEnabled(bool);
428     void clearResourceLoadStatistics();
429
430     bool alwaysRunsAtBackgroundPriority() const { return m_alwaysRunsAtBackgroundPriority; }
431     bool shouldTakeUIBackgroundAssertion() const { return m_shouldTakeUIBackgroundAssertion; }
432
433 #if ENABLE(GAMEPAD)
434     void gamepadConnected(const UIGamepad&);
435     void gamepadDisconnected(const UIGamepad&);
436
437     void setInitialConnectedGamepads(const Vector<std::unique_ptr<UIGamepad>>&);
438 #endif
439
440 #if PLATFORM(COCOA)
441     bool cookieStoragePartitioningEnabled() const { return m_cookieStoragePartitioningEnabled; }
442     void setCookieStoragePartitioningEnabled(bool);
443     bool storageAccessAPIEnabled() const { return m_storageAccessAPIEnabled; }
444     void setStorageAccessAPIEnabled(bool);
445 #endif
446
447 #if ENABLE(SERVICE_WORKER)
448     void postMessageToServiceWorkerClient(const WebCore::ServiceWorkerClientIdentifier& destinationIdentifier, WebCore::MessageWithMessagePorts&&, WebCore::ServiceWorkerIdentifier sourceIdentifier, const String& sourceOrigin);
449     void postMessageToServiceWorker(WebCore::ServiceWorkerIdentifier destination, WebCore::MessageWithMessagePorts&&, const WebCore::ServiceWorkerOrClientIdentifier& source, WebCore::SWServerConnectionIdentifier);
450 #endif
451
452     static uint64_t registerProcessPoolCreationListener(Function<void(WebProcessPool&)>&&);
453     static void unregisterProcessPoolCreationListener(uint64_t identifier);
454
455 #if PLATFORM(IOS_FAMILY)
456     ForegroundWebProcessToken foregroundWebProcessToken() const { return ForegroundWebProcessToken(m_foregroundWebProcessCounter.count()); }
457     BackgroundWebProcessToken backgroundWebProcessToken() const { return BackgroundWebProcessToken(m_backgroundWebProcessCounter.count()); }
458 #endif
459
460     void processForNavigation(WebPageProxy&, const API::Navigation&, Ref<WebProcessProxy>&& sourceProcess, const URL& sourceURL, ProcessSwapRequestedByClient, CompletionHandler<void(Ref<WebProcessProxy>&&, SuspendedPageProxy*, const String&)>&&);
461
462     // SuspendedPageProxy management.
463     void addSuspendedPage(std::unique_ptr<SuspendedPageProxy>&&);
464     void removeAllSuspendedPagesForPage(WebPageProxy&, WebProcessProxy* = nullptr);
465     void closeFailedSuspendedPagesForPage(WebPageProxy&);
466     std::unique_ptr<SuspendedPageProxy> takeSuspendedPage(SuspendedPageProxy&);
467     void removeSuspendedPage(SuspendedPageProxy&);
468     bool hasSuspendedPageFor(WebProcessProxy&, WebPageProxy&) const;
469     unsigned maxSuspendedPageCount() const { return m_maxSuspendedPageCount; }
470     RefPtr<WebProcessProxy> findReusableSuspendedPageProcess(const String&, WebPageProxy&);
471
472     void clearSuspendedPages(AllowProcessCaching);
473
474     void didReachGoodTimeToPrewarm();
475
476     void didCollectPrewarmInformation(const String& registrableDomain, const WebCore::PrewarmInformation&);
477
478     void screenPropertiesStateChanged();
479
480     void addMockMediaDevice(const WebCore::MockMediaDevice&);
481     void clearMockMediaDevices();
482     void removeMockMediaDevice(const String& persistentId);
483     void resetMockMediaDevices();
484
485     void sendDisplayConfigurationChangedMessageForTesting();
486     void clearCurrentModifierStateForTesting();
487
488     void dumpAdClickAttribution(PAL::SessionID, CompletionHandler<void(const String&)>&&);
489     void clearAdClickAttribution(PAL::SessionID, CompletionHandler<void()>&&);
490
491 #if PLATFORM(GTK) || PLATFORM(WPE)
492     void setSandboxEnabled(bool enabled) { m_sandboxEnabled = enabled; };
493     void addSandboxPath(const CString& path, SandboxPermission permission) { m_extraSandboxPaths.add(path, permission); };
494     const HashMap<CString, SandboxPermission>& sandboxPaths() const { return m_extraSandboxPaths; };
495     bool sandboxEnabled() const { return m_sandboxEnabled; };
496 #endif
497
498 private:
499     void platformInitialize();
500
501     void platformInitializeWebProcess(WebProcessCreationParameters&);
502     void platformInvalidateContext();
503
504     void processForNavigationInternal(WebPageProxy&, const API::Navigation&, Ref<WebProcessProxy>&& sourceProcess, const URL& sourceURL, ProcessSwapRequestedByClient, CompletionHandler<void(Ref<WebProcessProxy>&&, SuspendedPageProxy*, const String&)>&&);
505
506     RefPtr<WebProcessProxy> tryTakePrewarmedProcess(WebsiteDataStore&);
507
508     WebProcessProxy& createNewWebProcess(WebsiteDataStore&, WebProcessProxy::IsPrewarmed = WebProcessProxy::IsPrewarmed::No);
509     void initializeNewWebProcess(WebProcessProxy&, WebsiteDataStore&, WebProcessProxy::IsPrewarmed = WebProcessProxy::IsPrewarmed::No);
510
511     void requestWebContentStatistics(StatisticsRequest&);
512     void requestNetworkingStatistics(StatisticsRequest&);
513
514     void platformInitializeNetworkProcess(NetworkProcessCreationParameters&);
515
516     void handleMessage(IPC::Connection&, const String& messageName, const UserData& messageBody);
517     void handleSynchronousMessage(IPC::Connection&, const String& messageName, const UserData& messageBody, CompletionHandler<void(UserData&&)>&&);
518
519     void didGetStatistics(const StatisticsData&, uint64_t callbackID);
520
521 #if ENABLE(GAMEPAD)
522     void startedUsingGamepads(IPC::Connection&);
523     void stoppedUsingGamepads(IPC::Connection&);
524
525     void processStoppedUsingGamepads(WebProcessProxy&);
526 #endif
527
528     void reinstateNetworkProcessAssertionState(NetworkProcessProxy&);
529     void updateProcessAssertions();
530
531     // IPC::MessageReceiver.
532     // Implemented in generated WebProcessPoolMessageReceiver.cpp
533     void didReceiveMessage(IPC::Connection&, IPC::Decoder&) override;
534     void didReceiveSyncMessage(IPC::Connection&, IPC::Decoder&, std::unique_ptr<IPC::Encoder>&) override;
535
536     static void languageChanged(void* context);
537     void languageChanged();
538
539     bool usesSingleWebProcess() const { return m_configuration->usesSingleWebProcess(); }
540
541 #if PLATFORM(IOS_FAMILY)
542     String cookieStorageDirectory() const;
543 #endif
544
545 #if PLATFORM(IOS_FAMILY)
546     String parentBundleDirectory() const;
547     String networkingCachesDirectory() const;
548     String webContentCachesDirectory() const;
549     String containerTemporaryDirectory() const;
550 #endif
551
552 #if PLATFORM(COCOA)
553     void registerNotificationObservers();
554     void unregisterNotificationObservers();
555 #endif
556
557     void setApplicationIsActive(bool);
558
559     void addPlugInAutoStartOriginHash(const String& pageOrigin, unsigned plugInOriginHash, PAL::SessionID);
560     void plugInDidReceiveUserInteraction(unsigned plugInOriginHash, PAL::SessionID);
561
562     void setAnyPageGroupMightHavePrivateBrowsingEnabled(bool);
563
564     void resolvePathsForSandboxExtensions();
565     void platformResolvePathsForSandboxExtensions();
566
567     void addProcessToOriginCacheSet(WebProcessProxy&, const URL&);
568     void removeProcessFromOriginCacheSet(WebProcessProxy&);
569
570     void tryPrewarmWithDomainInformation(WebProcessProxy&, const URL&);
571
572     void updateMaxSuspendedPageCount();
573
574     Ref<API::ProcessPoolConfiguration> m_configuration;
575
576     IPC::MessageReceiverMap m_messageReceiverMap;
577
578     Vector<RefPtr<WebProcessProxy>> m_processes;
579     WebProcessProxy* m_prewarmedProcess { nullptr };
580
581     WebProcessProxy* m_processWithPageCache { nullptr };
582 #if ENABLE(SERVICE_WORKER)
583     HashMap<WebCore::SecurityOriginData, ServiceWorkerProcessProxy*> m_serviceWorkerProcesses;
584     bool m_waitingForWorkerContextProcessConnection { false };
585     bool m_allowsAnySSLCertificateForServiceWorker { false };
586     bool m_shouldDisableServiceWorkerProcessTerminationDelay { false };
587     String m_serviceWorkerUserAgent;
588     Optional<WebPreferencesStore> m_serviceWorkerPreferences;
589     HashMap<String, bool> m_mayHaveRegisteredServiceWorkers;
590 #endif
591
592     Ref<WebPageGroup> m_defaultPageGroup;
593
594     RefPtr<API::Object> m_injectedBundleInitializationUserData;
595     std::unique_ptr<API::InjectedBundleClient> m_injectedBundleClient;
596
597     WebContextClient m_client;
598     WebContextConnectionClient m_connectionClient;
599     std::unique_ptr<API::AutomationClient> m_automationClient;
600     std::unique_ptr<API::DownloadClient> m_downloadClient;
601     std::unique_ptr<API::LegacyContextHistoryClient> m_historyClient;
602     std::unique_ptr<API::CustomProtocolManagerClient> m_customProtocolManagerClient;
603
604     RefPtr<WebAutomationSession> m_automationSession;
605
606 #if ENABLE(NETSCAPE_PLUGIN_API)
607     PluginInfoStore m_pluginInfoStore;
608 #endif
609     Ref<VisitedLinkStore> m_visitedLinkStore;
610     bool m_visitedLinksPopulated { false };
611
612     PlugInAutoStartProvider m_plugInAutoStartProvider { this };
613         
614     HashSet<String> m_schemesToRegisterAsEmptyDocument;
615     HashSet<String> m_schemesToRegisterAsSecure;
616     HashSet<String> m_schemesToRegisterAsBypassingContentSecurityPolicy;
617     HashSet<String> m_schemesToSetDomainRelaxationForbiddenFor;
618     HashSet<String> m_schemesToRegisterAsLocal;
619     HashSet<String> m_schemesToRegisterAsNoAccess;
620     HashSet<String> m_schemesToRegisterAsDisplayIsolated;
621     HashSet<String> m_schemesToRegisterAsCORSEnabled;
622     HashSet<String> m_schemesToRegisterAsAlwaysRevalidated;
623     HashSet<String> m_schemesToRegisterAsCachePartitioned;
624     HashSet<String> m_schemesServiceWorkersCanHandle;
625     HashSet<String> m_schemesToRegisterAsCanDisplayOnlyIfCanRequest;
626
627     bool m_alwaysUsesComplexTextCodePath { false };
628     bool m_shouldUseFontSmoothing { true };
629
630     Vector<String> m_fontWhitelist;
631
632     // Messages that were posted before any pages were created.
633     // The client should use initialization messages instead, so that a restarted process would get the same state.
634     Vector<std::pair<String, RefPtr<API::Object>>> m_messagesToInjectedBundlePostedToEmptyContext;
635
636     bool m_memorySamplerEnabled { false };
637     double m_memorySamplerInterval { 1400.0 };
638
639     RefPtr<API::WebsiteDataStore> m_websiteDataStore;
640
641     typedef HashMap<const char*, RefPtr<WebContextSupplement>, PtrHash<const char*>> WebContextSupplementMap;
642     WebContextSupplementMap m_supplements;
643
644 #if USE(SOUP)
645     HTTPCookieAcceptPolicy m_initialHTTPCookieAcceptPolicy { HTTPCookieAcceptPolicyOnlyFromMainDocumentDomain };
646     WebCore::SoupNetworkProxySettings m_networkProxySettings;
647 #endif
648     HashSet<String, ASCIICaseInsensitiveHash> m_urlSchemesRegisteredForCustomProtocols;
649
650 #if PLATFORM(MAC)
651     RetainPtr<NSObject> m_enhancedAccessibilityObserver;
652     RetainPtr<NSObject> m_automaticTextReplacementNotificationObserver;
653     RetainPtr<NSObject> m_automaticSpellingCorrectionNotificationObserver;
654     RetainPtr<NSObject> m_automaticQuoteSubstitutionNotificationObserver;
655     RetainPtr<NSObject> m_automaticDashSubstitutionNotificationObserver;
656     RetainPtr<NSObject> m_accessibilityDisplayOptionsNotificationObserver;
657 #if ENABLE(WEBPROCESS_WINDOWSERVER_BLOCKING)
658     RetainPtr<NSObject> m_scrollerStyleNotificationObserver;
659 #endif
660     RetainPtr<NSObject> m_activationObserver;
661     RetainPtr<NSObject> m_deactivationObserver;
662
663     std::unique_ptr<HighPerformanceGraphicsUsageSampler> m_highPerformanceGraphicsUsageSampler;
664     std::unique_ptr<PerActivityStateCPUUsageSampler> m_perActivityStateCPUUsageSampler;
665 #endif
666
667     bool m_shouldUseTestingNetworkSession { false };
668
669     bool m_processTerminationEnabled { true };
670
671     bool m_canHandleHTTPSServerTrustEvaluation { true };
672     bool m_didNetworkProcessCrash { false };
673     std::unique_ptr<NetworkProcessProxy> m_networkProcess;
674
675     HashMap<uint64_t, RefPtr<DictionaryCallback>> m_dictionaryCallbacks;
676     HashMap<uint64_t, RefPtr<StatisticsRequest>> m_statisticsRequests;
677
678 #if USE(SOUP)
679     bool m_ignoreTLSErrors { true };
680 #endif
681
682     bool m_memoryCacheDisabled { false };
683     bool m_javaScriptConfigurationFileEnabled { false };
684     bool m_alwaysRunsAtBackgroundPriority;
685     bool m_shouldTakeUIBackgroundAssertion;
686     bool m_shouldMakeNextWebProcessLaunchFailForTesting { false };
687     bool m_shouldMakeNextNetworkProcessLaunchFailForTesting { false };
688
689     UserObservablePageCounter m_userObservablePageCounter;
690     ProcessSuppressionDisabledCounter m_processSuppressionDisabledForPageCounter;
691     HiddenPageThrottlingAutoIncreasesCounter m_hiddenPageThrottlingAutoIncreasesCounter;
692     RunLoop::Timer<WebProcessPool> m_hiddenPageThrottlingTimer;
693
694 #if PLATFORM(COCOA)
695     RetainPtr<NSMutableDictionary> m_bundleParameters;
696     ProcessSuppressionDisabledToken m_pluginProcessManagerProcessSuppressionDisabledToken;
697 #endif
698
699 #if ENABLE(CONTENT_EXTENSIONS)
700     HashMap<String, String> m_encodedContentExtensions;
701 #endif
702
703 #if ENABLE(NETSCAPE_PLUGIN_API)
704     HashMap<String, HashMap<String, HashMap<String, uint8_t>>> m_pluginLoadClientPolicies;
705 #endif
706
707 #if ENABLE(GAMEPAD)
708     HashSet<WebProcessProxy*> m_processesUsingGamepads;
709 #endif
710
711 #if PLATFORM(COCOA)
712     bool m_cookieStoragePartitioningEnabled { false };
713     bool m_storageAccessAPIEnabled { false };
714 #endif
715
716     struct Paths {
717         String injectedBundlePath;
718         String applicationCacheDirectory;
719         String webSQLDatabaseDirectory;
720         String mediaCacheDirectory;
721         String mediaKeyStorageDirectory;
722         String uiProcessBundleResourcePath;
723         String indexedDatabaseDirectory;
724
725 #if PLATFORM(IOS_FAMILY)
726         String cookieStorageDirectory;
727         String containerCachesDirectory;
728         String containerTemporaryDirectory;
729 #endif
730
731         Vector<String> additionalWebProcessSandboxExtensionPaths;
732     };
733     Paths m_resolvedPaths;
734
735     HashMap<PAL::SessionID, HashSet<WebPageProxy*>> m_sessionToPagesMap;
736     RunLoop::Timer<WebProcessPool> m_serviceWorkerProcessesTerminationTimer;
737
738 #if PLATFORM(IOS_FAMILY)
739     ForegroundWebProcessCounter m_foregroundWebProcessCounter;
740     BackgroundWebProcessCounter m_backgroundWebProcessCounter;
741     ProcessThrottler::ForegroundActivityToken m_foregroundTokenForNetworkProcess;
742     ProcessThrottler::BackgroundActivityToken m_backgroundTokenForNetworkProcess;
743 #if ENABLE(SERVICE_WORKER)
744     HashMap<WebCore::SecurityOriginData, ProcessThrottler::ForegroundActivityToken> m_foregroundTokensForServiceWorkerProcesses;
745     HashMap<WebCore::SecurityOriginData, ProcessThrottler::BackgroundActivityToken> m_backgroundTokensForServiceWorkerProcesses;
746 #endif
747 #endif
748
749     Deque<std::unique_ptr<SuspendedPageProxy>> m_suspendedPages;
750     unsigned m_maxSuspendedPageCount { 0 };
751
752     UniqueRef<WebProcessCache> m_webProcessCache;
753     HashMap<String, RefPtr<WebProcessProxy>> m_swappedProcessesPerRegistrableDomain;
754
755     HashMap<String, std::unique_ptr<WebCore::PrewarmInformation>> m_prewarmInformationPerRegistrableDomain;
756
757 #if PLATFORM(MAC) && ENABLE(WEBPROCESS_WINDOWSERVER_BLOCKING)
758     Vector<std::unique_ptr<DisplayLink>> m_displayLinks;
759 #endif
760
761 #if PLATFORM(GTK) || PLATFORM(WPE)
762     bool m_sandboxEnabled { false };
763     HashMap<CString, SandboxPermission> m_extraSandboxPaths;
764 #endif
765 };
766
767 template<typename T>
768 void WebProcessPool::sendToNetworkingProcess(T&& message)
769 {
770     if (m_networkProcess && m_networkProcess->canSendMessage())
771         m_networkProcess->send(std::forward<T>(message), 0);
772 }
773
774 template<typename T>
775 void WebProcessPool::sendToNetworkingProcessRelaunchingIfNecessary(T&& message)
776 {
777     ensureNetworkProcess();
778     m_networkProcess->send(std::forward<T>(message), 0);
779 }
780
781 template<typename T>
782 void WebProcessPool::sendToAllProcesses(const T& message)
783 {
784     size_t processCount = m_processes.size();
785     for (size_t i = 0; i < processCount; ++i) {
786         WebProcessProxy* process = m_processes[i].get();
787         if (process->canSendMessage())
788             process->send(T(message), 0);
789     }
790 }
791
792 template<typename T>
793 void WebProcessPool::sendToAllProcessesRelaunchingThemIfNecessary(const T& message)
794 {
795     // 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.
796     sendToAllProcesses(message);
797 }
798
799 template<typename T>
800 void WebProcessPool::sendToOneProcess(T&& message)
801 {
802     bool messageSent = false;
803     size_t processCount = m_processes.size();
804     for (size_t i = 0; i < processCount; ++i) {
805         WebProcessProxy* process = m_processes[i].get();
806         if (process->canSendMessage()) {
807             process->send(std::forward<T>(message), 0);
808             messageSent = true;
809             break;
810         }
811     }
812
813     if (!messageSent) {
814         prewarmProcess(MayCreateDefaultDataStore::No);
815         RefPtr<WebProcessProxy> process = m_processes.last();
816         if (process->canSendMessage())
817             process->send(std::forward<T>(message), 0);
818     }
819 }
820
821 } // namespace WebKit