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