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