c9674f9f70616a378164a636983c5c2bcacec0e1
[WebKit-https.git] / Source / WebKit / UIProcess / WebProcessPool.cpp
1 /*
2  * Copyright (C) 2010-2018 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 #include "config.h"
27 #include "WebProcessPool.h"
28
29 #include "APIArray.h"
30 #include "APIAutomationClient.h"
31 #include "APICustomProtocolManagerClient.h"
32 #include "APIDownloadClient.h"
33 #include "APIHTTPCookieStore.h"
34 #include "APIInjectedBundleClient.h"
35 #include "APILegacyContextHistoryClient.h"
36 #include "APINavigation.h"
37 #include "APIPageConfiguration.h"
38 #include "APIProcessPoolConfiguration.h"
39 #include "AuxiliaryProcessMessages.h"
40 #include "DownloadProxy.h"
41 #include "DownloadProxyMessages.h"
42 #include "GamepadData.h"
43 #include "HighPerformanceGraphicsUsageSampler.h"
44 #include "LogInitialization.h"
45 #include "Logging.h"
46 #include "NetworkProcessCreationParameters.h"
47 #include "NetworkProcessMessages.h"
48 #include "NetworkProcessProxy.h"
49 #include "PerActivityStateCPUUsageSampler.h"
50 #include "PluginProcessManager.h"
51 #include "SandboxExtension.h"
52 #include "ServiceWorkerProcessProxy.h"
53 #include "StatisticsData.h"
54 #include "TextChecker.h"
55 #include "UIGamepad.h"
56 #include "UIGamepadProvider.h"
57 #include "WKContextPrivate.h"
58 #include "WebAutomationSession.h"
59 #include "WebBackForwardList.h"
60 #include "WebBackForwardListItem.h"
61 #include "WebCertificateInfo.h"
62 #include "WebContextSupplement.h"
63 #include "WebCookieManagerProxy.h"
64 #include "WebCoreArgumentCoders.h"
65 #include "WebGeolocationManagerProxy.h"
66 #include "WebKit2Initialize.h"
67 #include "WebMemorySampler.h"
68 #include "WebNotificationManagerProxy.h"
69 #include "WebPageGroup.h"
70 #include "WebPreferences.h"
71 #include "WebPreferencesKeys.h"
72 #include "WebProcessCache.h"
73 #include "WebProcessCreationParameters.h"
74 #include "WebProcessMessages.h"
75 #include "WebProcessPoolMessages.h"
76 #include "WebProcessProxy.h"
77 #include "WebsiteDataStore.h"
78 #include "WebsiteDataStoreParameters.h"
79 #include <JavaScriptCore/JSCInlines.h>
80 #include <WebCore/ApplicationCacheStorage.h>
81 #include <WebCore/LogInitialization.h>
82 #include <WebCore/MockRealtimeMediaSourceCenter.h>
83 #include <WebCore/NetworkStorageSession.h>
84 #include <WebCore/PlatformScreen.h>
85 #include <WebCore/ProcessIdentifier.h>
86 #include <WebCore/ProcessWarming.h>
87 #include <WebCore/ResourceRequest.h>
88 #include <WebCore/RuntimeApplicationChecks.h>
89 #include <pal/SessionID.h>
90 #include <wtf/Language.h>
91 #include <wtf/MainThread.h>
92 #include <wtf/NeverDestroyed.h>
93 #include <wtf/ProcessPrivilege.h>
94 #include <wtf/RunLoop.h>
95 #include <wtf/Scope.h>
96 #include <wtf/URLParser.h>
97 #include <wtf/WallTime.h>
98 #include <wtf/text/StringBuilder.h>
99 #include <wtf/text/StringConcatenateNumbers.h>
100
101 #if ENABLE(LEGACY_CUSTOM_PROTOCOL_MANAGER)
102 #include "LegacyCustomProtocolManagerMessages.h"
103 #endif
104
105 #if ENABLE(SERVICE_CONTROLS)
106 #include "ServicesController.h"
107 #endif
108
109 #if ENABLE(REMOTE_INSPECTOR)
110 #include <JavaScriptCore/RemoteInspector.h>
111 #endif
112
113 #if OS(LINUX)
114 #include "MemoryPressureMonitor.h"
115 #endif
116
117 #if PLATFORM(WAYLAND)
118 #include "WaylandCompositor.h"
119 #include <WebCore/PlatformDisplay.h>
120 #endif
121
122 #if PLATFORM(COCOA)
123 #include "VersionChecks.h"
124 #endif
125
126 #ifndef NDEBUG
127 #include <wtf/RefCountedLeakCounter.h>
128 #endif
129
130 namespace WebKit {
131 using namespace WebCore;
132
133 DEFINE_DEBUG_ONLY_GLOBAL(WTF::RefCountedLeakCounter, processPoolCounter, ("WebProcessPool"));
134
135 const Seconds serviceWorkerTerminationDelay { 5_s };
136
137 static uint64_t generateListenerIdentifier()
138 {
139     static uint64_t nextIdentifier = 1;
140     return nextIdentifier++;
141 }
142
143 static HashMap<uint64_t, Function<void(WebProcessPool&)>>& processPoolCreationListenerFunctionMap()
144 {
145     static NeverDestroyed<HashMap<uint64_t, Function<void(WebProcessPool&)>>> map;
146     return map;
147 }
148
149 uint64_t WebProcessPool::registerProcessPoolCreationListener(Function<void(WebProcessPool&)>&& function)
150 {
151     ASSERT(function);
152
153     auto identifier = generateListenerIdentifier();
154     processPoolCreationListenerFunctionMap().set(identifier, WTFMove(function));
155     return identifier;
156 }
157
158 void WebProcessPool::unregisterProcessPoolCreationListener(uint64_t identifier)
159 {
160     processPoolCreationListenerFunctionMap().remove(identifier);
161 }
162
163 Ref<WebProcessPool> WebProcessPool::create(API::ProcessPoolConfiguration& configuration)
164 {
165     InitializeWebKit2();
166     return adoptRef(*new WebProcessPool(configuration));
167 }
168
169 void WebProcessPool::notifyThisWebProcessPoolWasCreated()
170 {
171     auto& listenerMap = processPoolCreationListenerFunctionMap();
172
173     Vector<uint64_t> identifiers;
174     identifiers.reserveInitialCapacity(listenerMap.size());
175     for (auto identifier : listenerMap.keys())
176         identifiers.uncheckedAppend(identifier);
177
178     for (auto identifier : identifiers) {
179         auto iterator = listenerMap.find(identifier);
180         if (iterator == listenerMap.end())
181             continue;
182
183         // To make sure the Function object stays alive until after the function call has been made,
184         // we temporarily move it out of the map.
185         // This protects it from the Function calling unregisterProcessPoolCreationListener thereby
186         // removing itself from the map of listeners.
187         // If the identifier still exists in the map later, we move it back in.
188         Function<void(WebProcessPool&)> function = WTFMove(iterator->value);
189         function(*this);
190
191         iterator = listenerMap.find(identifier);
192         if (iterator != listenerMap.end()) {
193             ASSERT(!iterator->value);
194             iterator->value = WTFMove(function);
195         }
196     }
197 }
198
199 static Vector<WebProcessPool*>& processPools()
200 {
201     static NeverDestroyed<Vector<WebProcessPool*>> processPools;
202     return processPools;
203 }
204
205 const Vector<WebProcessPool*>& WebProcessPool::allProcessPools()
206 {
207     return processPools();
208 }
209
210 static Ref<WebsiteDataStoreConfiguration> legacyWebsiteDataStoreConfiguration(API::ProcessPoolConfiguration& processPoolConfiguration)
211 {
212     auto configuration = WebsiteDataStoreConfiguration::create();
213
214     configuration->setCacheStorageDirectory(String(API::WebsiteDataStore::defaultCacheStorageDirectory()));
215     configuration->setServiceWorkerRegistrationDirectory(String(API::WebsiteDataStore::defaultServiceWorkerRegistrationDirectory()));
216     configuration->setLocalStorageDirectory(String(processPoolConfiguration.localStorageDirectory()));
217     configuration->setWebSQLDatabaseDirectory(String(processPoolConfiguration.webSQLDatabaseDirectory()));
218     configuration->setApplicationCacheDirectory(String(processPoolConfiguration.applicationCacheDirectory()));
219     configuration->setApplicationCacheFlatFileSubdirectoryName(String(processPoolConfiguration.applicationCacheFlatFileSubdirectoryName()));
220     configuration->setMediaCacheDirectory(String(processPoolConfiguration.mediaCacheDirectory()));
221     configuration->setMediaKeysStorageDirectory(String(processPoolConfiguration.mediaKeysStorageDirectory()));
222     configuration->setResourceLoadStatisticsDirectory(String(processPoolConfiguration.resourceLoadStatisticsDirectory()));
223     configuration->setNetworkCacheDirectory(String(processPoolConfiguration.diskCacheDirectory()));
224     configuration->setJavaScriptConfigurationDirectory(String(processPoolConfiguration.javaScriptConfigurationDirectory()));
225
226     return configuration;
227 }
228
229 static HashSet<String, ASCIICaseInsensitiveHash>& globalURLSchemesWithCustomProtocolHandlers()
230 {
231     static NeverDestroyed<HashSet<String, ASCIICaseInsensitiveHash>> set;
232     return set;
233 }
234
235 WebProcessPool::WebProcessPool(API::ProcessPoolConfiguration& configuration)
236     : m_configuration(configuration.copy())
237     , m_defaultPageGroup(WebPageGroup::create())
238     , m_injectedBundleClient(std::make_unique<API::InjectedBundleClient>())
239     , m_automationClient(std::make_unique<API::AutomationClient>())
240     , m_downloadClient(std::make_unique<API::DownloadClient>())
241     , m_historyClient(std::make_unique<API::LegacyContextHistoryClient>())
242     , m_customProtocolManagerClient(std::make_unique<API::CustomProtocolManagerClient>())
243     , m_visitedLinkStore(VisitedLinkStore::create())
244 #if PLATFORM(MAC)
245     , m_highPerformanceGraphicsUsageSampler(std::make_unique<HighPerformanceGraphicsUsageSampler>(*this))
246     , m_perActivityStateCPUUsageSampler(std::make_unique<PerActivityStateCPUUsageSampler>(*this))
247 #endif
248     , m_alwaysRunsAtBackgroundPriority(m_configuration->alwaysRunsAtBackgroundPriority())
249     , m_shouldTakeUIBackgroundAssertion(m_configuration->shouldTakeUIBackgroundAssertion())
250     , m_userObservablePageCounter([this](RefCounterEvent) { updateProcessSuppressionState(); })
251     , m_processSuppressionDisabledForPageCounter([this](RefCounterEvent) { updateProcessSuppressionState(); })
252     , m_hiddenPageThrottlingAutoIncreasesCounter([this](RefCounterEvent) { m_hiddenPageThrottlingTimer.startOneShot(0_s); })
253     , m_hiddenPageThrottlingTimer(RunLoop::main(), this, &WebProcessPool::updateHiddenPageThrottlingAutoIncreaseLimit)
254     , m_serviceWorkerProcessesTerminationTimer(RunLoop::main(), this, &WebProcessPool::terminateServiceWorkerProcesses)
255 #if PLATFORM(IOS_FAMILY)
256     , m_foregroundWebProcessCounter([this](RefCounterEvent) { updateProcessAssertions(); })
257     , m_backgroundWebProcessCounter([this](RefCounterEvent) { updateProcessAssertions(); })
258 #endif
259     , m_webProcessCache(makeUniqueRef<WebProcessCache>(*this))
260 {
261     static std::once_flag onceFlag;
262     std::call_once(onceFlag, [] {
263         WTF::setProcessPrivileges(allPrivileges());
264         WebCore::NetworkStorageSession::permitProcessToUseCookieAPI(true);
265         Process::setIdentifier(WebCore::ProcessIdentifier::generate());
266     });
267
268     if (m_configuration->shouldHaveLegacyDataStore())
269         m_websiteDataStore = API::WebsiteDataStore::createLegacy(legacyWebsiteDataStoreConfiguration(m_configuration));
270
271     if (!m_websiteDataStore && API::WebsiteDataStore::defaultDataStoreExists())
272         m_websiteDataStore = API::WebsiteDataStore::defaultDataStore();
273
274     for (auto& scheme : m_configuration->alwaysRevalidatedURLSchemes())
275         m_schemesToRegisterAsAlwaysRevalidated.add(scheme);
276
277     for (const auto& urlScheme : m_configuration->cachePartitionedURLSchemes())
278         m_schemesToRegisterAsCachePartitioned.add(urlScheme);
279
280     platformInitialize();
281
282 #if OS(LINUX)
283     MemoryPressureMonitor::singleton().start();
284 #endif
285
286     addMessageReceiver(Messages::WebProcessPool::messageReceiverName(), *this);
287
288     // NOTE: These sub-objects must be initialized after m_messageReceiverMap..
289     addSupplement<WebCookieManagerProxy>();
290     addSupplement<WebGeolocationManagerProxy>();
291     addSupplement<WebNotificationManagerProxy>();
292 #if ENABLE(MEDIA_SESSION)
293     addSupplement<WebMediaSessionFocusManager>();
294 #endif
295
296     processPools().append(this);
297
298     addLanguageChangeObserver(this, languageChanged);
299
300     resolvePathsForSandboxExtensions();
301
302 #if !LOG_DISABLED || !RELEASE_LOG_DISABLED
303     WebCore::initializeLogChannelsIfNecessary();
304     WebKit::initializeLogChannelsIfNecessary();
305 #endif // !LOG_DISABLED || !RELEASE_LOG_DISABLED
306
307 #ifndef NDEBUG
308     processPoolCounter.increment();
309 #endif
310
311     notifyThisWebProcessPoolWasCreated();
312
313     updateMaxSuspendedPageCount();
314 }
315
316 WebProcessPool::~WebProcessPool()
317 {
318     m_webProcessCache->clear();
319
320     bool removed = processPools().removeFirst(this);
321     ASSERT_UNUSED(removed, removed);
322
323     removeLanguageChangeObserver(this);
324
325     m_messageReceiverMap.invalidate();
326
327     for (auto& supplement : m_supplements.values()) {
328         supplement->processPoolDestroyed();
329         supplement->clearProcessPool();
330     }
331
332     invalidateCallbackMap(m_dictionaryCallbacks, CallbackBase::Error::OwnerWasInvalidated);
333
334     platformInvalidateContext();
335
336 #ifndef NDEBUG
337     processPoolCounter.decrement();
338 #endif
339
340     if (m_networkProcess)
341         m_networkProcess->shutDownProcess();
342
343 #if ENABLE(GAMEPAD)
344     if (!m_processesUsingGamepads.isEmpty())
345         UIGamepadProvider::singleton().processPoolStoppedUsingGamepads(*this);
346 #endif
347
348     // Only remaining processes should be pre-warmed ones as other keep the process pool alive.
349     while (!m_processes.isEmpty()) {
350         auto& process = m_processes.first();
351
352         ASSERT(process->isPrewarmed());
353         // We need to be the only one holding a reference to the pre-warmed process so that it gets destroyed.
354         // WebProcessProxies currently always expect to have a WebProcessPool.
355         ASSERT(process->hasOneRef());
356
357         process->shutDown();
358     }
359 }
360
361 void WebProcessPool::initializeClient(const WKContextClientBase* client)
362 {
363     m_client.initialize(client);
364 }
365
366 void WebProcessPool::setInjectedBundleClient(std::unique_ptr<API::InjectedBundleClient>&& client)
367 {
368     if (!client)
369         m_injectedBundleClient = std::make_unique<API::InjectedBundleClient>();
370     else
371         m_injectedBundleClient = WTFMove(client);
372 }
373
374 void WebProcessPool::initializeConnectionClient(const WKContextConnectionClientBase* client)
375 {
376     m_connectionClient.initialize(client);
377 }
378
379 void WebProcessPool::setHistoryClient(std::unique_ptr<API::LegacyContextHistoryClient>&& historyClient)
380 {
381     if (!historyClient)
382         m_historyClient = std::make_unique<API::LegacyContextHistoryClient>();
383     else
384         m_historyClient = WTFMove(historyClient);
385 }
386
387 void WebProcessPool::setDownloadClient(std::unique_ptr<API::DownloadClient>&& downloadClient)
388 {
389     if (!downloadClient)
390         m_downloadClient = std::make_unique<API::DownloadClient>();
391     else
392         m_downloadClient = WTFMove(downloadClient);
393 }
394
395 void WebProcessPool::setAutomationClient(std::unique_ptr<API::AutomationClient>&& automationClient)
396 {
397     if (!automationClient)
398         m_automationClient = std::make_unique<API::AutomationClient>();
399     else
400         m_automationClient = WTFMove(automationClient);
401 }
402
403 void WebProcessPool::setLegacyCustomProtocolManagerClient(std::unique_ptr<API::CustomProtocolManagerClient>&& customProtocolManagerClient)
404 {
405 #if ENABLE(LEGACY_CUSTOM_PROTOCOL_MANAGER)
406     if (!customProtocolManagerClient)
407         m_customProtocolManagerClient = std::make_unique<API::CustomProtocolManagerClient>();
408     else
409         m_customProtocolManagerClient = WTFMove(customProtocolManagerClient);
410 #endif
411 }
412
413 void WebProcessPool::setCustomWebContentServiceBundleIdentifier(const String& customWebContentServiceBundleIdentifier)
414 {
415     // Guard against API misuse.
416     if (!customWebContentServiceBundleIdentifier.isAllASCII())
417         CRASH();
418
419     m_configuration->setCustomWebContentServiceBundleIdentifier(customWebContentServiceBundleIdentifier);
420 }
421
422 IPC::Connection* WebProcessPool::networkingProcessConnection()
423 {
424     return m_networkProcess->connection();
425 }
426
427 void WebProcessPool::languageChanged(void* context)
428 {
429     static_cast<WebProcessPool*>(context)->languageChanged();
430 }
431
432 void WebProcessPool::languageChanged()
433 {
434     sendToAllProcesses(Messages::WebProcess::UserPreferredLanguagesChanged(userPreferredLanguages()));
435 #if USE(SOUP)
436     if (m_networkProcess)
437         m_networkProcess->send(Messages::NetworkProcess::UserPreferredLanguagesChanged(userPreferredLanguages()), 0);
438 #endif
439 }
440
441 void WebProcessPool::fullKeyboardAccessModeChanged(bool fullKeyboardAccessEnabled)
442 {
443     sendToAllProcesses(Messages::WebProcess::FullKeyboardAccessModeChanged(fullKeyboardAccessEnabled));
444 }
445
446 #if OS(LINUX)
447 void WebProcessPool::sendMemoryPressureEvent(bool isCritical)
448 {
449     sendToAllProcesses(Messages::AuxiliaryProcess::DidReceiveMemoryPressureEvent(isCritical));
450     sendToNetworkingProcess(Messages::AuxiliaryProcess::DidReceiveMemoryPressureEvent(isCritical));
451 #if ENABLE(NETSCAPE_PLUGIN_API)
452     PluginProcessManager::singleton().sendMemoryPressureEvent(isCritical);
453 #endif
454 }
455 #endif
456
457 void WebProcessPool::textCheckerStateChanged()
458 {
459     sendToAllProcesses(Messages::WebProcess::SetTextCheckerState(TextChecker::state()));
460 }
461
462 void WebProcessPool::setApplicationIsActive(bool isActive)
463 {
464     m_webProcessCache->setApplicationIsActive(isActive);
465 }
466
467 void WebProcessPool::screenPropertiesStateChanged()
468 {
469 #if PLATFORM(MAC)
470     auto screenProperties = WebCore::collectScreenProperties();
471     sendToAllProcesses(Messages::WebProcess::SetScreenProperties(screenProperties));
472 #endif
473 }
474
475 NetworkProcessProxy& WebProcessPool::ensureNetworkProcess(WebsiteDataStore* withWebsiteDataStore)
476 {
477     if (m_networkProcess) {
478         if (withWebsiteDataStore) {
479             m_networkProcess->addSession(makeRef(*withWebsiteDataStore));
480             withWebsiteDataStore->clearPendingCookies();
481         }
482         return *m_networkProcess;
483     }
484
485     m_networkProcess = std::make_unique<NetworkProcessProxy>(*this);
486
487     NetworkProcessCreationParameters parameters;
488
489     if (m_websiteDataStore) {
490         parameters.defaultDataStoreParameters.pendingCookies = copyToVector(m_websiteDataStore->websiteDataStore().pendingCookies());
491         m_websiteDataStore->websiteDataStore().clearPendingCookies();
492     }
493
494     parameters.cacheModel = cacheModel();
495     parameters.canHandleHTTPSServerTrustEvaluation = m_canHandleHTTPSServerTrustEvaluation;
496
497     for (auto& scheme : globalURLSchemesWithCustomProtocolHandlers())
498         parameters.urlSchemesRegisteredForCustomProtocols.append(scheme);
499
500     for (auto& scheme : m_urlSchemesRegisteredForCustomProtocols)
501         parameters.urlSchemesRegisteredForCustomProtocols.append(scheme);
502
503     parameters.diskCacheDirectory = m_configuration->diskCacheDirectory();
504     if (!parameters.diskCacheDirectory.isEmpty())
505         SandboxExtension::createHandleForReadWriteDirectory(parameters.diskCacheDirectory, parameters.diskCacheDirectoryExtensionHandle);
506 #if ENABLE(NETWORK_CACHE_SPECULATIVE_REVALIDATION)
507     parameters.shouldEnableNetworkCacheSpeculativeRevalidation = m_configuration->diskCacheSpeculativeValidationEnabled();
508 #endif
509
510 #if PLATFORM(IOS_FAMILY)
511     String cookieStorageDirectory = this->cookieStorageDirectory();
512     if (!cookieStorageDirectory.isEmpty())
513         SandboxExtension::createHandleForReadWriteDirectory(cookieStorageDirectory, parameters.cookieStorageDirectoryExtensionHandle);
514
515     String containerCachesDirectory = this->networkingCachesDirectory();
516     if (!containerCachesDirectory.isEmpty())
517         SandboxExtension::createHandleForReadWriteDirectory(containerCachesDirectory, parameters.containerCachesDirectoryExtensionHandle);
518
519     String parentBundleDirectory = this->parentBundleDirectory();
520     if (!parentBundleDirectory.isEmpty())
521         SandboxExtension::createHandle(parentBundleDirectory, SandboxExtension::Type::ReadOnly, parameters.parentBundleDirectoryExtensionHandle);
522
523 #if ENABLE(INDEXED_DATABASE)
524     SandboxExtension::createHandleForTemporaryFile(emptyString(), SandboxExtension::Type::ReadWrite, parameters.defaultDataStoreParameters.indexedDatabaseTempBlobDirectoryExtensionHandle);
525 #endif
526 #endif
527
528     parameters.shouldUseTestingNetworkSession = m_shouldUseTestingNetworkSession;
529
530     parameters.urlSchemesRegisteredAsSecure = copyToVector(m_schemesToRegisterAsSecure);
531     parameters.urlSchemesRegisteredAsBypassingContentSecurityPolicy = copyToVector(m_schemesToRegisterAsBypassingContentSecurityPolicy);
532     parameters.urlSchemesRegisteredAsLocal = copyToVector(m_schemesToRegisterAsLocal);
533     parameters.urlSchemesRegisteredAsNoAccess = copyToVector(m_schemesToRegisterAsNoAccess);
534     parameters.urlSchemesRegisteredAsDisplayIsolated = copyToVector(m_schemesToRegisterAsDisplayIsolated);
535     parameters.urlSchemesRegisteredAsCORSEnabled = copyToVector(m_schemesToRegisterAsCORSEnabled);
536     parameters.urlSchemesRegisteredAsCanDisplayOnlyIfCanRequest = copyToVector(m_schemesToRegisterAsCanDisplayOnlyIfCanRequest);
537
538 #if ENABLE(INDEXED_DATABASE)
539     // *********
540     // IMPORTANT: Do not change the directory structure for indexed databases on disk without first consulting a reviewer from Apple (<rdar://problem/17454712>)
541     // *********
542     parameters.defaultDataStoreParameters.indexedDatabaseDirectory = m_configuration->indexedDBDatabaseDirectory();
543     if (parameters.defaultDataStoreParameters.indexedDatabaseDirectory.isEmpty())
544         parameters.defaultDataStoreParameters.indexedDatabaseDirectory = API::WebsiteDataStore::defaultDataStore()->websiteDataStore().parameters().indexedDatabaseDirectory;
545     
546     SandboxExtension::createHandleForReadWriteDirectory(parameters.defaultDataStoreParameters.indexedDatabaseDirectory, parameters.defaultDataStoreParameters.indexedDatabaseDirectoryExtensionHandle);
547 #endif
548
549 #if ENABLE(SERVICE_WORKER)
550     if (m_websiteDataStore)
551         parameters.serviceWorkerRegistrationDirectory = m_websiteDataStore->websiteDataStore().resolvedServiceWorkerRegistrationDirectory();
552     if (!parameters.serviceWorkerRegistrationDirectory)
553         parameters.serviceWorkerRegistrationDirectory =  API::WebsiteDataStore::defaultServiceWorkerRegistrationDirectory();
554     SandboxExtension::createHandleForReadWriteDirectory(parameters.serviceWorkerRegistrationDirectory, parameters.serviceWorkerRegistrationDirectoryExtensionHandle);
555
556     if (!m_schemesServiceWorkersCanHandle.isEmpty())
557         parameters.urlSchemesServiceWorkersCanHandle = copyToVector(m_schemesServiceWorkersCanHandle);
558
559     parameters.shouldDisableServiceWorkerProcessTerminationDelay = m_shouldDisableServiceWorkerProcessTerminationDelay;
560 #endif
561
562     if (m_websiteDataStore)
563         parameters.defaultDataStoreParameters.networkSessionParameters.resourceLoadStatisticsDirectory = m_websiteDataStore->websiteDataStore().resolvedResourceLoadStatisticsDirectory();
564     if (parameters.defaultDataStoreParameters.networkSessionParameters.resourceLoadStatisticsDirectory.isEmpty())
565         parameters.defaultDataStoreParameters.networkSessionParameters.resourceLoadStatisticsDirectory = API::WebsiteDataStore::defaultResourceLoadStatisticsDirectory();
566
567     SandboxExtension::createHandleForReadWriteDirectory(parameters.defaultDataStoreParameters.networkSessionParameters.resourceLoadStatisticsDirectory, parameters.defaultDataStoreParameters.networkSessionParameters.resourceLoadStatisticsDirectoryExtensionHandle);
568
569     bool enableResourceLoadStatistics = false;
570     if (withWebsiteDataStore)
571         enableResourceLoadStatistics = withWebsiteDataStore->resourceLoadStatisticsEnabled();
572     else if (m_websiteDataStore)
573         enableResourceLoadStatistics = m_websiteDataStore->resourceLoadStatisticsEnabled();
574
575     parameters.defaultDataStoreParameters.networkSessionParameters.enableResourceLoadStatistics = enableResourceLoadStatistics;
576
577     // Add any platform specific parameters
578     platformInitializeNetworkProcess(parameters);
579
580     // Initialize the network process.
581     m_networkProcess->send(Messages::NetworkProcess::InitializeNetworkProcess(parameters), 0);
582
583     if (WebPreferences::anyPagesAreUsingPrivateBrowsing())
584         m_networkProcess->send(Messages::NetworkProcess::AddWebsiteDataStore(WebsiteDataStoreParameters::legacyPrivateSessionParameters()), 0);
585
586 #if PLATFORM(COCOA)
587     m_networkProcess->send(Messages::NetworkProcess::SetQOS(networkProcessLatencyQOS(), networkProcessThroughputQOS()), 0);
588 #endif
589
590     if (m_didNetworkProcessCrash) {
591         m_didNetworkProcessCrash = false;
592         reinstateNetworkProcessAssertionState(*m_networkProcess);
593     }
594
595     if (withWebsiteDataStore) {
596         m_networkProcess->addSession(makeRef(*withWebsiteDataStore));
597         withWebsiteDataStore->clearPendingCookies();
598     }
599
600     // Make sure the network process knows about all the sessions that have been registered before it started.
601     for (auto& sessionID : m_sessionToPagesMap.keys()) {
602         if (auto* websiteDataStore = WebsiteDataStore::existingNonDefaultDataStoreForSessionID(sessionID))
603             m_networkProcess->addSession(*websiteDataStore);
604     }
605
606     return *m_networkProcess;
607 }
608
609 void WebProcessPool::networkProcessCrashed(NetworkProcessProxy& networkProcessProxy, Vector<std::pair<RefPtr<WebProcessProxy>, Messages::WebProcessProxy::GetNetworkProcessConnection::DelayedReply>>&& pendingReplies)
610 {
611     ASSERT(m_networkProcess);
612     ASSERT(&networkProcessProxy == m_networkProcess.get());
613     m_didNetworkProcessCrash = true;
614
615     for (auto& supplement : m_supplements.values())
616         supplement->processDidClose(&networkProcessProxy);
617
618     m_client.networkProcessDidCrash(this);
619
620     if (m_automationSession)
621         m_automationSession->terminate();
622
623     // Leave the process proxy around during client call, so that the client could query the process identifier.
624     m_networkProcess = nullptr;
625
626     // Attempt to re-launch.
627     if (pendingReplies.isEmpty())
628         return;
629     auto& newNetworkProcess = ensureNetworkProcess();
630     for (auto& reply : pendingReplies)
631         newNetworkProcess.getNetworkProcessConnection(*reply.first, WTFMove(reply.second));
632 }
633
634 void WebProcessPool::getNetworkProcessConnection(WebProcessProxy& webProcessProxy, Messages::WebProcessProxy::GetNetworkProcessConnection::DelayedReply&& reply)
635 {
636     ensureNetworkProcess();
637     ASSERT(m_networkProcess);
638
639     m_networkProcess->getNetworkProcessConnection(webProcessProxy, WTFMove(reply));
640 }
641
642 #if ENABLE(SERVICE_WORKER)
643 void WebProcessPool::establishWorkerContextConnectionToNetworkProcess(NetworkProcessProxy& proxy, SecurityOriginData&& securityOrigin, Optional<PAL::SessionID> sessionID)
644 {
645     ASSERT_UNUSED(proxy, &proxy == m_networkProcess.get());
646
647     if (m_serviceWorkerProcesses.contains(securityOrigin))
648         return;
649
650     m_mayHaveRegisteredServiceWorkers.clear();
651
652     WebsiteDataStore* websiteDataStore = nullptr;
653     if (sessionID)
654         websiteDataStore = WebsiteDataStore::existingNonDefaultDataStoreForSessionID(*sessionID);
655
656     if (!websiteDataStore) {
657         if (!m_websiteDataStore)
658             m_websiteDataStore = API::WebsiteDataStore::defaultDataStore().ptr();
659         websiteDataStore = &m_websiteDataStore->websiteDataStore();
660     }
661
662     if (m_serviceWorkerProcesses.isEmpty())
663         sendToAllProcesses(Messages::WebProcess::RegisterServiceWorkerClients { });
664
665     auto serviceWorkerProcessProxy = ServiceWorkerProcessProxy::create(*this, securityOrigin, *websiteDataStore);
666     m_serviceWorkerProcesses.add(WTFMove(securityOrigin), serviceWorkerProcessProxy.ptr());
667
668     updateProcessAssertions();
669     initializeNewWebProcess(serviceWorkerProcessProxy, *websiteDataStore);
670
671     auto* serviceWorkerProcessProxyPtr = serviceWorkerProcessProxy.ptr();
672     m_processes.append(WTFMove(serviceWorkerProcessProxy));
673
674     serviceWorkerProcessProxyPtr->start(m_serviceWorkerPreferences ? m_serviceWorkerPreferences.value() : m_defaultPageGroup->preferences().store(), sessionID);
675     if (!m_serviceWorkerUserAgent.isNull())
676         serviceWorkerProcessProxyPtr->setUserAgent(m_serviceWorkerUserAgent);
677 }
678 #endif
679
680 void WebProcessPool::disableServiceWorkerProcessTerminationDelay()
681 {
682 #if ENABLE(SERVICE_WORKER)
683     if (m_shouldDisableServiceWorkerProcessTerminationDelay)
684         return;
685
686     m_shouldDisableServiceWorkerProcessTerminationDelay = true;
687     if (m_networkProcess)
688         m_networkProcess->send(Messages::NetworkProcess::DisableServiceWorkerProcessTerminationDelay(), 0);
689 #endif
690 }
691
692 void WebProcessPool::willStartUsingPrivateBrowsing()
693 {
694     for (auto* processPool : allProcessPools())
695         processPool->setAnyPageGroupMightHavePrivateBrowsingEnabled(true);
696 }
697
698 void WebProcessPool::willStopUsingPrivateBrowsing()
699 {
700     for (auto* processPool : allProcessPools())
701         processPool->setAnyPageGroupMightHavePrivateBrowsingEnabled(false);
702 }
703
704 void WebProcessPool::windowServerConnectionStateChanged()
705 {
706     size_t processCount = m_processes.size();
707     for (size_t i = 0; i < processCount; ++i)
708         m_processes[i]->windowServerConnectionStateChanged();
709 }
710
711 void WebProcessPool::setAnyPageGroupMightHavePrivateBrowsingEnabled(bool privateBrowsingEnabled)
712 {
713     if (privateBrowsingEnabled) {
714         sendToNetworkingProcess(Messages::NetworkProcess::AddWebsiteDataStore(WebsiteDataStoreParameters::legacyPrivateSessionParameters()));
715     } else {
716         networkProcess()->removeSession(PAL::SessionID::legacyPrivateSessionID());
717     }
718 }
719
720 void (*s_invalidMessageCallback)(WKStringRef messageName);
721
722 void WebProcessPool::setInvalidMessageCallback(void (*invalidMessageCallback)(WKStringRef messageName))
723 {
724     s_invalidMessageCallback = invalidMessageCallback;
725 }
726
727 void WebProcessPool::didReceiveInvalidMessage(const IPC::StringReference& messageReceiverName, const IPC::StringReference& messageName)
728 {
729     if (!s_invalidMessageCallback)
730         return;
731
732     StringBuilder messageNameStringBuilder;
733     messageNameStringBuilder.append(messageReceiverName.data(), messageReceiverName.size());
734     messageNameStringBuilder.append('.');
735     messageNameStringBuilder.append(messageName.data(), messageName.size());
736
737     s_invalidMessageCallback(toAPI(API::String::create(messageNameStringBuilder.toString()).ptr()));
738 }
739
740 void WebProcessPool::processDidCachePage(WebProcessProxy* process)
741 {
742     if (m_processWithPageCache && m_processWithPageCache != process)
743         m_processWithPageCache->releasePageCache();
744     m_processWithPageCache = process;
745 }
746
747 void WebProcessPool::resolvePathsForSandboxExtensions()
748 {
749     m_resolvedPaths.injectedBundlePath = resolvePathForSandboxExtension(injectedBundlePath());
750     m_resolvedPaths.applicationCacheDirectory = resolveAndCreateReadWriteDirectoryForSandboxExtension(m_configuration->applicationCacheDirectory());
751     m_resolvedPaths.webSQLDatabaseDirectory = resolveAndCreateReadWriteDirectoryForSandboxExtension(m_configuration->webSQLDatabaseDirectory());
752     m_resolvedPaths.mediaCacheDirectory = resolveAndCreateReadWriteDirectoryForSandboxExtension(m_configuration->mediaCacheDirectory());
753     m_resolvedPaths.mediaKeyStorageDirectory = resolveAndCreateReadWriteDirectoryForSandboxExtension(m_configuration->mediaKeysStorageDirectory());
754     m_resolvedPaths.indexedDatabaseDirectory = resolveAndCreateReadWriteDirectoryForSandboxExtension(m_configuration->indexedDBDatabaseDirectory());
755
756     m_resolvedPaths.additionalWebProcessSandboxExtensionPaths.reserveCapacity(m_configuration->additionalReadAccessAllowedPaths().size());
757     for (const auto& path : m_configuration->additionalReadAccessAllowedPaths())
758         m_resolvedPaths.additionalWebProcessSandboxExtensionPaths.uncheckedAppend(resolvePathForSandboxExtension(path.data()));
759
760     platformResolvePathsForSandboxExtensions();
761 }
762
763 WebProcessProxy& WebProcessPool::createNewWebProcess(WebsiteDataStore& websiteDataStore, WebProcessProxy::IsPrewarmed isPrewarmed)
764 {
765     auto processProxy = WebProcessProxy::create(*this, websiteDataStore, isPrewarmed);
766     auto& process = processProxy.get();
767     initializeNewWebProcess(process, websiteDataStore, isPrewarmed);
768     m_processes.append(WTFMove(processProxy));
769
770     if (m_serviceWorkerProcessesTerminationTimer.isActive())
771         m_serviceWorkerProcessesTerminationTimer.stop();
772
773     return process;
774 }
775
776 RefPtr<WebProcessProxy> WebProcessPool::tryTakePrewarmedProcess(WebsiteDataStore& websiteDataStore)
777 {
778     if (!m_prewarmedProcess)
779         return nullptr;
780
781     ASSERT(m_prewarmedProcess->isPrewarmed());
782     m_prewarmedProcess->markIsNoLongerInPrewarmedPool();
783
784     return std::exchange(m_prewarmedProcess, nullptr);
785 }
786
787 #if PLATFORM(MAC)
788 static void displayReconfigurationCallBack(CGDirectDisplayID display, CGDisplayChangeSummaryFlags flags, void *userInfo)
789 {
790     auto screenProperties = WebCore::collectScreenProperties();
791     for (auto& processPool : WebProcessPool::allProcessPools()) {
792         processPool->sendToAllProcesses(Messages::WebProcess::SetScreenProperties(screenProperties));
793 #if ENABLE(WEBPROCESS_WINDOWSERVER_BLOCKING)
794         processPool->sendToAllProcesses(Messages::WebProcess::DisplayConfigurationChanged(display, flags));
795 #endif
796     }
797 }
798
799 static void registerDisplayConfigurationCallback()
800 {
801     static std::once_flag onceFlag;
802     std::call_once(
803         onceFlag,
804         [] {
805             CGDisplayRegisterReconfigurationCallback(displayReconfigurationCallBack, nullptr);
806         });
807 }
808 #endif
809
810 void WebProcessPool::initializeNewWebProcess(WebProcessProxy& process, WebsiteDataStore& websiteDataStore, WebProcessProxy::IsPrewarmed isPrewarmed)
811 {
812     auto initializationActivityToken = process.throttler().backgroundActivityToken();
813     auto scopeExit = makeScopeExit([&process, initializationActivityToken] {
814         // Round-trip to the Web Content process before releasing the
815         // initialization activity token, so that we're sure that all
816         // messages sent from this function have been handled.
817         process.isResponsive([initializationActivityToken] (bool) { });
818     });
819
820     ensureNetworkProcess();
821
822     WebProcessCreationParameters parameters;
823
824     websiteDataStore.resolveDirectoriesIfNecessary();
825
826     parameters.injectedBundlePath = m_resolvedPaths.injectedBundlePath;
827     if (!parameters.injectedBundlePath.isEmpty())
828         SandboxExtension::createHandleWithoutResolvingPath(parameters.injectedBundlePath, SandboxExtension::Type::ReadOnly, parameters.injectedBundlePathExtensionHandle);
829
830     parameters.additionalSandboxExtensionHandles.allocate(m_resolvedPaths.additionalWebProcessSandboxExtensionPaths.size());
831     for (size_t i = 0, size = m_resolvedPaths.additionalWebProcessSandboxExtensionPaths.size(); i < size; ++i)
832         SandboxExtension::createHandleWithoutResolvingPath(m_resolvedPaths.additionalWebProcessSandboxExtensionPaths[i], SandboxExtension::Type::ReadOnly, parameters.additionalSandboxExtensionHandles[i]);
833
834     parameters.applicationCacheDirectory = websiteDataStore.resolvedApplicationCacheDirectory();
835     if (parameters.applicationCacheDirectory.isEmpty())
836         parameters.applicationCacheDirectory = m_resolvedPaths.applicationCacheDirectory;
837     if (!parameters.applicationCacheDirectory.isEmpty())
838         SandboxExtension::createHandleWithoutResolvingPath(parameters.applicationCacheDirectory, SandboxExtension::Type::ReadWrite, parameters.applicationCacheDirectoryExtensionHandle);
839
840     parameters.applicationCacheFlatFileSubdirectoryName = m_configuration->applicationCacheFlatFileSubdirectoryName();
841
842     parameters.webSQLDatabaseDirectory = websiteDataStore.resolvedDatabaseDirectory();
843     if (parameters.webSQLDatabaseDirectory.isEmpty())
844         parameters.webSQLDatabaseDirectory = m_resolvedPaths.webSQLDatabaseDirectory;
845     if (!parameters.webSQLDatabaseDirectory.isEmpty())
846         SandboxExtension::createHandleWithoutResolvingPath(parameters.webSQLDatabaseDirectory, SandboxExtension::Type::ReadWrite, parameters.webSQLDatabaseDirectoryExtensionHandle);
847
848     parameters.mediaCacheDirectory = websiteDataStore.resolvedMediaCacheDirectory();
849     if (parameters.mediaCacheDirectory.isEmpty())
850         parameters.mediaCacheDirectory = m_resolvedPaths.mediaCacheDirectory;
851     if (!parameters.mediaCacheDirectory.isEmpty())
852         SandboxExtension::createHandleWithoutResolvingPath(parameters.mediaCacheDirectory, SandboxExtension::Type::ReadWrite, parameters.mediaCacheDirectoryExtensionHandle);
853
854     parameters.mediaKeyStorageDirectory = websiteDataStore.resolvedMediaKeysDirectory();
855     if (parameters.mediaKeyStorageDirectory.isEmpty())
856         parameters.mediaKeyStorageDirectory = m_resolvedPaths.mediaKeyStorageDirectory;
857     if (!parameters.mediaKeyStorageDirectory.isEmpty())
858         SandboxExtension::createHandleWithoutResolvingPath(parameters.mediaKeyStorageDirectory, SandboxExtension::Type::ReadWrite, parameters.mediaKeyStorageDirectoryExtensionHandle);
859
860 #if PLATFORM(IOS_FAMILY)
861     setJavaScriptConfigurationFileEnabledFromDefaults();
862 #endif
863
864     if (javaScriptConfigurationFileEnabled()) {
865         parameters.javaScriptConfigurationDirectory = websiteDataStore.resolvedJavaScriptConfigurationDirectory();
866         if (!parameters.javaScriptConfigurationDirectory.isEmpty())
867             SandboxExtension::createHandleWithoutResolvingPath(parameters.javaScriptConfigurationDirectory, SandboxExtension::Type::ReadWrite, parameters.javaScriptConfigurationDirectoryExtensionHandle);
868     }
869
870     parameters.cacheModel = cacheModel();
871     parameters.languages = userPreferredLanguages();
872
873     parameters.urlSchemesRegisteredAsEmptyDocument = copyToVector(m_schemesToRegisterAsEmptyDocument);
874     parameters.urlSchemesRegisteredAsSecure = copyToVector(m_schemesToRegisterAsSecure);
875     parameters.urlSchemesRegisteredAsBypassingContentSecurityPolicy = copyToVector(m_schemesToRegisterAsBypassingContentSecurityPolicy);
876     parameters.urlSchemesForWhichDomainRelaxationIsForbidden = copyToVector(m_schemesToSetDomainRelaxationForbiddenFor);
877     parameters.urlSchemesRegisteredAsLocal = copyToVector(m_schemesToRegisterAsLocal);
878     parameters.urlSchemesRegisteredAsNoAccess = copyToVector(m_schemesToRegisterAsNoAccess);
879     parameters.urlSchemesRegisteredAsDisplayIsolated = copyToVector(m_schemesToRegisterAsDisplayIsolated);
880     parameters.urlSchemesRegisteredAsCORSEnabled = copyToVector(m_schemesToRegisterAsCORSEnabled);
881     parameters.urlSchemesRegisteredAsAlwaysRevalidated = copyToVector(m_schemesToRegisterAsAlwaysRevalidated);
882     parameters.urlSchemesRegisteredAsCachePartitioned = copyToVector(m_schemesToRegisterAsCachePartitioned);
883     parameters.urlSchemesServiceWorkersCanHandle = copyToVector(m_schemesServiceWorkersCanHandle);
884     parameters.urlSchemesRegisteredAsCanDisplayOnlyIfCanRequest = copyToVector(m_schemesToRegisterAsCanDisplayOnlyIfCanRequest);
885
886     parameters.shouldAlwaysUseComplexTextCodePath = m_alwaysUsesComplexTextCodePath;
887     parameters.shouldUseFontSmoothing = m_shouldUseFontSmoothing;
888
889     parameters.terminationTimeout = 0_s;
890
891     parameters.textCheckerState = TextChecker::state();
892
893     parameters.fullKeyboardAccessEnabled = WebProcessProxy::fullKeyboardAccessEnabled();
894
895     parameters.defaultRequestTimeoutInterval = API::URLRequest::defaultTimeoutInterval();
896
897 #if ENABLE(NOTIFICATIONS)
898     // FIXME: There should be a generic way for supplements to add to the intialization parameters.
899     parameters.notificationPermissions = supplement<WebNotificationManagerProxy>()->notificationPermissions();
900 #endif
901
902     parameters.plugInAutoStartOriginHashes = m_plugInAutoStartProvider.autoStartOriginHashesCopy();
903     parameters.plugInAutoStartOrigins = copyToVector(m_plugInAutoStartProvider.autoStartOrigins());
904
905     parameters.memoryCacheDisabled = m_memoryCacheDisabled;
906     parameters.attrStyleEnabled = m_configuration->attrStyleEnabled();
907
908 #if ENABLE(SERVICE_CONTROLS)
909     auto& serviceController = ServicesController::singleton();
910     parameters.hasImageServices = serviceController.hasImageServices();
911     parameters.hasSelectionServices = serviceController.hasSelectionServices();
912     parameters.hasRichContentServices = serviceController.hasRichContentServices();
913     serviceController.refreshExistingServices();
914 #endif
915
916 #if ENABLE(NETSCAPE_PLUGIN_API)
917     parameters.pluginLoadClientPolicies = m_pluginLoadClientPolicies;
918 #endif
919
920 #if OS(LINUX)
921     parameters.shouldEnableMemoryPressureReliefLogging = true;
922 #endif
923
924 #if PLATFORM(WAYLAND) && USE(EGL)
925     if (PlatformDisplay::sharedDisplay().type() == PlatformDisplay::Type::Wayland)
926         parameters.waylandCompositorDisplayName = WaylandCompositor::singleton().displayName();
927 #endif
928
929     parameters.resourceLoadStatisticsEnabled = websiteDataStore.resourceLoadStatisticsEnabled();
930 #if ENABLE(MEDIA_STREAM)
931     parameters.shouldCaptureAudioInUIProcess = m_configuration->shouldCaptureAudioInUIProcess();
932     parameters.shouldCaptureVideoInUIProcess = m_configuration->shouldCaptureVideoInUIProcess();
933     parameters.shouldCaptureDisplayInUIProcess = m_configuration->shouldCaptureDisplayInUIProcess();
934 #endif
935
936     parameters.presentingApplicationPID = m_configuration->presentingApplicationPID();
937
938 #if PLATFORM(COCOA)
939     parameters.mediaMIMETypes = process.mediaMIMETypes();
940 #endif
941
942     // Add any platform specific parameters
943     platformInitializeWebProcess(parameters);
944
945     RefPtr<API::Object> injectedBundleInitializationUserData = m_injectedBundleClient->getInjectedBundleInitializationUserData(*this);
946     if (!injectedBundleInitializationUserData)
947         injectedBundleInitializationUserData = m_injectedBundleInitializationUserData;
948     parameters.initializationUserData = UserData(process.transformObjectsToHandles(injectedBundleInitializationUserData.get()));
949
950     process.send(Messages::WebProcess::InitializeWebProcess(parameters), 0);
951
952 #if PLATFORM(COCOA)
953     process.send(Messages::WebProcess::SetQOS(webProcessLatencyQOS(), webProcessThroughputQOS()), 0);
954 #endif
955
956     if (m_automationSession)
957         process.send(Messages::WebProcess::EnsureAutomationSessionProxy(m_automationSession->sessionIdentifier()), 0);
958
959     ASSERT(m_messagesToInjectedBundlePostedToEmptyContext.isEmpty());
960
961     if (isPrewarmed == WebProcessProxy::IsPrewarmed::Yes) {
962         ASSERT(!m_prewarmedProcess);
963         m_prewarmedProcess = &process;
964         process.send(Messages::WebProcess::PrewarmGlobally(), 0);
965     }
966
967 #if ENABLE(REMOTE_INSPECTOR)
968     // Initialize remote inspector connection now that we have a sub-process that is hosting one of our web views.
969     Inspector::RemoteInspector::singleton(); 
970 #endif
971
972 #if PLATFORM(MAC)
973     registerDisplayConfigurationCallback();
974 #endif
975 }
976
977 void WebProcessPool::prewarmProcess(MayCreateDefaultDataStore mayCreateDefaultDataStore)
978 {
979     if (m_prewarmedProcess)
980         return;
981
982     auto* websiteDataStore = m_websiteDataStore ? &m_websiteDataStore->websiteDataStore() : nullptr;
983     if (!websiteDataStore) {
984         if (!m_processes.isEmpty())
985             websiteDataStore = &m_processes.last()->websiteDataStore();
986         else if (mayCreateDefaultDataStore == MayCreateDefaultDataStore::Yes || API::WebsiteDataStore::defaultDataStoreExists())
987             websiteDataStore = &API::WebsiteDataStore::defaultDataStore()->websiteDataStore();
988         else {
989             RELEASE_LOG(PerformanceLogging, "Unable to prewarming a WebProcess because we could not find a usable data store");
990             return;
991         }
992     }
993     ASSERT(websiteDataStore);
994
995     RELEASE_LOG(PerformanceLogging, "Prewarming a WebProcess for performance");
996     createNewWebProcess(*websiteDataStore, WebProcessProxy::IsPrewarmed::Yes);
997 }
998
999 void WebProcessPool::enableProcessTermination()
1000 {
1001     m_processTerminationEnabled = true;
1002     Vector<RefPtr<WebProcessProxy>> processes = m_processes;
1003     for (size_t i = 0; i < processes.size(); ++i) {
1004         if (shouldTerminate(processes[i].get()))
1005             processes[i]->terminate();
1006     }
1007 }
1008
1009 bool WebProcessPool::shouldTerminate(WebProcessProxy* process)
1010 {
1011     ASSERT(m_processes.contains(process));
1012
1013     if (!m_processTerminationEnabled || m_configuration->alwaysKeepAndReuseSwappedProcesses())
1014         return false;
1015
1016     return true;
1017 }
1018
1019 void WebProcessPool::processDidFinishLaunching(WebProcessProxy* process)
1020 {
1021     ASSERT(m_processes.contains(process));
1022
1023     if (!m_visitedLinksPopulated) {
1024         populateVisitedLinks();
1025         m_visitedLinksPopulated = true;
1026     }
1027
1028     // Sometimes the memorySampler gets initialized after process initialization has happened but before the process has finished launching
1029     // so check if it needs to be started here
1030     if (m_memorySamplerEnabled) {
1031         SandboxExtension::Handle sampleLogSandboxHandle;        
1032         WallTime now = WallTime::now();
1033         String sampleLogFilePath = makeString("WebProcess", static_cast<unsigned long long>(now.secondsSinceEpoch().seconds()), "pid", process->processIdentifier());
1034         sampleLogFilePath = SandboxExtension::createHandleForTemporaryFile(sampleLogFilePath, SandboxExtension::Type::ReadWrite, sampleLogSandboxHandle);
1035         
1036         process->send(Messages::WebProcess::StartMemorySampler(sampleLogSandboxHandle, sampleLogFilePath, m_memorySamplerInterval), 0);
1037     }
1038
1039     if (m_configuration->fullySynchronousModeIsAllowedForTesting())
1040         process->connection()->allowFullySynchronousModeForTesting();
1041
1042     if (m_configuration->ignoreSynchronousMessagingTimeoutsForTesting())
1043         process->connection()->ignoreTimeoutsForTesting();
1044
1045     m_connectionClient.didCreateConnection(this, process->webConnection());
1046
1047     if (m_websiteDataStore)
1048         m_websiteDataStore->websiteDataStore().didCreateNetworkProcess();
1049 }
1050
1051 void WebProcessPool::disconnectProcess(WebProcessProxy* process)
1052 {
1053     ASSERT(m_processes.contains(process));
1054
1055     if (m_prewarmedProcess == process) {
1056         ASSERT(m_prewarmedProcess->isPrewarmed());
1057         m_prewarmedProcess = nullptr;
1058     }
1059
1060     // FIXME (Multi-WebProcess): <rdar://problem/12239765> Some of the invalidation calls of the other supplements are still necessary in multi-process mode, but they should only affect data structures pertaining to the process being disconnected.
1061     // Clearing everything causes assertion failures, so it's less trouble to skip that for now.
1062     RefPtr<WebProcessProxy> protect(process);
1063     if (m_processWithPageCache == process)
1064         m_processWithPageCache = nullptr;
1065
1066     m_suspendedPages.removeAllMatching([process](auto& suspendedPage) {
1067         return &suspendedPage->process() == process;
1068     });
1069
1070 #if ENABLE(SERVICE_WORKER)
1071     if (is<ServiceWorkerProcessProxy>(*process)) {
1072         auto* removedProcess = m_serviceWorkerProcesses.take(downcast<ServiceWorkerProcessProxy>(*process).securityOrigin());
1073         ASSERT_UNUSED(removedProcess, removedProcess == process);
1074         updateProcessAssertions();
1075     }
1076 #endif
1077
1078     static_cast<WebContextSupplement*>(supplement<WebGeolocationManagerProxy>())->processDidClose(process);
1079
1080     m_processes.removeFirst(process);
1081
1082 #if ENABLE(GAMEPAD)
1083     if (m_processesUsingGamepads.contains(process))
1084         processStoppedUsingGamepads(*process);
1085 #endif
1086
1087     removeProcessFromOriginCacheSet(*process);
1088
1089 #if ENABLE(SERVICE_WORKER)
1090     // FIXME: We should do better than this. For now, we just destroy the ServiceWorker process
1091     // whenever there is no regular WebContent process remaining.
1092     if (m_processes.size() == m_serviceWorkerProcesses.size()) {
1093         if (!m_serviceWorkerProcessesTerminationTimer.isActive())
1094             m_serviceWorkerProcessesTerminationTimer.startOneShot(serviceWorkerTerminationDelay);
1095     }
1096 #endif
1097 }
1098
1099 WebProcessProxy& WebProcessPool::createNewWebProcessRespectingProcessCountLimit(WebsiteDataStore& websiteDataStore)
1100 {
1101     if (!usesSingleWebProcess())
1102         return createNewWebProcess(websiteDataStore);
1103
1104 #if PLATFORM(COCOA)
1105     bool mustMatchDataStore = API::WebsiteDataStore::defaultDataStoreExists() && &websiteDataStore != &API::WebsiteDataStore::defaultDataStore()->websiteDataStore();
1106 #else
1107     bool mustMatchDataStore = false;
1108 #endif
1109
1110     for (auto& process : m_processes) {
1111         if (mustMatchDataStore && &process->websiteDataStore() != &websiteDataStore)
1112             continue;
1113 #if ENABLE(SERVICE_WORKER)
1114         if (is<ServiceWorkerProcessProxy>(*process))
1115             continue;
1116 #endif
1117         return *process;
1118     }
1119     return createNewWebProcess(websiteDataStore);
1120 }
1121
1122 Ref<WebPageProxy> WebProcessPool::createWebPage(PageClient& pageClient, Ref<API::PageConfiguration>&& pageConfiguration)
1123 {
1124     if (!pageConfiguration->pageGroup())
1125         pageConfiguration->setPageGroup(m_defaultPageGroup.ptr());
1126     if (!pageConfiguration->preferences())
1127         pageConfiguration->setPreferences(&pageConfiguration->pageGroup()->preferences());
1128     if (!pageConfiguration->userContentController())
1129         pageConfiguration->setUserContentController(&pageConfiguration->pageGroup()->userContentController());
1130     if (!pageConfiguration->visitedLinkStore())
1131         pageConfiguration->setVisitedLinkStore(m_visitedLinkStore.ptr());
1132
1133     if (!pageConfiguration->websiteDataStore()) {
1134         // We try to avoid creating the default data store as long as possible.
1135         // But if there is an attempt to create a web page without any specified data store, then we have to create it.
1136         if (!m_websiteDataStore)
1137             m_websiteDataStore = API::WebsiteDataStore::defaultDataStore().ptr();
1138
1139         ASSERT(!pageConfiguration->sessionID().isValid());
1140         pageConfiguration->setWebsiteDataStore(m_websiteDataStore.get());
1141         pageConfiguration->setSessionID(pageConfiguration->preferences()->privateBrowsingEnabled() ? PAL::SessionID::legacyPrivateSessionID() : m_websiteDataStore->websiteDataStore().sessionID());
1142     }
1143
1144     RefPtr<WebProcessProxy> process;
1145     if (pageConfiguration->relatedPage()) {
1146         // Sharing processes, e.g. when creating the page via window.open().
1147         process = &pageConfiguration->relatedPage()->process();
1148     } else {
1149         process = tryTakePrewarmedProcess(pageConfiguration->websiteDataStore()->websiteDataStore());
1150         if (!process)
1151             process = &createNewWebProcessRespectingProcessCountLimit(pageConfiguration->websiteDataStore()->websiteDataStore());
1152     }
1153
1154 #if ENABLE(SERVICE_WORKER)
1155     ASSERT(!is<ServiceWorkerProcessProxy>(*process));
1156 #endif
1157
1158     auto page = process->createWebPage(pageClient, WTFMove(pageConfiguration));
1159
1160     bool enableProcessSwapOnCrossSiteNavigation = page->preferences().processSwapOnCrossSiteNavigationEnabled();
1161 #if PLATFORM(IOS_FAMILY)
1162     if (WebCore::IOSApplication::isFirefox() && !linkedOnOrAfter(WebKit::SDKVersion::FirstWithProcessSwapOnCrossSiteNavigation))
1163         enableProcessSwapOnCrossSiteNavigation = false;
1164 #endif
1165
1166     bool wasProcessSwappingOnNavigationEnabled = m_configuration->processSwapsOnNavigation();
1167     m_configuration->setProcessSwapsOnNavigationFromExperimentalFeatures(enableProcessSwapOnCrossSiteNavigation);
1168     if (wasProcessSwappingOnNavigationEnabled != m_configuration->processSwapsOnNavigation())
1169         m_webProcessCache->updateCapacity(*this);
1170
1171     m_configuration->setShouldCaptureAudioInUIProcess(page->preferences().captureAudioInUIProcessEnabled());
1172     m_configuration->setShouldCaptureVideoInUIProcess(page->preferences().captureVideoInUIProcessEnabled());
1173
1174     return page;
1175 }
1176
1177 #if ENABLE(SERVICE_WORKER)
1178 void WebProcessPool::updateServiceWorkerUserAgent(const String& userAgent)
1179 {
1180     if (m_serviceWorkerUserAgent == userAgent)
1181         return;
1182     m_serviceWorkerUserAgent = userAgent;
1183     for (auto* serviceWorkerProcess : m_serviceWorkerProcesses.values())
1184         serviceWorkerProcess->setUserAgent(m_serviceWorkerUserAgent);
1185 }
1186
1187 bool WebProcessPool::mayHaveRegisteredServiceWorkers(const WebsiteDataStore& store)
1188 {
1189     if (!m_serviceWorkerProcesses.isEmpty())
1190         return true;
1191
1192     String serviceWorkerRegistrationDirectory = store.resolvedServiceWorkerRegistrationDirectory();
1193     if (serviceWorkerRegistrationDirectory.isEmpty())
1194         serviceWorkerRegistrationDirectory = API::WebsiteDataStore::defaultDataStoreConfiguration()->serviceWorkerRegistrationDirectory();
1195
1196     return m_mayHaveRegisteredServiceWorkers.ensure(serviceWorkerRegistrationDirectory, [&] {
1197         // FIXME: Make this computation on a background thread.
1198         return ServiceWorkerProcessProxy::hasRegisteredServiceWorkers(serviceWorkerRegistrationDirectory);
1199     }).iterator->value;
1200 }
1201 #endif
1202
1203 void WebProcessPool::pageBeginUsingWebsiteDataStore(WebPageProxy& page)
1204 {
1205     auto result = m_sessionToPagesMap.add(page.sessionID(), HashSet<WebPageProxy*>()).iterator->value.add(&page);
1206     ASSERT_UNUSED(result, result.isNewEntry);
1207
1208     auto sessionID = page.sessionID();
1209     if (sessionID.isEphemeral()) {
1210         ASSERT(page.websiteDataStore().parameters().networkSessionParameters.sessionID == sessionID);
1211         if (m_networkProcess)
1212             m_networkProcess->addSession(makeRef(page.websiteDataStore()));
1213         page.websiteDataStore().clearPendingCookies();
1214     } else if (sessionID != PAL::SessionID::defaultSessionID()) {
1215         if (m_networkProcess)
1216             m_networkProcess->addSession(makeRef(page.websiteDataStore()));
1217         page.websiteDataStore().clearPendingCookies();
1218     }
1219
1220 #if ENABLE(SERVICE_WORKER)
1221     if (!m_serviceWorkerPreferences) {
1222         m_serviceWorkerPreferences = page.preferencesStore();
1223         for (auto* serviceWorkerProcess : m_serviceWorkerProcesses.values())
1224             serviceWorkerProcess->updatePreferencesStore(*m_serviceWorkerPreferences);
1225     }
1226 #endif
1227 }
1228
1229 void WebProcessPool::pageEndUsingWebsiteDataStore(WebPageProxy& page)
1230 {
1231     auto sessionID = page.sessionID();
1232     auto iterator = m_sessionToPagesMap.find(sessionID);
1233     ASSERT(iterator != m_sessionToPagesMap.end());
1234
1235     auto takenPage = iterator->value.take(&page);
1236     ASSERT_UNUSED(takenPage, takenPage == &page);
1237
1238     if (iterator->value.isEmpty()) {
1239         m_sessionToPagesMap.remove(iterator);
1240
1241         if (sessionID == PAL::SessionID::defaultSessionID())
1242             return;
1243
1244         // The last user of this non-default PAL::SessionID is gone, so clean it up in the child processes.
1245         if (networkProcess())
1246             networkProcess()->removeSession(sessionID);
1247     }
1248 }
1249
1250 DownloadProxy* WebProcessPool::download(WebPageProxy* initiatingPage, const ResourceRequest& request, const String& suggestedFilename)
1251 {
1252     auto* downloadProxy = createDownloadProxy(request, initiatingPage);
1253     PAL::SessionID sessionID = initiatingPage ? initiatingPage->sessionID() : PAL::SessionID::defaultSessionID();
1254
1255     if (initiatingPage)
1256         initiatingPage->handleDownloadRequest(downloadProxy);
1257
1258     if (networkProcess()) {
1259         ResourceRequest updatedRequest(request);
1260         // Request's firstPartyForCookies will be used as Original URL of the download request.
1261         // We set the value to top level document's URL.
1262         if (initiatingPage) {
1263             URL initiatingPageURL = URL { URL { }, initiatingPage->pageLoadState().url() };
1264             updatedRequest.setFirstPartyForCookies(initiatingPageURL);
1265             updatedRequest.setIsSameSite(registrableDomainsAreEqual(initiatingPageURL, request.url()));
1266             if (!updatedRequest.hasHTTPHeaderField(HTTPHeaderName::UserAgent))
1267                 updatedRequest.setHTTPUserAgent(initiatingPage->userAgent());
1268         } else {
1269             updatedRequest.setFirstPartyForCookies(URL());
1270             updatedRequest.setIsSameSite(false);
1271             if (!updatedRequest.hasHTTPHeaderField(HTTPHeaderName::UserAgent))
1272                 updatedRequest.setHTTPUserAgent(WebPageProxy::standardUserAgent());
1273         }
1274         updatedRequest.setIsTopSite(false);
1275         networkProcess()->send(Messages::NetworkProcess::DownloadRequest(sessionID, downloadProxy->downloadID(), updatedRequest, suggestedFilename), 0);
1276         return downloadProxy;
1277     }
1278
1279     return downloadProxy;
1280 }
1281
1282 DownloadProxy* WebProcessPool::resumeDownload(WebPageProxy* initiatingPage, const API::Data* resumeData, const String& path)
1283 {
1284     auto* downloadProxy = createDownloadProxy(ResourceRequest(), initiatingPage);
1285     PAL::SessionID sessionID = initiatingPage ? initiatingPage->sessionID() : PAL::SessionID::defaultSessionID();
1286
1287     SandboxExtension::Handle sandboxExtensionHandle;
1288     if (!path.isEmpty())
1289         SandboxExtension::createHandle(path, SandboxExtension::Type::ReadWrite, sandboxExtensionHandle);
1290
1291     if (networkProcess()) {
1292         networkProcess()->send(Messages::NetworkProcess::ResumeDownload(sessionID, downloadProxy->downloadID(), resumeData->dataReference(), path, sandboxExtensionHandle), 0);
1293         return downloadProxy;
1294     }
1295
1296     return downloadProxy;
1297 }
1298
1299 void WebProcessPool::postMessageToInjectedBundle(const String& messageName, API::Object* messageBody)
1300 {
1301     for (auto& process : m_processes) {
1302         // FIXME: Return early if the message body contains any references to WKPageRefs/WKFrameRefs etc. since they're local to a process.
1303         process->send(Messages::WebProcess::HandleInjectedBundleMessage(messageName, UserData(process->transformObjectsToHandles(messageBody).get())), 0);
1304     }
1305 }
1306
1307 void WebProcessPool::didReachGoodTimeToPrewarm()
1308 {
1309     if (!configuration().isAutomaticProcessWarmingEnabled() || !configuration().processSwapsOnNavigation() || usesSingleWebProcess())
1310         return;
1311
1312     if (MemoryPressureHandler::singleton().isUnderMemoryPressure()) {
1313         if (!m_prewarmedProcess)
1314             RELEASE_LOG(PerformanceLogging, "Not automatically prewarming a WebProcess due to memory pressure");
1315         return;
1316     }
1317
1318     prewarmProcess(MayCreateDefaultDataStore::No);
1319 }
1320
1321 void WebProcessPool::populateVisitedLinks()
1322 {
1323     m_historyClient->populateVisitedLinks(*this);
1324 }
1325
1326 WebProcessPool::Statistics& WebProcessPool::statistics()
1327 {
1328     static Statistics statistics = Statistics();
1329
1330     return statistics;
1331 }
1332
1333 void WebProcessPool::handleMemoryPressureWarning(Critical)
1334 {
1335     RELEASE_LOG(PerformanceLogging, "%p - WebProcessPool::handleMemoryPressureWarning", this);
1336
1337     m_webProcessCache->clear();
1338
1339     if (m_prewarmedProcess)
1340         m_prewarmedProcess->shutDown();
1341     ASSERT(!m_prewarmedProcess);
1342
1343     clearSuspendedPages();
1344 }
1345
1346 #if ENABLE(NETSCAPE_PLUGIN_API)
1347 void WebProcessPool::setAdditionalPluginsDirectory(const String& directory)
1348 {
1349     Vector<String> directories;
1350     directories.append(directory);
1351
1352     m_pluginInfoStore.setAdditionalPluginsDirectories(directories);
1353 }
1354
1355 void WebProcessPool::refreshPlugins()
1356 {
1357     m_pluginInfoStore.refresh();
1358     sendToAllProcesses(Messages::WebProcess::RefreshPlugins());
1359 }
1360
1361 #endif // ENABLE(NETSCAPE_PLUGIN_API)
1362
1363 ProcessID WebProcessPool::networkProcessIdentifier()
1364 {
1365     if (!m_networkProcess)
1366         return 0;
1367
1368     return m_networkProcess->processIdentifier();
1369 }
1370
1371 void WebProcessPool::activePagesOriginsInWebProcessForTesting(ProcessID pid, CompletionHandler<void(Vector<String>&&)>&& completionHandler)
1372 {
1373     for (auto& process : m_processes) {
1374         if (process->processIdentifier() == pid)
1375             return process->activePagesDomainsForTesting(WTFMove(completionHandler));
1376     }
1377     completionHandler({ });
1378 }
1379
1380 void WebProcessPool::setAlwaysUsesComplexTextCodePath(bool alwaysUseComplexText)
1381 {
1382     m_alwaysUsesComplexTextCodePath = alwaysUseComplexText;
1383     sendToAllProcesses(Messages::WebProcess::SetAlwaysUsesComplexTextCodePath(alwaysUseComplexText));
1384 }
1385
1386 void WebProcessPool::setShouldUseFontSmoothing(bool useFontSmoothing)
1387 {
1388     m_shouldUseFontSmoothing = useFontSmoothing;
1389     sendToAllProcesses(Messages::WebProcess::SetShouldUseFontSmoothing(useFontSmoothing));
1390 }
1391
1392 void WebProcessPool::setResourceLoadStatisticsEnabled(bool enabled)
1393 {
1394     sendToAllProcesses(Messages::WebProcess::SetResourceLoadStatisticsEnabled(enabled));
1395 }
1396
1397 void WebProcessPool::clearResourceLoadStatistics()
1398 {
1399     sendToAllProcesses(Messages::WebProcess::ClearResourceLoadStatistics());
1400 }
1401
1402 void WebProcessPool::registerURLSchemeAsEmptyDocument(const String& urlScheme)
1403 {
1404     m_schemesToRegisterAsEmptyDocument.add(urlScheme);
1405     sendToAllProcesses(Messages::WebProcess::RegisterURLSchemeAsEmptyDocument(urlScheme));
1406 }
1407
1408 void WebProcessPool::registerURLSchemeAsSecure(const String& urlScheme)
1409 {
1410     m_schemesToRegisterAsSecure.add(urlScheme);
1411     sendToAllProcesses(Messages::WebProcess::RegisterURLSchemeAsSecure(urlScheme));
1412     sendToNetworkingProcess(Messages::NetworkProcess::RegisterURLSchemeAsSecure(urlScheme));
1413 }
1414
1415 void WebProcessPool::registerURLSchemeAsBypassingContentSecurityPolicy(const String& urlScheme)
1416 {
1417     m_schemesToRegisterAsBypassingContentSecurityPolicy.add(urlScheme);
1418     sendToAllProcesses(Messages::WebProcess::RegisterURLSchemeAsBypassingContentSecurityPolicy(urlScheme));
1419     sendToNetworkingProcess(Messages::NetworkProcess::RegisterURLSchemeAsBypassingContentSecurityPolicy(urlScheme));
1420 }
1421
1422 void WebProcessPool::setDomainRelaxationForbiddenForURLScheme(const String& urlScheme)
1423 {
1424     m_schemesToSetDomainRelaxationForbiddenFor.add(urlScheme);
1425     sendToAllProcesses(Messages::WebProcess::SetDomainRelaxationForbiddenForURLScheme(urlScheme));
1426 }
1427
1428 void WebProcessPool::setCanHandleHTTPSServerTrustEvaluation(bool value)
1429 {
1430     m_canHandleHTTPSServerTrustEvaluation = value;
1431     if (m_networkProcess) {
1432         m_networkProcess->send(Messages::NetworkProcess::SetCanHandleHTTPSServerTrustEvaluation(value), 0);
1433         return;
1434     }
1435 }
1436
1437 void WebProcessPool::preconnectToServer(const URL& url)
1438 {
1439     if (!url.isValid() || !url.protocolIsInHTTPFamily())
1440         return;
1441
1442     ensureNetworkProcess().send(Messages::NetworkProcess::PreconnectTo(url, StoredCredentialsPolicy::Use), 0);
1443 }
1444
1445 void WebProcessPool::registerURLSchemeAsLocal(const String& urlScheme)
1446 {
1447     m_schemesToRegisterAsLocal.add(urlScheme);
1448     sendToAllProcesses(Messages::WebProcess::RegisterURLSchemeAsLocal(urlScheme));
1449     sendToNetworkingProcess(Messages::NetworkProcess::RegisterURLSchemeAsLocal(urlScheme));
1450 }
1451
1452 void WebProcessPool::registerURLSchemeAsNoAccess(const String& urlScheme)
1453 {
1454     m_schemesToRegisterAsNoAccess.add(urlScheme);
1455     sendToAllProcesses(Messages::WebProcess::RegisterURLSchemeAsNoAccess(urlScheme));
1456     sendToNetworkingProcess(Messages::NetworkProcess::RegisterURLSchemeAsNoAccess(urlScheme));
1457 }
1458
1459 void WebProcessPool::registerURLSchemeAsDisplayIsolated(const String& urlScheme)
1460 {
1461     m_schemesToRegisterAsDisplayIsolated.add(urlScheme);
1462     sendToAllProcesses(Messages::WebProcess::RegisterURLSchemeAsDisplayIsolated(urlScheme));
1463     sendToNetworkingProcess(Messages::NetworkProcess::RegisterURLSchemeAsDisplayIsolated(urlScheme));
1464 }
1465
1466 void WebProcessPool::registerURLSchemeAsCORSEnabled(const String& urlScheme)
1467 {
1468     m_schemesToRegisterAsCORSEnabled.add(urlScheme);
1469     sendToAllProcesses(Messages::WebProcess::RegisterURLSchemeAsCORSEnabled(urlScheme));
1470     sendToNetworkingProcess(Messages::NetworkProcess::RegisterURLSchemeAsCORSEnabled(urlScheme));
1471 }
1472
1473 void WebProcessPool::registerGlobalURLSchemeAsHavingCustomProtocolHandlers(const String& urlScheme)
1474 {
1475     if (!urlScheme)
1476         return;
1477
1478     globalURLSchemesWithCustomProtocolHandlers().add(urlScheme);
1479     for (auto* processPool : allProcessPools())
1480         processPool->registerSchemeForCustomProtocol(urlScheme);
1481 }
1482
1483 void WebProcessPool::unregisterGlobalURLSchemeAsHavingCustomProtocolHandlers(const String& urlScheme)
1484 {
1485     if (!urlScheme)
1486         return;
1487
1488     globalURLSchemesWithCustomProtocolHandlers().remove(urlScheme);
1489     for (auto* processPool : allProcessPools())
1490         processPool->unregisterSchemeForCustomProtocol(urlScheme);
1491 }
1492
1493 void WebProcessPool::registerURLSchemeAsCachePartitioned(const String& urlScheme)
1494 {
1495     m_schemesToRegisterAsCachePartitioned.add(urlScheme);
1496     sendToAllProcesses(Messages::WebProcess::RegisterURLSchemeAsCachePartitioned(urlScheme));
1497 }
1498
1499 void WebProcessPool::registerURLSchemeServiceWorkersCanHandle(const String& urlScheme)
1500 {
1501     m_schemesServiceWorkersCanHandle.add(urlScheme);
1502     sendToAllProcesses(Messages::AuxiliaryProcess::RegisterURLSchemeServiceWorkersCanHandle(urlScheme));
1503     if (m_networkProcess)
1504         m_networkProcess->send(Messages::AuxiliaryProcess::RegisterURLSchemeServiceWorkersCanHandle(urlScheme), 0);
1505 }
1506
1507 void WebProcessPool::registerURLSchemeAsCanDisplayOnlyIfCanRequest(const String& urlScheme)
1508 {
1509     m_schemesToRegisterAsCanDisplayOnlyIfCanRequest.add(urlScheme);
1510     sendToAllProcesses(Messages::WebProcess::RegisterURLSchemeAsCanDisplayOnlyIfCanRequest(urlScheme));
1511     sendToNetworkingProcess(Messages::NetworkProcess::RegisterURLSchemeAsCanDisplayOnlyIfCanRequest(urlScheme));
1512 }
1513
1514 void WebProcessPool::updateMaxSuspendedPageCount()
1515 {
1516     unsigned dummy = 0;
1517     Seconds dummyInterval;
1518     unsigned pageCacheSize = 0;
1519     calculateMemoryCacheSizes(m_configuration->cacheModel(), dummy, dummy, dummy, dummyInterval, pageCacheSize);
1520
1521     m_maxSuspendedPageCount = pageCacheSize;
1522
1523     while (m_suspendedPages.size() > m_maxSuspendedPageCount)
1524         m_suspendedPages.removeFirst();
1525 }
1526
1527 bool WebProcessPool::usesNetworkingDaemon() const
1528 {
1529 #if PLATFORM(COCOA)
1530     return m_configuration->usesNetworkingDaemon();
1531 #else
1532     return false;
1533 #endif
1534 }
1535     
1536 void WebProcessPool::setCacheModel(CacheModel cacheModel)
1537 {
1538     m_configuration->setCacheModel(cacheModel);
1539     updateMaxSuspendedPageCount();
1540
1541     sendToAllProcesses(Messages::WebProcess::SetCacheModel(cacheModel));
1542
1543     if (m_networkProcess)
1544         m_networkProcess->send(Messages::NetworkProcess::SetCacheModel(cacheModel), 0);
1545 }
1546
1547 void WebProcessPool::setDefaultRequestTimeoutInterval(double timeoutInterval)
1548 {
1549     sendToAllProcesses(Messages::WebProcess::SetDefaultRequestTimeoutInterval(timeoutInterval));
1550 }
1551
1552 DownloadProxy* WebProcessPool::createDownloadProxy(const ResourceRequest& request, WebPageProxy* originatingPage)
1553 {
1554     auto downloadProxy = ensureNetworkProcess().createDownloadProxy(request);
1555     downloadProxy->setOriginatingPage(originatingPage);
1556     return downloadProxy;
1557 }
1558
1559 void WebProcessPool::addMessageReceiver(IPC::StringReference messageReceiverName, IPC::MessageReceiver& messageReceiver)
1560 {
1561     m_messageReceiverMap.addMessageReceiver(messageReceiverName, messageReceiver);
1562 }
1563
1564 void WebProcessPool::addMessageReceiver(IPC::StringReference messageReceiverName, uint64_t destinationID, IPC::MessageReceiver& messageReceiver)
1565 {
1566     m_messageReceiverMap.addMessageReceiver(messageReceiverName, destinationID, messageReceiver);
1567 }
1568
1569 void WebProcessPool::removeMessageReceiver(IPC::StringReference messageReceiverName)
1570 {
1571     m_messageReceiverMap.removeMessageReceiver(messageReceiverName);
1572 }
1573
1574 void WebProcessPool::removeMessageReceiver(IPC::StringReference messageReceiverName, uint64_t destinationID)
1575 {
1576     m_messageReceiverMap.removeMessageReceiver(messageReceiverName, destinationID);
1577 }
1578
1579 bool WebProcessPool::dispatchMessage(IPC::Connection& connection, IPC::Decoder& decoder)
1580 {
1581     return m_messageReceiverMap.dispatchMessage(connection, decoder);
1582 }
1583
1584 bool WebProcessPool::dispatchSyncMessage(IPC::Connection& connection, IPC::Decoder& decoder, std::unique_ptr<IPC::Encoder>& replyEncoder)
1585 {
1586     return m_messageReceiverMap.dispatchSyncMessage(connection, decoder, replyEncoder);
1587 }
1588
1589 void WebProcessPool::setEnhancedAccessibility(bool flag)
1590 {
1591     sendToAllProcesses(Messages::WebProcess::SetEnhancedAccessibility(flag));
1592 }
1593     
1594 void WebProcessPool::startMemorySampler(const double interval)
1595 {    
1596     // For new WebProcesses we will also want to start the Memory Sampler
1597     m_memorySamplerEnabled = true;
1598     m_memorySamplerInterval = interval;
1599     
1600     // For UIProcess
1601 #if ENABLE(MEMORY_SAMPLER)
1602     WebMemorySampler::singleton()->start(interval);
1603 #endif
1604     
1605     // For WebProcess
1606     SandboxExtension::Handle sampleLogSandboxHandle;    
1607     WallTime now = WallTime::now();
1608     String sampleLogFilePath = makeString("WebProcess", static_cast<unsigned long long>(now.secondsSinceEpoch().seconds()));
1609     sampleLogFilePath = SandboxExtension::createHandleForTemporaryFile(sampleLogFilePath, SandboxExtension::Type::ReadWrite, sampleLogSandboxHandle);
1610     
1611     sendToAllProcesses(Messages::WebProcess::StartMemorySampler(sampleLogSandboxHandle, sampleLogFilePath, interval));
1612 }
1613
1614 void WebProcessPool::stopMemorySampler()
1615 {    
1616     // For WebProcess
1617     m_memorySamplerEnabled = false;
1618     
1619     // For UIProcess
1620 #if ENABLE(MEMORY_SAMPLER)
1621     WebMemorySampler::singleton()->stop();
1622 #endif
1623
1624     sendToAllProcesses(Messages::WebProcess::StopMemorySampler());
1625 }
1626
1627 void WebProcessPool::useTestingNetworkSession()
1628 {
1629     ASSERT(m_processes.isEmpty());
1630     ASSERT(!m_networkProcess);
1631
1632     if (m_networkProcess)
1633         return;
1634
1635     if (!m_processes.isEmpty())
1636         return;
1637
1638     m_shouldUseTestingNetworkSession = true;
1639 }
1640
1641 template<typename T, typename U>
1642 void WebProcessPool::sendSyncToNetworkingProcess(T&& message, U&& reply)
1643 {
1644     if (m_networkProcess && m_networkProcess->canSendMessage())
1645         m_networkProcess->sendSync(std::forward<T>(message), std::forward<U>(reply), 0);
1646 }
1647
1648 void WebProcessPool::setAllowsAnySSLCertificateForWebSocket(bool allows)
1649 {
1650     sendSyncToNetworkingProcess(Messages::NetworkProcess::SetAllowsAnySSLCertificateForWebSocket(allows), Messages::NetworkProcess::SetAllowsAnySSLCertificateForWebSocket::Reply());
1651 }
1652
1653 void WebProcessPool::clearCachedCredentials()
1654 {
1655     if (m_networkProcess)
1656         m_networkProcess->send(Messages::NetworkProcess::ClearCachedCredentials(), 0);
1657 }
1658
1659 void WebProcessPool::terminateNetworkProcess()
1660 {
1661     if (!m_networkProcess)
1662         return;
1663     
1664     m_networkProcess->terminate();
1665     m_networkProcess = nullptr;
1666     m_didNetworkProcessCrash = true;
1667 }
1668
1669 void WebProcessPool::terminateServiceWorkerProcesses()
1670 {
1671 #if ENABLE(SERVICE_WORKER)
1672     auto protectedThis = makeRef(*this);
1673     while (!m_serviceWorkerProcesses.isEmpty())
1674         m_serviceWorkerProcesses.begin()->value->requestTermination(ProcessTerminationReason::RequestedByClient);
1675 #endif
1676 }
1677
1678 void WebProcessPool::syncNetworkProcessCookies()
1679 {
1680     ensureNetworkProcess().syncAllCookies();
1681 }
1682
1683 void WebProcessPool::setIDBPerOriginQuota(uint64_t quota)
1684 {
1685 #if ENABLE(INDEXED_DATABASE)
1686     ensureNetworkProcess().send(Messages::NetworkProcess::SetIDBPerOriginQuota(quota), 0);
1687 #endif
1688 }
1689
1690 void WebProcessPool::allowSpecificHTTPSCertificateForHost(const WebCertificateInfo* certificate, const String& host)
1691 {
1692     ensureNetworkProcess();
1693     m_networkProcess->send(Messages::NetworkProcess::AllowSpecificHTTPSCertificateForHost(certificate->certificateInfo(), host), 0);
1694 }
1695
1696 void WebProcessPool::updateAutomationCapabilities() const
1697 {
1698 #if ENABLE(REMOTE_INSPECTOR)
1699     Inspector::RemoteInspector::singleton().clientCapabilitiesDidChange();
1700 #endif
1701 }
1702
1703 void WebProcessPool::setAutomationSession(RefPtr<WebAutomationSession>&& automationSession)
1704 {
1705     if (m_automationSession)
1706         m_automationSession->setProcessPool(nullptr);
1707     
1708     m_automationSession = WTFMove(automationSession);
1709
1710 #if ENABLE(REMOTE_INSPECTOR)
1711     if (m_automationSession) {
1712         m_automationSession->init();
1713         m_automationSession->setProcessPool(this);
1714
1715         sendToAllProcesses(Messages::WebProcess::EnsureAutomationSessionProxy(m_automationSession->sessionIdentifier()));
1716     } else
1717         sendToAllProcesses(Messages::WebProcess::DestroyAutomationSessionProxy());
1718 #endif
1719 }
1720
1721 void WebProcessPool::setHTTPPipeliningEnabled(bool enabled)
1722 {
1723 #if PLATFORM(COCOA)
1724     ResourceRequest::setHTTPPipeliningEnabled(enabled);
1725 #else
1726     UNUSED_PARAM(enabled);
1727 #endif
1728 }
1729
1730 bool WebProcessPool::httpPipeliningEnabled() const
1731 {
1732 #if PLATFORM(COCOA)
1733     return ResourceRequest::httpPipeliningEnabled();
1734 #else
1735     return false;
1736 #endif
1737 }
1738
1739 void WebProcessPool::getStatistics(uint32_t statisticsMask, Function<void (API::Dictionary*, CallbackBase::Error)>&& callbackFunction)
1740 {
1741     if (!statisticsMask) {
1742         callbackFunction(nullptr, CallbackBase::Error::Unknown);
1743         return;
1744     }
1745
1746     auto request = StatisticsRequest::create(DictionaryCallback::create(WTFMove(callbackFunction)));
1747
1748     if (statisticsMask & StatisticsRequestTypeWebContent)
1749         requestWebContentStatistics(request.get());
1750     
1751     if (statisticsMask & StatisticsRequestTypeNetworking)
1752         requestNetworkingStatistics(request.get());
1753 }
1754
1755 void WebProcessPool::requestWebContentStatistics(StatisticsRequest& request)
1756 {
1757     // FIXME (Multi-WebProcess) <rdar://problem/13200059>: Make getting statistics from multiple WebProcesses work.
1758 }
1759
1760 void WebProcessPool::requestNetworkingStatistics(StatisticsRequest& request)
1761 {
1762     if (!m_networkProcess) {
1763         LOG_ERROR("Attempt to get NetworkProcess statistics but the NetworkProcess is unavailable");
1764         return;
1765     }
1766
1767     uint64_t requestID = request.addOutstandingRequest();
1768     m_statisticsRequests.set(requestID, &request);
1769     m_networkProcess->send(Messages::NetworkProcess::GetNetworkProcessStatistics(requestID), 0);
1770 }
1771
1772 static WebProcessProxy* webProcessProxyFromConnection(IPC::Connection& connection, const Vector<RefPtr<WebProcessProxy>>& processes)
1773 {
1774     for (auto& process : processes) {
1775         if (process->hasConnection(connection))
1776             return process.get();
1777     }
1778
1779     ASSERT_NOT_REACHED();
1780     return nullptr;
1781 }
1782
1783 void WebProcessPool::handleMessage(IPC::Connection& connection, const String& messageName, const WebKit::UserData& messageBody)
1784 {
1785     auto* webProcessProxy = webProcessProxyFromConnection(connection, m_processes);
1786     if (!webProcessProxy)
1787         return;
1788     m_injectedBundleClient->didReceiveMessageFromInjectedBundle(*this, messageName, webProcessProxy->transformHandlesToObjects(messageBody.object()).get());
1789 }
1790
1791 void WebProcessPool::handleSynchronousMessage(IPC::Connection& connection, const String& messageName, const UserData& messageBody, CompletionHandler<void(UserData&&)>&& completionHandler)
1792 {
1793     auto* webProcessProxy = webProcessProxyFromConnection(connection, m_processes);
1794     if (!webProcessProxy)
1795         return completionHandler({ });
1796
1797     RefPtr<API::Object> returnData;
1798     m_injectedBundleClient->didReceiveSynchronousMessageFromInjectedBundle(*this, messageName, webProcessProxy->transformHandlesToObjects(messageBody.object()).get(), returnData);
1799     completionHandler(UserData(webProcessProxy->transformObjectsToHandles(returnData.get())));
1800 }
1801
1802 void WebProcessPool::didGetStatistics(const StatisticsData& statisticsData, uint64_t requestID)
1803 {
1804     RefPtr<StatisticsRequest> request = m_statisticsRequests.take(requestID);
1805     if (!request) {
1806         LOG_ERROR("Cannot report networking statistics.");
1807         return;
1808     }
1809
1810     request->completedRequest(requestID, statisticsData);
1811 }
1812
1813 #if ENABLE(GAMEPAD)
1814
1815 void WebProcessPool::startedUsingGamepads(IPC::Connection& connection)
1816 {
1817     auto* proxy = webProcessProxyFromConnection(connection, m_processes);
1818     if (!proxy)
1819         return;
1820
1821     bool wereAnyProcessesUsingGamepads = !m_processesUsingGamepads.isEmpty();
1822
1823     ASSERT(!m_processesUsingGamepads.contains(proxy));
1824     m_processesUsingGamepads.add(proxy);
1825
1826     if (!wereAnyProcessesUsingGamepads)
1827         UIGamepadProvider::singleton().processPoolStartedUsingGamepads(*this);
1828
1829     proxy->send(Messages::WebProcess::SetInitialGamepads(UIGamepadProvider::singleton().snapshotGamepads()), 0);
1830 }
1831
1832 void WebProcessPool::stoppedUsingGamepads(IPC::Connection& connection)
1833 {
1834     auto* proxy = webProcessProxyFromConnection(connection, m_processes);
1835     if (!proxy)
1836         return;
1837
1838     ASSERT(m_processesUsingGamepads.contains(proxy));
1839     processStoppedUsingGamepads(*proxy);
1840 }
1841
1842 void WebProcessPool::processStoppedUsingGamepads(WebProcessProxy& process)
1843 {
1844     bool wereAnyProcessesUsingGamepads = !m_processesUsingGamepads.isEmpty();
1845
1846     ASSERT(m_processesUsingGamepads.contains(&process));
1847     m_processesUsingGamepads.remove(&process);
1848
1849     if (wereAnyProcessesUsingGamepads && m_processesUsingGamepads.isEmpty())
1850         UIGamepadProvider::singleton().processPoolStoppedUsingGamepads(*this);
1851 }
1852
1853 void WebProcessPool::gamepadConnected(const UIGamepad& gamepad)
1854 {
1855     for (auto& process : m_processesUsingGamepads)
1856         process->send(Messages::WebProcess::GamepadConnected(gamepad.fullGamepadData()), 0);
1857 }
1858
1859 void WebProcessPool::gamepadDisconnected(const UIGamepad& gamepad)
1860 {
1861     for (auto& process : m_processesUsingGamepads)
1862         process->send(Messages::WebProcess::GamepadDisconnected(gamepad.index()), 0);
1863 }
1864
1865 void WebProcessPool::setInitialConnectedGamepads(const Vector<std::unique_ptr<UIGamepad>>& gamepads)
1866 {
1867     Vector<GamepadData> gamepadDatas;
1868     gamepadDatas.grow(gamepads.size());
1869     for (size_t i = 0; i < gamepads.size(); ++i) {
1870         if (!gamepads[i])
1871             continue;
1872         gamepadDatas[i] = gamepads[i]->fullGamepadData();
1873     }
1874
1875     for (auto& process : m_processesUsingGamepads)
1876         process->send(Messages::WebProcess::SetInitialGamepads(gamepadDatas), 0);
1877 }
1878
1879 #endif // ENABLE(GAMEPAD)
1880
1881 void WebProcessPool::setJavaScriptConfigurationFileEnabled(bool flag)
1882 {
1883     m_javaScriptConfigurationFileEnabled = flag;
1884 }
1885
1886 void WebProcessPool::garbageCollectJavaScriptObjects()
1887 {
1888     sendToAllProcesses(Messages::WebProcess::GarbageCollectJavaScriptObjects());
1889 }
1890
1891 void WebProcessPool::setJavaScriptGarbageCollectorTimerEnabled(bool flag)
1892 {
1893     sendToAllProcesses(Messages::WebProcess::SetJavaScriptGarbageCollectorTimerEnabled(flag));
1894 }
1895
1896 void WebProcessPool::addPlugInAutoStartOriginHash(const String& pageOrigin, unsigned plugInOriginHash, PAL::SessionID sessionID)
1897 {
1898     m_plugInAutoStartProvider.addAutoStartOriginHash(pageOrigin, plugInOriginHash, sessionID);
1899 }
1900
1901 void WebProcessPool::plugInDidReceiveUserInteraction(unsigned plugInOriginHash, PAL::SessionID sessionID)
1902 {
1903     m_plugInAutoStartProvider.didReceiveUserInteraction(plugInOriginHash, sessionID);
1904 }
1905
1906 Ref<API::Dictionary> WebProcessPool::plugInAutoStartOriginHashes() const
1907 {
1908     return m_plugInAutoStartProvider.autoStartOriginsTableCopy();
1909 }
1910
1911 void WebProcessPool::setPlugInAutoStartOriginHashes(API::Dictionary& dictionary)
1912 {
1913     m_plugInAutoStartProvider.setAutoStartOriginsTable(dictionary);
1914 }
1915
1916 void WebProcessPool::setPlugInAutoStartOrigins(API::Array& array)
1917 {
1918     m_plugInAutoStartProvider.setAutoStartOriginsArray(array);
1919 }
1920
1921 void WebProcessPool::setPlugInAutoStartOriginsFilteringOutEntriesAddedAfterTime(API::Dictionary& dictionary, WallTime time)
1922 {
1923     m_plugInAutoStartProvider.setAutoStartOriginsFilteringOutEntriesAddedAfterTime(dictionary, time);
1924 }
1925
1926 void WebProcessPool::registerSchemeForCustomProtocol(const String& scheme)
1927 {
1928 #if ENABLE(LEGACY_CUSTOM_PROTOCOL_MANAGER)
1929     if (!globalURLSchemesWithCustomProtocolHandlers().contains(scheme))
1930         m_urlSchemesRegisteredForCustomProtocols.add(scheme);
1931     sendToNetworkingProcess(Messages::LegacyCustomProtocolManager::RegisterScheme(scheme));
1932 #endif
1933 }
1934
1935 void WebProcessPool::unregisterSchemeForCustomProtocol(const String& scheme)
1936 {
1937 #if ENABLE(LEGACY_CUSTOM_PROTOCOL_MANAGER)
1938     m_urlSchemesRegisteredForCustomProtocols.remove(scheme);
1939     sendToNetworkingProcess(Messages::LegacyCustomProtocolManager::UnregisterScheme(scheme));
1940 #endif
1941 }
1942
1943 #if ENABLE(NETSCAPE_PLUGIN_API)
1944 void WebProcessPool::setPluginLoadClientPolicy(WebCore::PluginLoadClientPolicy policy, const String& host, const String& bundleIdentifier, const String& versionString)
1945 {
1946     auto& policiesForHost = m_pluginLoadClientPolicies.ensure(host, [] { return HashMap<String, HashMap<String, uint8_t>>(); }).iterator->value;
1947     auto& versionsToPolicies = policiesForHost.ensure(bundleIdentifier, [] { return HashMap<String, uint8_t>(); }).iterator->value;
1948     versionsToPolicies.set(versionString, policy);
1949
1950     sendToAllProcesses(Messages::WebProcess::SetPluginLoadClientPolicy(policy, host, bundleIdentifier, versionString));
1951 }
1952
1953 void WebProcessPool::resetPluginLoadClientPolicies(HashMap<String, HashMap<String, HashMap<String, uint8_t>>>&& pluginLoadClientPolicies)
1954 {
1955     m_pluginLoadClientPolicies = WTFMove(pluginLoadClientPolicies);
1956     sendToAllProcesses(Messages::WebProcess::ResetPluginLoadClientPolicies(m_pluginLoadClientPolicies));
1957 }
1958
1959 void WebProcessPool::clearPluginClientPolicies()
1960 {
1961     m_pluginLoadClientPolicies.clear();
1962     sendToAllProcesses(Messages::WebProcess::ClearPluginClientPolicies());
1963 }
1964 #endif
1965
1966 void WebProcessPool::addSupportedPlugin(String&& matchingDomain, String&& name, HashSet<String>&& mimeTypes, HashSet<String> extensions)
1967 {
1968 #if ENABLE(NETSCAPE_PLUGIN_API)
1969     m_pluginInfoStore.addSupportedPlugin(WTFMove(matchingDomain), WTFMove(name), WTFMove(mimeTypes), WTFMove(extensions));
1970 #else
1971     UNUSED_PARAM(matchingDomain);
1972     UNUSED_PARAM(name);
1973     UNUSED_PARAM(mimeTypes);
1974     UNUSED_PARAM(extensions);
1975 #endif
1976 }
1977
1978 void WebProcessPool::clearSupportedPlugins()
1979 {
1980 #if ENABLE(NETSCAPE_PLUGIN_API)
1981     m_pluginInfoStore.clearSupportedPlugins();
1982 #endif
1983 }
1984
1985 void WebProcessPool::setMemoryCacheDisabled(bool disabled)
1986 {
1987     m_memoryCacheDisabled = disabled;
1988     sendToAllProcesses(Messages::WebProcess::SetMemoryCacheDisabled(disabled));
1989 }
1990
1991 void WebProcessPool::setFontWhitelist(API::Array* array)
1992 {
1993     m_fontWhitelist.clear();
1994     if (array) {
1995         for (size_t i = 0; i < array->size(); ++i) {
1996             if (API::String* font = array->at<API::String>(i))
1997                 m_fontWhitelist.append(font->string());
1998         }
1999     }
2000 }
2001
2002 void WebProcessPool::updateHiddenPageThrottlingAutoIncreaseLimit()
2003 {
2004     // We're estimating an upper bound for a set of background timer fires for a page to be 200ms
2005     // (including all timer fires, all paging-in, and any resulting GC). To ensure this does not
2006     // result in more than 1% CPU load allow for one timer fire per 100x this duration.
2007     static int maximumTimerThrottlePerPageInMS = 200 * 100;
2008
2009     int limitInMilliseconds = maximumTimerThrottlePerPageInMS * m_hiddenPageThrottlingAutoIncreasesCounter.value();
2010     sendToAllProcesses(Messages::WebProcess::SetHiddenPageDOMTimerThrottlingIncreaseLimit(limitInMilliseconds));
2011 }
2012
2013 void WebProcessPool::reportWebContentCPUTime(Seconds cpuTime, uint64_t activityState)
2014 {
2015 #if PLATFORM(MAC)
2016     if (m_perActivityStateCPUUsageSampler)
2017         m_perActivityStateCPUUsageSampler->reportWebContentCPUTime(cpuTime, static_cast<WebCore::ActivityStateForCPUSampling>(activityState));
2018 #else
2019     UNUSED_PARAM(cpuTime);
2020     UNUSED_PARAM(activityState);
2021 #endif
2022 }
2023
2024 void WebProcessPool::updateProcessAssertions()
2025 {
2026 #if PLATFORM(IOS_FAMILY)
2027 #if ENABLE(SERVICE_WORKER)
2028     auto updateServiceWorkerProcessAssertion = [&] {
2029         if (!m_serviceWorkerProcesses.isEmpty() && m_foregroundWebProcessCounter.value()) {
2030             // FIXME: We can do better than this once we have process per origin.
2031             for (auto* serviceWorkerProcess : m_serviceWorkerProcesses.values()) {
2032                 auto& securityOrigin = serviceWorkerProcess->securityOrigin();
2033                 if (!m_foregroundTokensForServiceWorkerProcesses.contains(securityOrigin))
2034                     m_foregroundTokensForServiceWorkerProcesses.add(securityOrigin, serviceWorkerProcess->throttler().foregroundActivityToken());
2035             }
2036             m_backgroundTokensForServiceWorkerProcesses.clear();
2037             return;
2038         }
2039         if (!m_serviceWorkerProcesses.isEmpty() && m_backgroundWebProcessCounter.value()) {
2040             // FIXME: We can do better than this once we have process per origin.
2041             for (auto* serviceWorkerProcess : m_serviceWorkerProcesses.values()) {
2042                 auto& securityOrigin = serviceWorkerProcess->securityOrigin();
2043                 if (!m_backgroundTokensForServiceWorkerProcesses.contains(securityOrigin))
2044                     m_backgroundTokensForServiceWorkerProcesses.add(securityOrigin, serviceWorkerProcess->throttler().backgroundActivityToken());
2045             }
2046             m_foregroundTokensForServiceWorkerProcesses.clear();
2047             return;
2048         }
2049         m_foregroundTokensForServiceWorkerProcesses.clear();
2050         m_backgroundTokensForServiceWorkerProcesses.clear();
2051     };
2052     updateServiceWorkerProcessAssertion();
2053 #endif
2054
2055     auto updateNetworkProcessAssertion = [&] {
2056         auto& networkProcess = ensureNetworkProcess();
2057
2058         if (m_foregroundWebProcessCounter.value()) {
2059             if (!m_foregroundTokenForNetworkProcess) {
2060                 m_foregroundTokenForNetworkProcess = networkProcess.throttler().foregroundActivityToken();
2061                 networkProcess.sendProcessDidTransitionToForeground();
2062             }
2063             m_backgroundTokenForNetworkProcess = nullptr;
2064             return;
2065         }
2066         if (m_backgroundWebProcessCounter.value()) {
2067             if (!m_backgroundTokenForNetworkProcess) {
2068                 m_backgroundTokenForNetworkProcess = networkProcess.throttler().backgroundActivityToken();
2069                 networkProcess.sendProcessDidTransitionToBackground();
2070             }
2071             m_foregroundTokenForNetworkProcess = nullptr;
2072             return;
2073         }
2074         m_foregroundTokenForNetworkProcess = nullptr;
2075         m_backgroundTokenForNetworkProcess = nullptr;
2076     };
2077     updateNetworkProcessAssertion();
2078 #endif
2079 }
2080
2081 #if ENABLE(SERVICE_WORKER)
2082 void WebProcessPool::postMessageToServiceWorkerClient(const ServiceWorkerClientIdentifier& destination, MessageWithMessagePorts&& message, ServiceWorkerIdentifier source, const String& sourceOrigin)
2083 {
2084     sendToNetworkingProcessRelaunchingIfNecessary(Messages::NetworkProcess::PostMessageToServiceWorkerClient(destination, WTFMove(message), source, sourceOrigin));
2085 }
2086
2087 void WebProcessPool::postMessageToServiceWorker(ServiceWorkerIdentifier destination, MessageWithMessagePorts&& message, const ServiceWorkerOrClientIdentifier& source, SWServerConnectionIdentifier connectionIdentifier)
2088 {
2089     sendToNetworkingProcessRelaunchingIfNecessary(Messages::NetworkProcess::PostMessageToServiceWorker(destination, WTFMove(message), source, connectionIdentifier));
2090 }
2091 #endif
2092
2093 void WebProcessPool::reinstateNetworkProcessAssertionState(NetworkProcessProxy& newNetworkProcessProxy)
2094 {
2095 #if PLATFORM(IOS_FAMILY)
2096     // The network process crashed; take new tokens for the new network process.
2097     if (m_backgroundTokenForNetworkProcess)
2098         m_backgroundTokenForNetworkProcess = newNetworkProcessProxy.throttler().backgroundActivityToken();
2099     else if (m_foregroundTokenForNetworkProcess)
2100         m_foregroundTokenForNetworkProcess = newNetworkProcessProxy.throttler().foregroundActivityToken();
2101 #else
2102     UNUSED_PARAM(newNetworkProcessProxy);
2103 #endif
2104 }
2105
2106 #if ENABLE(SERVICE_WORKER)
2107 ServiceWorkerProcessProxy* WebProcessPool::serviceWorkerProcessProxyFromPageID(uint64_t pageID) const
2108 {
2109     // FIXME: This is inefficient.
2110     for (auto* serviceWorkerProcess : m_serviceWorkerProcesses.values()) {
2111         if (serviceWorkerProcess->pageID() == pageID)
2112             return serviceWorkerProcess;
2113     }
2114     return nullptr;
2115 }
2116 #endif
2117
2118 void WebProcessPool::addProcessToOriginCacheSet(WebProcessProxy& process, const URL& url)
2119 {
2120     auto registrableDomain = toRegistrableDomain(url);
2121     auto result = m_swappedProcessesPerRegistrableDomain.add(registrableDomain, &process);
2122     if (!result.isNewEntry)
2123         result.iterator->value = &process;
2124
2125     LOG(ProcessSwapping, "(ProcessSwapping) Registrable domain %s just saved a cached process with pid %i", registrableDomain.utf8().data(), process.processIdentifier());
2126     if (!result.isNewEntry)
2127         LOG(ProcessSwapping, "(ProcessSwapping) Note: It already had one saved");
2128 }
2129
2130 void WebProcessPool::removeProcessFromOriginCacheSet(WebProcessProxy& process)
2131 {
2132     LOG(ProcessSwapping, "(ProcessSwapping) Removing process with pid %i from the origin cache set", process.processIdentifier());
2133
2134     // FIXME: This can be very inefficient as the number of remembered origins and processes grows
2135     Vector<String> registrableDomainsToRemove;
2136     for (auto entry : m_swappedProcessesPerRegistrableDomain) {
2137         if (entry.value == &process)
2138             registrableDomainsToRemove.append(entry.key);
2139     }
2140
2141     for (auto& registrableDomain : registrableDomainsToRemove)
2142         m_swappedProcessesPerRegistrableDomain.remove(registrableDomain);
2143 }
2144
2145 void WebProcessPool::processForNavigation(WebPageProxy& page, const API::Navigation& navigation, Ref<WebProcessProxy>&& sourceProcess, const URL& sourceURL, ProcessSwapRequestedByClient processSwapRequestedByClient, CompletionHandler<void(Ref<WebProcessProxy>&&, SuspendedPageProxy*, const String&)>&& completionHandler)
2146 {
2147     processForNavigationInternal(page, navigation, sourceProcess.copyRef(), sourceURL, processSwapRequestedByClient, [this, page = makeRefPtr(page), navigation = makeRef(navigation), sourceProcess = sourceProcess.copyRef(), sourceURL, processSwapRequestedByClient, completionHandler = WTFMove(completionHandler)](Ref<WebProcessProxy>&& process, SuspendedPageProxy* suspendedPage, const String& reason) mutable {
2148         // We are process-swapping so automatic process prewarming would be beneficial if the client has not explicitly enabled / disabled it.
2149         bool doingAnAutomaticProcessSwap = processSwapRequestedByClient == ProcessSwapRequestedByClient::No && process.ptr() != sourceProcess.ptr();
2150         if (doingAnAutomaticProcessSwap && !configuration().wasAutomaticProcessWarmingSetByClient() && !configuration().clientWouldBenefitFromAutomaticProcessPrewarming()) {
2151             RELEASE_LOG(PerformanceLogging, "Automatically turning on process prewarming because the client would benefit from it");
2152             configuration().setClientWouldBenefitFromAutomaticProcessPrewarming(true);
2153         }
2154
2155         if (m_configuration->alwaysKeepAndReuseSwappedProcesses() && process.ptr() != sourceProcess.ptr()) {
2156             static std::once_flag onceFlag;
2157             std::call_once(onceFlag, [] {
2158                 WTFLogAlways("WARNING: The option to always keep swapped web processes alive is active. This is meant for debugging and testing only.");
2159             });
2160
2161             addProcessToOriginCacheSet(sourceProcess, sourceURL);
2162
2163             LOG(ProcessSwapping, "(ProcessSwapping) Navigating from %s to %s, keeping around old process. Now holding on to old processes for %u origins.", sourceURL.string().utf8().data(), navigation->currentRequest().url().string().utf8().data(), m_swappedProcessesPerRegistrableDomain.size());
2164         }
2165
2166         completionHandler(WTFMove(process), suspendedPage, reason);
2167     });
2168 }
2169
2170 void WebProcessPool::processForNavigationInternal(WebPageProxy& page, const API::Navigation& navigation, Ref<WebProcessProxy>&& sourceProcess, const URL& pageSourceURL, ProcessSwapRequestedByClient processSwapRequestedByClient, CompletionHandler<void(Ref<WebProcessProxy>&&, SuspendedPageProxy*, const String&)>&& completionHandler)
2171 {
2172     auto& targetURL = navigation.currentRequest().url();
2173     auto registrableDomain = toRegistrableDomain(targetURL);
2174
2175     auto createNewProcess = [this, protectedThis = makeRef(*this), page = makeRef(page), targetURL, registrableDomain] () -> Ref<WebProcessProxy> {
2176         if (auto process = webProcessCache().takeProcess(registrableDomain, page->websiteDataStore()))
2177             return process.releaseNonNull();
2178
2179         // Check if we have a suspended page for the given registrable domain and use its process if we do, for performance reasons.
2180         if (auto process = findReusableSuspendedPageProcess(registrableDomain, page)) {
2181             RELEASE_LOG(ProcessSwapping, "Using WebProcess %i from a SuspendedPage", process->processIdentifier());
2182             return process.releaseNonNull();
2183         }
2184
2185         if (auto process = tryTakePrewarmedProcess(page->websiteDataStore())) {
2186             RELEASE_LOG(ProcessSwapping, "Using prewarmed process %i", process->processIdentifier());
2187             tryPrewarmWithDomainInformation(*process, targetURL);
2188             return process.releaseNonNull();
2189         }
2190
2191         RELEASE_LOG(ProcessSwapping, "Launching a new process");
2192         return createNewWebProcess(page->websiteDataStore());
2193     };
2194
2195     if (usesSingleWebProcess())
2196         return completionHandler(WTFMove(sourceProcess), nullptr, "Single WebProcess mode is enabled"_s);
2197
2198     if (processSwapRequestedByClient == ProcessSwapRequestedByClient::Yes)
2199         return completionHandler(createNewProcess(), nullptr, "Process swap was requested by the client"_s);
2200
2201     if (!m_configuration->processSwapsOnNavigation())
2202         return completionHandler(WTFMove(sourceProcess), nullptr, "Feature is disabled"_s);
2203
2204     if (m_automationSession)
2205         return completionHandler(WTFMove(sourceProcess), nullptr, "An automation session is active"_s);
2206
2207     if (!sourceProcess->hasCommittedAnyProvisionalLoads()) {
2208         tryPrewarmWithDomainInformation(sourceProcess, targetURL);
2209         return completionHandler(WTFMove(sourceProcess), nullptr, "Process has not yet committed any provisional loads"_s);
2210     }
2211
2212     // FIXME: We should support process swap when a window has been opened via window.open() without 'noopener'.
2213     // The issue is that the opener has a handle to the WindowProxy.
2214     if (navigation.openedByDOMWithOpener() && !m_configuration->processSwapsOnWindowOpenWithOpener())
2215         return completionHandler(WTFMove(sourceProcess), nullptr, "Browsing context been opened by DOM without 'noopener'"_s);
2216
2217     // FIXME: We should support process swap when a window has opened other windows via window.open.
2218     if (navigation.hasOpenedFrames())
2219         return completionHandler(WTFMove(sourceProcess), nullptr, "Browsing context has opened other windows"_s);
2220
2221     if (auto* targetItem = navigation.targetItem()) {
2222         if (auto* suspendedPage = targetItem->suspendedPage()) {
2223             return suspendedPage->waitUntilReadyToUnsuspend([createNewProcess = WTFMove(createNewProcess), completionHandler = WTFMove(completionHandler)](SuspendedPageProxy* suspendedPage) mutable {
2224                 if (!suspendedPage)
2225                     return completionHandler(createNewProcess(), nullptr, "Using new process because target back/forward item's suspended page is not reusable"_s);
2226                 Ref<WebProcessProxy> process = suspendedPage->process();
2227                 completionHandler(WTFMove(process), suspendedPage, "Using target back/forward item's process and suspended page"_s);
2228             });
2229         }
2230
2231         if (RefPtr<WebProcessProxy> process = WebProcessProxy::processForIdentifier(targetItem->lastProcessIdentifier())) {
2232             // FIXME: Architecturally we do not currently support multiple WebPage's with the same ID in a given WebProcess.
2233             // In the case where this WebProcess has a SuspendedPageProxy for this WebPage, we can throw it away to support
2234             // WebProcess re-use.
2235             removeAllSuspendedPagesForPage(page, process.get());
2236
2237             // Make sure we remove the process from the cache if it is in there since we're about to use it.
2238             if (process->isInProcessCache()) {
2239                 auto removedProcess = webProcessCache().takeProcess(process->registrableDomain(), process->websiteDataStore());
2240                 ASSERT_UNUSED(removedProcess, removedProcess.get() == process.get());
2241             }
2242
2243             return completionHandler(process.releaseNonNull(), nullptr, "Using target back/forward item's process"_s);
2244         }
2245     }
2246
2247     if (navigation.treatAsSameOriginNavigation())
2248         return completionHandler(WTFMove(sourceProcess), nullptr, "The treatAsSameOriginNavigation flag is set"_s);
2249
2250     URL sourceURL;
2251     if (page.isPageOpenedByDOMShowingInitialEmptyDocument() && !navigation.requesterOrigin().isEmpty())
2252         sourceURL = URL { URL(), navigation.requesterOrigin().toString() };
2253     else
2254         sourceURL = pageSourceURL;
2255
2256     if (sourceURL.isEmpty() && page.configuration().relatedPage()) {
2257         sourceURL = URL { { }, page.configuration().relatedPage()->pageLoadState().url() };
2258         RELEASE_LOG(ProcessSwapping, "Using related page %p's URL as source URL for process swap decision", page.configuration().relatedPage());
2259     }
2260
2261     if (!sourceURL.isValid() || !targetURL.isValid() || sourceURL.isEmpty() || sourceURL.protocolIsAbout() || registrableDomainsAreEqual(sourceURL, targetURL))
2262         return completionHandler(WTFMove(sourceProcess), nullptr, "Navigation is same-site"_s);
2263
2264     String reason = "Navigation is cross-site"_s;
2265     
2266     if (m_configuration->alwaysKeepAndReuseSwappedProcesses()) {
2267         LOG(ProcessSwapping, "(ProcessSwapping) Considering re-use of a previously cached process for domain %s", registrableDomain.utf8().data());
2268
2269         if (auto* process = m_swappedProcessesPerRegistrableDomain.get(registrableDomain)) {
2270             if (&process->websiteDataStore() == &page.websiteDataStore()) {
2271                 LOG(ProcessSwapping, "(ProcessSwapping) Reusing a previously cached process with pid %i to continue navigation to URL %s", process->processIdentifier(), targetURL.string().utf8().data());
2272
2273                 // FIXME: Architecturally we do not currently support multiple WebPage's with the same ID in a given WebProcess.
2274                 // In the case where this WebProcess has a SuspendedPageProxy for this WebPage, we can throw it away to support
2275                 // WebProcess re-use.
2276                 // In the future it would be great to refactor-out this limitation (https://bugs.webkit.org/show_bug.cgi?id=191166).
2277                 removeAllSuspendedPagesForPage(page, process);
2278
2279                 return completionHandler(makeRef(*process), nullptr, reason);
2280             }
2281         }
2282     }
2283
2284     return completionHandler(createNewProcess(), nullptr, reason);
2285 }
2286
2287 RefPtr<WebProcessProxy> WebProcessPool::findReusableSuspendedPageProcess(const String& registrableDomain, WebPageProxy& page)
2288 {
2289     auto it = m_suspendedPages.findIf([&](auto& suspendedPage) {
2290         return suspendedPage->registrableDomain() == registrableDomain && &suspendedPage->process().websiteDataStore() == &page.websiteDataStore();
2291     });
2292     if (it == m_suspendedPages.end())
2293         return nullptr;
2294
2295     Ref<WebProcessProxy> process = (*it)->process();
2296
2297     // FIXME: If the SuspendedPage is for this page, then we need to destroy the suspended page as we do not support having
2298     // multiple WebPages with the same ID in a given WebProcess currently (https://bugs.webkit.org/show_bug.cgi?id=191166).
2299     if (&(*it)->page() == &page)
2300         m_suspendedPages.remove(it);
2301
2302
2303     return WTFMove(process);
2304 }
2305
2306 void WebProcessPool::addSuspendedPage(std::unique_ptr<SuspendedPageProxy>&& suspendedPage)
2307 {
2308     if (!m_maxSuspendedPageCount)
2309         return;
2310
2311     if (m_suspendedPages.size() >= m_maxSuspendedPageCount)
2312         m_suspendedPages.removeFirst();
2313
2314     m_suspendedPages.append(WTFMove(suspendedPage));
2315 }
2316
2317 void WebProcessPool::removeAllSuspendedPagesForPage(WebPageProxy& page, WebProcessProxy* process)
2318 {
2319     m_suspendedPages.removeAllMatching([&page, process](auto& suspendedPage) {
2320         return &suspendedPage->page() == &page && (!process || &suspendedPage->process() == process);
2321     });
2322 }
2323
2324 void WebProcessPool::closeFailedSuspendedPagesForPage(WebPageProxy& page)
2325 {
2326     for (auto& suspendedPage : m_suspendedPages) {
2327         if (&suspendedPage->page() == &page && suspendedPage->failedToSuspend())
2328             suspendedPage->close();
2329     }
2330 }
2331
2332 std::unique_ptr<SuspendedPageProxy> WebProcessPool::takeSuspendedPage(SuspendedPageProxy& suspendedPage)
2333 {
2334     return m_suspendedPages.takeFirst([&suspendedPage](auto& item) {
2335         return item.get() == &suspendedPage;
2336     });
2337 }
2338
2339 void WebProcessPool::removeSuspendedPage(SuspendedPageProxy& suspendedPage)
2340 {
2341     auto it = m_suspendedPages.findIf([&suspendedPage](auto& item) {
2342         return item.get() == &suspendedPage;
2343     });
2344     if (it != m_suspendedPages.end())
2345         m_suspendedPages.remove(it);
2346 }
2347
2348 bool WebProcessPool::hasSuspendedPageFor(WebProcessProxy& process, WebPageProxy* page) const
2349 {
2350     return m_suspendedPages.findIf([&process, page](auto& suspendedPage) {
2351         return &suspendedPage->process() == &process && (!page || &suspendedPage->page() == page);
2352     }) != m_suspendedPages.end();
2353 }
2354
2355 void WebProcessPool::clearSuspendedPages()
2356 {
2357     m_suspendedPages.clear();
2358 }
2359
2360 void WebProcessPool::addMockMediaDevice(const MockMediaDevice& device)
2361 {
2362 #if ENABLE(MEDIA_STREAM)
2363     MockRealtimeMediaSourceCenter::addDevice(device);
2364     sendToAllProcesses(Messages::WebProcess::AddMockMediaDevice { device });
2365 #endif
2366 }
2367
2368 void WebProcessPool::clearMockMediaDevices()
2369 {
2370 #if ENABLE(MEDIA_STREAM)
2371     MockRealtimeMediaSourceCenter::setDevices({ });
2372     sendToAllProcesses(Messages::WebProcess::ClearMockMediaDevices { });
2373 #endif
2374 }
2375
2376 void WebProcessPool::removeMockMediaDevice(const String& persistentId)
2377 {
2378 #if ENABLE(MEDIA_STREAM)
2379     MockRealtimeMediaSourceCenter::removeDevice(persistentId);
2380     sendToAllProcesses(Messages::WebProcess::RemoveMockMediaDevice { persistentId });
2381 #endif
2382 }
2383
2384 void WebProcessPool::resetMockMediaDevices()
2385 {
2386 #if ENABLE(MEDIA_STREAM)
2387     MockRealtimeMediaSourceCenter::resetDevices();
2388     sendToAllProcesses(Messages::WebProcess::ResetMockMediaDevices { });
2389 #endif
2390 }
2391
2392 void WebProcessPool::sendDisplayConfigurationChangedMessageForTesting()
2393 {
2394 #if PLATFORM(MAC) && ENABLE(WEBPROCESS_WINDOWSERVER_BLOCKING)
2395     auto display = CGSMainDisplayID();
2396
2397     for (auto& processPool : WebProcessPool::allProcessPools()) {
2398         processPool->sendToAllProcesses(Messages::WebProcess::DisplayConfigurationChanged(display, kCGDisplayBeginConfigurationFlag));
2399         processPool->sendToAllProcesses(Messages::WebProcess::DisplayConfigurationChanged(display, kCGDisplaySetModeFlag | kCGDisplayDesktopShapeChangedFlag));
2400     }
2401 #endif
2402 }
2403
2404 void WebProcessPool::didCollectPrewarmInformation(const String& registrableDomain, const WebCore::PrewarmInformation& prewarmInformation)
2405 {
2406     static const size_t maximumSizeToPreventUnlimitedGrowth = 100;
2407     if (m_prewarmInformationPerRegistrableDomain.size() == maximumSizeToPreventUnlimitedGrowth)
2408         m_prewarmInformationPerRegistrableDomain.remove(m_prewarmInformationPerRegistrableDomain.random());
2409
2410     auto& value = m_prewarmInformationPerRegistrableDomain.ensure(registrableDomain, [] {
2411         return std::make_unique<WebCore::PrewarmInformation>();
2412     }).iterator->value;
2413
2414     *value = prewarmInformation;
2415 }
2416
2417 void WebProcessPool::tryPrewarmWithDomainInformation(WebProcessProxy& process, const URL& url)
2418 {
2419     auto* prewarmInformation = m_prewarmInformationPerRegistrableDomain.get(toRegistrableDomain(url));
2420     if (!prewarmInformation)
2421         return;
2422     process.send(Messages::WebProcess::PrewarmWithDomainInformation(*prewarmInformation), 0);
2423 }
2424
2425 void WebProcessPool::clearCurrentModifierStateForTesting()
2426 {
2427     sendToAllProcesses(Messages::WebProcess::ClearCurrentModifierStateForTesting());
2428 }
2429
2430 void WebProcessPool::dumpAdClickAttribution(PAL::SessionID sessionID, CompletionHandler<void(const String&)>&& completionHandler)
2431 {
2432     if (!m_networkProcess) {
2433         completionHandler(emptyString());
2434         return;
2435     }
2436
2437     m_networkProcess->dumpAdClickAttribution(sessionID, WTFMove(completionHandler));
2438 }
2439
2440 void WebProcessPool::clearAdClickAttribution(PAL::SessionID sessionID, CompletionHandler<void()>&& completionHandler)
2441 {
2442     if (!m_networkProcess) {
2443         completionHandler();
2444         return;
2445     }
2446     
2447     m_networkProcess->clearAdClickAttribution(sessionID, WTFMove(completionHandler));
2448 }
2449
2450 } // namespace WebKit