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