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