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