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