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