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