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