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