ce10e281881dd7a341e773f973c4ce904690ee65
[WebKit-https.git] / Source / WebKit / UIProcess / WebProcessPool.cpp
1 /*
2  * Copyright (C) 2010-2018 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 "APINavigation.h"
37 #include "APIPageConfiguration.h"
38 #include "APIProcessPoolConfiguration.h"
39 #include "AuxiliaryProcessMessages.h"
40 #include "DownloadProxy.h"
41 #include "DownloadProxyMessages.h"
42 #include "GamepadData.h"
43 #include "HighPerformanceGraphicsUsageSampler.h"
44 #include "LegacyGlobalSettings.h"
45 #include "LogInitialization.h"
46 #include "Logging.h"
47 #include "NetworkProcessCreationParameters.h"
48 #include "NetworkProcessMessages.h"
49 #include "NetworkProcessProxy.h"
50 #include "PerActivityStateCPUUsageSampler.h"
51 #include "PluginProcessManager.h"
52 #include "SandboxExtension.h"
53 #include "StatisticsData.h"
54 #include "TextChecker.h"
55 #include "UIGamepad.h"
56 #include "UIGamepadProvider.h"
57 #include "WKContextPrivate.h"
58 #include "WebAutomationSession.h"
59 #include "WebBackForwardList.h"
60 #include "WebBackForwardListItem.h"
61 #include "WebCertificateInfo.h"
62 #include "WebContextSupplement.h"
63 #include "WebCookieManagerProxy.h"
64 #include "WebCoreArgumentCoders.h"
65 #include "WebGeolocationManagerProxy.h"
66 #include "WebInspectorUtilities.h"
67 #include "WebKit2Initialize.h"
68 #include "WebMemorySampler.h"
69 #include "WebNotificationManagerProxy.h"
70 #include "WebPageGroup.h"
71 #include "WebPreferences.h"
72 #include "WebPreferencesKeys.h"
73 #include "WebProcessCache.h"
74 #include "WebProcessCreationParameters.h"
75 #include "WebProcessDataStoreParameters.h"
76 #include "WebProcessMessages.h"
77 #include "WebProcessPoolMessages.h"
78 #include "WebProcessProxy.h"
79 #include "WebsiteDataStore.h"
80 #include "WebsiteDataStoreParameters.h"
81 #include <JavaScriptCore/JSCInlines.h>
82 #include <WebCore/ApplicationCacheStorage.h>
83 #include <WebCore/LogInitialization.h>
84 #include <WebCore/MockRealtimeMediaSourceCenter.h>
85 #include <WebCore/NetworkStorageSession.h>
86 #include <WebCore/PlatformScreen.h>
87 #include <WebCore/ProcessIdentifier.h>
88 #include <WebCore/ProcessWarming.h>
89 #include <WebCore/RegistrationDatabase.h>
90 #include <WebCore/ResourceRequest.h>
91 #include <WebCore/RuntimeApplicationChecks.h>
92 #include <WebCore/RuntimeEnabledFeatures.h>
93 #include <pal/SessionID.h>
94 #include <wtf/Language.h>
95 #include <wtf/MainThread.h>
96 #include <wtf/NeverDestroyed.h>
97 #include <wtf/ProcessPrivilege.h>
98 #include <wtf/RunLoop.h>
99 #include <wtf/Scope.h>
100 #include <wtf/URLParser.h>
101 #include <wtf/WallTime.h>
102 #include <wtf/text/StringBuilder.h>
103 #include <wtf/text/StringConcatenateNumbers.h>
104
105 #if ENABLE(LEGACY_CUSTOM_PROTOCOL_MANAGER)
106 #include "LegacyCustomProtocolManagerMessages.h"
107 #endif
108
109 #if ENABLE(SERVICE_CONTROLS)
110 #include "ServicesController.h"
111 #endif
112
113 #if ENABLE(REMOTE_INSPECTOR)
114 #include <JavaScriptCore/RemoteInspector.h>
115 #endif
116
117 #if OS(LINUX)
118 #include "MemoryPressureMonitor.h"
119 #endif
120
121 #if PLATFORM(COCOA)
122 #include "VersionChecks.h"
123 #endif
124
125 #ifndef NDEBUG
126 #include <wtf/RefCountedLeakCounter.h>
127 #endif
128
129 namespace WebKit {
130 using namespace WebCore;
131
132 DEFINE_DEBUG_ONLY_GLOBAL(WTF::RefCountedLeakCounter, processPoolCounter, ("WebProcessPool"));
133
134 const Seconds serviceWorkerTerminationDelay { 5_s };
135
136 static uint64_t generateListenerIdentifier()
137 {
138     static uint64_t nextIdentifier = 1;
139     return nextIdentifier++;
140 }
141
142 static HashMap<uint64_t, Function<void(WebProcessPool&)>>& processPoolCreationListenerFunctionMap()
143 {
144     static NeverDestroyed<HashMap<uint64_t, Function<void(WebProcessPool&)>>> map;
145     return map;
146 }
147
148 uint64_t WebProcessPool::registerProcessPoolCreationListener(Function<void(WebProcessPool&)>&& function)
149 {
150     ASSERT(function);
151
152     auto identifier = generateListenerIdentifier();
153     processPoolCreationListenerFunctionMap().set(identifier, WTFMove(function));
154     return identifier;
155 }
156
157 void WebProcessPool::unregisterProcessPoolCreationListener(uint64_t identifier)
158 {
159     processPoolCreationListenerFunctionMap().remove(identifier);
160 }
161
162 Ref<WebProcessPool> WebProcessPool::create(API::ProcessPoolConfiguration& configuration)
163 {
164     InitializeWebKit2();
165     return adoptRef(*new WebProcessPool(configuration));
166 }
167
168 void WebProcessPool::notifyThisWebProcessPoolWasCreated()
169 {
170     auto& listenerMap = processPoolCreationListenerFunctionMap();
171
172     Vector<uint64_t> identifiers;
173     identifiers.reserveInitialCapacity(listenerMap.size());
174     for (auto identifier : listenerMap.keys())
175         identifiers.uncheckedAppend(identifier);
176
177     for (auto identifier : identifiers) {
178         auto iterator = listenerMap.find(identifier);
179         if (iterator == listenerMap.end())
180             continue;
181
182         // To make sure the Function object stays alive until after the function call has been made,
183         // we temporarily move it out of the map.
184         // This protects it from the Function calling unregisterProcessPoolCreationListener thereby
185         // removing itself from the map of listeners.
186         // If the identifier still exists in the map later, we move it back in.
187         Function<void(WebProcessPool&)> function = WTFMove(iterator->value);
188         function(*this);
189
190         iterator = listenerMap.find(identifier);
191         if (iterator != listenerMap.end()) {
192             ASSERT(!iterator->value);
193             iterator->value = WTFMove(function);
194         }
195     }
196 }
197
198 static Vector<WebProcessPool*>& processPools()
199 {
200     static NeverDestroyed<Vector<WebProcessPool*>> processPools;
201     return processPools;
202 }
203
204 const Vector<WebProcessPool*>& WebProcessPool::allProcessPools()
205 {
206     return processPools();
207 }
208
209 static HashSet<String, ASCIICaseInsensitiveHash>& globalURLSchemesWithCustomProtocolHandlers()
210 {
211     static NeverDestroyed<HashSet<String, ASCIICaseInsensitiveHash>> set;
212     return set;
213 }
214
215 WebProcessPool::WebProcessPool(API::ProcessPoolConfiguration& configuration)
216     : m_configuration(configuration.copy())
217     , m_defaultPageGroup(WebPageGroup::create())
218     , m_injectedBundleClient(makeUnique<API::InjectedBundleClient>())
219     , m_automationClient(makeUnique<API::AutomationClient>())
220     , m_downloadClient(makeUniqueRef<API::DownloadClient>())
221     , m_historyClient(makeUnique<API::LegacyContextHistoryClient>())
222     , m_customProtocolManagerClient(makeUnique<API::CustomProtocolManagerClient>())
223     , m_visitedLinkStore(VisitedLinkStore::create())
224 #if PLATFORM(MAC)
225     , m_highPerformanceGraphicsUsageSampler(makeUnique<HighPerformanceGraphicsUsageSampler>(*this))
226     , m_perActivityStateCPUUsageSampler(makeUnique<PerActivityStateCPUUsageSampler>(*this))
227 #endif
228     , m_alwaysRunsAtBackgroundPriority(m_configuration->alwaysRunsAtBackgroundPriority())
229     , m_shouldTakeUIBackgroundAssertion(m_configuration->shouldTakeUIBackgroundAssertion())
230     , m_userObservablePageCounter([this](RefCounterEvent) { updateProcessSuppressionState(); })
231     , m_processSuppressionDisabledForPageCounter([this](RefCounterEvent) { updateProcessSuppressionState(); })
232     , m_hiddenPageThrottlingAutoIncreasesCounter([this](RefCounterEvent) { m_hiddenPageThrottlingTimer.startOneShot(0_s); })
233     , m_hiddenPageThrottlingTimer(RunLoop::main(), this, &WebProcessPool::updateHiddenPageThrottlingAutoIncreaseLimit)
234     , m_serviceWorkerProcessesTerminationTimer(RunLoop::main(), this, &WebProcessPool::terminateServiceWorkerProcesses)
235 #if PLATFORM(IOS_FAMILY)
236     , m_foregroundWebProcessCounter([this](RefCounterEvent) { updateProcessAssertions(); })
237     , m_backgroundWebProcessCounter([this](RefCounterEvent) { updateProcessAssertions(); })
238 #endif
239     , m_webProcessCache(makeUniqueRef<WebProcessCache>(*this))
240 {
241     static std::once_flag onceFlag;
242     std::call_once(onceFlag, [] {
243         WTF::setProcessPrivileges(allPrivileges());
244         WebCore::NetworkStorageSession::permitProcessToUseCookieAPI(true);
245         Process::setIdentifier(WebCore::ProcessIdentifier::generate());
246     });
247
248     if (!m_websiteDataStore && WebKit::WebsiteDataStore::defaultDataStoreExists())
249         m_websiteDataStore = WebKit::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 #if OS(LINUX)
260     MemoryPressureMonitor::singleton().start();
261 #endif
262
263     addMessageReceiver(Messages::WebProcessPool::messageReceiverName(), *this);
264
265     // NOTE: These sub-objects must be initialized after m_messageReceiverMap..
266     addSupplement<WebCookieManagerProxy>();
267     addSupplement<WebGeolocationManagerProxy>();
268     addSupplement<WebNotificationManagerProxy>();
269 #if ENABLE(MEDIA_SESSION)
270     addSupplement<WebMediaSessionFocusManager>();
271 #endif
272
273     processPools().append(this);
274
275     addLanguageChangeObserver(this, languageChanged);
276
277     resolvePathsForSandboxExtensions();
278
279 #if !LOG_DISABLED || !RELEASE_LOG_DISABLED
280     WebCore::initializeLogChannelsIfNecessary();
281     WebKit::initializeLogChannelsIfNecessary();
282 #endif // !LOG_DISABLED || !RELEASE_LOG_DISABLED
283
284 #ifndef NDEBUG
285     processPoolCounter.increment();
286 #endif
287
288     notifyThisWebProcessPoolWasCreated();
289
290     updateMaxSuspendedPageCount();
291 }
292
293 WebProcessPool::~WebProcessPool()
294 {
295     m_webProcessCache->clear();
296
297     bool removed = processPools().removeFirst(this);
298     ASSERT_UNUSED(removed, removed);
299
300     removeLanguageChangeObserver(this);
301
302     m_messageReceiverMap.invalidate();
303
304     for (auto& supplement : m_supplements.values()) {
305         supplement->processPoolDestroyed();
306         supplement->clearProcessPool();
307     }
308
309     invalidateCallbackMap(m_dictionaryCallbacks, CallbackBase::Error::OwnerWasInvalidated);
310
311     platformInvalidateContext();
312
313 #ifndef NDEBUG
314     processPoolCounter.decrement();
315 #endif
316
317     if (m_networkProcess)
318         m_networkProcess->shutDownProcess();
319
320 #if ENABLE(GAMEPAD)
321     if (!m_processesUsingGamepads.isEmpty())
322         UIGamepadProvider::singleton().processPoolStoppedUsingGamepads(*this);
323 #endif
324
325     // Only remaining processes should be pre-warmed ones as other keep the process pool alive.
326     while (!m_processes.isEmpty()) {
327         auto& process = m_processes.first();
328
329         ASSERT(process->isPrewarmed());
330         // We need to be the only one holding a reference to the pre-warmed process so that it gets destroyed.
331         // WebProcessProxies currently always expect to have a WebProcessPool.
332         ASSERT(process->hasOneRef());
333
334         process->shutDown();
335     }
336 }
337
338 void WebProcessPool::initializeClient(const WKContextClientBase* client)
339 {
340     m_client.initialize(client);
341 }
342
343 void WebProcessPool::setInjectedBundleClient(std::unique_ptr<API::InjectedBundleClient>&& client)
344 {
345     if (!client)
346         m_injectedBundleClient = makeUnique<API::InjectedBundleClient>();
347     else
348         m_injectedBundleClient = WTFMove(client);
349 }
350
351 void WebProcessPool::initializeConnectionClient(const WKContextConnectionClientBase* client)
352 {
353     m_connectionClient.initialize(client);
354 }
355
356 void WebProcessPool::setHistoryClient(std::unique_ptr<API::LegacyContextHistoryClient>&& historyClient)
357 {
358     if (!historyClient)
359         m_historyClient = makeUnique<API::LegacyContextHistoryClient>();
360     else
361         m_historyClient = WTFMove(historyClient);
362 }
363
364 void WebProcessPool::setDownloadClient(UniqueRef<API::DownloadClient>&& downloadClient)
365 {
366     m_downloadClient = WTFMove(downloadClient);
367 }
368
369 void WebProcessPool::setAutomationClient(std::unique_ptr<API::AutomationClient>&& automationClient)
370 {
371     if (!automationClient)
372         m_automationClient = makeUnique<API::AutomationClient>();
373     else
374         m_automationClient = WTFMove(automationClient);
375 }
376
377 void WebProcessPool::setLegacyCustomProtocolManagerClient(std::unique_ptr<API::CustomProtocolManagerClient>&& customProtocolManagerClient)
378 {
379 #if ENABLE(LEGACY_CUSTOM_PROTOCOL_MANAGER)
380     if (!customProtocolManagerClient)
381         m_customProtocolManagerClient = makeUnique<API::CustomProtocolManagerClient>();
382     else
383         m_customProtocolManagerClient = WTFMove(customProtocolManagerClient);
384 #endif
385 }
386
387 void WebProcessPool::setStorageAccessAPIEnabled(bool enabled)
388 {
389     m_storageAccessAPIEnabled = enabled;
390 #if PLATFORM(COCOA)
391     sendToNetworkingProcess(Messages::NetworkProcess::SetStorageAccessAPIEnabled(enabled));
392 #endif
393 }
394
395 void WebProcessPool::setCustomWebContentServiceBundleIdentifier(const String& customWebContentServiceBundleIdentifier)
396 {
397     // Guard against API misuse.
398     if (!customWebContentServiceBundleIdentifier.isAllASCII())
399         CRASH();
400
401     m_configuration->setCustomWebContentServiceBundleIdentifier(customWebContentServiceBundleIdentifier);
402 }
403
404 IPC::Connection* WebProcessPool::networkingProcessConnection()
405 {
406     return m_networkProcess->connection();
407 }
408
409 void WebProcessPool::languageChanged(void* context)
410 {
411     static_cast<WebProcessPool*>(context)->languageChanged();
412 }
413
414 void WebProcessPool::languageChanged()
415 {
416     sendToAllProcesses(Messages::WebProcess::UserPreferredLanguagesChanged(userPreferredLanguages()));
417 #if USE(SOUP)
418     if (m_networkProcess)
419         m_networkProcess->send(Messages::NetworkProcess::UserPreferredLanguagesChanged(userPreferredLanguages()), 0);
420 #endif
421 }
422
423 void WebProcessPool::fullKeyboardAccessModeChanged(bool fullKeyboardAccessEnabled)
424 {
425     sendToAllProcesses(Messages::WebProcess::FullKeyboardAccessModeChanged(fullKeyboardAccessEnabled));
426 }
427
428 #if OS(LINUX)
429 void WebProcessPool::sendMemoryPressureEvent(bool isCritical)
430 {
431     sendToAllProcesses(Messages::AuxiliaryProcess::DidReceiveMemoryPressureEvent(isCritical));
432     sendToNetworkingProcess(Messages::AuxiliaryProcess::DidReceiveMemoryPressureEvent(isCritical));
433 #if ENABLE(NETSCAPE_PLUGIN_API)
434     PluginProcessManager::singleton().sendMemoryPressureEvent(isCritical);
435 #endif
436 }
437 #endif
438
439 void WebProcessPool::textCheckerStateChanged()
440 {
441     sendToAllProcesses(Messages::WebProcess::SetTextCheckerState(TextChecker::state()));
442 }
443
444 void WebProcessPool::setApplicationIsActive(bool isActive)
445 {
446     m_webProcessCache->setApplicationIsActive(isActive);
447 }
448
449 void WebProcessPool::screenPropertiesStateChanged()
450 {
451 #if PLATFORM(MAC)
452     auto screenProperties = WebCore::collectScreenProperties();
453     sendToAllProcesses(Messages::WebProcess::SetScreenProperties(screenProperties));
454 #endif
455 }
456
457 NetworkProcessProxy& WebProcessPool::ensureNetworkProcess(WebsiteDataStore* withWebsiteDataStore)
458 {
459     ASSERT(RunLoop::isMain());
460     
461     // FIXME: This is a temporary workaround for apps using WebKit API on non-main threads.
462     // We should remove this once we enforce threading violation check on our APIs.
463     // https://bugs.webkit.org/show_bug.cgi?id=200246.
464     if (!RunLoop::isMain()) {
465         callOnMainRunLoopAndWait([this, protectedThis = makeRef(*this)] {
466             ensureNetworkProcess();
467         });
468         return *m_networkProcess;
469     }
470
471     if (m_networkProcess) {
472         if (withWebsiteDataStore) {
473             m_networkProcess->addSession(makeRef(*withWebsiteDataStore));
474             withWebsiteDataStore->clearPendingCookies();
475         }
476         return *m_networkProcess;
477     }
478
479     auto networkProcess = makeUnique<NetworkProcessProxy>(*this);
480
481     NetworkProcessCreationParameters parameters;
482
483     if (m_websiteDataStore) {
484         parameters.defaultDataStoreParameters.pendingCookies = copyToVector(m_websiteDataStore->pendingCookies());
485         m_websiteDataStore->clearPendingCookies();
486 #if PLATFORM(COCOA)
487         parameters.defaultDataStoreParameters.networkSessionParameters.sourceApplicationBundleIdentifier = m_websiteDataStore->sourceApplicationBundleIdentifier();
488         parameters.defaultDataStoreParameters.networkSessionParameters.sourceApplicationSecondaryIdentifier = m_websiteDataStore->sourceApplicationSecondaryIdentifier();
489 #endif
490         m_websiteDataStore->networkingHasBegun();
491     }
492
493     parameters.cacheModel = LegacyGlobalSettings::singleton().cacheModel();
494
495     for (auto& scheme : globalURLSchemesWithCustomProtocolHandlers())
496         parameters.urlSchemesRegisteredForCustomProtocols.append(scheme);
497
498     for (auto& scheme : m_urlSchemesRegisteredForCustomProtocols)
499         parameters.urlSchemesRegisteredForCustomProtocols.append(scheme);
500
501 #if PLATFORM(IOS_FAMILY)
502     String cookieStorageDirectory = WebProcessPool::cookieStorageDirectory();
503     if (!cookieStorageDirectory.isEmpty())
504         SandboxExtension::createHandleForReadWriteDirectory(cookieStorageDirectory, parameters.cookieStorageDirectoryExtensionHandle);
505
506     String containerCachesDirectory = WebProcessPool::networkingCachesDirectory();
507     if (!containerCachesDirectory.isEmpty())
508         SandboxExtension::createHandleForReadWriteDirectory(containerCachesDirectory, parameters.containerCachesDirectoryExtensionHandle);
509
510     String parentBundleDirectory = WebProcessPool::parentBundleDirectory();
511     if (!parentBundleDirectory.isEmpty())
512         SandboxExtension::createHandle(parentBundleDirectory, SandboxExtension::Type::ReadOnly, parameters.parentBundleDirectoryExtensionHandle);
513
514 #if ENABLE(INDEXED_DATABASE)
515     SandboxExtension::createHandleForTemporaryFile(emptyString(), SandboxExtension::Type::ReadWrite, parameters.defaultDataStoreParameters.indexedDatabaseTempBlobDirectoryExtensionHandle);
516 #endif
517 #endif
518
519     parameters.hstsStorageDirectory = LegacyGlobalSettings::singleton().hstsStorageDirectory();
520     if (!parameters.hstsStorageDirectory.isNull())
521         SandboxExtension::createHandleForReadWriteDirectory(parameters.hstsStorageDirectory, parameters.hstsStorageDirectoryExtensionHandle);
522
523     parameters.shouldUseTestingNetworkSession = m_shouldUseTestingNetworkSession;
524
525     parameters.urlSchemesRegisteredAsSecure = copyToVector(m_schemesToRegisterAsSecure);
526     parameters.urlSchemesRegisteredAsBypassingContentSecurityPolicy = copyToVector(m_schemesToRegisterAsBypassingContentSecurityPolicy);
527     parameters.urlSchemesRegisteredAsLocal = copyToVector(m_schemesToRegisterAsLocal);
528     parameters.urlSchemesRegisteredAsNoAccess = copyToVector(m_schemesToRegisterAsNoAccess);
529     parameters.urlSchemesRegisteredAsDisplayIsolated = copyToVector(m_schemesToRegisterAsDisplayIsolated);
530     parameters.urlSchemesRegisteredAsCORSEnabled = copyToVector(m_schemesToRegisterAsCORSEnabled);
531     parameters.urlSchemesRegisteredAsCanDisplayOnlyIfCanRequest = copyToVector(m_schemesToRegisterAsCanDisplayOnlyIfCanRequest);
532
533 #if ENABLE(INDEXED_DATABASE)
534     // *********
535     // IMPORTANT: Do not change the directory structure for indexed databases on disk without first consulting a reviewer from Apple (<rdar://problem/17454712>)
536     // *********
537     if (WebKit::WebsiteDataStore::defaultDataStoreExists())
538         parameters.defaultDataStoreParameters.indexedDatabaseDirectory = WebKit::WebsiteDataStore::defaultDataStore()->parameters().indexedDatabaseDirectory;
539     
540     if (!parameters.defaultDataStoreParameters.indexedDatabaseDirectory.isEmpty()) {
541         SandboxExtension::createHandleForReadWriteDirectory(parameters.defaultDataStoreParameters.indexedDatabaseDirectory, parameters.defaultDataStoreParameters.indexedDatabaseDirectoryExtensionHandle);
542         networkProcess->createSymLinkForFileUpgrade(parameters.defaultDataStoreParameters.indexedDatabaseDirectory);
543     }
544 #endif
545
546 #if ENABLE(SERVICE_WORKER)
547     if (m_websiteDataStore)
548         parameters.serviceWorkerRegistrationDirectory = m_websiteDataStore->resolvedServiceWorkerRegistrationDirectory();
549     if (!parameters.serviceWorkerRegistrationDirectory)
550         parameters.serviceWorkerRegistrationDirectory =  WebKit::WebsiteDataStore::defaultServiceWorkerRegistrationDirectory();
551     SandboxExtension::createHandleForReadWriteDirectory(parameters.serviceWorkerRegistrationDirectory, parameters.serviceWorkerRegistrationDirectoryExtensionHandle);
552
553     if (!m_schemesServiceWorkersCanHandle.isEmpty())
554         parameters.urlSchemesServiceWorkersCanHandle = copyToVector(m_schemesServiceWorkersCanHandle);
555
556     parameters.shouldDisableServiceWorkerProcessTerminationDelay = m_shouldDisableServiceWorkerProcessTerminationDelay;
557 #endif
558
559     auto localStorageDirectory = m_websiteDataStore ? m_websiteDataStore->resolvedLocalStorageDirectory() : nullString();
560     if (!localStorageDirectory)
561         localStorageDirectory = WebKit::WebsiteDataStore::defaultLocalStorageDirectory();
562     parameters.defaultDataStoreParameters.localStorageDirectory = localStorageDirectory;
563     SandboxExtension::createHandleForReadWriteDirectory(localStorageDirectory, parameters.defaultDataStoreParameters.localStorageDirectoryExtensionHandle);
564
565     if (m_websiteDataStore)
566         parameters.defaultDataStoreParameters.networkSessionParameters.resourceLoadStatisticsDirectory = m_websiteDataStore->resolvedResourceLoadStatisticsDirectory();
567     if (parameters.defaultDataStoreParameters.networkSessionParameters.resourceLoadStatisticsDirectory.isEmpty())
568         parameters.defaultDataStoreParameters.networkSessionParameters.resourceLoadStatisticsDirectory = WebKit::WebsiteDataStore::defaultResourceLoadStatisticsDirectory();
569
570     SandboxExtension::createHandleForReadWriteDirectory(parameters.defaultDataStoreParameters.networkSessionParameters.resourceLoadStatisticsDirectory, parameters.defaultDataStoreParameters.networkSessionParameters.resourceLoadStatisticsDirectoryExtensionHandle);
571
572     bool enableResourceLoadStatistics = m_shouldEnableITPForDefaultSessions;
573     bool enableResourceLoadStatisticsLogTestingEvent = false;
574     bool shouldIncludeLocalhost = true;
575     bool enableResourceLoadStatisticsDebugMode = false;
576     WebCore::RegistrableDomain manualPrevalentResource { };
577     if (withWebsiteDataStore) {
578         enableResourceLoadStatistics = withWebsiteDataStore->resourceLoadStatisticsEnabled();
579 #if ENABLE(RESOURCE_LOAD_STATISTICS)
580         enableResourceLoadStatisticsLogTestingEvent = withWebsiteDataStore->hasStatisticsTestingCallback();
581 #endif
582         if (enableResourceLoadStatistics) {
583             auto networkSessionParameters = withWebsiteDataStore->parameters().networkSessionParameters;
584             shouldIncludeLocalhost = networkSessionParameters.shouldIncludeLocalhostInResourceLoadStatistics;
585             enableResourceLoadStatisticsDebugMode = networkSessionParameters.enableResourceLoadStatisticsDebugMode;
586             manualPrevalentResource = networkSessionParameters.resourceLoadStatisticsManualPrevalentResource;
587         }
588
589         parameters.defaultDataStoreParameters.perOriginStorageQuota = withWebsiteDataStore->perOriginStorageQuota();
590         parameters.defaultDataStoreParameters.perThirdPartyOriginStorageQuota = withWebsiteDataStore->perThirdPartyOriginStorageQuota();
591         
592         const auto& networkCacheDirectory = withWebsiteDataStore->resolvedNetworkCacheDirectory();
593         if (!networkCacheDirectory.isNull()) {
594             parameters.defaultDataStoreParameters.networkSessionParameters.networkCacheDirectory = networkCacheDirectory;
595             SandboxExtension::createHandle(networkCacheDirectory, SandboxExtension::Type::ReadWrite, parameters.defaultDataStoreParameters.networkSessionParameters.networkCacheDirectoryExtensionHandle);
596         }
597     } else if (m_websiteDataStore) {
598         enableResourceLoadStatistics = m_websiteDataStore->resourceLoadStatisticsEnabled();
599 #if ENABLE(RESOURCE_LOAD_STATISTICS)
600         enableResourceLoadStatisticsLogTestingEvent = m_websiteDataStore->hasStatisticsTestingCallback();
601 #endif
602         if (enableResourceLoadStatistics) {
603             auto networkSessionParameters = m_websiteDataStore->parameters().networkSessionParameters;
604             shouldIncludeLocalhost = networkSessionParameters.shouldIncludeLocalhostInResourceLoadStatistics;
605             enableResourceLoadStatisticsDebugMode = networkSessionParameters.enableResourceLoadStatisticsDebugMode;
606             manualPrevalentResource = networkSessionParameters.resourceLoadStatisticsManualPrevalentResource;
607         }
608
609         parameters.defaultDataStoreParameters.perOriginStorageQuota = m_websiteDataStore->perOriginStorageQuota();
610         parameters.defaultDataStoreParameters.perThirdPartyOriginStorageQuota = m_websiteDataStore->perThirdPartyOriginStorageQuota();
611
612         const auto& networkCacheDirectory = m_websiteDataStore->resolvedNetworkCacheDirectory();
613         if (!networkCacheDirectory.isNull()) {
614             parameters.defaultDataStoreParameters.networkSessionParameters.networkCacheDirectory = networkCacheDirectory;
615             SandboxExtension::createHandle(networkCacheDirectory, SandboxExtension::Type::ReadWrite, parameters.defaultDataStoreParameters.networkSessionParameters.networkCacheDirectoryExtensionHandle);
616         }
617     } else {
618         auto networkCacheDirectory = WebsiteDataStore::defaultNetworkCacheDirectory();
619         parameters.defaultDataStoreParameters.networkSessionParameters.networkCacheDirectory = networkCacheDirectory;
620         SandboxExtension::createHandle(networkCacheDirectory, SandboxExtension::Type::ReadWrite, parameters.defaultDataStoreParameters.networkSessionParameters.networkCacheDirectoryExtensionHandle);
621     }
622
623     parameters.defaultDataStoreParameters.networkSessionParameters.enableResourceLoadStatistics = enableResourceLoadStatistics;
624     parameters.defaultDataStoreParameters.networkSessionParameters.enableResourceLoadStatisticsLogTestingEvent = enableResourceLoadStatisticsLogTestingEvent;
625     parameters.defaultDataStoreParameters.networkSessionParameters.shouldIncludeLocalhostInResourceLoadStatistics = shouldIncludeLocalhost;
626     parameters.defaultDataStoreParameters.networkSessionParameters.enableResourceLoadStatisticsDebugMode = enableResourceLoadStatisticsDebugMode;
627     parameters.defaultDataStoreParameters.networkSessionParameters.resourceLoadStatisticsManualPrevalentResource = manualPrevalentResource;
628
629     // Add any platform specific parameters
630     platformInitializeNetworkProcess(parameters);
631
632     // Make sure the network process knows about all the sessions that have been registered before it started.
633     for (auto& sessionID : m_sessionToPageIDsMap.keys()) {
634         if (auto* websiteDataStore = WebsiteDataStore::existingNonDefaultDataStoreForSessionID(sessionID))
635             parameters.nonDefaultDataStoreParameters.append(websiteDataStore->parameters());
636     }
637
638     // Initialize the network process.
639     networkProcess->send(Messages::NetworkProcess::InitializeNetworkProcess(parameters), 0);
640
641 #if PLATFORM(COCOA)
642     networkProcess->send(Messages::NetworkProcess::SetQOS(networkProcessLatencyQOS(), networkProcessThroughputQOS()), 0);
643 #endif
644
645     if (m_didNetworkProcessCrash) {
646         m_didNetworkProcessCrash = false;
647         reinstateNetworkProcessAssertionState(*networkProcess);
648     }
649
650     if (withWebsiteDataStore) {
651         networkProcess->addSession(makeRef(*withWebsiteDataStore));
652         withWebsiteDataStore->clearPendingCookies();
653     }
654
655     m_networkProcess = WTFMove(networkProcess);
656     return *m_networkProcess;
657 }
658
659 void WebProcessPool::networkProcessCrashed(NetworkProcessProxy& networkProcessProxy, Vector<std::pair<RefPtr<WebProcessProxy>, Messages::WebProcessProxy::GetNetworkProcessConnection::DelayedReply>>&& pendingReplies)
660 {
661     ASSERT(m_networkProcess);
662     ASSERT(&networkProcessProxy == m_networkProcess.get());
663     m_didNetworkProcessCrash = true;
664
665     for (auto& supplement : m_supplements.values())
666         supplement->processDidClose(&networkProcessProxy);
667
668     m_client.networkProcessDidCrash(this);
669
670     if (m_automationSession)
671         m_automationSession->terminate();
672
673     // Leave the process proxy around during client call, so that the client could query the process identifier.
674     m_networkProcess = nullptr;
675
676     // Attempt to re-launch.
677     if (pendingReplies.isEmpty())
678         return;
679     auto& newNetworkProcess = ensureNetworkProcess();
680     for (auto& reply : pendingReplies)
681         newNetworkProcess.getNetworkProcessConnection(*reply.first, WTFMove(reply.second));
682 }
683
684 void WebProcessPool::getNetworkProcessConnection(WebProcessProxy& webProcessProxy, Messages::WebProcessProxy::GetNetworkProcessConnection::DelayedReply&& reply)
685 {
686     ensureNetworkProcess();
687     ASSERT(m_networkProcess);
688
689     m_networkProcess->getNetworkProcessConnection(webProcessProxy, WTFMove(reply));
690 }
691
692 #if ENABLE(SERVICE_WORKER)
693 void WebProcessPool::establishWorkerContextConnectionToNetworkProcess(NetworkProcessProxy& proxy, RegistrableDomain&& registrableDomain, PAL::SessionID sessionID)
694 {
695     ASSERT_UNUSED(proxy, &proxy == m_networkProcess.get());
696
697     m_mayHaveRegisteredServiceWorkers.clear();
698
699     auto* websiteDataStore = WebsiteDataStore::existingNonDefaultDataStoreForSessionID(sessionID);
700
701     if (!websiteDataStore) {
702         if (!m_websiteDataStore)
703             m_websiteDataStore = WebKit::WebsiteDataStore::defaultDataStore().ptr();
704         websiteDataStore = m_websiteDataStore.get();
705     }
706
707     RegistrableDomainWithSessionID registrableDomainWithSessionID { RegistrableDomain { registrableDomain }, sessionID };
708     if (m_serviceWorkerProcesses.contains(registrableDomainWithSessionID))
709         return;
710
711     if (m_serviceWorkerProcesses.isEmpty())
712         sendToAllProcesses(Messages::WebProcess::RegisterServiceWorkerClients { });
713
714     auto serviceWorkerProcessProxy = WebProcessProxy::createForServiceWorkers(*this, WTFMove(registrableDomain), *websiteDataStore);
715     m_serviceWorkerProcesses.add(WTFMove(registrableDomainWithSessionID), serviceWorkerProcessProxy.ptr());
716
717     updateProcessAssertions();
718     initializeNewWebProcess(serviceWorkerProcessProxy, websiteDataStore);
719
720     auto* serviceWorkerProcessProxyPtr = serviceWorkerProcessProxy.ptr();
721     m_processes.append(WTFMove(serviceWorkerProcessProxy));
722
723     serviceWorkerProcessProxyPtr->establishServiceWorkerContext(m_serviceWorkerPreferences ? m_serviceWorkerPreferences.value() : m_defaultPageGroup->preferences().store());
724     if (!m_serviceWorkerUserAgent.isNull())
725         serviceWorkerProcessProxyPtr->setServiceWorkerUserAgent(m_serviceWorkerUserAgent);
726 }
727 #endif
728
729 void WebProcessPool::disableServiceWorkerProcessTerminationDelay()
730 {
731 #if ENABLE(SERVICE_WORKER)
732     if (m_shouldDisableServiceWorkerProcessTerminationDelay)
733         return;
734
735     m_shouldDisableServiceWorkerProcessTerminationDelay = true;
736     if (m_networkProcess)
737         m_networkProcess->send(Messages::NetworkProcess::DisableServiceWorkerProcessTerminationDelay(), 0);
738 #endif
739 }
740
741 void WebProcessPool::windowServerConnectionStateChanged()
742 {
743     size_t processCount = m_processes.size();
744     for (size_t i = 0; i < processCount; ++i)
745         m_processes[i]->windowServerConnectionStateChanged();
746 }
747
748 void (*s_invalidMessageCallback)(WKStringRef messageName);
749
750 void WebProcessPool::setInvalidMessageCallback(void (*invalidMessageCallback)(WKStringRef messageName))
751 {
752     s_invalidMessageCallback = invalidMessageCallback;
753 }
754
755 void WebProcessPool::didReceiveInvalidMessage(const IPC::StringReference& messageReceiverName, const IPC::StringReference& messageName)
756 {
757     if (!s_invalidMessageCallback)
758         return;
759
760     StringBuilder messageNameStringBuilder;
761     messageNameStringBuilder.appendCharacters(messageReceiverName.data(), messageReceiverName.size());
762     messageNameStringBuilder.append('.');
763     messageNameStringBuilder.appendCharacters(messageName.data(), messageName.size());
764
765     s_invalidMessageCallback(toAPI(API::String::create(messageNameStringBuilder.toString()).ptr()));
766 }
767
768 void WebProcessPool::processDidCachePage(WebProcessProxy* process)
769 {
770     if (m_processWithPageCache && m_processWithPageCache != process)
771         m_processWithPageCache->releasePageCache();
772     m_processWithPageCache = process;
773 }
774
775 void WebProcessPool::resolvePathsForSandboxExtensions()
776 {
777     m_resolvedPaths.injectedBundlePath = resolvePathForSandboxExtension(injectedBundlePath());
778
779     m_resolvedPaths.additionalWebProcessSandboxExtensionPaths.reserveCapacity(m_configuration->additionalReadAccessAllowedPaths().size());
780     for (const auto& path : m_configuration->additionalReadAccessAllowedPaths())
781         m_resolvedPaths.additionalWebProcessSandboxExtensionPaths.uncheckedAppend(resolvePathForSandboxExtension(path.data()));
782
783     platformResolvePathsForSandboxExtensions();
784 }
785
786 WebProcessProxy& WebProcessPool::createNewWebProcess(WebsiteDataStore* websiteDataStore, WebProcessProxy::IsPrewarmed isPrewarmed)
787 {
788     auto processProxy = WebProcessProxy::create(*this, websiteDataStore, isPrewarmed);
789     auto& process = processProxy.get();
790     initializeNewWebProcess(process, websiteDataStore, isPrewarmed);
791     m_processes.append(WTFMove(processProxy));
792
793     if (m_serviceWorkerProcessesTerminationTimer.isActive())
794         m_serviceWorkerProcessesTerminationTimer.stop();
795
796     return process;
797 }
798
799 RefPtr<WebProcessProxy> WebProcessPool::tryTakePrewarmedProcess(WebsiteDataStore& websiteDataStore)
800 {
801     if (!m_prewarmedProcess)
802         return nullptr;
803     
804     // There is sometimes a delay until we get notified that a prewarmed process has been terminated (e.g. after resuming
805     // from suspension) so make sure the process is still running here before deciding to use it.
806     if (m_prewarmedProcess->wasTerminated()) {
807         RELEASE_LOG_ERROR(Process, "Not using prewarmed process %d because it has been terminated", m_prewarmedProcess->processIdentifier());
808         m_prewarmedProcess = nullptr;
809         return nullptr;
810     }
811
812 #if PLATFORM(GTK) || PLATFORM(WPE)
813     // In platforms using Bubblewrap for sandboxing, prewarmed process is launched using the WebProcessPool primary WebsiteDataStore,
814     // so we don't use it in case of using a different WebsiteDataStore.
815     if (m_sandboxEnabled && m_websiteDataStore && m_websiteDataStore.get() != &websiteDataStore)
816         return nullptr;
817 #endif
818
819     ASSERT(m_prewarmedProcess->isPrewarmed());
820     m_prewarmedProcess->markIsNoLongerInPrewarmedPool();
821     m_prewarmedProcess->setWebsiteDataStore(websiteDataStore);
822
823     return std::exchange(m_prewarmedProcess, nullptr);
824 }
825
826 #if PLATFORM(MAC)
827 static void displayReconfigurationCallBack(CGDirectDisplayID display, CGDisplayChangeSummaryFlags flags, void *userInfo)
828 {
829     auto screenProperties = WebCore::collectScreenProperties();
830     for (auto& processPool : WebProcessPool::allProcessPools()) {
831         processPool->sendToAllProcesses(Messages::WebProcess::SetScreenProperties(screenProperties));
832 #if ENABLE(WEBPROCESS_WINDOWSERVER_BLOCKING)
833         processPool->sendToAllProcesses(Messages::WebProcess::DisplayConfigurationChanged(display, flags));
834 #endif
835     }
836 }
837
838 static void registerDisplayConfigurationCallback()
839 {
840     static std::once_flag onceFlag;
841     std::call_once(
842         onceFlag,
843         [] {
844             CGDisplayRegisterReconfigurationCallback(displayReconfigurationCallBack, nullptr);
845         });
846 }
847 #endif
848
849 WebProcessDataStoreParameters WebProcessPool::webProcessDataStoreParameters(WebProcessProxy& process, WebsiteDataStore& websiteDataStore)
850 {
851     websiteDataStore.resolveDirectoriesIfNecessary();
852
853     String applicationCacheDirectory = websiteDataStore.resolvedApplicationCacheDirectory();
854     SandboxExtension::Handle applicationCacheDirectoryExtensionHandle;
855     if (!applicationCacheDirectory.isEmpty())
856         SandboxExtension::createHandleWithoutResolvingPath(applicationCacheDirectory, SandboxExtension::Type::ReadWrite, applicationCacheDirectoryExtensionHandle);
857
858     String applicationCacheFlatFileSubdirectoryName = websiteDataStore.applicationCacheFlatFileSubdirectoryName();
859
860     String webSQLDatabaseDirectory = websiteDataStore.resolvedDatabaseDirectory();
861     SandboxExtension::Handle webSQLDatabaseDirectoryExtensionHandle;
862     if (!webSQLDatabaseDirectory.isEmpty())
863         SandboxExtension::createHandleWithoutResolvingPath(webSQLDatabaseDirectory, SandboxExtension::Type::ReadWrite, webSQLDatabaseDirectoryExtensionHandle);
864
865     String mediaCacheDirectory = websiteDataStore.resolvedMediaCacheDirectory();
866     SandboxExtension::Handle mediaCacheDirectoryExtensionHandle;
867     if (!mediaCacheDirectory.isEmpty())
868         SandboxExtension::createHandleWithoutResolvingPath(mediaCacheDirectory, SandboxExtension::Type::ReadWrite, mediaCacheDirectoryExtensionHandle);
869
870     String mediaKeyStorageDirectory = websiteDataStore.resolvedMediaKeysDirectory();
871     SandboxExtension::Handle mediaKeyStorageDirectoryExtensionHandle;
872     if (!mediaKeyStorageDirectory.isEmpty())
873         SandboxExtension::createHandleWithoutResolvingPath(mediaKeyStorageDirectory, SandboxExtension::Type::ReadWrite, mediaKeyStorageDirectoryExtensionHandle);
874
875     String javaScriptConfigurationDirectory;
876     if (!m_javaScriptConfigurationDirectory.isEmpty())
877         javaScriptConfigurationDirectory = m_javaScriptConfigurationDirectory;
878     else if (javaScriptConfigurationFileEnabled())
879         javaScriptConfigurationDirectory = websiteDataStore.resolvedJavaScriptConfigurationDirectory();
880
881     SandboxExtension::Handle javaScriptConfigurationDirectoryExtensionHandle;
882     if (!javaScriptConfigurationDirectory.isEmpty())
883         SandboxExtension::createHandleWithoutResolvingPath(javaScriptConfigurationDirectory, SandboxExtension::Type::ReadWrite, javaScriptConfigurationDirectoryExtensionHandle);
884         
885     auto plugInAutoStartOriginHashes = m_plugInAutoStartProvider.autoStartOriginHashesCopy(websiteDataStore.sessionID());
886
887     return WebProcessDataStoreParameters {
888         websiteDataStore.sessionID(),
889         WTFMove(applicationCacheDirectory),
890         WTFMove(applicationCacheDirectoryExtensionHandle),
891         WTFMove(applicationCacheFlatFileSubdirectoryName),
892         WTFMove(webSQLDatabaseDirectory),
893         WTFMove(webSQLDatabaseDirectoryExtensionHandle),
894         WTFMove(mediaCacheDirectory),
895         WTFMove(mediaCacheDirectoryExtensionHandle),
896         WTFMove(mediaKeyStorageDirectory),
897         WTFMove(mediaKeyStorageDirectoryExtensionHandle),
898         WTFMove(javaScriptConfigurationDirectory),
899         WTFMove(javaScriptConfigurationDirectoryExtensionHandle),
900         WTFMove(plugInAutoStartOriginHashes),
901         websiteDataStore.resourceLoadStatisticsEnabled()
902     };
903 }
904
905 void WebProcessPool::initializeNewWebProcess(WebProcessProxy& process, WebsiteDataStore* websiteDataStore, WebProcessProxy::IsPrewarmed isPrewarmed)
906 {
907     auto initializationActivityToken = process.throttler().backgroundActivityToken();
908     auto scopeExit = makeScopeExit([&process, initializationActivityToken] {
909         // Round-trip to the Web Content process before releasing the
910         // initialization activity token, so that we're sure that all
911         // messages sent from this function have been handled.
912         process.isResponsive([initializationActivityToken] (bool) { });
913     });
914
915     ensureNetworkProcess();
916
917     WebProcessCreationParameters parameters;
918
919     parameters.injectedBundlePath = m_resolvedPaths.injectedBundlePath;
920     if (!parameters.injectedBundlePath.isEmpty())
921         SandboxExtension::createHandleWithoutResolvingPath(parameters.injectedBundlePath, SandboxExtension::Type::ReadOnly, parameters.injectedBundlePathExtensionHandle);
922
923     parameters.additionalSandboxExtensionHandles.allocate(m_resolvedPaths.additionalWebProcessSandboxExtensionPaths.size());
924     for (size_t i = 0, size = m_resolvedPaths.additionalWebProcessSandboxExtensionPaths.size(); i < size; ++i)
925         SandboxExtension::createHandleWithoutResolvingPath(m_resolvedPaths.additionalWebProcessSandboxExtensionPaths[i], SandboxExtension::Type::ReadOnly, parameters.additionalSandboxExtensionHandles[i]);
926
927 #if PLATFORM(IOS_FAMILY)
928     setJavaScriptConfigurationFileEnabledFromDefaults();
929 #endif
930
931     parameters.cacheModel = LegacyGlobalSettings::singleton().cacheModel();
932     parameters.languages = configuration().overrideLanguages().isEmpty() ? userPreferredLanguages() : configuration().overrideLanguages();
933
934     parameters.urlSchemesRegisteredAsEmptyDocument = copyToVector(m_schemesToRegisterAsEmptyDocument);
935     parameters.urlSchemesRegisteredAsSecure = copyToVector(m_schemesToRegisterAsSecure);
936     parameters.urlSchemesRegisteredAsBypassingContentSecurityPolicy = copyToVector(m_schemesToRegisterAsBypassingContentSecurityPolicy);
937     parameters.urlSchemesForWhichDomainRelaxationIsForbidden = copyToVector(m_schemesToSetDomainRelaxationForbiddenFor);
938     parameters.urlSchemesRegisteredAsLocal = copyToVector(m_schemesToRegisterAsLocal);
939     parameters.urlSchemesRegisteredAsNoAccess = copyToVector(m_schemesToRegisterAsNoAccess);
940     parameters.urlSchemesRegisteredAsDisplayIsolated = copyToVector(m_schemesToRegisterAsDisplayIsolated);
941     parameters.urlSchemesRegisteredAsCORSEnabled = copyToVector(m_schemesToRegisterAsCORSEnabled);
942     parameters.urlSchemesRegisteredAsAlwaysRevalidated = copyToVector(m_schemesToRegisterAsAlwaysRevalidated);
943     parameters.urlSchemesRegisteredAsCachePartitioned = copyToVector(m_schemesToRegisterAsCachePartitioned);
944     parameters.urlSchemesServiceWorkersCanHandle = copyToVector(m_schemesServiceWorkersCanHandle);
945     parameters.urlSchemesRegisteredAsCanDisplayOnlyIfCanRequest = copyToVector(m_schemesToRegisterAsCanDisplayOnlyIfCanRequest);
946
947     parameters.shouldAlwaysUseComplexTextCodePath = m_alwaysUsesComplexTextCodePath;
948     parameters.shouldUseFontSmoothing = m_shouldUseFontSmoothing;
949
950     parameters.terminationTimeout = 0_s;
951
952     parameters.textCheckerState = TextChecker::state();
953
954     parameters.fullKeyboardAccessEnabled = WebProcessProxy::fullKeyboardAccessEnabled();
955
956     parameters.defaultRequestTimeoutInterval = API::URLRequest::defaultTimeoutInterval();
957
958 #if ENABLE(NOTIFICATIONS)
959     // FIXME: There should be a generic way for supplements to add to the intialization parameters.
960     parameters.notificationPermissions = supplement<WebNotificationManagerProxy>()->notificationPermissions();
961 #endif
962
963     parameters.plugInAutoStartOrigins = copyToVector(m_plugInAutoStartProvider.autoStartOrigins());
964
965     parameters.memoryCacheDisabled = m_memoryCacheDisabled;
966     parameters.attrStyleEnabled = m_configuration->attrStyleEnabled();
967
968 #if ENABLE(SERVICE_CONTROLS)
969     auto& serviceController = ServicesController::singleton();
970     parameters.hasImageServices = serviceController.hasImageServices();
971     parameters.hasSelectionServices = serviceController.hasSelectionServices();
972     parameters.hasRichContentServices = serviceController.hasRichContentServices();
973     serviceController.refreshExistingServices();
974 #endif
975
976 #if ENABLE(NETSCAPE_PLUGIN_API)
977     parameters.pluginLoadClientPolicies = m_pluginLoadClientPolicies;
978 #endif
979
980 #if OS(LINUX)
981     parameters.shouldEnableMemoryPressureReliefLogging = true;
982 #endif
983
984 #if ENABLE(MEDIA_STREAM)
985     parameters.shouldCaptureAudioInUIProcess = m_configuration->shouldCaptureAudioInUIProcess();
986     parameters.shouldCaptureVideoInUIProcess = m_configuration->shouldCaptureVideoInUIProcess();
987     parameters.shouldCaptureDisplayInUIProcess = m_configuration->shouldCaptureDisplayInUIProcess();
988 #endif
989
990     parameters.presentingApplicationPID = m_configuration->presentingApplicationPID();
991
992     // Add any platform specific parameters
993     platformInitializeWebProcess(process, parameters);
994
995     RefPtr<API::Object> injectedBundleInitializationUserData = m_injectedBundleClient->getInjectedBundleInitializationUserData(*this);
996     if (!injectedBundleInitializationUserData)
997         injectedBundleInitializationUserData = m_injectedBundleInitializationUserData;
998     parameters.initializationUserData = UserData(process.transformObjectsToHandles(injectedBundleInitializationUserData.get()));
999     
1000     if (websiteDataStore)
1001         parameters.websiteDataStoreParameters = webProcessDataStoreParameters(process, *websiteDataStore);
1002
1003     process.send(Messages::WebProcess::InitializeWebProcess(parameters), 0);
1004
1005 #if PLATFORM(COCOA)
1006     process.send(Messages::WebProcess::SetQOS(webProcessLatencyQOS(), webProcessThroughputQOS()), 0);
1007 #endif
1008
1009     if (m_automationSession)
1010         process.send(Messages::WebProcess::EnsureAutomationSessionProxy(m_automationSession->sessionIdentifier()), 0);
1011
1012     ASSERT(m_messagesToInjectedBundlePostedToEmptyContext.isEmpty());
1013
1014     if (isPrewarmed == WebProcessProxy::IsPrewarmed::Yes) {
1015         ASSERT(!m_prewarmedProcess);
1016         m_prewarmedProcess = &process;
1017         process.send(Messages::WebProcess::PrewarmGlobally(), 0);
1018     }
1019
1020 #if PLATFORM(IOS)
1021     process.send(Messages::WebProcess::BacklightLevelDidChange(displayBrightness()), 0);
1022 #endif
1023
1024 #if ENABLE(REMOTE_INSPECTOR)
1025     // Initialize remote inspector connection now that we have a sub-process that is hosting one of our web views.
1026     Inspector::RemoteInspector::singleton(); 
1027 #endif
1028
1029 #if PLATFORM(MAC)
1030     registerDisplayConfigurationCallback();
1031 #endif
1032 }
1033
1034 void WebProcessPool::prewarmProcess()
1035 {
1036     if (m_prewarmedProcess)
1037         return;
1038
1039     RELEASE_LOG(PerformanceLogging, "Prewarming a WebProcess for performance");
1040     createNewWebProcess(nullptr, WebProcessProxy::IsPrewarmed::Yes);
1041 }
1042
1043 void WebProcessPool::enableProcessTermination()
1044 {
1045     m_processTerminationEnabled = true;
1046     Vector<RefPtr<WebProcessProxy>> processes = m_processes;
1047     for (size_t i = 0; i < processes.size(); ++i) {
1048         if (shouldTerminate(processes[i].get()))
1049             processes[i]->terminate();
1050     }
1051 }
1052
1053 bool WebProcessPool::shouldTerminate(WebProcessProxy* process)
1054 {
1055     ASSERT(m_processes.contains(process));
1056
1057     if (!m_processTerminationEnabled || m_configuration->alwaysKeepAndReuseSwappedProcesses())
1058         return false;
1059
1060     return true;
1061 }
1062
1063 void WebProcessPool::processDidFinishLaunching(WebProcessProxy* process)
1064 {
1065     ASSERT(m_processes.contains(process));
1066
1067     if (!m_visitedLinksPopulated) {
1068         populateVisitedLinks();
1069         m_visitedLinksPopulated = true;
1070     }
1071
1072     // Sometimes the memorySampler gets initialized after process initialization has happened but before the process has finished launching
1073     // so check if it needs to be started here
1074     if (m_memorySamplerEnabled) {
1075         SandboxExtension::Handle sampleLogSandboxHandle;        
1076         WallTime now = WallTime::now();
1077         String sampleLogFilePath = makeString("WebProcess", static_cast<unsigned long long>(now.secondsSinceEpoch().seconds()), "pid", process->processIdentifier());
1078         sampleLogFilePath = SandboxExtension::createHandleForTemporaryFile(sampleLogFilePath, SandboxExtension::Type::ReadWrite, sampleLogSandboxHandle);
1079         
1080         process->send(Messages::WebProcess::StartMemorySampler(sampleLogSandboxHandle, sampleLogFilePath, m_memorySamplerInterval), 0);
1081     }
1082
1083     if (m_configuration->fullySynchronousModeIsAllowedForTesting())
1084         process->connection()->allowFullySynchronousModeForTesting();
1085
1086     if (m_configuration->ignoreSynchronousMessagingTimeoutsForTesting())
1087         process->connection()->ignoreTimeoutsForTesting();
1088
1089     m_connectionClient.didCreateConnection(this, process->webConnection());
1090
1091     if (m_websiteDataStore)
1092         m_websiteDataStore->didCreateNetworkProcess();
1093 }
1094
1095 void WebProcessPool::disconnectProcess(WebProcessProxy* process)
1096 {
1097     ASSERT(m_processes.contains(process));
1098     ASSERT(!m_processesPlayingAudibleMedia.contains(process->coreProcessIdentifier()));
1099
1100     if (m_prewarmedProcess == process) {
1101         ASSERT(m_prewarmedProcess->isPrewarmed());
1102         m_prewarmedProcess = nullptr;
1103     }
1104
1105     if (m_dummyProcessProxy == process)
1106         m_dummyProcessProxy = nullptr;
1107
1108     // 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.
1109     // Clearing everything causes assertion failures, so it's less trouble to skip that for now.
1110     RefPtr<WebProcessProxy> protect(process);
1111     if (m_processWithPageCache == process)
1112         m_processWithPageCache = nullptr;
1113
1114     m_suspendedPages.removeAllMatching([process](auto& suspendedPage) {
1115         return &suspendedPage->process() == process;
1116     });
1117
1118 #if ENABLE(SERVICE_WORKER)
1119     if (process->isRunningServiceWorkers()) {
1120         auto* removedProcess = m_serviceWorkerProcesses.take(RegistrableDomainWithSessionID { process->registrableDomain(), process->websiteDataStore().sessionID() });
1121         ASSERT_UNUSED(removedProcess, removedProcess == process);
1122         updateProcessAssertions();
1123     }
1124 #endif
1125
1126     static_cast<WebContextSupplement*>(supplement<WebGeolocationManagerProxy>())->processDidClose(process);
1127
1128     m_processes.removeFirst(process);
1129
1130 #if ENABLE(GAMEPAD)
1131     if (m_processesUsingGamepads.contains(process))
1132         processStoppedUsingGamepads(*process);
1133 #endif
1134
1135     removeProcessFromOriginCacheSet(*process);
1136
1137 #if ENABLE(SERVICE_WORKER)
1138     // FIXME: We should do better than this. For now, we just destroy the ServiceWorker process
1139     // whenever there is no regular WebContent process remaining.
1140     if (m_processes.size() == m_serviceWorkerProcesses.size()) {
1141         if (!m_serviceWorkerProcessesTerminationTimer.isActive())
1142             m_serviceWorkerProcessesTerminationTimer.startOneShot(serviceWorkerTerminationDelay);
1143     }
1144 #endif
1145 }
1146
1147 WebProcessProxy& WebProcessPool::processForRegistrableDomain(WebsiteDataStore& websiteDataStore, WebPageProxy* page, const RegistrableDomain& registrableDomain)
1148 {
1149     if (!registrableDomain.isEmpty()) {
1150         if (auto process = webProcessCache().takeProcess(registrableDomain, websiteDataStore))
1151             return *process;
1152
1153         // Check if we have a suspended page for the given registrable domain and use its process if we do, for performance reasons.
1154         if (auto process = page ? findReusableSuspendedPageProcess(registrableDomain, *page, websiteDataStore) : nullptr) {
1155             RELEASE_LOG(ProcessSwapping, "Using WebProcess %i from a SuspendedPage", process->processIdentifier());
1156             return *process;
1157         }
1158     }
1159
1160     if (auto process = tryTakePrewarmedProcess(websiteDataStore)) {
1161         RELEASE_LOG(ProcessSwapping, "Using prewarmed process %i", process->processIdentifier());
1162         if (!registrableDomain.isEmpty())
1163             tryPrewarmWithDomainInformation(*process, registrableDomain);
1164         return *process;
1165     }
1166
1167     if (!usesSingleWebProcess())
1168         return createNewWebProcess(&websiteDataStore);
1169
1170 #if PLATFORM(COCOA)
1171     bool mustMatchDataStore = WebKit::WebsiteDataStore::defaultDataStoreExists() && &websiteDataStore != WebKit::WebsiteDataStore::defaultDataStore().ptr();
1172 #else
1173     bool mustMatchDataStore = false;
1174 #endif
1175
1176     for (auto& process : m_processes) {
1177         if (process == m_prewarmedProcess || process == m_dummyProcessProxy)
1178             continue;
1179 #if ENABLE(SERVICE_WORKER)
1180         if (process->isRunningServiceWorkers())
1181             continue;
1182 #endif
1183         if (mustMatchDataStore && &process->websiteDataStore() != &websiteDataStore)
1184             continue;
1185         return *process;
1186     }
1187     return createNewWebProcess(&websiteDataStore);
1188 }
1189
1190 Ref<WebPageProxy> WebProcessPool::createWebPage(PageClient& pageClient, Ref<API::PageConfiguration>&& pageConfiguration)
1191 {
1192     if (!pageConfiguration->pageGroup())
1193         pageConfiguration->setPageGroup(m_defaultPageGroup.ptr());
1194     if (!pageConfiguration->preferences())
1195         pageConfiguration->setPreferences(&pageConfiguration->pageGroup()->preferences());
1196     if (!pageConfiguration->userContentController())
1197         pageConfiguration->setUserContentController(&pageConfiguration->pageGroup()->userContentController());
1198     if (!pageConfiguration->visitedLinkStore())
1199         pageConfiguration->setVisitedLinkStore(m_visitedLinkStore.ptr());
1200
1201     if (!pageConfiguration->websiteDataStore()) {
1202         // We try to avoid creating the default data store as long as possible.
1203         // But if there is an attempt to create a web page without any specified data store, then we have to create it.
1204         if (!m_websiteDataStore)
1205             m_websiteDataStore = WebKit::WebsiteDataStore::defaultDataStore().ptr();
1206
1207         pageConfiguration->setWebsiteDataStore(m_websiteDataStore.get());
1208     }
1209
1210     RefPtr<WebProcessProxy> process;
1211     auto* relatedPage = pageConfiguration->relatedPage();
1212     if (relatedPage && !relatedPage->isClosed()) {
1213         // Sharing processes, e.g. when creating the page via window.open().
1214         process = &pageConfiguration->relatedPage()->ensureRunningProcess();
1215         // We do not support several WebsiteDataStores sharing a single process.
1216         ASSERT(process.get() == m_dummyProcessProxy || pageConfiguration->websiteDataStore() == &process->websiteDataStore());
1217         ASSERT(&pageConfiguration->relatedPage()->websiteDataStore() == pageConfiguration->websiteDataStore());
1218     } else if (!m_isDelayedWebProcessLaunchDisabled) {
1219         // In the common case, we delay process launch until something is actually loaded in the page.
1220         if (!m_dummyProcessProxy) {
1221             auto dummyProcessProxy = WebProcessProxy::create(*this, nullptr, WebProcessProxy::IsPrewarmed::No, WebProcessProxy::ShouldLaunchProcess::No);
1222             m_dummyProcessProxy = dummyProcessProxy.ptr();
1223             m_processes.append(WTFMove(dummyProcessProxy));
1224         }
1225         process = m_dummyProcessProxy;
1226     } else
1227         process = &processForRegistrableDomain(*pageConfiguration->websiteDataStore(), nullptr, { });
1228
1229     ASSERT(process);
1230
1231     auto page = process->createWebPage(pageClient, WTFMove(pageConfiguration));
1232
1233 #if ENABLE(SERVICE_WORKER)
1234     ASSERT(!process->isRunningServiceWorkers());
1235
1236     if (!m_serviceWorkerPreferences) {
1237         m_serviceWorkerPreferences = page->preferencesStore();
1238         for (auto* serviceWorkerProcess : m_serviceWorkerProcesses.values())
1239             serviceWorkerProcess->updateServiceWorkerPreferencesStore(*m_serviceWorkerPreferences);
1240     }
1241 #endif
1242
1243     bool enableProcessSwapOnCrossSiteNavigation = page->preferences().processSwapOnCrossSiteNavigationEnabled();
1244 #if PLATFORM(IOS_FAMILY)
1245     if (WebCore::IOSApplication::isFirefox() && !linkedOnOrAfter(WebKit::SDKVersion::FirstWithProcessSwapOnCrossSiteNavigation))
1246         enableProcessSwapOnCrossSiteNavigation = false;
1247 #endif
1248
1249     bool wasProcessSwappingOnNavigationEnabled = m_configuration->processSwapsOnNavigation();
1250     m_configuration->setProcessSwapsOnNavigationFromExperimentalFeatures(enableProcessSwapOnCrossSiteNavigation);
1251     if (wasProcessSwappingOnNavigationEnabled != m_configuration->processSwapsOnNavigation())
1252         m_webProcessCache->updateCapacity(*this);
1253
1254     m_configuration->setShouldCaptureAudioInUIProcess(page->preferences().captureAudioInUIProcessEnabled());
1255     m_configuration->setShouldCaptureVideoInUIProcess(page->preferences().captureVideoInUIProcessEnabled());
1256
1257     return page;
1258 }
1259
1260 #if ENABLE(SERVICE_WORKER)
1261 void WebProcessPool::updateServiceWorkerUserAgent(const String& userAgent)
1262 {
1263     if (m_serviceWorkerUserAgent == userAgent)
1264         return;
1265     m_serviceWorkerUserAgent = userAgent;
1266     for (auto* serviceWorkerProcess : m_serviceWorkerProcesses.values())
1267         serviceWorkerProcess->setServiceWorkerUserAgent(m_serviceWorkerUserAgent);
1268 }
1269
1270 bool WebProcessPool::mayHaveRegisteredServiceWorkers(const WebsiteDataStore& store)
1271 {
1272     if (!m_serviceWorkerProcesses.isEmpty())
1273         return true;
1274
1275     String serviceWorkerRegistrationDirectory = store.resolvedServiceWorkerRegistrationDirectory();
1276     if (serviceWorkerRegistrationDirectory.isEmpty())
1277         serviceWorkerRegistrationDirectory = WebsiteDataStore::defaultServiceWorkerRegistrationDirectory();
1278
1279     return m_mayHaveRegisteredServiceWorkers.ensure(serviceWorkerRegistrationDirectory, [&] {
1280         // FIXME: Make this computation on a background thread.
1281         return FileSystem::fileExists(WebCore::serviceWorkerRegistrationDatabaseFilename(serviceWorkerRegistrationDirectory));
1282     }).iterator->value;
1283 }
1284 #endif
1285
1286 void WebProcessPool::pageBeginUsingWebsiteDataStore(WebPageProxyIdentifier pageID, WebsiteDataStore& dataStore)
1287 {
1288     auto result = m_sessionToPageIDsMap.add(dataStore.sessionID(), HashSet<WebPageProxyIdentifier>()).iterator->value.add(pageID);
1289     ASSERT_UNUSED(result, result.isNewEntry);
1290
1291     auto sessionID = dataStore.sessionID();
1292     if (sessionID != PAL::SessionID::defaultSessionID()) {
1293         ASSERT(!sessionID.isEphemeral() || dataStore.parameters().networkSessionParameters.sessionID == sessionID);
1294         if (m_networkProcess) {
1295             m_networkProcess->addSession(makeRef(dataStore));
1296             dataStore.clearPendingCookies();
1297         }
1298     }
1299 }
1300
1301 void WebProcessPool::pageEndUsingWebsiteDataStore(WebPageProxyIdentifier pageID, WebsiteDataStore& dataStore)
1302 {
1303     auto sessionID = dataStore.sessionID();
1304     auto iterator = m_sessionToPageIDsMap.find(sessionID);
1305     ASSERT(iterator != m_sessionToPageIDsMap.end());
1306
1307     auto takenPageID = iterator->value.take(pageID);
1308     ASSERT_UNUSED(takenPageID, takenPageID == pageID);
1309
1310     if (iterator->value.isEmpty()) {
1311         m_sessionToPageIDsMap.remove(iterator);
1312
1313         if (sessionID.isEphemeral())
1314             m_webProcessCache->clearAllProcessesForSession(sessionID);
1315     }
1316 }
1317
1318 bool WebProcessPool::hasPagesUsingWebsiteDataStore(WebsiteDataStore& dataStore) const
1319 {
1320     return m_sessionToPageIDsMap.contains(dataStore.sessionID());
1321 }
1322
1323 DownloadProxy& WebProcessPool::download(WebsiteDataStore& dataStore, WebPageProxy* initiatingPage, const ResourceRequest& request, const String& suggestedFilename)
1324 {
1325     auto& downloadProxy = createDownloadProxy(dataStore, request, initiatingPage);
1326     PAL::SessionID sessionID = dataStore.sessionID();
1327
1328     if (initiatingPage)
1329         initiatingPage->handleDownloadRequest(downloadProxy);
1330
1331     if (networkProcess()) {
1332         ResourceRequest updatedRequest(request);
1333         // Request's firstPartyForCookies will be used as Original URL of the download request.
1334         // We set the value to top level document's URL.
1335         if (initiatingPage) {
1336             URL initiatingPageURL = URL { URL { }, initiatingPage->pageLoadState().url() };
1337             updatedRequest.setFirstPartyForCookies(initiatingPageURL);
1338             updatedRequest.setIsSameSite(areRegistrableDomainsEqual(initiatingPageURL, request.url()));
1339             if (!updatedRequest.hasHTTPHeaderField(HTTPHeaderName::UserAgent))
1340                 updatedRequest.setHTTPUserAgent(initiatingPage->userAgent());
1341         } else {
1342             updatedRequest.setFirstPartyForCookies(URL());
1343             updatedRequest.setIsSameSite(false);
1344             if (!updatedRequest.hasHTTPHeaderField(HTTPHeaderName::UserAgent))
1345                 updatedRequest.setHTTPUserAgent(WebPageProxy::standardUserAgent());
1346         }
1347         updatedRequest.setIsTopSite(false);
1348         networkProcess()->send(Messages::NetworkProcess::DownloadRequest(sessionID, downloadProxy.downloadID(), updatedRequest, suggestedFilename), 0);
1349         return downloadProxy;
1350     }
1351
1352     return downloadProxy;
1353 }
1354
1355 DownloadProxy& WebProcessPool::resumeDownload(WebsiteDataStore& dataStore, WebPageProxy* initiatingPage, const API::Data& resumeData, const String& path)
1356 {
1357     auto& downloadProxy = createDownloadProxy(dataStore, ResourceRequest(), initiatingPage);
1358     PAL::SessionID sessionID = dataStore.sessionID();
1359
1360     SandboxExtension::Handle sandboxExtensionHandle;
1361     if (!path.isEmpty())
1362         SandboxExtension::createHandle(path, SandboxExtension::Type::ReadWrite, sandboxExtensionHandle);
1363
1364     if (networkProcess()) {
1365         networkProcess()->send(Messages::NetworkProcess::ResumeDownload(sessionID, downloadProxy.downloadID(), resumeData.dataReference(), path, sandboxExtensionHandle), 0);
1366         return downloadProxy;
1367     }
1368
1369     return downloadProxy;
1370 }
1371
1372 void WebProcessPool::postMessageToInjectedBundle(const String& messageName, API::Object* messageBody)
1373 {
1374     for (auto& process : m_processes) {
1375         // FIXME: Return early if the message body contains any references to WKPageRefs/WKFrameRefs etc. since they're local to a process.
1376         process->send(Messages::WebProcess::HandleInjectedBundleMessage(messageName, UserData(process->transformObjectsToHandles(messageBody).get())), 0);
1377     }
1378 }
1379
1380 void WebProcessPool::didReachGoodTimeToPrewarm()
1381 {
1382     if (!configuration().isAutomaticProcessWarmingEnabled() || !configuration().processSwapsOnNavigation() || usesSingleWebProcess())
1383         return;
1384
1385     if (MemoryPressureHandler::singleton().isUnderMemoryPressure()) {
1386         if (!m_prewarmedProcess)
1387             RELEASE_LOG(PerformanceLogging, "Not automatically prewarming a WebProcess due to memory pressure");
1388         return;
1389     }
1390
1391     prewarmProcess();
1392 }
1393
1394 void WebProcessPool::populateVisitedLinks()
1395 {
1396     m_historyClient->populateVisitedLinks(*this);
1397 }
1398
1399 WebProcessPool::Statistics& WebProcessPool::statistics()
1400 {
1401     static Statistics statistics = Statistics();
1402
1403     return statistics;
1404 }
1405
1406 void WebProcessPool::handleMemoryPressureWarning(Critical)
1407 {
1408     RELEASE_LOG(PerformanceLogging, "%p - WebProcessPool::handleMemoryPressureWarning", this);
1409
1410
1411     clearSuspendedPages(AllowProcessCaching::No);
1412     m_webProcessCache->clear();
1413
1414     if (m_prewarmedProcess)
1415         m_prewarmedProcess->shutDown();
1416     ASSERT(!m_prewarmedProcess);
1417 }
1418
1419 #if ENABLE(NETSCAPE_PLUGIN_API)
1420 void WebProcessPool::setAdditionalPluginsDirectory(const String& directory)
1421 {
1422     Vector<String> directories;
1423     directories.append(directory);
1424
1425     m_pluginInfoStore.setAdditionalPluginsDirectories(directories);
1426 }
1427
1428 void WebProcessPool::refreshPlugins()
1429 {
1430     m_pluginInfoStore.refresh();
1431     sendToAllProcesses(Messages::WebProcess::RefreshPlugins());
1432 }
1433
1434 #endif // ENABLE(NETSCAPE_PLUGIN_API)
1435
1436 ProcessID WebProcessPool::networkProcessIdentifier()
1437 {
1438     return m_networkProcess ? m_networkProcess->processIdentifier() : 0;
1439 }
1440
1441 ProcessID WebProcessPool::prewarmedProcessIdentifier()
1442 {
1443     return m_prewarmedProcess ? m_prewarmedProcess->processIdentifier() : 0;
1444 }
1445
1446 void WebProcessPool::activePagesOriginsInWebProcessForTesting(ProcessID pid, CompletionHandler<void(Vector<String>&&)>&& completionHandler)
1447 {
1448     for (auto& process : m_processes) {
1449         if (process->processIdentifier() == pid)
1450             return process->activePagesDomainsForTesting(WTFMove(completionHandler));
1451     }
1452     completionHandler({ });
1453 }
1454
1455 void WebProcessPool::setAlwaysUsesComplexTextCodePath(bool alwaysUseComplexText)
1456 {
1457     m_alwaysUsesComplexTextCodePath = alwaysUseComplexText;
1458     sendToAllProcesses(Messages::WebProcess::SetAlwaysUsesComplexTextCodePath(alwaysUseComplexText));
1459 }
1460
1461 void WebProcessPool::setShouldUseFontSmoothing(bool useFontSmoothing)
1462 {
1463     m_shouldUseFontSmoothing = useFontSmoothing;
1464     sendToAllProcesses(Messages::WebProcess::SetShouldUseFontSmoothing(useFontSmoothing));
1465 }
1466
1467 void WebProcessPool::setResourceLoadStatisticsEnabled(bool enabled)
1468 {
1469     m_shouldEnableITPForDefaultSessions = enabled;
1470     sendToAllProcesses(Messages::WebProcess::SetResourceLoadStatisticsEnabled(enabled));
1471 #if ENABLE(RESOURCE_LOAD_STATISTICS)
1472     sendToNetworkingProcess(Messages::NetworkProcess::SetResourceLoadStatisticsEnabled(enabled));
1473 #endif
1474 }
1475
1476 void WebProcessPool::clearResourceLoadStatistics()
1477 {
1478     sendToAllProcesses(Messages::WebProcess::ClearResourceLoadStatistics());
1479 }
1480
1481 void WebProcessPool::registerURLSchemeAsEmptyDocument(const String& urlScheme)
1482 {
1483     m_schemesToRegisterAsEmptyDocument.add(urlScheme);
1484     sendToAllProcesses(Messages::WebProcess::RegisterURLSchemeAsEmptyDocument(urlScheme));
1485 }
1486
1487 void WebProcessPool::registerURLSchemeAsSecure(const String& urlScheme)
1488 {
1489     m_schemesToRegisterAsSecure.add(urlScheme);
1490     sendToAllProcesses(Messages::WebProcess::RegisterURLSchemeAsSecure(urlScheme));
1491     sendToNetworkingProcess(Messages::NetworkProcess::RegisterURLSchemeAsSecure(urlScheme));
1492 }
1493
1494 void WebProcessPool::registerURLSchemeAsBypassingContentSecurityPolicy(const String& urlScheme)
1495 {
1496     m_schemesToRegisterAsBypassingContentSecurityPolicy.add(urlScheme);
1497     sendToAllProcesses(Messages::WebProcess::RegisterURLSchemeAsBypassingContentSecurityPolicy(urlScheme));
1498     sendToNetworkingProcess(Messages::NetworkProcess::RegisterURLSchemeAsBypassingContentSecurityPolicy(urlScheme));
1499 }
1500
1501 void WebProcessPool::setDomainRelaxationForbiddenForURLScheme(const String& urlScheme)
1502 {
1503     m_schemesToSetDomainRelaxationForbiddenFor.add(urlScheme);
1504     sendToAllProcesses(Messages::WebProcess::SetDomainRelaxationForbiddenForURLScheme(urlScheme));
1505 }
1506
1507 void WebProcessPool::registerURLSchemeAsLocal(const String& urlScheme)
1508 {
1509     m_schemesToRegisterAsLocal.add(urlScheme);
1510     sendToAllProcesses(Messages::WebProcess::RegisterURLSchemeAsLocal(urlScheme));
1511     sendToNetworkingProcess(Messages::NetworkProcess::RegisterURLSchemeAsLocal(urlScheme));
1512 }
1513
1514 void WebProcessPool::registerURLSchemeAsNoAccess(const String& urlScheme)
1515 {
1516     m_schemesToRegisterAsNoAccess.add(urlScheme);
1517     sendToAllProcesses(Messages::WebProcess::RegisterURLSchemeAsNoAccess(urlScheme));
1518     sendToNetworkingProcess(Messages::NetworkProcess::RegisterURLSchemeAsNoAccess(urlScheme));
1519 }
1520
1521 void WebProcessPool::registerURLSchemeAsDisplayIsolated(const String& urlScheme)
1522 {
1523     m_schemesToRegisterAsDisplayIsolated.add(urlScheme);
1524     sendToAllProcesses(Messages::WebProcess::RegisterURLSchemeAsDisplayIsolated(urlScheme));
1525     sendToNetworkingProcess(Messages::NetworkProcess::RegisterURLSchemeAsDisplayIsolated(urlScheme));
1526 }
1527
1528 void WebProcessPool::registerURLSchemeAsCORSEnabled(const String& urlScheme)
1529 {
1530     m_schemesToRegisterAsCORSEnabled.add(urlScheme);
1531     sendToAllProcesses(Messages::WebProcess::RegisterURLSchemeAsCORSEnabled(urlScheme));
1532     sendToNetworkingProcess(Messages::NetworkProcess::RegisterURLSchemeAsCORSEnabled(urlScheme));
1533 }
1534
1535 void WebProcessPool::registerGlobalURLSchemeAsHavingCustomProtocolHandlers(const String& urlScheme)
1536 {
1537     if (!urlScheme)
1538         return;
1539
1540     globalURLSchemesWithCustomProtocolHandlers().add(urlScheme);
1541     for (auto* processPool : allProcessPools())
1542         processPool->registerSchemeForCustomProtocol(urlScheme);
1543 }
1544
1545 void WebProcessPool::unregisterGlobalURLSchemeAsHavingCustomProtocolHandlers(const String& urlScheme)
1546 {
1547     if (!urlScheme)
1548         return;
1549
1550     globalURLSchemesWithCustomProtocolHandlers().remove(urlScheme);
1551     for (auto* processPool : allProcessPools())
1552         processPool->unregisterSchemeForCustomProtocol(urlScheme);
1553 }
1554
1555 void WebProcessPool::registerURLSchemeAsCachePartitioned(const String& urlScheme)
1556 {
1557     m_schemesToRegisterAsCachePartitioned.add(urlScheme);
1558     sendToAllProcesses(Messages::WebProcess::RegisterURLSchemeAsCachePartitioned(urlScheme));
1559 }
1560
1561 void WebProcessPool::registerURLSchemeServiceWorkersCanHandle(const String& urlScheme)
1562 {
1563     m_schemesServiceWorkersCanHandle.add(urlScheme);
1564     sendToAllProcesses(Messages::AuxiliaryProcess::RegisterURLSchemeServiceWorkersCanHandle(urlScheme));
1565     if (m_networkProcess)
1566         m_networkProcess->send(Messages::AuxiliaryProcess::RegisterURLSchemeServiceWorkersCanHandle(urlScheme), 0);
1567 }
1568
1569 void WebProcessPool::registerURLSchemeAsCanDisplayOnlyIfCanRequest(const String& urlScheme)
1570 {
1571     m_schemesToRegisterAsCanDisplayOnlyIfCanRequest.add(urlScheme);
1572     sendToAllProcesses(Messages::WebProcess::RegisterURLSchemeAsCanDisplayOnlyIfCanRequest(urlScheme));
1573     sendToNetworkingProcess(Messages::NetworkProcess::RegisterURLSchemeAsCanDisplayOnlyIfCanRequest(urlScheme));
1574 }
1575
1576 void WebProcessPool::updateMaxSuspendedPageCount()
1577 {
1578     if (!m_configuration->usesPageCache())
1579         return;
1580
1581     unsigned dummy = 0;
1582     Seconds dummyInterval;
1583     unsigned pageCacheSize = 0;
1584     calculateMemoryCacheSizes(LegacyGlobalSettings::singleton().cacheModel(), dummy, dummy, dummy, dummyInterval, pageCacheSize);
1585
1586     m_maxSuspendedPageCount = pageCacheSize;
1587
1588     while (m_suspendedPages.size() > m_maxSuspendedPageCount)
1589         m_suspendedPages.removeFirst();
1590 }
1591
1592 void WebProcessPool::setCacheModel(CacheModel cacheModel)
1593 {
1594     updateMaxSuspendedPageCount();
1595
1596     sendToAllProcesses(Messages::WebProcess::SetCacheModel(cacheModel));
1597
1598     if (m_networkProcess)
1599         m_networkProcess->send(Messages::NetworkProcess::SetCacheModel(cacheModel, { }), 0);
1600 }
1601
1602 void WebProcessPool::setDefaultRequestTimeoutInterval(double timeoutInterval)
1603 {
1604     sendToAllProcesses(Messages::WebProcess::SetDefaultRequestTimeoutInterval(timeoutInterval));
1605 }
1606
1607 DownloadProxy& WebProcessPool::createDownloadProxy(WebsiteDataStore& dataStore, const ResourceRequest& request, WebPageProxy* originatingPage)
1608 {
1609     auto& downloadProxy = ensureNetworkProcess().createDownloadProxy(dataStore, request);
1610     downloadProxy.setOriginatingPage(originatingPage);
1611     return downloadProxy;
1612 }
1613
1614 void WebProcessPool::synthesizeAppIsBackground(bool background)
1615 {
1616     ensureNetworkProcess().synthesizeAppIsBackground(background);
1617 }
1618
1619 void WebProcessPool::addMessageReceiver(IPC::StringReference messageReceiverName, IPC::MessageReceiver& messageReceiver)
1620 {
1621     m_messageReceiverMap.addMessageReceiver(messageReceiverName, messageReceiver);
1622 }
1623
1624 void WebProcessPool::addMessageReceiver(IPC::StringReference messageReceiverName, uint64_t destinationID, IPC::MessageReceiver& messageReceiver)
1625 {
1626     m_messageReceiverMap.addMessageReceiver(messageReceiverName, destinationID, messageReceiver);
1627 }
1628
1629 void WebProcessPool::removeMessageReceiver(IPC::StringReference messageReceiverName)
1630 {
1631     m_messageReceiverMap.removeMessageReceiver(messageReceiverName);
1632 }
1633
1634 void WebProcessPool::removeMessageReceiver(IPC::StringReference messageReceiverName, uint64_t destinationID)
1635 {
1636     m_messageReceiverMap.removeMessageReceiver(messageReceiverName, destinationID);
1637 }
1638
1639 bool WebProcessPool::dispatchMessage(IPC::Connection& connection, IPC::Decoder& decoder)
1640 {
1641     return m_messageReceiverMap.dispatchMessage(connection, decoder);
1642 }
1643
1644 bool WebProcessPool::dispatchSyncMessage(IPC::Connection& connection, IPC::Decoder& decoder, std::unique_ptr<IPC::Encoder>& replyEncoder)
1645 {
1646     return m_messageReceiverMap.dispatchSyncMessage(connection, decoder, replyEncoder);
1647 }
1648
1649 void WebProcessPool::setEnhancedAccessibility(bool flag)
1650 {
1651     sendToAllProcesses(Messages::WebProcess::SetEnhancedAccessibility(flag));
1652 }
1653     
1654 void WebProcessPool::startMemorySampler(const double interval)
1655 {    
1656     // For new WebProcesses we will also want to start the Memory Sampler
1657     m_memorySamplerEnabled = true;
1658     m_memorySamplerInterval = interval;
1659     
1660     // For UIProcess
1661 #if ENABLE(MEMORY_SAMPLER)
1662     WebMemorySampler::singleton()->start(interval);
1663 #endif
1664     
1665     // For WebProcess
1666     SandboxExtension::Handle sampleLogSandboxHandle;    
1667     WallTime now = WallTime::now();
1668     String sampleLogFilePath = makeString("WebProcess", static_cast<unsigned long long>(now.secondsSinceEpoch().seconds()));
1669     sampleLogFilePath = SandboxExtension::createHandleForTemporaryFile(sampleLogFilePath, SandboxExtension::Type::ReadWrite, sampleLogSandboxHandle);
1670     
1671     sendToAllProcesses(Messages::WebProcess::StartMemorySampler(sampleLogSandboxHandle, sampleLogFilePath, interval));
1672 }
1673
1674 void WebProcessPool::stopMemorySampler()
1675 {    
1676     // For WebProcess
1677     m_memorySamplerEnabled = false;
1678     
1679     // For UIProcess
1680 #if ENABLE(MEMORY_SAMPLER)
1681     WebMemorySampler::singleton()->stop();
1682 #endif
1683
1684     sendToAllProcesses(Messages::WebProcess::StopMemorySampler());
1685 }
1686
1687 void WebProcessPool::useTestingNetworkSession()
1688 {
1689     ASSERT(m_processes.isEmpty());
1690     ASSERT(!m_networkProcess);
1691
1692     if (m_networkProcess)
1693         return;
1694
1695     if (!m_processes.isEmpty())
1696         return;
1697
1698     m_shouldUseTestingNetworkSession = true;
1699 }
1700
1701 template<typename T, typename U>
1702 void WebProcessPool::sendSyncToNetworkingProcess(T&& message, U&& reply)
1703 {
1704     if (m_networkProcess && m_networkProcess->canSendMessage())
1705         m_networkProcess->sendSync(std::forward<T>(message), std::forward<U>(reply), 0);
1706 }
1707
1708 void WebProcessPool::setAllowsAnySSLCertificateForWebSocket(bool allows)
1709 {
1710     sendSyncToNetworkingProcess(Messages::NetworkProcess::SetAllowsAnySSLCertificateForWebSocket(allows), Messages::NetworkProcess::SetAllowsAnySSLCertificateForWebSocket::Reply());
1711 }
1712
1713 void WebProcessPool::clearCachedCredentials()
1714 {
1715     if (m_networkProcess)
1716         m_networkProcess->send(Messages::NetworkProcess::ClearCachedCredentials(), 0);
1717 }
1718
1719 void WebProcessPool::terminateNetworkProcess()
1720 {
1721     if (!m_networkProcess)
1722         return;
1723     
1724     m_networkProcess->terminate();
1725     m_networkProcess = nullptr;
1726     m_didNetworkProcessCrash = true;
1727 }
1728
1729 void WebProcessPool::sendNetworkProcessWillSuspendImminentlyForTesting()
1730 {
1731     if (m_networkProcess)
1732         m_networkProcess->sendProcessWillSuspendImminentlyForTesting();
1733 }
1734
1735 void WebProcessPool::sendNetworkProcessDidResume()
1736 {
1737     if (m_networkProcess)
1738         m_networkProcess->sendProcessDidResume();
1739 }
1740
1741 void WebProcessPool::terminateServiceWorkerProcesses()
1742 {
1743 #if ENABLE(SERVICE_WORKER)
1744     auto protectedThis = makeRef(*this);
1745     while (!m_serviceWorkerProcesses.isEmpty())
1746         m_serviceWorkerProcesses.begin()->value->requestTermination(ProcessTerminationReason::RequestedByClient);
1747 #endif
1748 }
1749
1750 void WebProcessPool::syncNetworkProcessCookies()
1751 {
1752     ensureNetworkProcess().syncAllCookies();
1753 }
1754
1755 void WebProcessPool::syncLocalStorage(CompletionHandler<void()>&& completionHandler)
1756 {
1757     sendSyncToNetworkingProcess(Messages::NetworkProcess::SyncLocalStorage(), Messages::NetworkProcess::SyncLocalStorage::Reply());
1758     completionHandler();
1759 }
1760
1761 void WebProcessPool::clearLegacyPrivateBrowsingLocalStorage(CompletionHandler<void()>&& completionHandler)
1762 {
1763     if (m_networkProcess)
1764         m_networkProcess->send(Messages::NetworkProcess::ClearLegacyPrivateBrowsingLocalStorage(), 0);
1765     completionHandler();
1766 }
1767
1768 void WebProcessPool::allowSpecificHTTPSCertificateForHost(const WebCertificateInfo* certificate, const String& host)
1769 {
1770     ensureNetworkProcess();
1771     m_networkProcess->send(Messages::NetworkProcess::AllowSpecificHTTPSCertificateForHost(certificate->certificateInfo(), host), 0);
1772 }
1773
1774 void WebProcessPool::updateAutomationCapabilities() const
1775 {
1776 #if ENABLE(REMOTE_INSPECTOR)
1777     Inspector::RemoteInspector::singleton().clientCapabilitiesDidChange();
1778 #endif
1779 }
1780
1781 void WebProcessPool::setAutomationSession(RefPtr<WebAutomationSession>&& automationSession)
1782 {
1783     if (m_automationSession)
1784         m_automationSession->setProcessPool(nullptr);
1785     
1786     m_automationSession = WTFMove(automationSession);
1787
1788 #if ENABLE(REMOTE_INSPECTOR)
1789     if (m_automationSession) {
1790         m_automationSession->init();
1791         m_automationSession->setProcessPool(this);
1792
1793         sendToAllProcesses(Messages::WebProcess::EnsureAutomationSessionProxy(m_automationSession->sessionIdentifier()));
1794     } else
1795         sendToAllProcesses(Messages::WebProcess::DestroyAutomationSessionProxy());
1796 #endif
1797 }
1798
1799 void WebProcessPool::setHTTPPipeliningEnabled(bool enabled)
1800 {
1801 #if PLATFORM(COCOA)
1802     ResourceRequest::setHTTPPipeliningEnabled(enabled);
1803 #else
1804     UNUSED_PARAM(enabled);
1805 #endif
1806 }
1807
1808 bool WebProcessPool::httpPipeliningEnabled() const
1809 {
1810 #if PLATFORM(COCOA)
1811     return ResourceRequest::httpPipeliningEnabled();
1812 #else
1813     return false;
1814 #endif
1815 }
1816
1817 void WebProcessPool::getStatistics(uint32_t statisticsMask, Function<void (API::Dictionary*, CallbackBase::Error)>&& callbackFunction)
1818 {
1819     if (!statisticsMask) {
1820         callbackFunction(nullptr, CallbackBase::Error::Unknown);
1821         return;
1822     }
1823
1824     auto request = StatisticsRequest::create(DictionaryCallback::create(WTFMove(callbackFunction)));
1825
1826     if (statisticsMask & StatisticsRequestTypeWebContent)
1827         requestWebContentStatistics(request.get());
1828     
1829     if (statisticsMask & StatisticsRequestTypeNetworking)
1830         requestNetworkingStatistics(request.get());
1831 }
1832
1833 void WebProcessPool::requestWebContentStatistics(StatisticsRequest& request)
1834 {
1835     // FIXME (Multi-WebProcess) <rdar://problem/13200059>: Make getting statistics from multiple WebProcesses work.
1836 }
1837
1838 void WebProcessPool::requestNetworkingStatistics(StatisticsRequest& request)
1839 {
1840     if (!m_networkProcess) {
1841         LOG_ERROR("Attempt to get NetworkProcess statistics but the NetworkProcess is unavailable");
1842         return;
1843     }
1844
1845     uint64_t requestID = request.addOutstandingRequest();
1846     m_statisticsRequests.set(requestID, &request);
1847     m_networkProcess->send(Messages::NetworkProcess::GetNetworkProcessStatistics(requestID), 0);
1848 }
1849
1850 static WebProcessProxy* webProcessProxyFromConnection(IPC::Connection& connection, const Vector<RefPtr<WebProcessProxy>>& processes)
1851 {
1852     for (auto& process : processes) {
1853         if (process->hasConnection(connection))
1854             return process.get();
1855     }
1856
1857     ASSERT_NOT_REACHED();
1858     return nullptr;
1859 }
1860
1861 void WebProcessPool::handleMessage(IPC::Connection& connection, const String& messageName, const WebKit::UserData& messageBody)
1862 {
1863     auto* webProcessProxy = webProcessProxyFromConnection(connection, m_processes);
1864     if (!webProcessProxy)
1865         return;
1866     m_injectedBundleClient->didReceiveMessageFromInjectedBundle(*this, messageName, webProcessProxy->transformHandlesToObjects(messageBody.object()).get());
1867 }
1868
1869 void WebProcessPool::handleSynchronousMessage(IPC::Connection& connection, const String& messageName, const UserData& messageBody, CompletionHandler<void(UserData&&)>&& completionHandler)
1870 {
1871     auto* webProcessProxy = webProcessProxyFromConnection(connection, m_processes);
1872     if (!webProcessProxy)
1873         return completionHandler({ });
1874
1875     m_injectedBundleClient->didReceiveSynchronousMessageFromInjectedBundle(*this, messageName, webProcessProxy->transformHandlesToObjects(messageBody.object()).get(), [webProcessProxy = makeRef(*webProcessProxy), completionHandler = WTFMove(completionHandler)] (RefPtr<API::Object>&& returnData) mutable {
1876         completionHandler(UserData(webProcessProxy->transformObjectsToHandles(returnData.get())));
1877     });
1878 }
1879
1880 void WebProcessPool::didGetStatistics(const StatisticsData& statisticsData, uint64_t requestID)
1881 {
1882     RefPtr<StatisticsRequest> request = m_statisticsRequests.take(requestID);
1883     if (!request) {
1884         LOG_ERROR("Cannot report networking statistics.");
1885         return;
1886     }
1887
1888     request->completedRequest(requestID, statisticsData);
1889 }
1890
1891 #if ENABLE(GAMEPAD)
1892
1893 void WebProcessPool::startedUsingGamepads(IPC::Connection& connection)
1894 {
1895     auto* proxy = webProcessProxyFromConnection(connection, m_processes);
1896     if (!proxy)
1897         return;
1898
1899     bool wereAnyProcessesUsingGamepads = !m_processesUsingGamepads.isEmpty();
1900
1901     ASSERT(!m_processesUsingGamepads.contains(proxy));
1902     m_processesUsingGamepads.add(proxy);
1903
1904     if (!wereAnyProcessesUsingGamepads)
1905         UIGamepadProvider::singleton().processPoolStartedUsingGamepads(*this);
1906
1907     proxy->send(Messages::WebProcess::SetInitialGamepads(UIGamepadProvider::singleton().snapshotGamepads()), 0);
1908 }
1909
1910 void WebProcessPool::stoppedUsingGamepads(IPC::Connection& connection)
1911 {
1912     auto* proxy = webProcessProxyFromConnection(connection, m_processes);
1913     if (!proxy)
1914         return;
1915
1916     ASSERT(m_processesUsingGamepads.contains(proxy));
1917     processStoppedUsingGamepads(*proxy);
1918 }
1919
1920 void WebProcessPool::processStoppedUsingGamepads(WebProcessProxy& process)
1921 {
1922     bool wereAnyProcessesUsingGamepads = !m_processesUsingGamepads.isEmpty();
1923
1924     ASSERT(m_processesUsingGamepads.contains(&process));
1925     m_processesUsingGamepads.remove(&process);
1926
1927     if (wereAnyProcessesUsingGamepads && m_processesUsingGamepads.isEmpty())
1928         UIGamepadProvider::singleton().processPoolStoppedUsingGamepads(*this);
1929 }
1930
1931 void WebProcessPool::gamepadConnected(const UIGamepad& gamepad)
1932 {
1933     for (auto& process : m_processesUsingGamepads)
1934         process->send(Messages::WebProcess::GamepadConnected(gamepad.fullGamepadData()), 0);
1935 }
1936
1937 void WebProcessPool::gamepadDisconnected(const UIGamepad& gamepad)
1938 {
1939     for (auto& process : m_processesUsingGamepads)
1940         process->send(Messages::WebProcess::GamepadDisconnected(gamepad.index()), 0);
1941 }
1942
1943 void WebProcessPool::setInitialConnectedGamepads(const Vector<std::unique_ptr<UIGamepad>>& gamepads)
1944 {
1945     Vector<GamepadData> gamepadDatas;
1946     gamepadDatas.grow(gamepads.size());
1947     for (size_t i = 0; i < gamepads.size(); ++i) {
1948         if (!gamepads[i])
1949             continue;
1950         gamepadDatas[i] = gamepads[i]->fullGamepadData();
1951     }
1952
1953     for (auto& process : m_processesUsingGamepads)
1954         process->send(Messages::WebProcess::SetInitialGamepads(gamepadDatas), 0);
1955 }
1956
1957 #endif // ENABLE(GAMEPAD)
1958
1959 void WebProcessPool::setJavaScriptConfigurationFileEnabled(bool flag)
1960 {
1961     m_javaScriptConfigurationFileEnabled = flag;
1962 }
1963
1964 void WebProcessPool::garbageCollectJavaScriptObjects()
1965 {
1966     sendToAllProcesses(Messages::WebProcess::GarbageCollectJavaScriptObjects());
1967 }
1968
1969 void WebProcessPool::setJavaScriptGarbageCollectorTimerEnabled(bool flag)
1970 {
1971     sendToAllProcesses(Messages::WebProcess::SetJavaScriptGarbageCollectorTimerEnabled(flag));
1972 }
1973
1974 Ref<API::Dictionary> WebProcessPool::plugInAutoStartOriginHashes() const
1975 {
1976     return m_plugInAutoStartProvider.autoStartOriginsTableCopy();
1977 }
1978
1979 void WebProcessPool::setPlugInAutoStartOriginHashes(API::Dictionary& dictionary)
1980 {
1981     m_plugInAutoStartProvider.setAutoStartOriginsTable(dictionary);
1982 }
1983
1984 void WebProcessPool::setPlugInAutoStartOrigins(API::Array& array)
1985 {
1986     m_plugInAutoStartProvider.setAutoStartOriginsArray(array);
1987 }
1988
1989 void WebProcessPool::setPlugInAutoStartOriginsFilteringOutEntriesAddedAfterTime(API::Dictionary& dictionary, WallTime time)
1990 {
1991     m_plugInAutoStartProvider.setAutoStartOriginsFilteringOutEntriesAddedAfterTime(dictionary, time);
1992 }
1993
1994 void WebProcessPool::registerSchemeForCustomProtocol(const String& scheme)
1995 {
1996 #if ENABLE(LEGACY_CUSTOM_PROTOCOL_MANAGER)
1997     if (!globalURLSchemesWithCustomProtocolHandlers().contains(scheme))
1998         m_urlSchemesRegisteredForCustomProtocols.add(scheme);
1999     sendToNetworkingProcess(Messages::LegacyCustomProtocolManager::RegisterScheme(scheme));
2000 #endif
2001 }
2002
2003 void WebProcessPool::unregisterSchemeForCustomProtocol(const String& scheme)
2004 {
2005 #if ENABLE(LEGACY_CUSTOM_PROTOCOL_MANAGER)
2006     m_urlSchemesRegisteredForCustomProtocols.remove(scheme);
2007     sendToNetworkingProcess(Messages::LegacyCustomProtocolManager::UnregisterScheme(scheme));
2008 #endif
2009 }
2010
2011 #if ENABLE(NETSCAPE_PLUGIN_API)
2012 void WebProcessPool::setPluginLoadClientPolicy(WebCore::PluginLoadClientPolicy policy, const String& host, const String& bundleIdentifier, const String& versionString)
2013 {
2014     auto& policiesForHost = m_pluginLoadClientPolicies.ensure(host, [] { return HashMap<String, HashMap<String, uint8_t>>(); }).iterator->value;
2015     auto& versionsToPolicies = policiesForHost.ensure(bundleIdentifier, [] { return HashMap<String, uint8_t>(); }).iterator->value;
2016     versionsToPolicies.set(versionString, policy);
2017
2018     sendToAllProcesses(Messages::WebProcess::SetPluginLoadClientPolicy(policy, host, bundleIdentifier, versionString));
2019 }
2020
2021 void WebProcessPool::resetPluginLoadClientPolicies(HashMap<String, HashMap<String, HashMap<String, uint8_t>>>&& pluginLoadClientPolicies)
2022 {
2023     m_pluginLoadClientPolicies = WTFMove(pluginLoadClientPolicies);
2024     sendToAllProcesses(Messages::WebProcess::ResetPluginLoadClientPolicies(m_pluginLoadClientPolicies));
2025 }
2026
2027 void WebProcessPool::clearPluginClientPolicies()
2028 {
2029     m_pluginLoadClientPolicies.clear();
2030     sendToAllProcesses(Messages::WebProcess::ClearPluginClientPolicies());
2031 }
2032 #endif
2033
2034 void WebProcessPool::addSupportedPlugin(String&& matchingDomain, String&& name, HashSet<String>&& mimeTypes, HashSet<String> extensions)
2035 {
2036 #if ENABLE(NETSCAPE_PLUGIN_API)
2037     m_pluginInfoStore.addSupportedPlugin(WTFMove(matchingDomain), WTFMove(name), WTFMove(mimeTypes), WTFMove(extensions));
2038 #else
2039     UNUSED_PARAM(matchingDomain);
2040     UNUSED_PARAM(name);
2041     UNUSED_PARAM(mimeTypes);
2042     UNUSED_PARAM(extensions);
2043 #endif
2044 }
2045
2046 void WebProcessPool::clearSupportedPlugins()
2047 {
2048 #if ENABLE(NETSCAPE_PLUGIN_API)
2049     m_pluginInfoStore.clearSupportedPlugins();
2050 #endif
2051 }
2052
2053 void WebProcessPool::setMemoryCacheDisabled(bool disabled)
2054 {
2055     m_memoryCacheDisabled = disabled;
2056     sendToAllProcesses(Messages::WebProcess::SetMemoryCacheDisabled(disabled));
2057 }
2058
2059 void WebProcessPool::setFontWhitelist(API::Array* array)
2060 {
2061     m_fontWhitelist.clear();
2062     if (array) {
2063         for (size_t i = 0; i < array->size(); ++i) {
2064             if (API::String* font = array->at<API::String>(i))
2065                 m_fontWhitelist.append(font->string());
2066         }
2067     }
2068 }
2069
2070 void WebProcessPool::updateHiddenPageThrottlingAutoIncreaseLimit()
2071 {
2072     // We're estimating an upper bound for a set of background timer fires for a page to be 200ms
2073     // (including all timer fires, all paging-in, and any resulting GC). To ensure this does not
2074     // result in more than 1% CPU load allow for one timer fire per 100x this duration.
2075     static int maximumTimerThrottlePerPageInMS = 200 * 100;
2076
2077     int limitInMilliseconds = maximumTimerThrottlePerPageInMS * m_hiddenPageThrottlingAutoIncreasesCounter.value();
2078     sendToAllProcesses(Messages::WebProcess::SetHiddenPageDOMTimerThrottlingIncreaseLimit(limitInMilliseconds));
2079 }
2080
2081 void WebProcessPool::reportWebContentCPUTime(Seconds cpuTime, uint64_t activityState)
2082 {
2083 #if PLATFORM(MAC)
2084     if (m_perActivityStateCPUUsageSampler)
2085         m_perActivityStateCPUUsageSampler->reportWebContentCPUTime(cpuTime, static_cast<WebCore::ActivityStateForCPUSampling>(activityState));
2086 #else
2087     UNUSED_PARAM(cpuTime);
2088     UNUSED_PARAM(activityState);
2089 #endif
2090 }
2091
2092 void WebProcessPool::updateProcessAssertions()
2093 {
2094 #if PLATFORM(IOS_FAMILY)
2095 #if ENABLE(SERVICE_WORKER)
2096     auto updateServiceWorkerProcessAssertion = [&] {
2097         if (!m_serviceWorkerProcesses.isEmpty() && m_foregroundWebProcessCounter.value()) {
2098             // FIXME: We can do better than this once we have process per origin.
2099             for (auto* serviceWorkerProcess : m_serviceWorkerProcesses.values()) {
2100                 auto registrableDomain = serviceWorkerProcess->registrableDomain();
2101                 if (!m_foregroundTokensForServiceWorkerProcesses.contains(registrableDomain))
2102                     m_foregroundTokensForServiceWorkerProcesses.add(WTFMove(registrableDomain), serviceWorkerProcess->throttler().foregroundActivityToken());
2103             }
2104             m_backgroundTokensForServiceWorkerProcesses.clear();
2105             return;
2106         }
2107         if (!m_serviceWorkerProcesses.isEmpty() && m_backgroundWebProcessCounter.value()) {
2108             // FIXME: We can do better than this once we have process per origin.
2109             for (auto* serviceWorkerProcess : m_serviceWorkerProcesses.values()) {
2110                 auto registrableDomain = serviceWorkerProcess->registrableDomain();
2111                 if (!m_backgroundTokensForServiceWorkerProcesses.contains(registrableDomain))
2112                     m_backgroundTokensForServiceWorkerProcesses.add(WTFMove(registrableDomain), serviceWorkerProcess->throttler().backgroundActivityToken());
2113             }
2114             m_foregroundTokensForServiceWorkerProcesses.clear();
2115             return;
2116         }
2117         m_foregroundTokensForServiceWorkerProcesses.clear();
2118         m_backgroundTokensForServiceWorkerProcesses.clear();
2119     };
2120     updateServiceWorkerProcessAssertion();
2121 #endif
2122
2123     auto updateNetworkProcessAssertion = [&] {
2124         auto& networkProcess = ensureNetworkProcess();
2125
2126         if (m_foregroundWebProcessCounter.value()) {
2127             if (!m_foregroundTokenForNetworkProcess) {
2128                 m_foregroundTokenForNetworkProcess = networkProcess.throttler().foregroundActivityToken();
2129                 networkProcess.sendProcessDidTransitionToForeground();
2130             }
2131             m_backgroundTokenForNetworkProcess = nullptr;
2132             return;
2133         }
2134         if (m_backgroundWebProcessCounter.value()) {
2135             if (!m_backgroundTokenForNetworkProcess) {
2136                 m_backgroundTokenForNetworkProcess = networkProcess.throttler().backgroundActivityToken();
2137                 networkProcess.sendProcessDidTransitionToBackground();
2138             }
2139             m_foregroundTokenForNetworkProcess = nullptr;
2140             return;
2141         }
2142         m_foregroundTokenForNetworkProcess = nullptr;
2143         m_backgroundTokenForNetworkProcess = nullptr;
2144     };
2145     updateNetworkProcessAssertion();
2146 #endif
2147 }
2148
2149 void WebProcessPool::reinstateNetworkProcessAssertionState(NetworkProcessProxy& newNetworkProcessProxy)
2150 {
2151 #if PLATFORM(IOS_FAMILY)
2152     // The network process crashed; take new tokens for the new network process.
2153     if (m_backgroundTokenForNetworkProcess)
2154         m_backgroundTokenForNetworkProcess = newNetworkProcessProxy.throttler().backgroundActivityToken();
2155     else if (m_foregroundTokenForNetworkProcess)
2156         m_foregroundTokenForNetworkProcess = newNetworkProcessProxy.throttler().foregroundActivityToken();
2157 #else
2158     UNUSED_PARAM(newNetworkProcessProxy);
2159 #endif
2160 }
2161
2162 bool WebProcessPool::isServiceWorkerPageID(WebPageProxyIdentifier pageID) const
2163 {
2164 #if ENABLE(SERVICE_WORKER)
2165     // FIXME: This is inefficient.
2166     return WTF::anyOf(m_serviceWorkerProcesses.values(), [pageID](auto* process) {
2167         return process->hasServiceWorkerPageProxy(pageID);
2168     });
2169 #endif
2170     return false;
2171 }
2172
2173 void WebProcessPool::addProcessToOriginCacheSet(WebProcessProxy& process, const URL& url)
2174 {
2175     auto registrableDomain = WebCore::RegistrableDomain { url };
2176     auto result = m_swappedProcessesPerRegistrableDomain.add(registrableDomain, &process);
2177     if (!result.isNewEntry)
2178         result.iterator->value = &process;
2179
2180     LOG(ProcessSwapping, "(ProcessSwapping) Registrable domain %s just saved a cached process with pid %i", registrableDomain.string().utf8().data(), process.processIdentifier());
2181     if (!result.isNewEntry)
2182         LOG(ProcessSwapping, "(ProcessSwapping) Note: It already had one saved");
2183 }
2184
2185 void WebProcessPool::removeProcessFromOriginCacheSet(WebProcessProxy& process)
2186 {
2187     LOG(ProcessSwapping, "(ProcessSwapping) Removing process with pid %i from the origin cache set", process.processIdentifier());
2188
2189     // FIXME: This can be very inefficient as the number of remembered origins and processes grows
2190     Vector<WebCore::RegistrableDomain> registrableDomainsToRemove;
2191     for (auto entry : m_swappedProcessesPerRegistrableDomain) {
2192         if (entry.value == &process)
2193             registrableDomainsToRemove.append(entry.key);
2194     }
2195
2196     for (auto& registrableDomain : registrableDomainsToRemove)
2197         m_swappedProcessesPerRegistrableDomain.remove(registrableDomain);
2198 }
2199
2200 void WebProcessPool::processForNavigation(WebPageProxy& page, const API::Navigation& navigation, Ref<WebProcessProxy>&& sourceProcess, const URL& sourceURL, ProcessSwapRequestedByClient processSwapRequestedByClient, Ref<WebsiteDataStore>&& dataStore, CompletionHandler<void(Ref<WebProcessProxy>&&, SuspendedPageProxy*, const String&)>&& completionHandler)
2201 {
2202     processForNavigationInternal(page, navigation, sourceProcess.copyRef(), sourceURL, processSwapRequestedByClient, WTFMove(dataStore), [this, page = makeRefPtr(page), navigation = makeRef(navigation), sourceProcess = sourceProcess.copyRef(), sourceURL, processSwapRequestedByClient, completionHandler = WTFMove(completionHandler)](Ref<WebProcessProxy>&& process, SuspendedPageProxy* suspendedPage, const String& reason) mutable {
2203         // We are process-swapping so automatic process prewarming would be beneficial if the client has not explicitly enabled / disabled it.
2204         bool doingAnAutomaticProcessSwap = processSwapRequestedByClient == ProcessSwapRequestedByClient::No && process.ptr() != sourceProcess.ptr();
2205         if (doingAnAutomaticProcessSwap && !configuration().wasAutomaticProcessWarmingSetByClient() && !configuration().clientWouldBenefitFromAutomaticProcessPrewarming()) {
2206             RELEASE_LOG(PerformanceLogging, "Automatically turning on process prewarming because the client would benefit from it");
2207             configuration().setClientWouldBenefitFromAutomaticProcessPrewarming(true);
2208         }
2209
2210         if (m_configuration->alwaysKeepAndReuseSwappedProcesses() && process.ptr() != sourceProcess.ptr()) {
2211             static std::once_flag onceFlag;
2212             std::call_once(onceFlag, [] {
2213                 WTFLogAlways("WARNING: The option to always keep swapped web processes alive is active. This is meant for debugging and testing only.");
2214             });
2215
2216             addProcessToOriginCacheSet(sourceProcess, sourceURL);
2217
2218             LOG(ProcessSwapping, "(ProcessSwapping) Navigating from %s to %s, keeping around old process. Now holding on to old processes for %u origins.", sourceURL.string().utf8().data(), navigation->currentRequest().url().string().utf8().data(), m_swappedProcessesPerRegistrableDomain.size());
2219         }
2220
2221         completionHandler(WTFMove(process), suspendedPage, reason);
2222     });
2223 }
2224
2225 void WebProcessPool::processForNavigationInternal(WebPageProxy& page, const API::Navigation& navigation, Ref<WebProcessProxy>&& sourceProcess, const URL& pageSourceURL, ProcessSwapRequestedByClient processSwapRequestedByClient, Ref<WebsiteDataStore>&& dataStore, CompletionHandler<void(Ref<WebProcessProxy>&&, SuspendedPageProxy*, const String&)>&& completionHandler)
2226 {
2227     auto& targetURL = navigation.currentRequest().url();
2228     auto targetRegistrableDomain = WebCore::RegistrableDomain { targetURL };
2229
2230     auto createNewProcess = [this, protectedThis = makeRef(*this), page = makeRef(page), targetRegistrableDomain, dataStore = dataStore.copyRef()] () -> Ref<WebProcessProxy> {
2231         return processForRegistrableDomain(dataStore, page.ptr(), targetRegistrableDomain);
2232     };
2233
2234     if (usesSingleWebProcess())
2235         return completionHandler(WTFMove(sourceProcess), nullptr, "Single WebProcess mode is enabled"_s);
2236
2237     if (processSwapRequestedByClient == ProcessSwapRequestedByClient::Yes)
2238         return completionHandler(createNewProcess(), nullptr, "Process swap was requested by the client"_s);
2239
2240     if (!m_configuration->processSwapsOnNavigation())
2241         return completionHandler(WTFMove(sourceProcess), nullptr, "Feature is disabled"_s);
2242
2243     if (m_automationSession)
2244         return completionHandler(WTFMove(sourceProcess), nullptr, "An automation session is active"_s);
2245
2246     if (!sourceProcess->hasCommittedAnyProvisionalLoads()) {
2247         tryPrewarmWithDomainInformation(sourceProcess, targetRegistrableDomain);
2248         return completionHandler(WTFMove(sourceProcess), nullptr, "Process has not yet committed any provisional loads"_s);
2249     }
2250
2251     // FIXME: We should support process swap when a window has been opened via window.open() without 'noopener'.
2252     // The issue is that the opener has a handle to the WindowProxy.
2253     if (navigation.openedByDOMWithOpener() && !m_configuration->processSwapsOnWindowOpenWithOpener())
2254         return completionHandler(WTFMove(sourceProcess), nullptr, "Browsing context been opened by DOM without 'noopener'"_s);
2255
2256     // FIXME: We should support process swap when a window has opened other windows via window.open.
2257     if (navigation.hasOpenedFrames())
2258         return completionHandler(WTFMove(sourceProcess), nullptr, "Browsing context has opened other windows"_s);
2259
2260     if (auto* targetItem = navigation.targetItem()) {
2261         if (auto* suspendedPage = targetItem->suspendedPage()) {
2262             return suspendedPage->waitUntilReadyToUnsuspend([createNewProcess = WTFMove(createNewProcess), completionHandler = WTFMove(completionHandler)](SuspendedPageProxy* suspendedPage) mutable {
2263                 if (!suspendedPage)
2264                     return completionHandler(createNewProcess(), nullptr, "Using new process because target back/forward item's suspended page is not reusable"_s);
2265                 Ref<WebProcessProxy> process = suspendedPage->process();
2266                 completionHandler(WTFMove(process), suspendedPage, "Using target back/forward item's process and suspended page"_s);
2267             });
2268         }
2269
2270         if (RefPtr<WebProcessProxy> process = WebProcessProxy::processForIdentifier(targetItem->lastProcessIdentifier())) {
2271             if (process->state() != WebProcessProxy::State::Terminated) {
2272                 // Make sure we remove the process from the cache if it is in there since we're about to use it.
2273                 if (process->isInProcessCache()) {
2274                     webProcessCache().removeProcess(*process, WebProcessCache::ShouldShutDownProcess::No);
2275                     ASSERT(!process->isInProcessCache());
2276                 }
2277
2278                 return completionHandler(process.releaseNonNull(), nullptr, "Using target back/forward item's process"_s);
2279             }
2280         }
2281     }
2282
2283     if (navigation.treatAsSameOriginNavigation())
2284         return completionHandler(WTFMove(sourceProcess), nullptr, "The treatAsSameOriginNavigation flag is set"_s);
2285
2286     URL sourceURL;
2287     if (page.isPageOpenedByDOMShowingInitialEmptyDocument() && !navigation.requesterOrigin().isEmpty())
2288         sourceURL = URL { URL(), navigation.requesterOrigin().toString() };
2289     else
2290         sourceURL = pageSourceURL;
2291
2292     if (sourceURL.isEmpty() && page.configuration().relatedPage()) {
2293         sourceURL = URL { { }, page.configuration().relatedPage()->pageLoadState().url() };
2294         RELEASE_LOG(ProcessSwapping, "Using related page %p's URL as source URL for process swap decision", page.configuration().relatedPage());
2295     }
2296
2297     if (!sourceURL.isValid() || !targetURL.isValid() || sourceURL.isEmpty() || sourceURL.protocolIsAbout() || targetRegistrableDomain.matches(sourceURL))
2298         return completionHandler(WTFMove(sourceProcess), nullptr, "Navigation is same-site"_s);
2299
2300     String reason = "Navigation is cross-site"_s;
2301     
2302     if (m_configuration->alwaysKeepAndReuseSwappedProcesses()) {
2303         LOG(ProcessSwapping, "(ProcessSwapping) Considering re-use of a previously cached process for domain %s", targetRegistrableDomain.string().utf8().data());
2304
2305         if (auto* process = m_swappedProcessesPerRegistrableDomain.get(targetRegistrableDomain)) {
2306             if (&process->websiteDataStore() == dataStore.ptr()) {
2307                 LOG(ProcessSwapping, "(ProcessSwapping) Reusing a previously cached process with pid %i to continue navigation to URL %s", process->processIdentifier(), targetURL.string().utf8().data());
2308
2309                 return completionHandler(makeRef(*process), nullptr, reason);
2310             }
2311         }
2312     }
2313
2314     return completionHandler(createNewProcess(), nullptr, reason);
2315 }
2316
2317 RefPtr<WebProcessProxy> WebProcessPool::findReusableSuspendedPageProcess(const WebCore::RegistrableDomain& registrableDomain, WebPageProxy& page, WebsiteDataStore& dataStore)
2318 {
2319     auto it = m_suspendedPages.findIf([&](auto& suspendedPage) {
2320         return suspendedPage->process().registrableDomain() == registrableDomain && &suspendedPage->process().websiteDataStore() == &dataStore;
2321     });
2322     return it == m_suspendedPages.end() ? nullptr : &(*it)->process();
2323 }
2324
2325 void WebProcessPool::addSuspendedPage(std::unique_ptr<SuspendedPageProxy>&& suspendedPage)
2326 {
2327     if (!m_maxSuspendedPageCount)
2328         return;
2329
2330     if (m_suspendedPages.size() >= m_maxSuspendedPageCount)
2331         m_suspendedPages.removeFirst();
2332
2333     m_suspendedPages.append(WTFMove(suspendedPage));
2334 }
2335
2336 void WebProcessPool::removeAllSuspendedPagesForPage(WebPageProxy& page, WebProcessProxy* process)
2337 {
2338     m_suspendedPages.removeAllMatching([&page, process](auto& suspendedPage) {
2339         return &suspendedPage->page() == &page && (!process || &suspendedPage->process() == process);
2340     });
2341 }
2342
2343 std::unique_ptr<SuspendedPageProxy> WebProcessPool::takeSuspendedPage(SuspendedPageProxy& suspendedPage)
2344 {
2345     return m_suspendedPages.takeFirst([&suspendedPage](auto& item) {
2346         return item.get() == &suspendedPage;
2347     });
2348 }
2349
2350 void WebProcessPool::removeSuspendedPage(SuspendedPageProxy& suspendedPage)
2351 {
2352     auto it = m_suspendedPages.findIf([&suspendedPage](auto& item) {
2353         return item.get() == &suspendedPage;
2354     });
2355     if (it != m_suspendedPages.end())
2356         m_suspendedPages.remove(it);
2357 }
2358
2359 bool WebProcessPool::hasSuspendedPageFor(WebProcessProxy& process, WebPageProxy& page) const
2360 {
2361     return m_suspendedPages.findIf([&process, &page](auto& suspendedPage) {
2362         return &suspendedPage->process() == &process && &suspendedPage->page() == &page;
2363     }) != m_suspendedPages.end();
2364 }
2365
2366 void WebProcessPool::clearSuspendedPages(AllowProcessCaching allowProcessCaching)
2367 {
2368     HashSet<RefPtr<WebProcessProxy>> processes;
2369     for (auto& suspendedPage : m_suspendedPages)
2370         processes.add(&suspendedPage->process());
2371
2372     m_suspendedPages.clear();
2373
2374     for (auto& process : processes)
2375         process->maybeShutDown(allowProcessCaching);
2376 }
2377
2378 void WebProcessPool::addMockMediaDevice(const MockMediaDevice& device)
2379 {
2380 #if ENABLE(MEDIA_STREAM)
2381     MockRealtimeMediaSourceCenter::addDevice(device);
2382     sendToAllProcesses(Messages::WebProcess::AddMockMediaDevice { device });
2383 #endif
2384 }
2385
2386 void WebProcessPool::clearMockMediaDevices()
2387 {
2388 #if ENABLE(MEDIA_STREAM)
2389     MockRealtimeMediaSourceCenter::setDevices({ });
2390     sendToAllProcesses(Messages::WebProcess::ClearMockMediaDevices { });
2391 #endif
2392 }
2393
2394 void WebProcessPool::removeMockMediaDevice(const String& persistentId)
2395 {
2396 #if ENABLE(MEDIA_STREAM)
2397     MockRealtimeMediaSourceCenter::removeDevice(persistentId);
2398     sendToAllProcesses(Messages::WebProcess::RemoveMockMediaDevice { persistentId });
2399 #endif
2400 }
2401
2402 void WebProcessPool::resetMockMediaDevices()
2403 {
2404 #if ENABLE(MEDIA_STREAM)
2405     MockRealtimeMediaSourceCenter::resetDevices();
2406     sendToAllProcesses(Messages::WebProcess::ResetMockMediaDevices { });
2407 #endif
2408 }
2409
2410 void WebProcessPool::sendDisplayConfigurationChangedMessageForTesting()
2411 {
2412 #if PLATFORM(MAC) && ENABLE(WEBPROCESS_WINDOWSERVER_BLOCKING)
2413     auto display = CGSMainDisplayID();
2414
2415     for (auto& processPool : WebProcessPool::allProcessPools()) {
2416         processPool->sendToAllProcesses(Messages::WebProcess::DisplayConfigurationChanged(display, kCGDisplayBeginConfigurationFlag));
2417         processPool->sendToAllProcesses(Messages::WebProcess::DisplayConfigurationChanged(display, kCGDisplaySetModeFlag | kCGDisplayDesktopShapeChangedFlag));
2418     }
2419 #endif
2420 }
2421
2422 void WebProcessPool::didCollectPrewarmInformation(const WebCore::RegistrableDomain& registrableDomain, const WebCore::PrewarmInformation& prewarmInformation)
2423 {
2424     static const size_t maximumSizeToPreventUnlimitedGrowth = 100;
2425     if (m_prewarmInformationPerRegistrableDomain.size() == maximumSizeToPreventUnlimitedGrowth)
2426         m_prewarmInformationPerRegistrableDomain.remove(m_prewarmInformationPerRegistrableDomain.random());
2427
2428     auto& value = m_prewarmInformationPerRegistrableDomain.ensure(registrableDomain, [] {
2429         return makeUnique<WebCore::PrewarmInformation>();
2430     }).iterator->value;
2431
2432     *value = prewarmInformation;
2433 }
2434
2435 void WebProcessPool::tryPrewarmWithDomainInformation(WebProcessProxy& process, const RegistrableDomain& registrableDomain)
2436 {
2437     auto* prewarmInformation = m_prewarmInformationPerRegistrableDomain.get(registrableDomain);
2438     if (!prewarmInformation)
2439         return;
2440     process.send(Messages::WebProcess::PrewarmWithDomainInformation(*prewarmInformation), 0);
2441 }
2442
2443 void WebProcessPool::clearCurrentModifierStateForTesting()
2444 {
2445     sendToAllProcesses(Messages::WebProcess::ClearCurrentModifierStateForTesting());
2446 }
2447
2448 #if ENABLE(RESOURCE_LOAD_STATISTICS)
2449 void WebProcessPool::didCommitCrossSiteLoadWithDataTransfer(PAL::SessionID sessionID, const RegistrableDomain& fromDomain, const RegistrableDomain& toDomain, OptionSet<CrossSiteNavigationDataTransfer::Flag> navigationDataTransfer, WebPageProxyIdentifier webPageProxyID, PageIdentifier webPageID)
2450 {
2451     if (!m_networkProcess)
2452         return;
2453
2454     m_networkProcess->didCommitCrossSiteLoadWithDataTransfer(sessionID, fromDomain, toDomain, navigationDataTransfer, webPageProxyID, webPageID);
2455 }
2456 #endif
2457
2458 void WebProcessPool::setWebProcessHasUploads(ProcessIdentifier processID)
2459 {
2460     ASSERT(processID);
2461     auto* process = WebProcessProxy::processForIdentifier(processID);
2462     ASSERT(process);
2463
2464     if (!process)
2465         return;
2466
2467     RELEASE_LOG(ProcessSuspension, "Web process pid %u now has uploads in progress", (unsigned)process->processIdentifier());
2468
2469     if (m_processesWithUploads.isEmpty()) {
2470         RELEASE_LOG(ProcessSuspension, "The number of uploads in progress is now one. Taking Networking and UI process assertions.");
2471
2472         ASSERT(m_networkProcess);
2473         m_networkProcess->takeUploadAssertion();
2474         
2475         ASSERT(!m_uiProcessUploadAssertion);
2476         m_uiProcessUploadAssertion = makeUnique<ProcessAssertion>(getCurrentProcessID(), "WebKit uploads"_s, AssertionState::UnboundedNetworking);
2477     }
2478     
2479     auto result = m_processesWithUploads.add(processID, nullptr);
2480     ASSERT(result.isNewEntry);
2481     result.iterator->value = makeUnique<ProcessAssertion>(process->processIdentifier(), "WebKit uploads"_s, AssertionState::UnboundedNetworking);
2482 }
2483
2484 void WebProcessPool::clearWebProcessHasUploads(ProcessIdentifier processID)
2485 {
2486     ASSERT(processID);
2487     auto result = m_processesWithUploads.take(processID);
2488     if (!result)
2489         return;
2490
2491     auto* process = WebProcessProxy::processForIdentifier(processID);
2492     ASSERT_UNUSED(process, process);
2493     RELEASE_LOG(ProcessSuspension, "Web process pid %u no longer has uploads in progress", (unsigned)process->processIdentifier());
2494
2495     if (m_processesWithUploads.isEmpty()) {
2496         RELEASE_LOG(ProcessSuspension, "The number of uploads in progress is now zero. Releasing Networking and UI process assertions.");
2497
2498         if (m_networkProcess)
2499             m_networkProcess->clearUploadAssertion();
2500         
2501         ASSERT(m_uiProcessUploadAssertion);
2502         m_uiProcessUploadAssertion = nullptr;
2503     }
2504     
2505 }
2506
2507 void WebProcessPool::setWebProcessIsPlayingAudibleMedia(WebCore::ProcessIdentifier processID)
2508 {
2509     auto* process = WebProcessProxy::processForIdentifier(processID);
2510     ASSERT(process);
2511
2512     RELEASE_LOG(ProcessSuspension, "Web process pid %u is now playing audible media", (unsigned)process->processIdentifier());
2513
2514     if (m_processesPlayingAudibleMedia.isEmpty()) {
2515         RELEASE_LOG(ProcessSuspension, "The number of processes playing audible media is now one. Taking UI process assertion.");
2516
2517         ASSERT(!m_uiProcessMediaPlaybackAssertion);
2518         m_uiProcessMediaPlaybackAssertion = makeUnique<ProcessAssertion>(getCurrentProcessID(), "WebKit Media Playback"_s, AssertionState::Foreground, AssertionReason::MediaPlayback);
2519     }
2520
2521     auto result = m_processesPlayingAudibleMedia.add(processID, nullptr);
2522     ASSERT(result.isNewEntry);
2523     result.iterator->value = makeUnique<ProcessAssertion>(process->processIdentifier(), "WebKit Media Playback"_s, AssertionState::Foreground, AssertionReason::MediaPlayback);
2524 }
2525
2526 void WebProcessPool::clearWebProcessIsPlayingAudibleMedia(WebCore::ProcessIdentifier processID)
2527 {
2528     auto result = m_processesPlayingAudibleMedia.take(processID);
2529     ASSERT_UNUSED(result, result);
2530
2531     auto* process = WebProcessProxy::processForIdentifier(processID);
2532     ASSERT_UNUSED(process, process);
2533
2534     RELEASE_LOG(ProcessSuspension, "Web process pid %u is no longer playing audible media", (unsigned)process->processIdentifier());
2535
2536     if (m_processesPlayingAudibleMedia.isEmpty()) {
2537         RELEASE_LOG(ProcessSuspension, "The number of processes playing audible media now zero. Releasing UI process assertion.");
2538
2539         ASSERT(m_uiProcessMediaPlaybackAssertion);
2540         m_uiProcessMediaPlaybackAssertion = nullptr;
2541     }
2542 }
2543
2544 } // namespace WebKit