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