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