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