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