Change more of the IPC code to take connections by reference
[WebKit-https.git] / Source / WebKit2 / UIProcess / WebProcessPool.h
1 /*
2  * Copyright (C) 2010, 2011, 2012, 2013 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 #ifndef WebProcessPool_h
27 #define WebProcessPool_h
28
29 #include "APIDictionary.h"
30 #include "APIObject.h"
31 #include "DownloadProxyMap.h"
32 #include "GenericCallback.h"
33 #include "MessageReceiver.h"
34 #include "MessageReceiverMap.h"
35 #include "PlugInAutoStartProvider.h"
36 #include "PluginInfoStore.h"
37 #include "ProcessModel.h"
38 #include "ProcessThrottler.h"
39 #include "StatisticsRequest.h"
40 #include "StorageManager.h"
41 #include "VisitedLinkProvider.h"
42 #include "WebContextClient.h"
43 #include "WebContextConnectionClient.h"
44 #include "WebContextInjectedBundleClient.h"
45 #include "WebProcessProxy.h"
46 #include <WebCore/LinkHash.h>
47 #include <WebCore/SessionID.h>
48 #include <wtf/Forward.h>
49 #include <wtf/HashMap.h>
50 #include <wtf/HashSet.h>
51 #include <wtf/PassRefPtr.h>
52 #include <wtf/RefCounter.h>
53 #include <wtf/RefPtr.h>
54 #include <wtf/text/StringHash.h>
55 #include <wtf/text/WTFString.h>
56
57 #if ENABLE(DATABASE_PROCESS)
58 #include "DatabaseProcessProxy.h"
59 #endif
60
61 #if ENABLE(NETWORK_PROCESS)
62 #include "NetworkProcessProxy.h"
63 #endif
64
65 #if PLATFORM(COCOA)
66 OBJC_CLASS NSMutableDictionary;
67 OBJC_CLASS NSObject;
68 OBJC_CLASS NSString;
69 #endif
70
71 namespace API {
72 class DownloadClient;
73 class LegacyContextHistoryClient;
74 }
75
76 namespace WebKit {
77
78 class DownloadProxy;
79 class WebContextSupplement;
80 class WebIconDatabase;
81 class WebPageGroup;
82 class WebPageProxy;
83 struct StatisticsData;
84 struct WebPageConfiguration;
85 struct WebProcessCreationParameters;
86     
87 typedef GenericCallback<API::Dictionary*> DictionaryCallback;
88
89 #if ENABLE(NETWORK_PROCESS)
90 struct NetworkProcessCreationParameters;
91 #endif
92
93 #if PLATFORM(COCOA)
94 int networkProcessLatencyQOS();
95 int networkProcessThroughputQOS();
96 int webProcessLatencyQOS();
97 int webProcessThroughputQOS();
98 #endif
99
100 struct WebProcessPoolConfiguration {
101     String injectedBundlePath;
102     String localStorageDirectory;
103     String webSQLDatabaseDirectory;
104     String indexedDBDatabaseDirectory;
105     String mediaKeysStorageDirectory;
106 };
107
108 class WebProcessPool : public API::ObjectImpl<API::Object::Type::ProcessPool>, private IPC::MessageReceiver
109 #if ENABLE(NETSCAPE_PLUGIN_API)
110     , private PluginInfoStoreClient
111 #endif
112     {
113 public:
114     static void applyPlatformSpecificConfigurationDefaults(WebProcessPoolConfiguration&);
115
116     WebProcessPool(WebProcessPoolConfiguration);
117         
118     static PassRefPtr<WebProcessPool> create(WebProcessPoolConfiguration);
119     virtual ~WebProcessPool();
120
121     static const Vector<WebProcessPool*>& allProcessPools();
122
123     template <typename T>
124     T* supplement()
125     {
126         return static_cast<T*>(m_supplements.get(T::supplementName()));
127     }
128
129     template <typename T>
130     void addSupplement()
131     {
132         m_supplements.add(T::supplementName(), T::create(this));
133     }
134
135     void addMessageReceiver(IPC::StringReference messageReceiverName, IPC::MessageReceiver&);
136     void addMessageReceiver(IPC::StringReference messageReceiverName, uint64_t destinationID, IPC::MessageReceiver&);
137     void removeMessageReceiver(IPC::StringReference messageReceiverName, uint64_t destinationID);
138
139     bool dispatchMessage(IPC::Connection&, IPC::MessageDecoder&);
140     bool dispatchSyncMessage(IPC::Connection&, IPC::MessageDecoder&, std::unique_ptr<IPC::MessageEncoder>&);
141
142     void initializeClient(const WKContextClientBase*);
143     void initializeInjectedBundleClient(const WKContextInjectedBundleClientBase*);
144     void initializeConnectionClient(const WKContextConnectionClientBase*);
145     void setHistoryClient(std::unique_ptr<API::LegacyContextHistoryClient>);
146     void setDownloadClient(std::unique_ptr<API::DownloadClient>);
147
148     void setProcessModel(ProcessModel); // Can only be called when there are no processes running.
149     ProcessModel processModel() const { return m_processModel; }
150
151     void setMaximumNumberOfProcesses(unsigned); // Can only be called when there are no processes running.
152     unsigned maximumNumberOfProcesses() const { return m_webProcessCountLimit; }
153
154     const Vector<RefPtr<WebProcessProxy>>& processes() const { return m_processes; }
155
156     // WebProcess or NetworkProcess as approporiate for current process model. The connection must be non-null.
157     IPC::Connection* networkingProcessConnection();
158
159     template<typename T> void sendToAllProcesses(const T& message);
160     template<typename T> void sendToAllProcessesRelaunchingThemIfNecessary(const T& message);
161     template<typename T> void sendToOneProcess(T&& message);
162
163     // Sends the message to WebProcess or NetworkProcess as approporiate for current process model.
164     template<typename T> void sendToNetworkingProcess(T&& message);
165     template<typename T> void sendToNetworkingProcessRelaunchingIfNecessary(T&& message);
166
167     // Sends the message to WebProcess or DatabaseProcess as approporiate for current process model.
168     template<typename T> void sendToDatabaseProcessRelaunchingIfNecessary(T&& message);
169
170     void processWillOpenConnection(WebProcessProxy*);
171     void processWillCloseConnection(WebProcessProxy*);
172     void processDidFinishLaunching(WebProcessProxy*);
173
174     void applicationWillTerminate();
175     // Disconnect the process from the context.
176     void disconnectProcess(WebProcessProxy*);
177
178     StorageManager& storageManager() const { return *m_storageManager; }
179
180     PassRefPtr<WebPageProxy> createWebPage(PageClient&, WebPageConfiguration);
181
182     const String& injectedBundlePath() const { return m_injectedBundlePath; }
183
184     DownloadProxy* download(WebPageProxy* initiatingPage, const WebCore::ResourceRequest&);
185     DownloadProxy* resumeDownload(const API::Data* resumeData, const String& path);
186
187     void setInjectedBundleInitializationUserData(PassRefPtr<API::Object> userData) { m_injectedBundleInitializationUserData = userData; }
188
189     void postMessageToInjectedBundle(const String&, API::Object*);
190
191     void populateVisitedLinks();
192
193 #if ENABLE(NETSCAPE_PLUGIN_API)
194     void setAdditionalPluginsDirectory(const String&);
195
196     PluginInfoStore& pluginInfoStore() { return m_pluginInfoStore; }
197 #endif
198
199     void setAlwaysUsesComplexTextCodePath(bool);
200     void setShouldUseFontSmoothing(bool);
201     
202     void registerURLSchemeAsEmptyDocument(const String&);
203     void registerURLSchemeAsSecure(const String&);
204     void setDomainRelaxationForbiddenForURLScheme(const String&);
205     void setCanHandleHTTPSServerTrustEvaluation(bool);
206     void registerURLSchemeAsLocal(const String&);
207     void registerURLSchemeAsNoAccess(const String&);
208     void registerURLSchemeAsDisplayIsolated(const String&);
209     void registerURLSchemeAsCORSEnabled(const String&);
210 #if ENABLE(CACHE_PARTITIONING)
211     void registerURLSchemeAsCachePartitioned(const String&);
212 #endif
213
214     VisitedLinkProvider& visitedLinkProvider() { return *m_visitedLinkProvider; }
215
216     void setCacheModel(CacheModel);
217     CacheModel cacheModel() const { return m_cacheModel; }
218
219     void setDefaultRequestTimeoutInterval(double);
220
221     void startMemorySampler(const double interval);
222     void stopMemorySampler();
223
224 #if USE(SOUP)
225     void setInitialHTTPCookieAcceptPolicy(HTTPCookieAcceptPolicy policy) { m_initialHTTPCookieAcceptPolicy = policy; }
226 #endif
227     void setEnhancedAccessibility(bool);
228     
229     // Downloads.
230     DownloadProxy* createDownloadProxy(const WebCore::ResourceRequest&);
231     API::DownloadClient& downloadClient() { return *m_downloadClient; }
232
233     API::LegacyContextHistoryClient& historyClient() { return *m_historyClient; }
234     WebContextClient& client() { return m_client; }
235
236     WebIconDatabase* iconDatabase() const { return m_iconDatabase.get(); }
237 #if ENABLE(NETSCAPE_PLUGIN_API)
238     WebPluginSiteDataManager* pluginSiteDataManager() const { return m_pluginSiteDataManager.get(); }
239 #endif
240
241     struct Statistics {
242         unsigned wkViewCount;
243         unsigned wkPageCount;
244         unsigned wkFrameCount;
245     };
246     static Statistics& statistics();    
247
248     void setApplicationCacheDirectory(const String& dir) { m_overrideApplicationCacheDirectory = dir; }
249     void setIconDatabasePath(const String&);
250     String iconDatabasePath() const;
251     void setDiskCacheDirectory(const String& dir) { m_overrideDiskCacheDirectory = dir; }
252     void setCookieStorageDirectory(const String& dir) { m_overrideCookieStorageDirectory = dir; }
253
254     void useTestingNetworkSession();
255
256     void allowSpecificHTTPSCertificateForHost(const WebCertificateInfo*, const String& host);
257
258     WebProcessProxy& ensureSharedWebProcess();
259     WebProcessProxy& createNewWebProcessRespectingProcessCountLimit(); // Will return an existing one if limit is met.
260     void warmInitialProcess();
261
262     bool shouldTerminate(WebProcessProxy*);
263
264     void disableProcessTermination() { m_processTerminationEnabled = false; }
265     void enableProcessTermination();
266
267     // Defaults to false.
268     void setHTTPPipeliningEnabled(bool);
269     bool httpPipeliningEnabled() const;
270
271     void getStatistics(uint32_t statisticsMask, std::function<void (API::Dictionary*, CallbackBase::Error)>);
272     
273     void garbageCollectJavaScriptObjects();
274     void setJavaScriptGarbageCollectorTimerEnabled(bool flag);
275
276 #if PLATFORM(COCOA)
277     static bool omitPDFSupport();
278 #endif
279
280     void fullKeyboardAccessModeChanged(bool fullKeyboardAccessEnabled);
281
282     void textCheckerStateChanged();
283
284     PassRefPtr<API::Dictionary> plugInAutoStartOriginHashes() const;
285     void setPlugInAutoStartOriginHashes(API::Dictionary&);
286     void setPlugInAutoStartOrigins(API::Array&);
287     void setPlugInAutoStartOriginsFilteringOutEntriesAddedAfterTime(API::Dictionary&, double time);
288
289     // Network Process Management
290
291     void setUsesNetworkProcess(bool);
292     bool usesNetworkProcess() const;
293
294 #if ENABLE(NETWORK_PROCESS)
295     void ensureNetworkProcess();
296     NetworkProcessProxy* networkProcess() { return m_networkProcess.get(); }
297     void networkProcessCrashed(NetworkProcessProxy*);
298
299     void getNetworkProcessConnection(PassRefPtr<Messages::WebProcessProxy::GetNetworkProcessConnection::DelayedReply>);
300 #endif
301
302 #if ENABLE(DATABASE_PROCESS)
303     void ensureDatabaseProcess();
304     void getDatabaseProcessConnection(PassRefPtr<Messages::WebProcessProxy::GetDatabaseProcessConnection::DelayedReply>);
305     void databaseProcessCrashed(DatabaseProcessProxy*);
306 #endif
307
308 #if PLATFORM(COCOA)
309     bool processSuppressionEnabled() const;
310 #endif
311
312     void windowServerConnectionStateChanged();
313
314     static void willStartUsingPrivateBrowsing();
315     static void willStopUsingPrivateBrowsing();
316
317     static bool isEphemeralSession(WebCore::SessionID);
318
319 #if USE(SOUP)
320     void setIgnoreTLSErrors(bool);
321     bool ignoreTLSErrors() const { return m_ignoreTLSErrors; }
322 #endif
323
324     static void setInvalidMessageCallback(void (*)(WKStringRef));
325     static void didReceiveInvalidMessage(const IPC::StringReference& messageReceiverName, const IPC::StringReference& messageName);
326
327     void processDidCachePage(WebProcessProxy*);
328
329     bool isURLKnownHSTSHost(const String& urlString, bool privateBrowsingEnabled) const;
330     void resetHSTSHosts();
331
332     void registerSchemeForCustomProtocol(const String&);
333     void unregisterSchemeForCustomProtocol(const String&);
334
335     static HashSet<String>& globalURLSchemesWithCustomProtocolHandlers();
336     static void registerGlobalURLSchemeAsHavingCustomProtocolHandlers(const String&);
337     static void unregisterGlobalURLSchemeAsHavingCustomProtocolHandlers(const String&);
338
339 #if PLATFORM(COCOA)
340     void updateProcessSuppressionState();
341
342     NSMutableDictionary *ensureBundleParameters();
343     NSMutableDictionary *bundleParameters() { return m_bundleParameters.get(); }
344 #else
345     void updateProcessSuppressionState() const { }
346 #endif
347
348     void setMemoryCacheDisabled(bool);
349
350     UserObservablePageToken userObservablePageCount()
351     {
352         return m_userObservablePageCounter.token<UserObservablePageTokenType>();
353     }
354
355     ProcessSuppressionDisabledToken processSuppressionDisabledForPageCount()
356     {
357         return m_processSuppressionDisabledForPageCounter.token<ProcessSuppressionDisabledTokenType>();
358     }
359
360 private:
361     void platformInitialize();
362
363     void platformInitializeWebProcess(WebProcessCreationParameters&);
364     void platformInvalidateContext();
365
366     WebProcessProxy& createNewWebProcess();
367
368     void requestWebContentStatistics(StatisticsRequest*);
369     void requestNetworkingStatistics(StatisticsRequest*);
370
371 #if ENABLE(NETWORK_PROCESS)
372     void platformInitializeNetworkProcess(NetworkProcessCreationParameters&);
373 #endif
374
375     void handleMessage(IPC::Connection&, const String& messageName, const UserData& messageBody);
376     void handleSynchronousMessage(IPC::Connection&, const String& messageName, const UserData& messageBody, UserData& returnUserData);
377
378     void didGetStatistics(const StatisticsData&, uint64_t callbackID);
379
380     // IPC::MessageReceiver.
381     // Implemented in generated WebProcessPoolMessageReceiver.cpp
382     virtual void didReceiveMessage(IPC::Connection&, IPC::MessageDecoder&) override;
383     virtual void didReceiveSyncMessage(IPC::Connection&, IPC::MessageDecoder&, std::unique_ptr<IPC::MessageEncoder>&) override;
384
385     static void languageChanged(void* context);
386     void languageChanged();
387
388     String applicationCacheDirectory() const;
389     String platformDefaultApplicationCacheDirectory() const;
390
391     String platformDefaultIconDatabasePath() const;
392
393     static String platformDefaultLocalStorageDirectory();
394     static String platformDefaultIndexedDBDatabaseDirectory();
395     static String platformDefaultWebSQLDatabaseDirectory();
396     static String platformDefaultMediaKeysStorageDirectory();
397
398     String diskCacheDirectory() const;
399     String platformDefaultDiskCacheDirectory() const;
400
401     String cookieStorageDirectory() const;
402     String platformDefaultCookieStorageDirectory() const;
403
404 #if PLATFORM(IOS)
405     String openGLCacheDirectory() const;
406     String parentBundleDirectory() const;
407     String networkingHSTSDatabasePath() const;
408     String webContentHSTSDatabasePath() const;
409     String containerTemporaryDirectory() const;
410 #endif
411
412 #if PLATFORM(COCOA)
413     void registerNotificationObservers();
414     void unregisterNotificationObservers();
415 #endif
416
417     void addPlugInAutoStartOriginHash(const String& pageOrigin, unsigned plugInOriginHash, WebCore::SessionID);
418     void plugInDidReceiveUserInteraction(unsigned plugInOriginHash, WebCore::SessionID);
419
420     void setAnyPageGroupMightHavePrivateBrowsingEnabled(bool);
421
422 #if ENABLE(NETSCAPE_PLUGIN_API)
423     // PluginInfoStoreClient:
424     virtual void pluginInfoStoreDidLoadPlugins(PluginInfoStore*) override;
425 #endif
426
427     IPC::MessageReceiverMap m_messageReceiverMap;
428
429     ProcessModel m_processModel;
430     unsigned m_webProcessCountLimit; // The limit has no effect when process model is ProcessModelSharedSecondaryProcess.
431     
432     Vector<RefPtr<WebProcessProxy>> m_processes;
433     bool m_haveInitialEmptyProcess;
434
435     WebProcessProxy* m_processWithPageCache;
436
437     Ref<WebPageGroup> m_defaultPageGroup;
438
439     RefPtr<API::Object> m_injectedBundleInitializationUserData;
440     String m_injectedBundlePath;
441     WebContextInjectedBundleClient m_injectedBundleClient;
442
443     WebContextClient m_client;
444     WebContextConnectionClient m_connectionClient;
445     std::unique_ptr<API::DownloadClient> m_downloadClient;
446     std::unique_ptr<API::LegacyContextHistoryClient> m_historyClient;
447
448 #if ENABLE(NETSCAPE_PLUGIN_API)
449     PluginInfoStore m_pluginInfoStore;
450 #endif
451     RefPtr<VisitedLinkProvider> m_visitedLinkProvider;
452     bool m_visitedLinksPopulated;
453
454     PlugInAutoStartProvider m_plugInAutoStartProvider;
455         
456     HashSet<String> m_schemesToRegisterAsEmptyDocument;
457     HashSet<String> m_schemesToRegisterAsSecure;
458     HashSet<String> m_schemesToSetDomainRelaxationForbiddenFor;
459     HashSet<String> m_schemesToRegisterAsLocal;
460     HashSet<String> m_schemesToRegisterAsNoAccess;
461     HashSet<String> m_schemesToRegisterAsDisplayIsolated;
462     HashSet<String> m_schemesToRegisterAsCORSEnabled;
463 #if ENABLE(CACHE_PARTITIONING)
464     HashSet<String> m_schemesToRegisterAsCachePartitioned;
465 #endif
466
467     bool m_alwaysUsesComplexTextCodePath;
468     bool m_shouldUseFontSmoothing;
469
470     // Messages that were posted before any pages were created.
471     // The client should use initialization messages instead, so that a restarted process would get the same state.
472     Vector<std::pair<String, RefPtr<API::Object>>> m_messagesToInjectedBundlePostedToEmptyContext;
473
474     CacheModel m_cacheModel;
475
476     bool m_memorySamplerEnabled;
477     double m_memorySamplerInterval;
478
479     RefPtr<WebIconDatabase> m_iconDatabase;
480 #if ENABLE(NETSCAPE_PLUGIN_API)
481     RefPtr<WebPluginSiteDataManager> m_pluginSiteDataManager;
482 #endif
483
484     RefPtr<WebsiteDataStore> m_websiteDataStore;
485     RefPtr<StorageManager> m_storageManager;
486
487     typedef HashMap<const char*, RefPtr<WebContextSupplement>, PtrHash<const char*>> WebContextSupplementMap;
488     WebContextSupplementMap m_supplements;
489
490 #if USE(SOUP)
491     HTTPCookieAcceptPolicy m_initialHTTPCookieAcceptPolicy;
492 #endif
493
494 #if PLATFORM(MAC)
495     RetainPtr<NSObject> m_enhancedAccessibilityObserver;
496     RetainPtr<NSObject> m_automaticTextReplacementNotificationObserver;
497     RetainPtr<NSObject> m_automaticSpellingCorrectionNotificationObserver;
498 #if __MAC_OS_X_VERSION_MIN_REQUIRED >= 1090
499     RetainPtr<NSObject> m_automaticQuoteSubstitutionNotificationObserver;
500     RetainPtr<NSObject> m_automaticDashSubstitutionNotificationObserver;
501 #endif
502 #endif
503
504     String m_overrideApplicationCacheDirectory;
505     String m_overrideIconDatabasePath;
506     String m_overrideDiskCacheDirectory;
507     String m_overrideCookieStorageDirectory;
508
509     String m_webSQLDatabaseDirectory;
510     String m_indexedDBDatabaseDirectory;
511     String m_mediaKeysStorageDirectory;
512
513     bool m_shouldUseTestingNetworkSession;
514
515     bool m_processTerminationEnabled;
516
517 #if ENABLE(NETWORK_PROCESS)
518     bool m_canHandleHTTPSServerTrustEvaluation;
519     bool m_usesNetworkProcess;
520     RefPtr<NetworkProcessProxy> m_networkProcess;
521 #endif
522
523 #if ENABLE(DATABASE_PROCESS)
524     RefPtr<DatabaseProcessProxy> m_databaseProcess;
525 #endif
526     
527     HashMap<uint64_t, RefPtr<DictionaryCallback>> m_dictionaryCallbacks;
528     HashMap<uint64_t, RefPtr<StatisticsRequest>> m_statisticsRequests;
529
530 #if USE(SOUP)
531     bool m_ignoreTLSErrors;
532 #endif
533
534     bool m_memoryCacheDisabled;
535
536     RefCounter m_userObservablePageCounter;
537     RefCounter m_processSuppressionDisabledForPageCounter;
538
539 #if PLATFORM(COCOA)
540     RetainPtr<NSMutableDictionary> m_bundleParameters;
541     ProcessSuppressionDisabledToken m_pluginProcessManagerProcessSuppressionDisabledToken;
542 #endif
543 };
544
545 template<typename T>
546 void WebProcessPool::sendToNetworkingProcess(T&& message)
547 {
548     switch (m_processModel) {
549     case ProcessModelSharedSecondaryProcess:
550 #if ENABLE(NETWORK_PROCESS)
551         if (m_usesNetworkProcess) {
552             if (m_networkProcess && m_networkProcess->canSendMessage())
553                 m_networkProcess->send(std::forward<T>(message), 0);
554             return;
555         }
556 #endif
557         if (!m_processes.isEmpty() && m_processes[0]->canSendMessage())
558             m_processes[0]->send(std::forward<T>(message), 0);
559         return;
560     case ProcessModelMultipleSecondaryProcesses:
561 #if ENABLE(NETWORK_PROCESS)
562         if (m_networkProcess && m_networkProcess->canSendMessage())
563             m_networkProcess->send(std::forward<T>(message), 0);
564         return;
565 #else
566         break;
567 #endif
568     }
569     ASSERT_NOT_REACHED();
570 }
571
572 template<typename T>
573 void WebProcessPool::sendToNetworkingProcessRelaunchingIfNecessary(T&& message)
574 {
575     switch (m_processModel) {
576     case ProcessModelSharedSecondaryProcess:
577 #if ENABLE(NETWORK_PROCESS)
578         if (m_usesNetworkProcess) {
579             ensureNetworkProcess();
580             m_networkProcess->send(std::forward<T>(message), 0);
581             return;
582         }
583 #endif
584         ensureSharedWebProcess();
585         m_processes[0]->send(std::forward<T>(message), 0);
586         return;
587     case ProcessModelMultipleSecondaryProcesses:
588 #if ENABLE(NETWORK_PROCESS)
589         ensureNetworkProcess();
590         m_networkProcess->send(std::forward<T>(message), 0);
591         return;
592 #else
593         break;
594 #endif
595     }
596     ASSERT_NOT_REACHED();
597 }
598
599 template<typename T>
600 void WebProcessPool::sendToDatabaseProcessRelaunchingIfNecessary(T&& message)
601 {
602 #if ENABLE(DATABASE_PROCESS)
603     ensureDatabaseProcess();
604     m_databaseProcess->send(std::forward<T>(message), 0);
605 #else
606     sendToAllProcessesRelaunchingThemIfNecessary(std::forward<T>(message));
607 #endif
608 }
609
610 template<typename T>
611 void WebProcessPool::sendToAllProcesses(const T& message)
612 {
613     size_t processCount = m_processes.size();
614     for (size_t i = 0; i < processCount; ++i) {
615         WebProcessProxy* process = m_processes[i].get();
616         if (process->canSendMessage())
617             process->send(T(message), 0);
618     }
619 }
620
621 template<typename T>
622 void WebProcessPool::sendToAllProcessesRelaunchingThemIfNecessary(const T& message)
623 {
624     // FIXME (Multi-WebProcess): WebProcessPool doesn't track processes that have exited, so it cannot relaunch these. Perhaps this functionality won't be needed in this mode.
625     if (m_processModel == ProcessModelSharedSecondaryProcess)
626         ensureSharedWebProcess();
627     sendToAllProcesses(message);
628 }
629
630 template<typename T>
631 void WebProcessPool::sendToOneProcess(T&& message)
632 {
633     if (m_processModel == ProcessModelSharedSecondaryProcess)
634         ensureSharedWebProcess();
635
636     bool messageSent = false;
637     size_t processCount = m_processes.size();
638     for (size_t i = 0; i < processCount; ++i) {
639         WebProcessProxy* process = m_processes[i].get();
640         if (process->canSendMessage()) {
641             process->send(std::forward<T>(message), 0);
642             messageSent = true;
643             break;
644         }
645     }
646
647     if (!messageSent && m_processModel == ProcessModelMultipleSecondaryProcesses) {
648         warmInitialProcess();
649         RefPtr<WebProcessProxy> process = m_processes.last();
650         if (process->canSendMessage())
651             process->send(std::forward<T>(message), 0);
652     }
653 }
654
655 } // namespace WebKit
656
657 #endif // UIProcessPool_h