⚠ Archived content — this site is no longer maintained.   Current WebKit documentation is at docs.webkit.org.

Changeset 282368 in webkit


Ignore:
Timestamp:
Sep 13, 2021, 3:36:21 PM (5 years ago)
Author:
achristensen@apple.com
Message:

Add unit test that uses PCM daemon
https://bugs.webkit.org/show_bug.cgi?id=230191

Reviewed by Chris Dumez.

Source/WebKit:

I make a way to specify what mach service to connect to,
then I temporarily register an executable with launchd to provide that mach service,
then I run the test communicating with that executable.

  • NetworkProcess/NetworkSession.cpp:

(WebKit::managerOrProxy):

  • NetworkProcess/NetworkSessionCreationParameters.cpp:

(WebKit::NetworkSessionCreationParameters::encode const):
(WebKit::NetworkSessionCreationParameters::decode):

  • NetworkProcess/NetworkSessionCreationParameters.h:
  • NetworkProcess/PrivateClickMeasurement/PrivateClickMeasurementConnection.cpp:

(WebKit::PCM::Connection::Connection):
(WebKit::PCM::Connection::send const):
(WebKit::PCM::Connection::sendWithReply const):
(WebKit::PCM::Connection::connectionToDaemon): Deleted.
(WebKit::PCM::Connection::send): Deleted.
(WebKit::PCM::Connection::sendWithReply): Deleted.

  • NetworkProcess/PrivateClickMeasurement/PrivateClickMeasurementConnection.h:
  • NetworkProcess/PrivateClickMeasurement/PrivateClickMeasurementManagerInterface.cpp:

(WebKit::PCM::managerPointer):
(WebKit::PCM::initializePCMStorageInDirectory):
(WebKit::PCM::daemonManager):

  • NetworkProcess/PrivateClickMeasurement/PrivateClickMeasurementManagerInterface.h:
  • NetworkProcess/PrivateClickMeasurement/PrivateClickMeasurementManagerProxy.cpp:

(WebKit::PCM::ManagerProxy::sendMessage const):
(WebKit::PCM::ManagerProxy::sendMessageWithReply const):
(WebKit::PCM::ManagerProxy::ManagerProxy):
(WebKit::PCM::sendMessage): Deleted.
(WebKit::PCM::sendMessageWithReply): Deleted.

  • NetworkProcess/PrivateClickMeasurement/PrivateClickMeasurementManagerProxy.h:
  • NetworkProcess/PrivateClickMeasurement/cocoa/PrivateClickMeasurementDaemonConnectionCocoa.mm:

(WebKit::PCM::Connection::Connection):
(WebKit::PCM::Connection::initializeConnectionIfNeeded const):
(WebKit::PCM::Connection::send const):
(WebKit::PCM::Connection::sendWithReply const):
(WebKit::PCM::Connection::connectionToDaemon): Deleted.
(WebKit::PCM::Connection::send): Deleted.
(WebKit::PCM::Connection::sendWithReply): Deleted.

  • NetworkProcess/mac/com.apple.WebKit.NetworkProcess.sb.in:
  • Shared/EntryPointUtilities/Cocoa/Daemon/PCMDaemonEntryPoint.mm:

(WebKit::startListeningForMachServiceConnections):
(WebKit::registerScheduledActivityHandler):
(WebKit::PCMDaemonMain):

  • UIProcess/API/Cocoa/_WKWebsiteDataStoreConfiguration.h:
  • UIProcess/API/Cocoa/_WKWebsiteDataStoreConfiguration.mm:

(-[_WKWebsiteDataStoreConfiguration pcmMachServiceName]):
(-[_WKWebsiteDataStoreConfiguration setPCMMachServiceName:]):

  • UIProcess/WebsiteData/WebsiteDataStore.cpp:

(WebKit::WebsiteDataStore::parameters):

  • UIProcess/WebsiteData/WebsiteDataStoreConfiguration.cpp:

(WebKit::WebsiteDataStoreConfiguration::WebsiteDataStoreConfiguration):
(WebKit::WebsiteDataStoreConfiguration::copy const):

  • UIProcess/WebsiteData/WebsiteDataStoreConfiguration.h:

(WebKit::WebsiteDataStoreConfiguration::setPCMMachServiceName):
(WebKit::WebsiteDataStoreConfiguration::pcmMachServiceName const):

Source/WTF:

  • wtf/PlatformHave.h:
  • wtf/spi/darwin/XPCSPI.h:

Tools:

  • TestWebKitAPI/Configurations/TestPCMDaemon.xcconfig: Added.
  • TestWebKitAPI/TestWebKitAPI.xcodeproj/project.pbxproj:
  • TestWebKitAPI/Tests/WebKitCocoa/EventAttribution.mm:

(TestWebKitAPI::currentExecutableLocation):
(TestWebKitAPI::testDaemonPList):
(TestWebKitAPI::TEST):

  • TestWebKitAPI/cocoa/TestPCMDaemonMain.c: Copied from Source/WebKit/NetworkProcess/PrivateClickMeasurement/PrivateClickMeasurementConnection.cpp.

(main):

Location:
trunk
Files:
2 added
27 edited

Legend:

Unmodified
Added
Removed
  • trunk/Source/WTF/ChangeLog

    r282361 r282368  
     12021-09-13  Alex Christensen  <achristensen@webkit.org>
     2
     3        Add unit test that uses PCM daemon
     4        https://bugs.webkit.org/show_bug.cgi?id=230191
     5
     6        Reviewed by Chris Dumez.
     7
     8        * wtf/PlatformHave.h:
     9        * wtf/spi/darwin/XPCSPI.h:
     10
    1112021-09-13  Sihui Liu  <sihui_liu@apple.com>
    212
  • trunk/Source/WTF/wtf/PlatformHave.h

    r282221 r282368  
    814814#define HAVE_NETWORK_LOADER 1
    815815#define HAVE_SEC_TRUST_COPY_CERTIFICATE_CHAIN 1
     816#define HAVE_OS_LAUNCHD_JOB 1
    816817#endif
    817818
  • trunk/Source/WTF/wtf/spi/darwin/XPCSPI.h

    r282230 r282368  
    115115#include <os/transaction_private.h>
    116116#include <xpc/private.h>
    117 #else
     117#if HAVE(OS_LAUNCHD_JOB)
     118#include <AppServerSupport/OSLaunchdJob.h>
     119#endif // HAVE(OS_LAUNCHD_JOB)
     120#else // USE(APPLE_INTERNAL_SDK)
     121
     122#ifdef __OBJC__
     123#if HAVE(OS_LAUNCHD_JOB)
     124@interface OSLaunchdJob : NSObject
     125- (instancetype)initWithPlist:(xpc_object_t)plist;
     126- (BOOL)submit:(NSError **)errorOut;
     127@end
     128#endif // HAVE(OS_LAUNCHD_JOB)
     129#endif // __OBJC__
    118130
    119131extern "C" const char * const XPC_ACTIVITY_RANDOM_INITIAL_DELAY;
  • trunk/Source/WebKit/ChangeLog

    r282367 r282368  
     12021-09-13  Alex Christensen  <achristensen@webkit.org>
     2
     3        Add unit test that uses PCM daemon
     4        https://bugs.webkit.org/show_bug.cgi?id=230191
     5
     6        Reviewed by Chris Dumez.
     7
     8        I make a way to specify what mach service to connect to,
     9        then I temporarily register an executable with launchd to provide that mach service,
     10        then I run the test communicating with that executable.
     11
     12        * NetworkProcess/NetworkSession.cpp:
     13        (WebKit::managerOrProxy):
     14        * NetworkProcess/NetworkSessionCreationParameters.cpp:
     15        (WebKit::NetworkSessionCreationParameters::encode const):
     16        (WebKit::NetworkSessionCreationParameters::decode):
     17        * NetworkProcess/NetworkSessionCreationParameters.h:
     18        * NetworkProcess/PrivateClickMeasurement/PrivateClickMeasurementConnection.cpp:
     19        (WebKit::PCM::Connection::Connection):
     20        (WebKit::PCM::Connection::send const):
     21        (WebKit::PCM::Connection::sendWithReply const):
     22        (WebKit::PCM::Connection::connectionToDaemon): Deleted.
     23        (WebKit::PCM::Connection::send): Deleted.
     24        (WebKit::PCM::Connection::sendWithReply): Deleted.
     25        * NetworkProcess/PrivateClickMeasurement/PrivateClickMeasurementConnection.h:
     26        * NetworkProcess/PrivateClickMeasurement/PrivateClickMeasurementManagerInterface.cpp:
     27        (WebKit::PCM::managerPointer):
     28        (WebKit::PCM::initializePCMStorageInDirectory):
     29        (WebKit::PCM::daemonManager):
     30        * NetworkProcess/PrivateClickMeasurement/PrivateClickMeasurementManagerInterface.h:
     31        * NetworkProcess/PrivateClickMeasurement/PrivateClickMeasurementManagerProxy.cpp:
     32        (WebKit::PCM::ManagerProxy::sendMessage const):
     33        (WebKit::PCM::ManagerProxy::sendMessageWithReply const):
     34        (WebKit::PCM::ManagerProxy::ManagerProxy):
     35        (WebKit::PCM::sendMessage): Deleted.
     36        (WebKit::PCM::sendMessageWithReply): Deleted.
     37        * NetworkProcess/PrivateClickMeasurement/PrivateClickMeasurementManagerProxy.h:
     38        * NetworkProcess/PrivateClickMeasurement/cocoa/PrivateClickMeasurementDaemonConnectionCocoa.mm:
     39        (WebKit::PCM::Connection::Connection):
     40        (WebKit::PCM::Connection::initializeConnectionIfNeeded const):
     41        (WebKit::PCM::Connection::send const):
     42        (WebKit::PCM::Connection::sendWithReply const):
     43        (WebKit::PCM::Connection::connectionToDaemon): Deleted.
     44        (WebKit::PCM::Connection::send): Deleted.
     45        (WebKit::PCM::Connection::sendWithReply): Deleted.
     46        * NetworkProcess/mac/com.apple.WebKit.NetworkProcess.sb.in:
     47        * Shared/EntryPointUtilities/Cocoa/Daemon/PCMDaemonEntryPoint.mm:
     48        (WebKit::startListeningForMachServiceConnections):
     49        (WebKit::registerScheduledActivityHandler):
     50        (WebKit::PCMDaemonMain):
     51        * UIProcess/API/Cocoa/_WKWebsiteDataStoreConfiguration.h:
     52        * UIProcess/API/Cocoa/_WKWebsiteDataStoreConfiguration.mm:
     53        (-[_WKWebsiteDataStoreConfiguration pcmMachServiceName]):
     54        (-[_WKWebsiteDataStoreConfiguration setPCMMachServiceName:]):
     55        * UIProcess/WebsiteData/WebsiteDataStore.cpp:
     56        (WebKit::WebsiteDataStore::parameters):
     57        * UIProcess/WebsiteData/WebsiteDataStoreConfiguration.cpp:
     58        (WebKit::WebsiteDataStoreConfiguration::WebsiteDataStoreConfiguration):
     59        (WebKit::WebsiteDataStoreConfiguration::copy const):
     60        * UIProcess/WebsiteData/WebsiteDataStoreConfiguration.h:
     61        (WebKit::WebsiteDataStoreConfiguration::setPCMMachServiceName):
     62        (WebKit::WebsiteDataStoreConfiguration::pcmMachServiceName const):
     63
    1642021-09-13  Tim Horton  <timothy_horton@apple.com>
    265
  • trunk/Source/WebKit/NetworkProcess/NetworkSession.cpp

    r282305 r282368  
    9696static UniqueRef<PCM::ManagerInterface> managerOrProxy(NetworkSession& networkSession, NetworkProcess& networkProcess, const NetworkSessionCreationParameters& parameters)
    9797{
    98     // FIXME: Turn this on and remove ManagerInterface once rdar://80701098 is closed.
    99     constexpr bool usePCMDaemon = false;
    100 
    101     if (usePCMDaemon)
    102         return makeUniqueRef<PCM::ManagerProxy>();
     98    if (!parameters.pcmMachServiceName.isEmpty())
     99        return makeUniqueRef<PCM::ManagerProxy>(parameters.pcmMachServiceName);
    103100    return makeUniqueRef<PrivateClickMeasurementManager>(makeUniqueRef<PCM::ClientImpl>(networkSession, networkProcess), pcmStoreDirectory(networkSession, parameters.resourceLoadStatisticsParameters.directory, parameters.resourceLoadStatisticsParameters.privateClickMeasurementStorageDirectory));
    104101}
  • trunk/Source/WebKit/NetworkProcess/NetworkSessionCreationParameters.cpp

    r280128 r282368  
    8888    encoder << useNetworkLoader;
    8989    encoder << allowsHSTSWithUntrustedRootCertificate;
     90    encoder << pcmMachServiceName;
    9091    encoder << resourceLoadStatisticsParameters;
    9192}
     
    294295    if (!allowsHSTSWithUntrustedRootCertificate)
    295296        return std::nullopt;
    296    
     297
     298    std::optional<String> pcmMachServiceName;
     299    decoder >> pcmMachServiceName;
     300    if (!pcmMachServiceName)
     301        return std::nullopt;
     302
    297303    std::optional<ResourceLoadStatisticsParameters> resourceLoadStatisticsParameters;
    298304    decoder >> resourceLoadStatisticsParameters;
    299305    if (!resourceLoadStatisticsParameters)
    300306        return std::nullopt;
    301    
     307
    302308    return {{
    303309        *sessionID
     
    348354        , WTFMove(*useNetworkLoader)
    349355        , WTFMove(*allowsHSTSWithUntrustedRootCertificate)
     356        , WTFMove(*pcmMachServiceName)
    350357        , WTFMove(*resourceLoadStatisticsParameters)
    351358    }};
  • trunk/Source/WebKit/NetworkProcess/NetworkSessionCreationParameters.h

    r280128 r282368  
    103103    bool useNetworkLoader { false };
    104104    bool allowsHSTSWithUntrustedRootCertificate { false };
     105    String pcmMachServiceName;
    105106
    106107    ResourceLoadStatisticsParameters resourceLoadStatisticsParameters;
  • trunk/Source/WebKit/NetworkProcess/PrivateClickMeasurement/PrivateClickMeasurementConnection.cpp

    r282230 r282368  
    3535#if !PLATFORM(COCOA)
    3636
    37 Connection Connection::connectionToDaemon()
    38 {
    39     notImplemented();
    40     return { };
    41 }
    42 
    43 void Connection::send(MessageType, EncodedMessage&&)
     37Connection::Connection(CString&&)
    4438{
    4539    notImplemented();
    4640}
    4741
    48 void Connection::sendWithReply(MessageType, EncodedMessage&&, CompletionHandler<void(EncodedMessage&&)>&& completionHandler)
     42void Connection::send(MessageType, EncodedMessage&&) const
     43{
     44    notImplemented();
     45}
     46
     47void Connection::sendWithReply(MessageType, EncodedMessage&&, CompletionHandler<void(EncodedMessage&&)>&& completionHandler) const
    4948{
    5049    notImplemented();
  • trunk/Source/WebKit/NetworkProcess/PrivateClickMeasurement/PrivateClickMeasurementConnection.h

    r282230 r282368  
    2727
    2828#include <wtf/Vector.h>
     29#include <wtf/WeakPtr.h>
    2930
    3031#if PLATFORM(COCOA)
     
    4041using EncodedMessage = Vector<uint8_t>;
    4142
    42 class Connection {
     43class Connection : public CanMakeWeakPtr<Connection> {
    4344public:
    44     static Connection connectionToDaemon();
     45    explicit Connection(CString&& machServiceName);
    4546
    46     void send(MessageType, EncodedMessage&&);
    47     void sendWithReply(MessageType, EncodedMessage&&, CompletionHandler<void(EncodedMessage&&)>&&);
     47    void send(MessageType, EncodedMessage&&) const;
     48    void sendWithReply(MessageType, EncodedMessage&&, CompletionHandler<void(EncodedMessage&&)>&&) const;
    4849
    4950private:
    5051#if PLATFORM(COCOA)
    51     Connection(OSObjectPtr<xpc_connection_t>&&);
     52    void initializeConnectionIfNeeded() const;
    5253
    53     OSObjectPtr<xpc_connection_t> m_connection;
     54    const CString m_machServiceName;
     55    mutable OSObjectPtr<xpc_connection_t> m_connection;
    5456#endif
    5557};
  • trunk/Source/WebKit/NetworkProcess/PrivateClickMeasurement/PrivateClickMeasurementManagerInterface.cpp

    r282269 r282368  
    168168}
    169169
     170static std::unique_ptr<PrivateClickMeasurementManager>& managerPointer()
     171{
     172    static NeverDestroyed<std::unique_ptr<PrivateClickMeasurementManager>> manager;
     173    return manager.get();
     174}
     175
     176void initializePCMStorageInDirectory(const String& storageDirectory)
     177{
     178    ASSERT(!managerPointer());
     179    managerPointer() = makeUnique<PrivateClickMeasurementManager>(makeUniqueRef<PCM::DaemonClient>(), storageDirectory);
     180}
     181
    170182static PrivateClickMeasurementManager& daemonManager()
    171183{
    172     // FIXME: Give the manager a valid storage directory.
    173     static NeverDestroyed<PrivateClickMeasurementManager> instance(makeUniqueRef<PCM::DaemonClient>(), String());
    174     return instance.get();
     184    ASSERT(managerPointer());
     185    return *managerPointer();
    175186}
    176187
  • trunk/Source/WebKit/NetworkProcess/PrivateClickMeasurement/PrivateClickMeasurementManagerInterface.h

    r282269 r282368  
    102102bool messageTypeSendsReply(MessageType);
    103103
     104void initializePCMStorageInDirectory(const String&);
     105
    104106} // namespace PCM
    105107
  • trunk/Source/WebKit/NetworkProcess/PrivateClickMeasurement/PrivateClickMeasurementManagerProxy.cpp

    r282269 r282368  
    3636
    3737template<MessageType messageType, typename... Args>
    38 void sendMessage(Args&&... args)
     38void ManagerProxy::sendMessage(Args&&... args) const
    3939{
    4040    Encoder encoder;
    4141    encoder.encode(std::forward<Args>(args)...);
    42     Connection::connectionToDaemon().send(messageType, encoder.takeBuffer());
     42    m_connection.send(messageType, encoder.takeBuffer());
    4343}
    4444
     
    6262
    6363template<MessageType messageType, typename... Args, typename... ReplyArgs>
    64 void sendMessageWithReply(CompletionHandler<void(ReplyArgs...)>&& completionHandler, Args&&... args)
     64void ManagerProxy::sendMessageWithReply(CompletionHandler<void(ReplyArgs...)>&& completionHandler, Args&&... args) const
    6565{
    6666    Encoder encoder;
    6767    encoder.encode(std::forward<Args>(args)...);
    68     Connection::connectionToDaemon().sendWithReply(messageType, encoder.takeBuffer(), [completionHandler = WTFMove(completionHandler)] (auto replyBuffer) mutable {
     68    m_connection.sendWithReply(messageType, encoder.takeBuffer(), [completionHandler = WTFMove(completionHandler)] (auto replyBuffer) mutable {
    6969        Decoder decoder(WTFMove(replyBuffer));
    7070        ReplyCaller<ReplyArgs...>::callReply(WTFMove(decoder), WTFMove(completionHandler));
    7171    });
    7272}
     73
     74ManagerProxy::ManagerProxy(const String& machServiceName)
     75    : m_connection(machServiceName.utf8()) { }
    7376
    7477void ManagerProxy::storeUnattributed(WebCore::PrivateClickMeasurement&& pcm)
  • trunk/Source/WebKit/NetworkProcess/PrivateClickMeasurement/PrivateClickMeasurementManagerProxy.h

    r282269 r282368  
    2626#pragma once
    2727
     28#include "PrivateClickMeasurementConnection.h"
    2829#include "PrivateClickMeasurementManagerInterface.h"
    2930#include <wtf/FastMalloc.h>
     31#include <wtf/text/CString.h>
    3032
    3133namespace WebKit {
     
    3638    WTF_MAKE_FAST_ALLOCATED;
    3739public:
     40    ManagerProxy(const String& machServiceName);
     41
    3842    void storeUnattributed(WebCore::PrivateClickMeasurement&&) final;
    3943    void handleAttribution(WebCore::PrivateClickMeasurement::AttributionTriggerData&&, const URL& requestURL, WebCore::RegistrableDomain&& redirectDomain, const URL& firstPartyURL) final;
     
    5458    void destroyStoreForTesting(CompletionHandler<void()>&&) final;
    5559    void allowTLSCertificateChainForLocalPCMTesting(const WebCore::CertificateInfo&) final;
     60
     61private:
     62    template<MessageType messageType, typename... Args>
     63    void sendMessage(Args&&...) const;
     64    template<MessageType messageType, typename... Args, typename... ReplyArgs>
     65    void sendMessageWithReply(CompletionHandler<void(ReplyArgs...)>&&, Args&&...) const;
     66
     67    Connection m_connection;
    5668};
    5769
  • trunk/Source/WebKit/NetworkProcess/PrivateClickMeasurement/cocoa/PrivateClickMeasurementDaemonConnectionCocoa.mm

    r282230 r282368  
    3434namespace PCM {
    3535
    36 Connection::Connection(OSObjectPtr<xpc_connection_t>&& connection)
    37     : m_connection(WTFMove(connection)) { }
     36Connection::Connection(CString&& machServiceName)
     37    : m_machServiceName(WTFMove(machServiceName)) { }
    3838
    39 Connection Connection::connectionToDaemon()
     39void Connection::initializeConnectionIfNeeded() const
    4040{
    41     ASSERT(RunLoop::isMain());
    42     static NeverDestroyed<OSObjectPtr<xpc_connection_t>> connection;
    43     if (!connection.get()) {
    44         connection.get() = adoptOSObject(xpc_connection_create_mach_service("com.apple.webkit.adattributiond.service", dispatch_get_main_queue(), 0));
    45         xpc_connection_set_event_handler(connection.get().get(), ^(xpc_object_t event) {
    46             ASSERT(RunLoop::isMain());
    47             if (event == XPC_ERROR_CONNECTION_INTERRUPTED) {
    48                 // Daemon crashed, we will need to make a new connection to a new instance of the daemon.
    49                 connection.get() = nullptr;
    50             } else
    51                 ASSERT_NOT_REACHED();
    52         });
    53         xpc_connection_activate(connection.get().get());
    54     }
    55     return Connection(OSObjectPtr<xpc_connection_t>(connection.get()));
     41    if (m_connection)
     42        return;
     43    m_connection = adoptOSObject(xpc_connection_create_mach_service(m_machServiceName.data(), dispatch_get_main_queue(), 0));
     44    xpc_connection_set_event_handler(m_connection.get(), [weakThis = makeWeakPtr(*this)](xpc_object_t event) {
     45        if (!weakThis)
     46            return;
     47        if (event == XPC_ERROR_CONNECTION_INVALID)
     48            WTFLogAlways("Failed to connect to mach service %s, likely because it is not registered with launchd", weakThis->m_machServiceName.data());
     49        if (event == XPC_ERROR_CONNECTION_INTERRUPTED) {
     50            // Daemon crashed, we will need to make a new connection to a new instance of the daemon.
     51            weakThis->m_connection = nullptr;
     52        }
     53    });
     54    xpc_connection_activate(m_connection.get());
    5655}
    5756
     
    6463}
    6564
    66 void Connection::send(MessageType messageType, EncodedMessage&& message)
     65void Connection::send(MessageType messageType, EncodedMessage&& message) const
    6766{
    68     if (!m_connection) {
    69         ASSERT_NOT_REACHED();
    70         return;
    71     }
     67    ASSERT(RunLoop::isMain());
     68    initializeConnectionIfNeeded();
    7269
    7370    xpc_connection_send_message(m_connection.get(), dictionaryFromMessage(messageType, WTFMove(message)).get());
    7471}
    7572
    76 void Connection::sendWithReply(MessageType messageType, EncodedMessage&& message, CompletionHandler<void(EncodedMessage&&)>&& completionHandler)
     73void Connection::sendWithReply(MessageType messageType, EncodedMessage&& message, CompletionHandler<void(EncodedMessage&&)>&& completionHandler) const
    7774{
    78     if (!m_connection) {
    79         ASSERT_NOT_REACHED();
    80         return completionHandler({ });
    81     }
     75    ASSERT(RunLoop::isMain());
     76    initializeConnectionIfNeeded();
    8277
    8378    auto dictionary = dictionaryFromMessage(messageType, WTFMove(message));
    8479    xpc_connection_send_message_with_reply(m_connection.get(), dictionary.get(), dispatch_get_main_queue(), makeBlockPtr([completionHandler = WTFMove(completionHandler)] (xpc_object_t reply) mutable {
     80        ASSERT(RunLoop::isMain());
    8581        if (xpc_get_type(reply) != XPC_TYPE_DICTIONARY) {
    8682            ASSERT_NOT_REACHED();
  • trunk/Source/WebKit/NetworkProcess/mac/com.apple.WebKit.NetworkProcess.sb.in

    r282230 r282368  
    359359
    360360(allow mach-lookup (global-name "com.apple.webkit.adattributiond.service"))
     361(allow mach-lookup (global-name "org.webkit.pcmtestdaemon.service"))
    361362
    362363(with-filter (uid 0)
  • trunk/Source/WebKit/Shared/EntryPointUtilities/Cocoa/Daemon/PCMDaemonEntryPoint.mm

    r282269 r282368  
    3232#import <Foundation/Foundation.h>
    3333#import <wtf/CompletionHandler.h>
     34#import <wtf/FileSystem.h>
    3435#import <wtf/HashSet.h>
    3536#import <wtf/NeverDestroyed.h>
     
    7778}
    7879
    79 static void startListeningForMachServiceConnections()
     80static void startListeningForMachServiceConnections(const char* serviceName)
    8081{
    81     static NeverDestroyed<OSObjectPtr<xpc_connection_t>> listener = xpc_connection_create_mach_service("com.apple.webkit.adattributiond.service", dispatch_get_main_queue(), XPC_CONNECTION_MACH_SERVICE_LISTENER);
     82    static NeverDestroyed<OSObjectPtr<xpc_connection_t>> listener = xpc_connection_create_mach_service(serviceName, dispatch_get_main_queue(), XPC_CONNECTION_MACH_SERVICE_LISTENER);
    8283    xpc_connection_set_event_handler(listener.get().get(), ^(xpc_object_t peer) {
    8384        if (xpc_get_type(peer) != XPC_TYPE_CONNECTION)
     
    8788
    8889        xpc_connection_set_event_handler(peer, ^(xpc_object_t event) {
     90            if (event == XPC_ERROR_CONNECTION_INVALID)
     91                NSLog(@"Failed to start listening for connections to mach service %s, likely because it is not registered with launchd", serviceName);
    8992            if (event == XPC_ERROR_CONNECTION_INTERRUPTED) {
    9093                NSLog(@"removing peer connection %p", peer);
     
    105108static void registerScheduledActivityHandler()
    106109{
     110    NSLog(@"Registering XPC activity");
    107111    xpc_activity_register("com.apple.webkit.adattributiond.activity", XPC_ACTIVITY_CHECK_IN, ^(xpc_activity_t activity) {
    108112        if (xpc_activity_get_state(activity) == XPC_ACTIVITY_STATE_CHECK_IN) {
     
    126130int PCMDaemonMain(int argc, const char** argv)
    127131{
    128     if (argc != 2 || strcmp(argv[1], "runAsDaemon")) {
    129         NSLog(@"This executable is intended to be run as a daemon.");
     132    if (argc < 5 || strcmp(argv[1], "--machServiceName") || strcmp(argv[3], "--storageLocation")) {
     133        NSLog(@"Usage: %s --machServiceName <name> --storageLocation <location> [--startActivity]", argv[0]);
    130134        return -1;
    131135    }
     136    const char* machServiceName = argv[2];
     137    const char* storageLocation = argv[4];
     138    bool startActivity = argc > 5 && !strcmp(argv[5], "--startActivity");
     139
    132140    @autoreleasepool {
    133141        enterSandbox();
    134         startListeningForMachServiceConnections();
    135         registerScheduledActivityHandler();
     142        startListeningForMachServiceConnections(machServiceName);
     143        if (startActivity)
     144            registerScheduledActivityHandler();
    136145        WTF::initializeMainThread();
     146        PCM::initializePCMStorageInDirectory(FileSystem::stringFromFileSystemRepresentation(storageLocation));
    137147    }
    138148    CFRunLoopRun();
  • trunk/Source/WebKit/UIProcess/API/Cocoa/_WKWebsiteDataStoreConfiguration.h

    r282130 r282368  
    7777@property (nonatomic) BOOL enableInAppBrowserPrivacyForTesting WK_API_AVAILABLE(macos(12.0), ios(15.0));
    7878@property (nonatomic) BOOL allowsHSTSWithUntrustedRootCertificate WK_API_AVAILABLE(macos(12.0), ios(15.0));
     79@property (nonatomic, nullable, copy, setter=setPCMMachServiceName:) NSString *pcmMachServiceName WK_API_AVAILABLE(macos(WK_MAC_TBA), ios(WK_IOS_TBA));
    7980
    8081@property (nonatomic, nullable, copy) NSURL *alternativeServicesStorageDirectory WK_API_AVAILABLE(macos(11.0), ios(14.0));
  • trunk/Source/WebKit/UIProcess/API/Cocoa/_WKWebsiteDataStoreConfiguration.mm

    r282130 r282368  
    522522}
    523523
     524- (NSString *)pcmMachServiceName
     525{
     526    return _configuration->pcmMachServiceName();
     527}
     528
     529- (void)setPCMMachServiceName:(NSString *)name
     530{
     531    _configuration->setPCMMachServiceName(name);
     532}
     533
    524534- (BOOL)allLoadsBlockedByDeviceManagementRestrictionsForTesting
    525535{
  • trunk/Source/WebKit/UIProcess/WebsiteData/WebsiteDataStore.cpp

    r282269 r282368  
    20612061    networkSessionParameters.preventsSystemHTTPProxyAuthentication = m_configuration->preventsSystemHTTPProxyAuthentication();
    20622062    networkSessionParameters.allowsHSTSWithUntrustedRootCertificate = m_configuration->allowsHSTSWithUntrustedRootCertificate();
     2063    networkSessionParameters.pcmMachServiceName = m_configuration->pcmMachServiceName();
    20632064
    20642065    parameters.networkSessionParameters = WTFMove(networkSessionParameters);
  • trunk/Source/WebKit/UIProcess/WebsiteData/WebsiteDataStoreConfiguration.cpp

    r282130 r282368  
    5252        setModelElementCacheDirectory(WebsiteDataStore::defaultModelElementCacheDirectory());
    5353#endif
     54        // FIXME: Give m_pcmMachServiceName a default value and remove PCM::ManagerInterface once rdar://80701098 is closed.
    5455    }
    5556}
     
    101102    copy->m_enableInAppBrowserPrivacyForTesting = this->m_enableInAppBrowserPrivacyForTesting;
    102103    copy->m_allowsHSTSWithUntrustedRootCertificate = this->m_allowsHSTSWithUntrustedRootCertificate;
     104    copy->m_pcmMachServiceName = this->m_pcmMachServiceName;
    103105#if PLATFORM(COCOA)
    104106    if (m_proxyConfiguration)
  • trunk/Source/WebKit/UIProcess/WebsiteData/WebsiteDataStoreConfiguration.h

    r282130 r282368  
    181181    void setAllowsHSTSWithUntrustedRootCertificate(bool allows) { m_allowsHSTSWithUntrustedRootCertificate = allows; }
    182182   
     183    void setPCMMachServiceName(String&& name) { m_pcmMachServiceName = WTFMove(name); }
     184    const String& pcmMachServiceName() const { return m_pcmMachServiceName; }
     185
    183186private:
    184187    IsPersistent m_isPersistent { IsPersistent::No };
     
    233236    bool m_enableInAppBrowserPrivacyForTesting { false };
    234237    bool m_allowsHSTSWithUntrustedRootCertificate { false };
     238    String m_pcmMachServiceName;
    235239#if PLATFORM(COCOA)
    236240    RetainPtr<CFDictionaryRef> m_proxyConfiguration;
  • trunk/Tools/ChangeLog

    r282365 r282368  
     12021-09-13  Alex Christensen  <achristensen@webkit.org>
     2
     3        Add unit test that uses PCM daemon
     4        https://bugs.webkit.org/show_bug.cgi?id=230191
     5
     6        Reviewed by Chris Dumez.
     7
     8        * TestWebKitAPI/Configurations/TestPCMDaemon.xcconfig: Added.
     9        * TestWebKitAPI/TestWebKitAPI.xcodeproj/project.pbxproj:
     10        * TestWebKitAPI/Tests/WebKitCocoa/EventAttribution.mm:
     11        (TestWebKitAPI::currentExecutableLocation):
     12        (TestWebKitAPI::testDaemonPList):
     13        (TestWebKitAPI::TEST):
     14        * TestWebKitAPI/cocoa/TestPCMDaemonMain.c: Copied from Source/WebKit/NetworkProcess/PrivateClickMeasurement/PrivateClickMeasurementConnection.cpp.
     15        (main):
     16
    1172021-09-13  Chris Dumez  <cdumez@apple.com>
    218
  • trunk/Tools/TestWebKitAPI/Configurations/TestWebKitAPI-macOS-internal.entitlements

    r270381 r282368  
    33<plist version="1.0">
    44<dict>
     5        <key>com.apple.private.xpc.launchd.job-manager</key>
     6        <string>TestWebKitAPI</string>
    57        <key>com.apple.hid.manager.user-access-device</key>
    68        <true/>
  • trunk/Tools/TestWebKitAPI/Configurations/TestWebKitAPI-macOS.entitlements

    r270381 r282368  
    33<plist version="1.0">
    44<dict>
     5        <key>com.apple.private.xpc.launchd.job-manager</key>
     6        <string>TestWebKitAPI</string>
    57        <key>keychain-access-groups</key>
    68        <array>
  • trunk/Tools/TestWebKitAPI/Configurations/TestWebKitAPI.xcconfig

    r279479 r282368  
    4444FRAMEWORK_SEARCH_PATHS_cocoatouch = $(inherited) $(WK_PRIVATE_FRAMEWORKS_DIR);
    4545
     46WK_APPSERVERSUPPORT_LDFLAGS = $(WK_APPSERVERSUPPORT_LDFLAGS_$(WK_PLATFORM_NAME));
     47WK_APPSERVERSUPPORT_LDFLAGS_macosx = $(WK_APPSERVERSUPPORT_LDFLAGS$(WK_MACOS_1200));
     48WK_APPSERVERSUPPORT_LDFLAGS_MACOS_SINCE_1200 = -framework AppServerSupport
     49
    4650WK_AUTHKIT_LDFLAGS = $(WK_AUTHKIT_LDFLAGS_$(WK_PLATFORM_NAME));
    4751WK_AUTHKIT_LDFLAGS_iphoneos = $(WK_AUTHKIT_LDFLAGS$(WK_IOS_13));
     
    8791OTHER_CPLUSPLUSFLAGS = $(inherited) -isystem $(SDKROOT)/System/Library/Frameworks/System.framework/PrivateHeaders;
    8892
    89 OTHER_LDFLAGS = $(inherited) -lgtest -force_load $(BUILT_PRODUCTS_DIR)/libTestWebKitAPI.a -framework JavaScriptCore -framework WebKit -lWebCoreTestSupport $(WK_AUTHKIT_LDFLAGS) -framework Network $(WK_HID_LDFLAGS) $(WK_OPENGL_LDFLAGS) $(WK_PDFKIT_LDFLAGS) $(WK_SYSTEM_LDFLAGS) $(WK_UIKITMACHELPER_LDFLAGS) $(WK_VISIONKITCORE_LDFLAGS) $(OTHER_LDFLAGS_PLATFORM_$(WK_COCOA_TOUCH));
     93OTHER_LDFLAGS = $(inherited) -lgtest -force_load $(BUILT_PRODUCTS_DIR)/libTestWebKitAPI.a -framework JavaScriptCore -framework WebKit -lWebCoreTestSupport $(WK_APPSERVERSUPPORT_LDFLAGS) $(WK_AUTHKIT_LDFLAGS) -framework Network $(WK_HID_LDFLAGS) $(WK_OPENGL_LDFLAGS) $(WK_PDFKIT_LDFLAGS) $(WK_SYSTEM_LDFLAGS) $(WK_UIKITMACHELPER_LDFLAGS) $(WK_VISIONKITCORE_LDFLAGS) $(OTHER_LDFLAGS_PLATFORM_$(WK_COCOA_TOUCH));
    9094OTHER_LDFLAGS_PLATFORM_ = -framework Cocoa -framework Carbon;
    9195
  • trunk/Tools/TestWebKitAPI/TestWebKitAPI.xcodeproj/project.pbxproj

    r281779 r282368  
    3737                        );
    3838                        dependencies = (
     39                                5C1B1D1C26EC2EEC00882DA2 /* PBXTargetDependency */,
    3940                                7C83E0301D0A5E1B00FEBCF3 /* PBXTargetDependency */,
    4041                                7C83E0321D0A5E1D00FEBCF3 /* PBXTargetDependency */,
     
    479480                5C16F8FC230C94370074C4A8 /* TextSize.mm in Sources */ = {isa = PBXBuildFile; fileRef = 5C16F8FB230C942B0074C4A8 /* TextSize.mm */; };
    480481                5C19A5241FD0F60100EEA323 /* CookiePrivateBrowsing.mm in Sources */ = {isa = PBXBuildFile; fileRef = 5C19A5231FD0F32600EEA323 /* CookiePrivateBrowsing.mm */; };
     482                5C1B1D1726EC27DE00882DA2 /* TestPCMDaemonMain.c in Sources */ = {isa = PBXBuildFile; fileRef = 5C1B1D1626EC27C500882DA2 /* TestPCMDaemonMain.c */; };
    481483                5C23DF0B2246015800F454B6 /* Challenge.mm in Sources */ = {isa = PBXBuildFile; fileRef = 5C23DF0A2245C9D700F454B6 /* Challenge.mm */; };
    482484                5C2936931D5BF70D00DEAB1E /* CookieAcceptPolicy.mm in Sources */ = {isa = PBXBuildFile; fileRef = 5C2936911D5BF63E00DEAB1E /* CookieAcceptPolicy.mm */; };
     
    12981300
    12991301/* Begin PBXContainerItemProxy section */
     1302                5C1B1D1B26EC2EEC00882DA2 /* PBXContainerItemProxy */ = {
     1303                        isa = PBXContainerItemProxy;
     1304                        containerPortal = 08FB7793FE84155DC02AAC07 /* Project object */;
     1305                        proxyType = 1;
     1306                        remoteGlobalIDString = 5C1B1D0826EC278500882DA2;
     1307                        remoteInfo = TestPCMDaemon;
     1308                };
    13001309                5C9D922122D7DC84008E9266 /* PBXContainerItemProxy */ = {
    13011310                        isa = PBXContainerItemProxy;
     
    23322341                5C16F8FB230C942B0074C4A8 /* TextSize.mm */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.objcpp; path = TextSize.mm; sourceTree = "<group>"; };
    23332342                5C19A5231FD0F32600EEA323 /* CookiePrivateBrowsing.mm */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.objcpp; path = CookiePrivateBrowsing.mm; sourceTree = "<group>"; };
     2343                5C1B1D1426EC278500882DA2 /* TestPCMDaemon */ = {isa = PBXFileReference; explicitFileType = "compiled.mach-o.executable"; includeInIndex = 0; path = TestPCMDaemon; sourceTree = BUILT_PRODUCTS_DIR; };
     2344                5C1B1D1626EC27C500882DA2 /* TestPCMDaemonMain.c */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.c; name = TestPCMDaemonMain.c; path = cocoa/TestPCMDaemonMain.c; sourceTree = "<group>"; };
     2345                5C1B1D1A26EC284E00882DA2 /* TestPCMDaemon.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = TestPCMDaemon.xcconfig; sourceTree = "<group>"; };
    23342346                5C23DF0A2245C9D700F454B6 /* Challenge.mm */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.objcpp; path = Challenge.mm; sourceTree = "<group>"; };
    23352347                5C2936911D5BF63E00DEAB1E /* CookieAcceptPolicy.mm */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.objcpp; path = CookieAcceptPolicy.mm; sourceTree = "<group>"; };
     
    31633175
    31643176/* Begin PBXFrameworksBuildPhase section */
     3177                5C1B1D0E26EC278500882DA2 /* Frameworks */ = {
     3178                        isa = PBXFrameworksBuildPhase;
     3179                        buildActionMask = 2147483647;
     3180                        files = (
     3181                        );
     3182                        runOnlyForDeploymentPostprocessing = 0;
     3183                };
    31653184                7C83DF641D0A590C00FEBCF3 /* Frameworks */ = {
    31663185                        isa = PBXFrameworksBuildPhase;
     
    33073326                                2D1C04A51D76298B000A6816 /* TestNavigationDelegate.h */,
    33083327                                2D1C04A61D76298B000A6816 /* TestNavigationDelegate.mm */,
     3328                                5C1B1D1626EC27C500882DA2 /* TestPCMDaemonMain.c */,
    33093329                                516281232325C17A00BB7E42 /* TestPDFDocument.h */,
    33103330                                516281242325C17B00BB7E42 /* TestPDFDocument.mm */,
     
    33653385                        isa = PBXGroup;
    33663386                        children = (
     3387                                5C1B1D1426EC278500882DA2 /* TestPCMDaemon */,
    33673388                                8DD76FA10486AA7600D96B5E /* TestWebKitAPI */,
    33683389                                7C83E0231D0A5AE400FEBCF3 /* TestWTF */,
     
    42944315                                BC575AE2126E88B1006F0F12 /* InjectedBundle.xcconfig */,
    42954316                                A1B89B99221E029F00EB4CEA /* SDKVariant.xcconfig */,
     4317                                5C1B1D1A26EC284E00882DA2 /* TestPCMDaemon.xcconfig */,
    42964318                                5735F0251F3A4EA6000EE801 /* TestWebKitAPI-iOS.entitlements */,
    42974319                                51EB125324C66BCB000CB030 /* TestWebKitAPI-macOS-internal.entitlements */,
     
    49805002
    49815003/* Begin PBXNativeTarget section */
     5004                5C1B1D0826EC278500882DA2 /* TestPCMDaemon */ = {
     5005                        isa = PBXNativeTarget;
     5006                        buildConfigurationList = 5C1B1D1126EC278500882DA2 /* Build configuration list for PBXNativeTarget "TestPCMDaemon" */;
     5007                        buildPhases = (
     5008                                5C1B1D0B26EC278500882DA2 /* Sources */,
     5009                                5C1B1D0E26EC278500882DA2 /* Frameworks */,
     5010                        );
     5011                        buildRules = (
     5012                        );
     5013                        dependencies = (
     5014                        );
     5015                        name = TestPCMDaemon;
     5016                        productInstallPath = "$(HOME)/bin";
     5017                        productName = TestPCMDaemon;
     5018                        productReference = 5C1B1D1426EC278500882DA2 /* TestPCMDaemon */;
     5019                        productType = "com.apple.product-type.tool";
     5020                };
    49825021                7C83DE951D0A590C00FEBCF3 /* TestWTFLibrary */ = {
    49835022                        isa = PBXNativeTarget;
     
    51395178                                A13EBB481B87339E00097110 /* WebProcessPlugIn */,
    51405179                                537CF84322EFD64100C6EBB3 /* Apply Configuration to XCFileLists */,
     5180                                5C1B1D0826EC278500882DA2 /* TestPCMDaemon */,
    51415181                        );
    51425182                };
     
    52155255
    52165256/* Begin PBXSourcesBuildPhase section */
     5257                5C1B1D0B26EC278500882DA2 /* Sources */ = {
     5258                        isa = PBXSourcesBuildPhase;
     5259                        buildActionMask = 2147483647;
     5260                        files = (
     5261                                5C1B1D1726EC27DE00882DA2 /* TestPCMDaemonMain.c in Sources */,
     5262                        );
     5263                        runOnlyForDeploymentPostprocessing = 0;
     5264                };
    52175265                7C83DE961D0A590C00FEBCF3 /* Sources */ = {
    52185266                        isa = PBXSourcesBuildPhase;
     
    60796127
    60806128/* Begin PBXTargetDependency section */
     6129                5C1B1D1C26EC2EEC00882DA2 /* PBXTargetDependency */ = {
     6130                        isa = PBXTargetDependency;
     6131                        target = 5C1B1D0826EC278500882DA2 /* TestPCMDaemon */;
     6132                        targetProxy = 5C1B1D1B26EC2EEC00882DA2 /* PBXContainerItemProxy */;
     6133                };
    60816134                5C9D922222D7DC84008E9266 /* PBXTargetDependency */ = {
    60826135                        isa = PBXTargetDependency;
     
    61616214                        name = Release;
    61626215                };
     6216                5C1B1D1226EC278500882DA2 /* Debug */ = {
     6217                        isa = XCBuildConfiguration;
     6218                        baseConfigurationReference = 5C1B1D1A26EC284E00882DA2 /* TestPCMDaemon.xcconfig */;
     6219                        buildSettings = {
     6220                                PRODUCT_NAME = "$(TARGET_NAME)";
     6221                        };
     6222                        name = Debug;
     6223                };
     6224                5C1B1D1326EC278500882DA2 /* Release */ = {
     6225                        isa = XCBuildConfiguration;
     6226                        baseConfigurationReference = 5C1B1D1A26EC284E00882DA2 /* TestPCMDaemon.xcconfig */;
     6227                        buildSettings = {
     6228                                PRODUCT_NAME = "$(TARGET_NAME)";
     6229                        };
     6230                        name = Release;
     6231                };
    61636232                5C9D921A22D7DA02008E9266 /* Debug */ = {
    61646233                        isa = XCBuildConfiguration;
     
    62896358                        defaultConfigurationName = Release;
    62906359                };
     6360                5C1B1D1126EC278500882DA2 /* Build configuration list for PBXNativeTarget "TestPCMDaemon" */ = {
     6361                        isa = XCConfigurationList;
     6362                        buildConfigurations = (
     6363                                5C1B1D1226EC278500882DA2 /* Debug */,
     6364                                5C1B1D1326EC278500882DA2 /* Release */,
     6365                        );
     6366                        defaultConfigurationIsVisible = 0;
     6367                        defaultConfigurationName = Release;
     6368                };
    62916369                5C9D921922D7DA02008E9266 /* Build configuration list for PBXAggregateTarget "Generate Unified Sources" */ = {
    62926370                        isa = XCConfigurationList;
  • trunk/Tools/TestWebKitAPI/Tests/WebKitCocoa/EventAttribution.mm

    r282269 r282368  
    2828#import "HTTPServer.h"
    2929#import "PlatformUtilities.h"
     30#import "Test.h"
    3031#import "TestNavigationDelegate.h"
    3132#import "TestWKWebView.h"
    3233#import "Utilities.h"
     34#import <WebKit/WKMain.h>
    3335#import <WebKit/WKWebViewPrivate.h>
    3436#import <WebKit/WKWebViewPrivateForTesting.h>
    3537#import <WebKit/WKWebsiteDataStorePrivate.h>
    3638#import <WebKit/_WKWebsiteDataStoreConfiguration.h>
     39#import <mach-o/dyld.h>
     40#import <wtf/OSObjectPtr.h>
     41#import <wtf/spi/darwin/XPCSPI.h>
    3742
    3843#if HAVE(RSA_BSSA)
     
    361366}
    362367
     368// FIXME: Get this working in the iOS simulator.
     369#if PLATFORM(MAC)
     370
     371static RetainPtr<NSURL> currentExecutableLocation()
     372{
     373    uint32_t size { 0 };
     374    _NSGetExecutablePath(nullptr, &size);
     375    Vector<char> buffer;
     376    buffer.resize(size + 1);
     377    _NSGetExecutablePath(buffer.data(), &size);
     378    buffer[size] = '\0';
     379    auto pathString = adoptNS([[NSString alloc] initWithUTF8String:buffer.data()]);
     380    return adoptNS([[NSURL alloc] initFileURLWithPath:pathString.get() isDirectory:NO]);
     381}
     382
     383static RetainPtr<NSURL> currentExecutableDirectory()
     384{
     385    return [currentExecutableLocation() URLByDeletingLastPathComponent];
     386}
     387
     388static RetainPtr<NSURL> testPCMDaemonLocation()
     389{
     390    return [currentExecutableDirectory() URLByAppendingPathComponent:@"TestPCMDaemon" isDirectory:NO];
     391}
     392
     393#if HAVE(OS_LAUNCHD_JOB)
     394
     395static OSObjectPtr<xpc_object_t> testDaemonPList(NSURL *storageLocation)
     396{
     397    auto plist = adoptOSObject(xpc_dictionary_create(nullptr, nullptr, 0));
     398    xpc_dictionary_set_string(plist.get(), "_ManagedBy", "TestWebKitAPI");
     399    xpc_dictionary_set_string(plist.get(), "Label", "org.webkit.pcmtestdaemon");
     400    xpc_dictionary_set_bool(plist.get(), "LaunchOnlyOnce", true);
     401
     402    {
     403        auto environmentVariables = adoptOSObject(xpc_dictionary_create(nullptr, nullptr, 0));
     404        xpc_dictionary_set_string(environmentVariables.get(), "DYLD_FRAMEWORK_PATH", currentExecutableDirectory().get().fileSystemRepresentation);
     405        xpc_dictionary_set_value(plist.get(), "EnvironmentVariables", environmentVariables.get());
     406    }
     407    {
     408        auto machServices = adoptOSObject(xpc_dictionary_create(nullptr, nullptr, 0));
     409        xpc_dictionary_set_bool(machServices.get(), "org.webkit.pcmtestdaemon.service", true);
     410        xpc_dictionary_set_value(plist.get(), "MachServices", machServices.get());
     411    }
     412    {
     413        auto programArguments = adoptOSObject(xpc_array_create(nullptr, 0));
     414        auto executableLocation = testPCMDaemonLocation();
     415        xpc_array_set_string(programArguments.get(), XPC_ARRAY_APPEND, executableLocation.get().fileSystemRepresentation);
     416        xpc_array_set_string(programArguments.get(), XPC_ARRAY_APPEND, "--machServiceName");
     417        xpc_array_set_string(programArguments.get(), XPC_ARRAY_APPEND, "org.webkit.pcmtestdaemon.service");
     418        xpc_array_set_string(programArguments.get(), XPC_ARRAY_APPEND, "--storageLocation");
     419        xpc_array_set_string(programArguments.get(), XPC_ARRAY_APPEND, storageLocation.fileSystemRepresentation);
     420        xpc_dictionary_set_value(plist.get(), "ProgramArguments", programArguments.get());
     421    }
     422    return plist;
     423}
     424
     425#else
     426
     427static RetainPtr<NSDictionary> testDaemonPList(NSURL *storageLocation)
     428{
     429    return @{
     430        @"Label" : @"org.webkit.pcmtestdaemon",
     431        @"LaunchOnlyOnce" : @YES,
     432        @"EnvironmentVariables" : @{ @"DYLD_FRAMEWORK_PATH" : currentExecutableDirectory().get().path },
     433        @"MachServices" : @{ @"org.webkit.pcmtestdaemon.service" : @YES },
     434        @"ProgramArguments" : @[
     435            testPCMDaemonLocation().get().path,
     436            @"--machServiceName",
     437            @"org.webkit.pcmtestdaemon.service",
     438            @"--storageLocation",
     439            storageLocation.path
     440        ]
     441    };
     442}
     443
     444#endif
     445
     446TEST(EventAttribution, Daemon)
     447{
     448    NSFileManager *fileManager = [NSFileManager defaultManager];
     449    NSURL *tempDir = [NSURL fileURLWithPath:[NSTemporaryDirectory() stringByAppendingPathComponent:@"EventAttributionDaemonTest"] isDirectory:YES];
     450    NSError *error = nil;
     451    if ([fileManager fileExistsAtPath:tempDir.path])
     452        [fileManager removeItemAtURL:tempDir error:&error];
     453    EXPECT_NULL(error);
     454
     455    auto plist = testDaemonPList(tempDir);
     456#if HAVE(OS_LAUNCHD_JOB)
     457    auto launchDJob = adoptNS([[OSLaunchdJob alloc] initWithPlist:plist.get()]);
     458    [launchDJob submit:&error];
     459#else
     460    NSURL *plistLocation = [tempDir URLByAppendingPathComponent:@"DaemonInfo.plist"];
     461    BOOL success = [fileManager createDirectoryAtURL:tempDir withIntermediateDirectories:YES attributes:nil error:&error];
     462    EXPECT_TRUE(success);
     463    EXPECT_NULL(error);
     464    success = [plist writeToURL:plistLocation error:&error];
     465    EXPECT_TRUE(success);
     466    system([NSString stringWithFormat:@"launchctl load %@", plistLocation.path].UTF8String);
     467#endif
     468    EXPECT_NULL(error);
     469
     470    auto dataStoreConfiguration = adoptNS([_WKWebsiteDataStoreConfiguration new]);
     471    dataStoreConfiguration.get().pcmMachServiceName = @"org.webkit.pcmtestdaemon.service";
     472    auto viewConfiguration = adoptNS([WKWebViewConfiguration new]);
     473    viewConfiguration.get().websiteDataStore = adoptNS([[WKWebsiteDataStore alloc] _initWithConfiguration:dataStoreConfiguration.get()]).get();
     474    runBasicEventAttributionTest(viewConfiguration.get(), [](WKWebView *webView, const HTTPServer& server) {
     475        [webView _addEventAttributionWithSourceID:42 destinationURL:exampleURL() sourceDescription:@"test source description" purchaser:@"test purchaser" reportEndpoint:server.request().URL optionalNonce:nil];
     476    });
     477
     478    system("killall TestPCMDaemon -9");
     479#if HAVE(OS_LAUNCHD_JOB)
     480    // LaunchOnlyOnce takes care of cleanup with launchd.
     481#else
     482    system([NSString stringWithFormat:@"launchctl unload %@", plistLocation.path].UTF8String);
     483#endif
     484
     485    EXPECT_TRUE([fileManager fileExistsAtPath:tempDir.path]);
     486    [fileManager removeItemAtURL:tempDir error:&error];
     487    EXPECT_NULL(error);
     488}
     489
     490#endif // PLATFORM(MAC)
     491
    363492#if HAVE(UI_EVENT_ATTRIBUTION)
    364493
Note: See TracChangeset for help on using the changeset viewer.