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