Actively prewarm processes created for prewarm pool
[WebKit-https.git] / Source / WebKit / WebProcess / WebProcess.h
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 #pragma once
27
28 #include "CacheModel.h"
29 #include "ChildProcess.h"
30 #include "PluginProcessConnectionManager.h"
31 #include "ResourceCachesToClear.h"
32 #include "SandboxExtension.h"
33 #include "TextCheckerState.h"
34 #include "ViewUpdateDispatcher.h"
35 #include "WebInspectorInterruptDispatcher.h"
36 #include <WebCore/ActivityState.h>
37 #if PLATFORM(MAC)
38 #include <WebCore/ScreenProperties.h>
39 #endif
40 #include <WebCore/Timer.h>
41 #include <pal/HysteresisActivity.h>
42 #include <pal/SessionID.h>
43 #include <wtf/Forward.h>
44 #include <wtf/HashMap.h>
45 #include <wtf/HashSet.h>
46 #include <wtf/RefCounter.h>
47 #include <wtf/text/AtomicString.h>
48 #include <wtf/text/AtomicStringHash.h>
49
50 #if PLATFORM(COCOA)
51 #include <dispatch/dispatch.h>
52 #include <wtf/MachSendRight.h>
53 #endif
54
55 namespace API {
56 class Object;
57 }
58
59 namespace PAL {
60 class SessionID;
61 }
62
63 namespace WebCore {
64 class ApplicationCacheStorage;
65 class CPUMonitor;
66 class CertificateInfo;
67 class PageGroup;
68 class ResourceRequest;
69 class UserGestureToken;
70 struct MessagePortIdentifier;
71 struct MessageWithMessagePorts;
72 struct MockMediaDevice;
73 struct PluginInfo;
74 struct SecurityOriginData;
75 struct SoupNetworkProxySettings;
76
77 #if ENABLE(SERVICE_WORKER)
78 struct ServiceWorkerContextData;
79 #endif
80 }
81
82 namespace WebKit {
83
84 class EventDispatcher;
85 class GamepadData;
86 class InjectedBundle;
87 class LibWebRTCNetwork;
88 class NetworkProcessConnection;
89 class ObjCObjectGraph;
90 class UserData;
91 class WaylandCompositorDisplay;
92 class WebAutomationSessionProxy;
93 class WebCacheStorageProvider;
94 class WebConnectionToUIProcess;
95 class WebFrame;
96 class WebLoaderStrategy;
97 class WebPage;
98 class WebPageGroupProxy;
99 class WebProcessSupplement;
100 class WebToStorageProcessConnection;
101 enum class WebsiteDataType;
102 struct WebPageCreationParameters;
103 struct WebPageGroupData;
104 struct WebPreferencesStore;
105 struct WebProcessCreationParameters;
106 struct WebsiteData;
107 struct WebsiteDataStoreParameters;
108
109 class WebProcess : public ChildProcess {
110 public:
111     static WebProcess& singleton();
112     static constexpr ProcessType processType = ProcessType::WebContent;
113
114     template <typename T>
115     T* supplement()
116     {
117         return static_cast<T*>(m_supplements.get(T::supplementName()));
118     }
119
120     template <typename T>
121     void addSupplement()
122     {
123         m_supplements.add(T::supplementName(), std::make_unique<T>(*this));
124     }
125
126     WebConnectionToUIProcess* webConnectionToUIProcess() const { return m_webConnection.get(); }
127
128     WebPage* webPage(uint64_t pageID) const;
129     void createWebPage(uint64_t pageID, WebPageCreationParameters&&);
130     void removeWebPage(uint64_t pageID);
131     WebPage* focusedWebPage() const;
132
133     InjectedBundle* injectedBundle() const { return m_injectedBundle.get(); }
134
135 #if PLATFORM(COCOA)
136     const WTF::MachSendRight& compositingRenderServerPort() const { return m_compositingRenderServerPort; }
137 #endif
138
139     bool shouldPlugInAutoStartFromOrigin(WebPage&, const String& pageOrigin, const String& pluginOrigin, const String& mimeType);
140     void plugInDidStartFromOrigin(const String& pageOrigin, const String& pluginOrigin, const String& mimeType, PAL::SessionID);
141     void plugInDidReceiveUserInteraction(const String& pageOrigin, const String& pluginOrigin, const String& mimeType, PAL::SessionID);
142     void setPluginLoadClientPolicy(uint8_t policy, const String& host, const String& bundleIdentifier, const String& versionString);
143     void resetPluginLoadClientPolicies(const HashMap<String, HashMap<String, HashMap<String, uint8_t>>>&);
144     void clearPluginClientPolicies();
145     void refreshPlugins();
146
147     bool fullKeyboardAccessEnabled() const { return m_fullKeyboardAccessEnabled; }
148
149     WebFrame* webFrame(uint64_t) const;
150     void addWebFrame(uint64_t, WebFrame*);
151     void removeWebFrame(uint64_t);
152
153     WebPageGroupProxy* webPageGroup(WebCore::PageGroup*);
154     WebPageGroupProxy* webPageGroup(uint64_t pageGroupID);
155     WebPageGroupProxy* webPageGroup(const WebPageGroupData&);
156
157     uint64_t userGestureTokenIdentifier(RefPtr<WebCore::UserGestureToken>);
158     void userGestureTokenDestroyed(WebCore::UserGestureToken&);
159     
160     const TextCheckerState& textCheckerState() const { return m_textCheckerState; }
161     void setTextCheckerState(const TextCheckerState&);
162
163     void clearResourceCaches(ResourceCachesToClear = AllResourceCaches);
164     
165 #if ENABLE(NETSCAPE_PLUGIN_API)
166     PluginProcessConnectionManager& pluginProcessConnectionManager();
167 #endif
168
169     EventDispatcher& eventDispatcher() { return *m_eventDispatcher; }
170
171     NetworkProcessConnection& ensureNetworkProcessConnection();
172     void networkProcessConnectionClosed(NetworkProcessConnection*);
173     WebLoaderStrategy& webLoaderStrategy();
174
175     LibWebRTCNetwork& libWebRTCNetwork();
176
177     void webToStorageProcessConnectionClosed(WebToStorageProcessConnection*);
178     WebToStorageProcessConnection* existingWebToStorageProcessConnection() { return m_webToStorageProcessConnection.get(); }
179     WebToStorageProcessConnection& ensureWebToStorageProcessConnection(PAL::SessionID initialSessionID);
180
181     void setCacheModel(uint32_t);
182
183     void ensureLegacyPrivateBrowsingSessionInNetworkProcess();
184     void addWebsiteDataStore(WebsiteDataStoreParameters&&);
185     void destroySession(PAL::SessionID);
186
187     void pageDidEnterWindow(uint64_t pageID);
188     void pageWillLeaveWindow(uint64_t pageID);
189
190     void nonVisibleProcessCleanupTimerFired();
191
192 #if PLATFORM(COCOA)
193     RetainPtr<CFDataRef> sourceApplicationAuditData() const;
194     void destroyRenderingResources();
195 #endif
196
197     void updateActivePages();
198     void pageActivityStateDidChange(uint64_t pageID, OptionSet<WebCore::ActivityState::Flag> changed);
199
200     void setHiddenPageDOMTimerThrottlingIncreaseLimit(int milliseconds);
201
202     void processWillSuspendImminently(bool& handled);
203     void prepareToSuspend();
204     void cancelPrepareToSuspend();
205     void processDidResume();
206
207 #if PLATFORM(IOS)
208     void resetAllGeolocationPermissions();
209 #endif
210
211 #if PLATFORM(WAYLAND)
212     WaylandCompositorDisplay* waylandCompositorDisplay() const { return m_waylandCompositorDisplay.get(); }
213 #endif
214
215     RefPtr<API::Object> transformHandlesToObjects(API::Object*);
216     static RefPtr<API::Object> transformObjectsToHandles(API::Object*);
217
218 #if PLATFORM(COCOA)
219     RefPtr<ObjCObjectGraph> transformHandlesToObjects(ObjCObjectGraph&);
220     static RefPtr<ObjCObjectGraph> transformObjectsToHandles(ObjCObjectGraph&);
221 #endif
222
223 #if ENABLE(SERVICE_CONTROLS)
224     bool hasImageServices() const { return m_hasImageServices; }
225     bool hasSelectionServices() const { return m_hasSelectionServices; }
226     bool hasRichContentServices() const { return m_hasRichContentServices; }
227 #endif
228
229     WebCore::ApplicationCacheStorage& applicationCacheStorage() { return *m_applicationCacheStorage; }
230
231     void prefetchDNS(const String&);
232
233     WebAutomationSessionProxy* automationSessionProxy() { return m_automationSessionProxy.get(); }
234
235     WebCacheStorageProvider& cacheStorageProvider() { return m_cacheStorageProvider.get(); }
236
237 #if PLATFORM(IOS)
238     void accessibilityProcessSuspendedNotification(bool);
239 #endif
240
241 #if PLATFORM(COCOA)
242     void setMediaMIMETypes(const Vector<String>);
243 #endif
244
245 private:
246     WebProcess();
247     ~WebProcess();
248
249     void initializeWebProcess(WebProcessCreationParameters&&);
250     void platformInitializeWebProcess(WebProcessCreationParameters&&);
251
252     void prewarm();
253
254 #if USE(OS_STATE)
255     void registerWithStateDumper();
256 #endif
257
258     void markAllLayersVolatile(WTF::Function<void(bool)>&& completionHandler);
259     void cancelMarkAllLayersVolatile();
260     void setAllLayerTreeStatesFrozen(bool);
261     void processSuspensionCleanupTimerFired();
262
263     void clearCachedCredentials();
264
265     void platformTerminate();
266
267     void registerURLSchemeAsEmptyDocument(const String&);
268     void registerURLSchemeAsSecure(const String&) const;
269     void registerURLSchemeAsBypassingContentSecurityPolicy(const String&) const;
270     void setDomainRelaxationForbiddenForURLScheme(const String&) const;
271     void registerURLSchemeAsLocal(const String&) const;
272     void registerURLSchemeAsNoAccess(const String&) const;
273     void registerURLSchemeAsDisplayIsolated(const String&) const;
274     void registerURLSchemeAsCORSEnabled(const String&) const;
275     void registerURLSchemeAsAlwaysRevalidated(const String&) const;
276     void registerURLSchemeAsCachePartitioned(const String&) const;
277     void registerURLSchemeAsCanDisplayOnlyIfCanRequest(const String&) const;
278
279     void setDefaultRequestTimeoutInterval(double);
280     void setAlwaysUsesComplexTextCodePath(bool);
281     void setShouldUseFontSmoothing(bool);
282     void setResourceLoadStatisticsEnabled(bool);
283     void clearResourceLoadStatistics();
284     void userPreferredLanguagesChanged(const Vector<String>&) const;
285     void fullKeyboardAccessModeChanged(bool fullKeyboardAccessEnabled);
286
287     bool isPlugInAutoStartOriginHash(unsigned plugInOriginHash, PAL::SessionID);
288     void didAddPlugInAutoStartOriginHash(unsigned plugInOriginHash, WallTime expirationTime, PAL::SessionID);
289     void resetPlugInAutoStartOriginDefaultHashes(const HashMap<unsigned, WallTime>& hashes);
290     void resetPlugInAutoStartOriginHashes(const HashMap<PAL::SessionID, HashMap<unsigned, WallTime>>& hashes);
291
292     void platformSetCacheModel(CacheModel);
293
294     void setEnhancedAccessibility(bool);
295     
296     void startMemorySampler(SandboxExtension::Handle&&, const String&, const double);
297     void stopMemorySampler();
298     
299     void getWebCoreStatistics(uint64_t callbackID);
300     void garbageCollectJavaScriptObjects();
301     void setJavaScriptGarbageCollectorTimerEnabled(bool flag);
302
303     void mainThreadPing();
304     void backgroundResponsivenessPing();
305
306     void syncIPCMessageWhileWaitingForSyncReplyForTesting();
307
308     void didTakeAllMessagesForPort(Vector<WebCore::MessageWithMessagePorts>&& messages, uint64_t messageCallbackIdentifier, uint64_t messageBatchIdentifier);
309     void checkProcessLocalPortForActivity(const WebCore::MessagePortIdentifier&, uint64_t callbackIdentifier);
310     void didCheckRemotePortForActivity(uint64_t callbackIdentifier, bool hasActivity);
311     void messagesAvailableForPort(const WebCore::MessagePortIdentifier&);
312
313 #if ENABLE(GAMEPAD)
314     void setInitialGamepads(const Vector<GamepadData>&);
315     void gamepadConnected(const GamepadData&);
316     void gamepadDisconnected(unsigned index);
317 #endif
318 #if USE(SOUP)
319     void setNetworkProxySettings(const WebCore::SoupNetworkProxySettings&);
320 #endif
321 #if ENABLE(SERVICE_WORKER)
322     void establishWorkerContextConnectionToStorageProcess(uint64_t pageGroupID, uint64_t pageID, const WebPreferencesStore&, PAL::SessionID);
323     void registerServiceWorkerClients();
324 #endif
325
326     void releasePageCache();
327
328     void fetchWebsiteData(PAL::SessionID, OptionSet<WebsiteDataType>, WebsiteData&);
329     void deleteWebsiteData(PAL::SessionID, OptionSet<WebsiteDataType>, WallTime modifiedSince);
330     void deleteWebsiteDataForOrigins(PAL::SessionID, OptionSet<WebsiteDataType>, const Vector<WebCore::SecurityOriginData>& origins);
331
332     void setMemoryCacheDisabled(bool);
333
334 #if ENABLE(SERVICE_CONTROLS)
335     void setEnabledServices(bool hasImageServices, bool hasSelectionServices, bool hasRichContentServices);
336 #endif
337
338     void handleInjectedBundleMessage(const String& messageName, const UserData& messageBody);
339     void setInjectedBundleParameter(const String& key, const IPC::DataReference&);
340     void setInjectedBundleParameters(const IPC::DataReference&);
341
342     enum class ShouldAcknowledgeWhenReadyToSuspend { No, Yes };
343     void actualPrepareToSuspend(ShouldAcknowledgeWhenReadyToSuspend);
344
345     void ensureAutomationSessionProxy(const String& sessionIdentifier);
346     void destroyAutomationSessionProxy();
347
348     void logDiagnosticMessageForNetworkProcessCrash();
349     bool hasVisibleWebPage() const;
350     void updateCPULimit();
351     enum class CPUMonitorUpdateReason { LimitHasChanged, VisibilityHasChanged };
352     void updateCPUMonitorState(CPUMonitorUpdateReason);
353
354     // ChildProcess
355     void initializeProcess(const ChildProcessInitializationParameters&) override;
356     void initializeProcessName(const ChildProcessInitializationParameters&) override;
357     void initializeSandbox(const ChildProcessInitializationParameters&, SandboxInitializationParameters&) override;
358     void initializeConnection(IPC::Connection*) override;
359     bool shouldTerminate() override;
360     void terminate() override;
361
362 #if USE(APPKIT)
363     void stopRunLoop() override;
364 #endif
365
366 #if ENABLE(MEDIA_STREAM)
367     void addMockMediaDevice(const WebCore::MockMediaDevice&);
368     void clearMockMediaDevices();
369     void removeMockMediaDevice(const String& persistentId);
370     void resetMockMediaDevices();
371 #endif
372
373     void platformInitializeProcess(const ChildProcessInitializationParameters&);
374
375     // IPC::Connection::Client
376     friend class WebConnectionToUIProcess;
377     void didReceiveMessage(IPC::Connection&, IPC::Decoder&) override;
378     void didReceiveSyncMessage(IPC::Connection&, IPC::Decoder&, std::unique_ptr<IPC::Encoder>&) override;
379
380     // Implemented in generated WebProcessMessageReceiver.cpp
381     void didReceiveWebProcessMessage(IPC::Connection&, IPC::Decoder&);
382     void didReceiveSyncWebProcessMessage(IPC::Connection&, IPC::Decoder&, std::unique_ptr<IPC::Encoder>&);
383
384 #if PLATFORM(MAC)
385     void setScreenProperties(const WebCore::ScreenProperties&);
386 #if ENABLE(WEBPROCESS_WINDOWSERVER_BLOCKING)
387     void scrollerStylePreferenceChanged(bool useOverlayScrollbars);
388     void displayConfigurationChanged(CGDirectDisplayID, CGDisplayChangeSummaryFlags);
389 #endif
390 #endif
391
392     RefPtr<WebConnectionToUIProcess> m_webConnection;
393
394     HashMap<uint64_t, RefPtr<WebPage>> m_pageMap;
395     HashMap<uint64_t, RefPtr<WebPageGroupProxy>> m_pageGroupMap;
396     RefPtr<InjectedBundle> m_injectedBundle;
397
398     RefPtr<EventDispatcher> m_eventDispatcher;
399 #if PLATFORM(IOS)
400     RefPtr<ViewUpdateDispatcher> m_viewUpdateDispatcher;
401 #endif
402     RefPtr<WebInspectorInterruptDispatcher> m_webInspectorInterruptDispatcher;
403
404     HashMap<PAL::SessionID, HashMap<unsigned, WallTime>> m_plugInAutoStartOriginHashes;
405     HashSet<String> m_plugInAutoStartOrigins;
406
407     bool m_hasSetCacheModel { false };
408     CacheModel m_cacheModel { CacheModelDocumentViewer };
409
410 #if PLATFORM(COCOA)
411     WTF::MachSendRight m_compositingRenderServerPort;
412 #endif
413
414     bool m_fullKeyboardAccessEnabled { false };
415
416     HashMap<uint64_t, WebFrame*> m_frameMap;
417
418     typedef HashMap<const char*, std::unique_ptr<WebProcessSupplement>, PtrHash<const char*>> WebProcessSupplementMap;
419     WebProcessSupplementMap m_supplements;
420
421     TextCheckerState m_textCheckerState;
422
423     RefPtr<NetworkProcessConnection> m_networkProcessConnection;
424     WebLoaderStrategy& m_webLoaderStrategy;
425
426     Ref<WebCacheStorageProvider> m_cacheStorageProvider;
427
428     std::unique_ptr<LibWebRTCNetwork> m_libWebRTCNetwork;
429
430     HashSet<String> m_dnsPrefetchedHosts;
431     PAL::HysteresisActivity m_dnsPrefetchHystereris;
432
433     std::unique_ptr<WebAutomationSessionProxy> m_automationSessionProxy;
434
435     RefPtr<WebToStorageProcessConnection> m_webToStorageProcessConnection;
436
437 #if ENABLE(NETSCAPE_PLUGIN_API)
438     RefPtr<PluginProcessConnectionManager> m_pluginProcessConnectionManager;
439 #endif
440
441 #if ENABLE(SERVICE_CONTROLS)
442     bool m_hasImageServices { false };
443     bool m_hasSelectionServices { false };
444     bool m_hasRichContentServices { false };
445 #endif
446
447     HashSet<uint64_t> m_pagesInWindows;
448     WebCore::Timer m_nonVisibleProcessCleanupTimer;
449
450     RefPtr<WebCore::ApplicationCacheStorage> m_applicationCacheStorage;
451
452     enum PageMarkingLayersAsVolatileCounterType { };
453     using PageMarkingLayersAsVolatileCounter = RefCounter<PageMarkingLayersAsVolatileCounterType>;
454     std::unique_ptr<PageMarkingLayersAsVolatileCounter> m_pageMarkingLayersAsVolatileCounter;
455     unsigned m_countOfPagesFailingToMarkVolatile { 0 };
456
457     bool m_suppressMemoryPressureHandler { false };
458 #if PLATFORM(MAC)
459     std::unique_ptr<WebCore::CPUMonitor> m_cpuMonitor;
460     std::optional<double> m_cpuLimit;
461 #endif
462
463     HashMap<WebCore::UserGestureToken *, uint64_t> m_userGestureTokens;
464
465 #if PLATFORM(WAYLAND)
466     std::unique_ptr<WaylandCompositorDisplay> m_waylandCompositorDisplay;
467 #endif
468 };
469
470 } // namespace WebKit