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