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