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