Title: [285548] trunk
Revision
285548
Author
commit-qu...@webkit.org
Date
2021-11-09 17:09:29 -0800 (Tue, 09 Nov 2021)

Log Message

Unreviewed, reverting r285536.
https://bugs.webkit.org/show_bug.cgi?id=232915

causes API test crashes

Reverted changeset:

"[CF] Reduce duplication and unneeded buffer allocations and
copying in URL code, also remove unused methods and functions"
https://bugs.webkit.org/show_bug.cgi?id=232220
https://commits.webkit.org/r285536

Modified Paths

Diff

Modified: trunk/Source/WTF/ChangeLog (285547 => 285548)


--- trunk/Source/WTF/ChangeLog	2021-11-10 01:05:06 UTC (rev 285547)
+++ trunk/Source/WTF/ChangeLog	2021-11-10 01:09:29 UTC (rev 285548)
@@ -1,5 +1,19 @@
 2021-11-09  Commit Queue  <commit-qu...@webkit.org>
 
+        Unreviewed, reverting r285536.
+        https://bugs.webkit.org/show_bug.cgi?id=232915
+
+        causes API test crashes
+
+        Reverted changeset:
+
+        "[CF] Reduce duplication and unneeded buffer allocations and
+        copying in URL code, also remove unused methods and functions"
+        https://bugs.webkit.org/show_bug.cgi?id=232220
+        https://commits.webkit.org/r285536
+
+2021-11-09  Commit Queue  <commit-qu...@webkit.org>
+
         Unreviewed, reverting r285246.
         https://bugs.webkit.org/show_bug.cgi?id=232907
 

Modified: trunk/Source/WTF/wtf/URL.h (285547 => 285548)


--- trunk/Source/WTF/wtf/URL.h	2021-11-10 01:05:06 UTC (rev 285547)
+++ trunk/Source/WTF/wtf/URL.h	2021-11-10 01:09:29 UTC (rev 285548)
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2003-2021 Apple Inc. All rights reserved.
+ * Copyright (C) 2003-2019 Apple Inc. All rights reserved.
  *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
@@ -25,6 +25,8 @@
 
 #pragma once
 
+#include <wtf/Forward.h>
+#include <wtf/RetainPtr.h>
 #include <wtf/text/WTFString.h>
 
 #if USE(GLIB) && HAVE(GURI)
@@ -48,7 +50,7 @@
 public:
     virtual Vector<uint8_t> encodeForURLParsing(StringView) const = 0;
 protected:
-    virtual ~URLTextEncoding() = default;
+    virtual ~URLTextEncoding() { }
 };
 
 class URL {
@@ -80,7 +82,7 @@
     bool isEmpty() const;
     bool isValid() const;
 
-    // Since we overload operator NSURL * we have this to prevent accidentally using that operator
+    // Since we overload operator NSURL* we have this to prevent accidentally using that operator
     // when placing a URL in an if statment.
     operator bool() const = delete;
 
@@ -193,9 +195,8 @@
 #ifndef NDEBUG
     void print() const;
 #endif
+    WTF_EXPORT_PRIVATE void dump(PrintStream& out) const;
 
-    WTF_EXPORT_PRIVATE void dump(PrintStream&) const;
-
     template<typename Encoder> void encode(Encoder&) const;
     template<typename Decoder> static WARN_UNUSED_RETURN bool decode(Decoder&, URL&);
     template<typename Decoder> static std::optional<URL> decode(Decoder&);
@@ -213,10 +214,6 @@
 
     friend WTF_EXPORT_PRIVATE bool protocolHostAndPortAreEqual(const URL&, const URL&);
 
-#if USE(CF)
-    static RetainPtr<CFURLRef> emptyCFURL();
-#endif
-
     String m_string;
 
     unsigned m_isValid : 1;

Modified: trunk/Source/WTF/wtf/cf/CFURLExtras.cpp (285547 => 285548)


--- trunk/Source/WTF/wtf/cf/CFURLExtras.cpp	2021-11-10 01:05:06 UTC (rev 285547)
+++ trunk/Source/WTF/wtf/cf/CFURLExtras.cpp	2021-11-10 01:09:29 UTC (rev 285548)
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2013-2021 Apple Inc. All rights reserved.
+ * Copyright (C) 2013 Apple Inc. All rights reserved.
  *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
@@ -27,63 +27,43 @@
 #include <wtf/cf/CFURLExtras.h>
 
 #include <wtf/URL.h>
+#include <wtf/text/CString.h>
 
 namespace WTF {
 
-RetainPtr<CFDataRef> bytesAsCFData(CFURLRef url)
+void getURLBytes(CFURLRef url, URLCharBuffer& result)
 {
-    auto bytesLength = CFURLGetBytes(url, nullptr, 0);
-    RELEASE_ASSERT(bytesLength != -1);
-    auto buffer = static_cast<uint8_t*>(malloc(bytesLength));
-    RELEASE_ASSERT(buffer);
-    CFURLGetBytes(url, buffer, bytesLength);
-    return adoptCF(CFDataCreateWithBytesNoCopy(nullptr, buffer, bytesLength, kCFAllocatorMalloc));
+    CFIndex bytesLength = CFURLGetBytes(url, nullptr, 0);
+    result.resize(bytesLength);
+    CFIndex finalLength = CFURLGetBytes(url, reinterpret_cast<UInt8*>(result.data()), bytesLength);
+    ASSERT_UNUSED(finalLength, finalLength == bytesLength);
 }
 
-String bytesAsString(CFURLRef url)
+void getURLBytes(CFURLRef url, CString& result)
 {
-    auto bytesLength = CFURLGetBytes(url, nullptr, 0);
-    RELEASE_ASSERT(bytesLength != -1);
-    RELEASE_ASSERT(bytesLength <= static_cast<CFIndex>(String::MaxLength));
-    LChar* buffer;
-    auto result = String::createUninitialized(bytesLength, buffer);
-    CFURLGetBytes(url, buffer, bytesLength);
-    return result;
+    CFIndex bytesLength = CFURLGetBytes(url, nullptr, 0);
+    char* bytes;
+    result = CString::newUninitialized(bytesLength, bytes);
+    CFIndex finalLength = CFURLGetBytes(url, reinterpret_cast<UInt8*>(bytes), bytesLength);
+    ASSERT_UNUSED(finalLength, finalLength == bytesLength);
 }
 
-Vector<uint8_t, URLBytesVectorInlineCapacity> bytesAsVector(CFURLRef url)
+bool isCFURLSameOrigin(CFURLRef cfURL, const URL& url)
 {
-    Vector<uint8_t, URLBytesVectorInlineCapacity> result(URLBytesVectorInlineCapacity);
-    auto bytesLength = CFURLGetBytes(url, result.data(), URLBytesVectorInlineCapacity);
-    if (bytesLength != -1)
-        result.shrink(bytesLength);
-    else {
-        bytesLength = CFURLGetBytes(url, nullptr, 0);
-        RELEASE_ASSERT(bytesLength != -1);
-        result.grow(bytesLength);
-        CFURLGetBytes(url, result.data(), bytesLength);
-    }
+    ASSERT(url.protocolIsInHTTPFamily());
 
-    // This may look like it copies the bytes in the vector, but due to the return value optimization it does not.
-    return result;
-}
+    if (url.hasCredentials())
+        return protocolHostAndPortAreEqual(url, URL { cfURL });
 
-bool isSameOrigin(CFURLRef a, const URL& b)
-{
-    ASSERT(b.protocolIsInHTTPFamily());
+    URLCharBuffer bytes;
+    getURLBytes(cfURL, bytes);
+    StringView cfURLString { reinterpret_cast<const LChar*>(bytes.data()), static_cast<unsigned>(bytes.size()) };
 
-    if (b.hasCredentials())
-        return protocolHostAndPortAreEqual(a, b);
+    if (!url.hasPath())
+        return StringView { url.string() } == cfURLString;
 
-    auto aBytes = bytesAsVector(a);
-    StringView aString { aBytes.data(), static_cast<unsigned>(aBytes.size()) };
-    StringView bString { b.string() };
-
-    if (!b.hasPath())
-        return aString == bString;
-
-    unsigned afterPathSeparator = b.pathStart() + 1;
-    return aString.left(afterPathSeparator) == bString.left(afterPathSeparator);
+    auto urlWithoutPath = StringView { url.string() }.substring(0, url.pathStart() + 1);
+    return cfURLString.startsWith(urlWithoutPath);
 }
 
 }

Modified: trunk/Source/WTF/wtf/cf/CFURLExtras.h (285547 => 285548)


--- trunk/Source/WTF/wtf/cf/CFURLExtras.h	2021-11-10 01:05:06 UTC (rev 285547)
+++ trunk/Source/WTF/wtf/cf/CFURLExtras.h	2021-11-10 01:09:29 UTC (rev 285548)
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2013-2021 Apple Inc. All rights reserved.
+ * Copyright (C) 2013 Apple Inc. All rights reserved.
  *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
@@ -26,22 +26,17 @@
 #pragma once
 
 #include <wtf/Forward.h>
+#include <wtf/RetainPtr.h>
+#include <wtf/Vector.h>
 
-typedef const struct __CFData* CFDataRef;
-typedef const struct __CFURL* CFURLRef;
-
 namespace WTF {
 
-constexpr size_t URLBytesVectorInlineCapacity = 2048;
+class URL;
+typedef Vector<char, 512> URLCharBuffer;
 
-RetainPtr<CFDataRef> bytesAsCFData(CFURLRef);
-WTF_EXPORT_PRIVATE String bytesAsString(CFURLRef);
-WTF_EXPORT_PRIVATE Vector<uint8_t, URLBytesVectorInlineCapacity> bytesAsVector(CFURLRef);
+WTF_EXPORT_PRIVATE void getURLBytes(CFURLRef, URLCharBuffer&);
+WTF_EXPORT_PRIVATE void getURLBytes(CFURLRef, CString&);
 
-bool isSameOrigin(CFURLRef, const URL&);
+bool isCFURLSameOrigin(CFURLRef, const URL&);
 
 }
-
-using WTF::bytesAsCFData;
-using WTF::bytesAsString;
-using WTF::bytesAsVector;

Modified: trunk/Source/WTF/wtf/cf/URLCF.cpp (285547 => 285548)


--- trunk/Source/WTF/wtf/cf/URLCF.cpp	2021-11-10 01:05:06 UTC (rev 285547)
+++ trunk/Source/WTF/wtf/cf/URLCF.cpp	2021-11-10 01:09:29 UTC (rev 285548)
@@ -35,47 +35,39 @@
 
 URL::URL(CFURLRef url)
 {
-    // FIXME: Why is it OK to ignore the base URL in the CFURL here?
-    if (!url)
+    if (!url) {
         invalidate();
-    else
-        *this = URLParser(bytesAsString(url)).result();
+        return;
+    }
+
+    // FIXME: Why is it OK to ignore base URL here?
+    CString urlBytes;
+    getURLBytes(url, urlBytes);
+    URLParser parser(urlBytes.data());
+    *this = parser.result();
 }
 
 #if !USE(FOUNDATION)
-
-RetainPtr<CFURLRef> URL::emptyCFURL()
-{
-    return nullptr;
-}
-
-#endif
-
 RetainPtr<CFURLRef> URL::createCFURL() const
 {
-    if (isNull())
-        return nullptr;
-
-    if (isEmpty())
-        return emptyCFURL();
-
-    RetainPtr<CFURLRef> result;
+    RetainPtr<CFURLRef> cfURL;
     if (LIKELY(m_string.is8Bit() && m_string.isAllASCII()))
-        result = adoptCF(CFURLCreateAbsoluteURLWithBytes(nullptr, m_string.characters8(), m_string.length(), kCFStringEncodingUTF8, nullptr, true));
+        cfURL = adoptCF(CFURLCreateAbsoluteURLWithBytes(nullptr, m_string.characters8(), m_string.length(), kCFStringEncodingUTF8, nullptr, true));
     else {
         CString utf8 = m_string.utf8();
-        result = adoptCF(CFURLCreateAbsoluteURLWithBytes(nullptr, utf8.dataAsUInt8Ptr(), utf8.length(), kCFStringEncodingUTF8, nullptr, true));
+        cfURL = adoptCF(CFURLCreateAbsoluteURLWithBytes(nullptr, utf8.dataAsUInt8Ptr(), utf8.length(), kCFStringEncodingUTF8, nullptr, true));
     }
 
-    if (protocolIsInHTTPFamily() && !isSameOrigin(result.get(), *this))
+    if (protocolIsInHTTPFamily() && !isCFURLSameOrigin(cfURL.get(), *this))
         return nullptr;
 
-    return result;
+    return cfURL;
 }
+#endif
 
 String URL::fileSystemPath() const
 {
-    auto cfURL = createCFURL();
+    RetainPtr<CFURLRef> cfURL = createCFURL();
     if (!cfURL)
         return String();
 

Modified: trunk/Source/WTF/wtf/cocoa/NSURLExtras.h (285547 => 285548)


--- trunk/Source/WTF/wtf/cocoa/NSURLExtras.h	2021-11-10 01:05:06 UTC (rev 285547)
+++ trunk/Source/WTF/wtf/cocoa/NSURLExtras.h	2021-11-10 01:09:29 UTC (rev 285548)
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2005-2021 Apple, Inc. All rights reserved.
+ * Copyright (C) 2005, 2007, 2012, 2014 Apple, Inc. All rights reserved.
  *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
@@ -33,7 +33,7 @@
 namespace WTF {
 
 WTF_EXPORT_PRIVATE NSString *userVisibleString(NSURL *);
-WTF_EXPORT_PRIVATE NSURL *URLWithUserTypedString(NSString *, NSURL *ignored = nil); // Return value of nil means error.
+WTF_EXPORT_PRIVATE NSURL *URLWithUserTypedString(NSString *, NSURL *baseURL); // Return value of nil means error.
 WTF_EXPORT_PRIVATE NSURL *URLByRemovingUserInfo(NSURL *);
 WTF_EXPORT_PRIVATE NSString *decodeHostName(NSString *); // Return value of nil means error.
 WTF_EXPORT_PRIVATE NSString *encodeHostName(NSString *); // Return value of nil means error.
@@ -41,8 +41,10 @@
 WTF_EXPORT_PRIVATE NSURL *URLWithData(NSData *, NSURL *baseURL);
 WTF_EXPORT_PRIVATE NSData *originalURLData(NSURL *);
 WTF_EXPORT_PRIVATE NSData *dataForURLComponentType(NSURL *, CFURLComponentType);
-WTF_EXPORT_PRIVATE NSURL *URLWithUserTypedStringDeprecated(NSString *);
+WTF_EXPORT_PRIVATE NSURL *URLWithUserTypedStringDeprecated(NSString *, NSURL *baseURL);
 
+NSRange rangeOfURLScheme(NSString *);
 WTF_EXPORT_PRIVATE BOOL isUserVisibleURL(NSString *);
+WTF_EXPORT_PRIVATE BOOL looksLikeAbsoluteURL(NSString *);
 
 } // namespace WTF

Modified: trunk/Source/WTF/wtf/cocoa/NSURLExtras.mm (285547 => 285548)


--- trunk/Source/WTF/wtf/cocoa/NSURLExtras.mm	2021-11-10 01:05:06 UTC (rev 285547)
+++ trunk/Source/WTF/wtf/cocoa/NSURLExtras.mm	2021-11-10 01:09:29 UTC (rev 285548)
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2005-2021 Apple Inc. All rights reserved.
+ * Copyright (C) 2005, 2007, 2014 Apple Inc. All rights reserved.
  *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
@@ -32,14 +32,17 @@
 #import <mutex>
 #import <wtf/Function.h>
 #import <wtf/RetainPtr.h>
-#import <wtf/URL.h>
 #import <wtf/URLHelpers.h>
+#import <wtf/URLParser.h>
 #import <wtf/Vector.h>
 #import <wtf/cf/CFURLExtras.h>
-#import <wtf/cocoa/TypeCastsCocoa.h>
 
 namespace WTF {
 
+using namespace URLHelpers;
+
+constexpr unsigned urlBytesBufferLength = 2048;
+
 static BOOL readIDNAllowedScriptListFile(NSString *filename)
 {
     if (!filename)
@@ -64,7 +67,7 @@
         
         if (result == 1) {
             // Got a word, map to script code and put it into the array.
-            URLHelpers::addScriptToIDNAllowedScriptList(word);
+            addScriptToIDNAllowedScriptList(word);
         }
     }
     fclose(file);
@@ -97,7 +100,7 @@
 
 NSString *decodeHostName(NSString *string)
 {
-    std::optional<String> host = URLHelpers::mapHostName(string, nullptr);
+    std::optional<String> host = mapHostName(string, nullptr);
     if (!host)
         return nil;
     return !*host ? string : (NSString *)*host;
@@ -105,7 +108,7 @@
 
 NSString *encodeHostName(NSString *string)
 {
-    std::optional<String> host = URLHelpers::mapHostName(string, decodePercentEscapes);
+    std::optional<String> host = mapHostName(string, decodePercentEscapes);
     if (!host)
         return nil;
     return !*host ? string : (NSString *)*host;
@@ -123,19 +126,30 @@
     if (!URL)
         return nil;
     
-    CFRange range = CFURLGetByteRangeForComponent(bridge_cast(URL), component, nullptr);
-    if (range.location == kCFNotFound)
+    CFRange fragRg = CFURLGetByteRangeForComponent((__bridge CFURLRef)URL, component, nullptr);
+    if (fragRg.location == kCFNotFound)
         return URL;
 
-    auto bytes = bytesAsVector(bridge_cast(URL));
+    Vector<UInt8, urlBytesBufferLength> urlBytes(urlBytesBufferLength);
+    CFIndex numBytes = CFURLGetBytes((__bridge CFURLRef)URL, urlBytes.data(), urlBytes.size());
+    if (numBytes == -1) {
+        numBytes = CFURLGetBytes((__bridge CFURLRef)URL, nullptr, 0);
+        urlBytes.grow(numBytes);
+        CFURLGetBytes((__bridge CFURLRef)URL, urlBytes.data(), numBytes);
+    }
 
-    auto result = adoptCF(CFURLCreateWithBytes(nullptr, bytes.data(), range.location - 1, kCFStringEncodingUTF8, nullptr));
+    auto result = adoptCF(CFURLCreateWithBytes(nullptr, urlBytes.data(), fragRg.location - 1, kCFStringEncodingUTF8, nullptr));
     if (!result)
-        result = adoptCF(CFURLCreateWithBytes(nullptr, bytes.data(), range.location - 1, kCFStringEncodingISOLatin1, nullptr));
-
+        result = adoptCF(CFURLCreateWithBytes(nullptr, urlBytes.data(), fragRg.location - 1, kCFStringEncodingISOLatin1, nullptr));
+        
     return result ? result.bridgingAutorelease() : URL;
 }
 
+static NSURL *URLByRemovingResourceSpecifier(NSURL *URL)
+{
+    return URLByTruncatingOneCharacterBeforeComponent(URL, kCFURLComponentResourceSpecifier);
+}
+
 NSURL *URLWithData(NSData *data, NSURL *baseURL)
 {
     if (!data)
@@ -143,15 +157,15 @@
     
     size_t length = [data length];
     if (length > 0) {
-        // Work around <rdar://4470771>: CFURLCreateAbsoluteURLWithBytes(.., TRUE) doesn't remove non-path components.
-        baseURL = URLByTruncatingOneCharacterBeforeComponent(baseURL, kCFURLComponentResourceSpecifier);
-
+        // work around <rdar://4470771>: CFURLCreateAbsoluteURLWithBytes(.., TRUE) doesn't remove non-path components.
+        baseURL = URLByRemovingResourceSpecifier(baseURL);
+        
         const UInt8 *bytes = static_cast<const UInt8*>([data bytes]);
-
+        
         // CFURLCreateAbsoluteURLWithBytes would complain to console if we passed a path to it.
         if (bytes[0] == '/' && !baseURL)
             return nil;
-
+        
         // NOTE: We use UTF-8 here since this encoding is used when computing strings when returning URL components
         // (e.g calls to NSURL -path). However, this function is not tolerant of illegal UTF-8 sequences, which
         // could either be a malformed string or bytes in a different encoding, like shift-jis, so we fall back
@@ -163,7 +177,6 @@
     }
     return [NSURL URLWithString:@""];
 }
-
 static NSData *dataWithUserTypedString(NSString *string)
 {
     NSData *userTypedData = [string dataUsingEncoding:NSUTF8StringEncoding];
@@ -198,17 +211,17 @@
     return [NSData dataWithBytesNoCopy:outBytes length:outLength]; // adopts outBytes
 }
 
-NSURL *URLWithUserTypedString(NSString *string, NSURL *)
+NSURL *URLWithUserTypedString(NSString *string, NSURL *nsURL)
 {
     if (!string)
         return nil;
 
-    auto mappedString = URLHelpers::mapHostNames(stringByTrimmingWhitespace(string).get(), decodePercentEscapes);
+    auto mappedString = mapHostNames(stringByTrimmingWhitespace(string).get(), decodePercentEscapes);
     if (!mappedString)
         return nil;
 
     // Let's check whether the URL is bogus.
-    URL url { URL { }, mappedString };
+    URL url { URL { nsURL }, mappedString };
     if (!url.createCFURL())
         return nil;
 
@@ -218,86 +231,113 @@
     if (!data)
         return [NSURL URLWithString:@""];
 
-    return URLWithData(data, nil);
+    return URLWithData(data, nsURL);
 }
 
-NSURL *URLWithUserTypedStringDeprecated(NSString *string)
+NSURL *URLWithUserTypedStringDeprecated(NSString *string, NSURL *URL)
 {
     if (!string)
         return nil;
 
-    NSURL *result = URLWithUserTypedString(string);
+    NSURL *result = URLWithUserTypedString(string, URL);
     if (!result) {
         NSData *resultData = dataWithUserTypedString(string);
         if (!resultData)
             return [NSURL URLWithString:@""];
-        result = URLWithData(resultData, nil);
+        result = URLWithData(resultData, URL);
     }
 
     return result;
 }
 
-static bool hasQuestionMarkOnlyQueryString(NSURL *URL)
+static BOOL hasQuestionMarkOnlyQueryString(NSURL *URL)
 {
     CFRange rangeWithSeparators;
-    CFURLGetByteRangeForComponent(bridge_cast(URL), kCFURLComponentQuery, &rangeWithSeparators);
-    return rangeWithSeparators.location != kCFNotFound && rangeWithSeparators.length == 1;
+    CFURLGetByteRangeForComponent((__bridge CFURLRef)URL, kCFURLComponentQuery, &rangeWithSeparators);
+    if (rangeWithSeparators.location != kCFNotFound && rangeWithSeparators.length == 1)
+        return YES;
+
+    return NO;
 }
 
 NSData *dataForURLComponentType(NSURL *URL, CFURLComponentType componentType)
 {
-    CFRange range = CFURLGetByteRangeForComponent(bridge_cast(URL), componentType, nullptr);
-    if (range.location == kCFNotFound)
-        return nil;
-
-    auto bytesBuffer = bytesAsVector(bridge_cast(URL));
-    auto bytes = bytesBuffer.data() + range.location;
-
-    NSMutableData *result = [NSMutableData data];
-
-    // We add leading '?' to non-zero length query strings including question-mark only query strings.
+    Vector<UInt8, urlBytesBufferLength> allBytesBuffer(urlBytesBufferLength);
+    CFIndex bytesFilled = CFURLGetBytes((__bridge CFURLRef)URL, allBytesBuffer.data(), allBytesBuffer.size());
+    if (bytesFilled == -1) {
+        CFIndex bytesToAllocate = CFURLGetBytes((__bridge CFURLRef)URL, nullptr, 0);
+        allBytesBuffer.grow(bytesToAllocate);
+        bytesFilled = CFURLGetBytes((__bridge CFURLRef)URL, allBytesBuffer.data(), bytesToAllocate);
+    }
+    
+    const CFURLComponentType completeURL = (CFURLComponentType)-1;
+    CFRange range;
+    if (componentType != completeURL) {
+        range = CFURLGetByteRangeForComponent((__bridge CFURLRef)URL, componentType, nullptr);
+        if (range.location == kCFNotFound)
+            return nil;
+    } else {
+        range.location = 0;
+        range.length = bytesFilled;
+    }
+    
+    NSData *componentData = [NSData dataWithBytes:allBytesBuffer.data() + range.location length:range.length]; 
+    
+    const unsigned char *bytes = static_cast<const unsigned char *>([componentData bytes]);
+    NSMutableData *resultData = [NSMutableData data];
+    // NOTE: add leading '?' to query strings non-zero length query strings.
+    // NOTE: retain question-mark only query strings.
     if (componentType == kCFURLComponentQuery) {
-        if (range.length || hasQuestionMarkOnlyQueryString(URL))
-            [result appendBytes:"?" length:1];
+        if (range.length > 0 || hasQuestionMarkOnlyQueryString(URL))
+            [resultData appendBytes:"?" length:1];    
     }
-
-    for (CFIndex i = 0; i < range.length; i++) {
+    for (int i = 0; i < range.length; i++) {
         unsigned char c = bytes[i];
-        if (c > 0x20 && c < 0x7F)
-            [result appendBytes:&bytes[i] length:1];
-        else {
-            char escaped[3] = { '%', upperNibbleToASCIIHexDigit(c), lowerNibbleToASCIIHexDigit(c) };
-            [result appendBytes:escaped length:3];
-        }
+        if (c <= 0x20 || c >= 0x7f) {
+            char escaped[3];
+            escaped[0] = '%';
+            escaped[1] = upperNibbleToASCIIHexDigit(c);
+            escaped[2] = lowerNibbleToASCIIHexDigit(c);
+            [resultData appendBytes:escaped length:3];    
+        } else {
+            char b[1];
+            b[0] = c;
+            [resultData appendBytes:b length:1];    
+        }               
     }
-
-    return result;
+    
+    return resultData;
 }
 
 static NSURL *URLByRemovingComponentAndSubsequentCharacter(NSURL *URL, CFURLComponentType component)
 {
-    CFRange range = CFURLGetByteRangeForComponent(bridge_cast(URL), component, 0);
+    CFRange range = CFURLGetByteRangeForComponent((__bridge CFURLRef)URL, component, 0);
     if (range.location == kCFNotFound)
         return URL;
-
+    
     // Remove one subsequent character.
     range.length++;
 
-    auto bytes = bytesAsVector(bridge_cast(URL));
-    auto urlBytes = bytes.data();
-    CFIndex numBytes = bytes.size();
-
+    Vector<UInt8, urlBytesBufferLength> buffer(urlBytesBufferLength);
+    CFIndex numBytes = CFURLGetBytes((__bridge CFURLRef)URL, buffer.data(), buffer.size());
+    if (numBytes == -1) {
+        numBytes = CFURLGetBytes((__bridge CFURLRef)URL, nullptr, 0);
+        buffer.grow(numBytes);
+        CFURLGetBytes((__bridge CFURLRef)URL, buffer.data(), numBytes);
+    }
+    UInt8* urlBytes = buffer.data();
+        
     if (numBytes < range.location)
         return URL;
     if (numBytes < range.location + range.length)
         range.length = numBytes - range.location;
-
+        
     memmove(urlBytes + range.location, urlBytes + range.location + range.length, numBytes - range.location + range.length);
-
+    
     auto result = adoptCF(CFURLCreateWithBytes(nullptr, urlBytes, numBytes - range.length, kCFStringEncodingUTF8, nullptr));
     if (!result)
         result = adoptCF(CFURLCreateWithBytes(nullptr, urlBytes, numBytes - range.length, kCFStringEncodingISOLatin1, nullptr));
-
+                
     return result ? result.bridgingAutorelease() : URL;
 }
 
@@ -308,42 +348,97 @@
 
 NSData *originalURLData(NSURL *URL)
 {
-    auto data = ""
-    if (auto baseURL = bridge_cast(CFURLGetBaseURL(bridge_cast(URL))))
-        return originalURLData(URLWithData(data.get(), baseURL));
-    return data.autorelease();
+    UInt8 *buffer = (UInt8 *)malloc(urlBytesBufferLength);
+    CFIndex bytesFilled = CFURLGetBytes((__bridge CFURLRef)URL, buffer, urlBytesBufferLength);
+    if (bytesFilled == -1) {
+        CFIndex bytesToAllocate = CFURLGetBytes((__bridge CFURLRef)URL, nullptr, 0);
+        buffer = (UInt8 *)realloc(buffer, bytesToAllocate);
+        bytesFilled = CFURLGetBytes((__bridge CFURLRef)URL, buffer, bytesToAllocate);
+        ASSERT(bytesFilled == bytesToAllocate);
+    }
+    
+    // buffer is adopted by the NSData
+    NSData *data = "" dataWithBytesNoCopy:buffer length:bytesFilled freeWhenDone:YES];
+    
+    NSURL *baseURL = (__bridge NSURL *)CFURLGetBaseURL((__bridge CFURLRef)URL);
+    if (baseURL)
+        return originalURLData(URLWithData(data, baseURL));
+    return data;
 }
 
 NSString *userVisibleString(NSURL *URL)
 {
     NSData *data = ""
-    return URLHelpers::userVisibleURL(CString(static_cast<const char*>([data bytes]), [data length]));
+    CString string(static_cast<const char*>([data bytes]), [data length]);
+    return userVisibleURL(string);
 }
 
 BOOL isUserVisibleURL(NSString *string)
 {
-    // Return true if the userVisibleString function is guaranteed to not change the passed-in URL.
-    // This function is used to optimize all the most common cases where we don't need the userVisibleString algorithm.
+    BOOL valid = YES;
+    // get buffer
+    
+    char static_buffer[1024];
+    const char *p;
+    BOOL success = CFStringGetCString((__bridge CFStringRef)string, static_buffer, 1023, kCFStringEncodingUTF8);
+    p = success ? static_buffer : [string UTF8String];
+    
+    int length = strlen(p);
+    
+    // check for characters <= 0x20 or >=0x7f, %-escape sequences of %7f, and xn--, these
+    // are the things that will lead _web_userVisibleString to actually change things.
+    for (int i = 0; i < length; i++) {
+        unsigned char c = p[i];
+        // escape control characters, space, and delete
+        if (c <= 0x20 || c == 0x7f) {
+            valid = NO;
+            break;
+        } else if (c == '%' && (i + 1 < length && isASCIIHexDigit(p[i + 1])) && i + 2 < length && isASCIIHexDigit(p[i + 2])) {
+            auto u = toASCIIHexValue(p[i + 1], p[i + 2]);
+            if (u > 0x7f) {
+                valid = NO;
+                break;
+            }
+            i += 2;
+        } else {
+            // Check for "xn--" in an efficient, non-case-sensitive, way.
+            if (c == '-' && i >= 3 && (p[i - 3] | 0x20) == 'x' && (p[i - 2] | 0x20) == 'n' && p[i - 1] == '-') {
+                valid = NO;
+                break;
+            }
+        }
+    }
+    
+    return valid;
+}
 
-    char buffer[1024];
-    auto success = CFStringGetCString(bridge_cast(string), reinterpret_cast<char*>(buffer), sizeof(buffer) - 1, kCFStringEncodingUTF8);
-    auto characters = success ? buffer : [string UTF8String];
-
-    // Check for control characters, %-escape sequences that are non-ASCII, and xn--: these
-    // are the things that might lead the userVisibleString function to actually change the string.
-    while (auto character = *characters++) {
-        // Control characters, including space, will be escaped by userVisibleString.
-        if (character <= 0x20 || character == 0x7F)
-            return NO;
-        // Escape sequences that expand to non-ASCII characters may be converted to non-escaped UTF-8 sequences.
-        if (character == '%' && isASCIIHexDigit(characters[0]) && isASCIIHexDigit(characters[1]) && !isASCII(toASCIIHexValue(characters[0], characters[1])))
-            return NO;
-        // If "xn--" appears, then we might need to run the IDN algorithm if it's a host name.
-        if (isASCIIAlphaCaselessEqual(character, 'x') && isASCIIAlphaCaselessEqual(characters[0], 'n') && characters[1] == '-' && characters[2] == '-')
-            return NO;
+NSRange rangeOfURLScheme(NSString *string)
+{
+    NSRange colon = [string rangeOfString:@":"];
+    if (colon.location != NSNotFound && colon.location > 0) {
+        NSRange scheme = {0, colon.location};
+        /*
+         This stuff is very expensive.  10-15 msec on a 2x1.2GHz.  If not cached it swamps
+         everything else when adding items to the autocomplete DB.  Makes me wonder if we
+         even need to enforce the character set here.
+         */
+        NSString *acceptableCharacters = @"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+.-";
+        static LazyNeverDestroyed<RetainPtr<NSCharacterSet>> inverseSchemeCharacterSet;
+        static std::once_flag onceKey;
+        std::call_once(onceKey, [&] {
+            inverseSchemeCharacterSet.construct([[NSCharacterSet characterSetWithCharactersInString:acceptableCharacters] invertedSet]);
+        });
+        NSRange illegals = [string rangeOfCharacterFromSet:inverseSchemeCharacterSet.get().get() options:0 range:scheme];
+        if (illegals.location == NSNotFound)
+            return scheme;
     }
+    return NSMakeRange(NSNotFound, 0);
+}
 
-    return YES;
+BOOL looksLikeAbsoluteURL(NSString *string)
+{
+    // Trim whitespace because _web_URLWithString allows whitespace.
+    return rangeOfURLScheme(stringByTrimmingWhitespace(string).get()).location != NSNotFound;
 }
 
-}
+} // namespace WebCore

Modified: trunk/Source/WTF/wtf/cocoa/URLCocoa.mm (285547 => 285548)


--- trunk/Source/WTF/wtf/cocoa/URLCocoa.mm	2021-11-10 01:05:06 UTC (rev 285547)
+++ trunk/Source/WTF/wtf/cocoa/URLCocoa.mm	2021-11-10 01:09:29 UTC (rev 285548)
@@ -39,8 +39,17 @@
 namespace WTF {
 
 URL::URL(NSURL *cocoaURL)
-    : URL(bridge_cast(cocoaURL))
 {
+    if (!cocoaURL) {
+        invalidate();
+        return;
+    }
+
+    // FIXME: Why is it OK to ignore base URL here?
+    CString bytes;
+    WTF::getURLBytes(bridge_cast(cocoaURL), bytes);
+    URLParser parser(bytes.data());
+    *this = parser.result();
 }
 
 URL::operator NSURL *() const
@@ -50,11 +59,28 @@
     return createCFURL().bridgingAutorelease();
 }
 
-RetainPtr<CFURLRef> URL::emptyCFURL()
+RetainPtr<CFURLRef> URL::createCFURL() const
 {
-    // We use the toll-free bridge to create an empty value that is distinct from null that no CFURL function can create.
-    // FIXME: When we originally wrote this, we thought that creating empty CF URLs was valuable; can we do without it now?
-    return bridge_cast(adoptNS([[NSURL alloc] initWithString:@""]));
+    if (isNull())
+        return nullptr;
+
+    if (isEmpty()) {
+        // We use the toll-free bridge between NSURL and CFURL to create a CFURLRef supporting both empty and null values.
+        return bridge_cast(adoptNS([[NSURL alloc] initWithString:@""]));
+    }
+
+    RetainPtr<CFURLRef> cfURL;
+    if (LIKELY(m_string.is8Bit() && m_string.isAllASCII()))
+        cfURL = adoptCF(CFURLCreateAbsoluteURLWithBytes(nullptr, m_string.characters8(), m_string.length(), kCFStringEncodingUTF8, nullptr, true));
+    else {
+        CString utf8 = m_string.utf8();
+        cfURL = adoptCF(CFURLCreateAbsoluteURLWithBytes(nullptr, utf8.dataAsUInt8Ptr(), utf8.length(), kCFStringEncodingUTF8, nullptr, true));
+    }
+
+    if (protocolIsInHTTPFamily() && !WTF::isCFURLSameOrigin(cfURL.get(), *this))
+        return nullptr;
+
+    return cfURL;
 }
 
 bool URL::hostIsIPAddress(StringView host)
@@ -64,7 +90,7 @@
 
 RetainPtr<id> makeNSArrayElement(const URL& vectorElement)
 {
-    return bridge_cast(vectorElement.createCFURL());
+    return adoptNS((__bridge_transfer id)vectorElement.createCFURL().leakRef());
 }
 
 std::optional<URL> makeVectorElement(const URL*, id arrayElement)

Modified: trunk/Source/WTF/wtf/mac/FileSystemMac.mm (285547 => 285548)


--- trunk/Source/WTF/wtf/mac/FileSystemMac.mm	2021-11-10 01:05:06 UTC (rev 285547)
+++ trunk/Source/WTF/wtf/mac/FileSystemMac.mm	2021-11-10 01:09:29 UTC (rev 285548)
@@ -37,8 +37,8 @@
 void FileSystem::setMetadataURL(const String& path, const String& metadataURLString, const String& referrer)
 {
     String urlString;
-    if (NSURL *url = ""
-        urlString = userVisibleString(URLByRemovingUserInfo(url));
+    if (NSURL *url = "" nil))
+        urlString = WTF::userVisibleString(WTF::URLByRemovingUserInfo(url));
     else
         urlString = metadataURLString;
 

Modified: trunk/Source/WTF/wtf/text/cocoa/StringCocoa.mm (285547 => 285548)


--- trunk/Source/WTF/wtf/text/cocoa/StringCocoa.mm	2021-11-10 01:05:06 UTC (rev 285547)
+++ trunk/Source/WTF/wtf/text/cocoa/StringCocoa.mm	2021-11-10 01:09:29 UTC (rev 285548)
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2006-2021 Apple Inc. All rights reserved.
+ * Copyright (C) 2006-2018 Apple Inc. All rights reserved.
  *
  * This library is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Library General Public
@@ -22,20 +22,17 @@
 #import <wtf/text/WTFString.h>
 
 #import <CoreFoundation/CFString.h>
-#import <wtf/cocoa/TypeCastsCocoa.h>
 
 namespace WTF {
 
 #if HAVE(SAFARI_FOR_WEBKIT_DEVELOPMENT_REQUIRING_EXTRA_SYMBOLS)
 String::String(NSString *string)
-    : String(bridge_cast(string))
-{
-}
+    : String((__bridge CFStringRef)string) { }
 #endif
 
 RetainPtr<id> makeNSArrayElement(const String& vectorElement)
 {
-    return bridge_cast(vectorElement.createCFString());
+    return adoptNS((__bridge_transfer id)vectorElement.createCFString().leakRef());
 }
 
 std::optional<String> makeVectorElement(const String*, id arrayElement)

Modified: trunk/Source/WebKit/ChangeLog (285547 => 285548)


--- trunk/Source/WebKit/ChangeLog	2021-11-10 01:05:06 UTC (rev 285547)
+++ trunk/Source/WebKit/ChangeLog	2021-11-10 01:09:29 UTC (rev 285548)
@@ -1,3 +1,17 @@
+2021-11-09  Commit Queue  <commit-qu...@webkit.org>
+
+        Unreviewed, reverting r285536.
+        https://bugs.webkit.org/show_bug.cgi?id=232915
+
+        causes API test crashes
+
+        Reverted changeset:
+
+        "[CF] Reduce duplication and unneeded buffer allocations and
+        copying in URL code, also remove unused methods and functions"
+        https://bugs.webkit.org/show_bug.cgi?id=232220
+        https://commits.webkit.org/r285536
+
 2021-11-09  Per Arne  <pvol...@apple.com>
 
         [iOS][GPUP] Add syscalls to sandbox

Modified: trunk/Source/WebKit/Shared/API/c/cf/WKURLCF.mm (285547 => 285548)


--- trunk/Source/WebKit/Shared/API/c/cf/WKURLCF.mm	2021-11-10 01:05:06 UTC (rev 285547)
+++ trunk/Source/WebKit/Shared/API/c/cf/WKURLCF.mm	2021-11-10 01:09:29 UTC (rev 285548)
@@ -30,6 +30,7 @@
 #import "WKNSURL.h"
 #import <objc/runtime.h>
 #import <wtf/cf/CFURLExtras.h>
+#import <wtf/text/CString.h>
 
 static inline Class wkNSURLClass()
 {
@@ -44,14 +45,16 @@
 WKURLRef WKURLCreateWithCFURL(CFURLRef cfURL)
 {
     if (!cfURL)
-        return nullptr;
+        return 0;
 
     // Since WKNSURL is an internal class with no subclasses, we can do a simple equality check.
     if (object_getClass((__bridge NSURL *)cfURL) == wkNSURLClass())
         return WebKit::toAPI(static_cast<API::URL*>(&[(WKNSURL *)(__bridge NSURL *)CFRetain(cfURL) _apiObject]));
 
-    // FIXME: Why is it OK to ignore the base URL in the CFURL here?
-    return WebKit::toCopiedURLAPI(bytesAsString(cfURL));
+    CString urlBytes;
+    WTF::getURLBytes(cfURL, urlBytes);
+
+    return WebKit::toCopiedURLAPI(urlBytes.data());
 }
 
 CFURLRef WKURLCopyCFURL(CFAllocatorRef allocatorRef, WKURLRef URLRef)

Modified: trunk/Source/WebKit/Shared/Cocoa/ArgumentCodersCocoa.mm (285547 => 285548)


--- trunk/Source/WebKit/Shared/Cocoa/ArgumentCodersCocoa.mm	2021-11-10 01:05:06 UTC (rev 285547)
+++ trunk/Source/WebKit/Shared/Cocoa/ArgumentCodersCocoa.mm	2021-11-10 01:09:29 UTC (rev 285548)
@@ -104,8 +104,9 @@
     if (hasBaseURL)
         [coder encodeObject:baseURL forKey:baseURLKey];
 
-    auto bytes = bytesAsVector(bridge_cast(m_wrappedURL.get()));
-    [coder encodeBytes:bytes.data() length:bytes.size()];
+    WTF::URLCharBuffer urlBytes;
+    WTF::getURLBytes(bridge_cast(m_wrappedURL.get()), urlBytes);
+    [coder encodeBytes:urlBytes.data() length:urlBytes.size()];
 }
 
 - (_Nullable instancetype)initWithCoder:(NSCoder *)coder

Modified: trunk/Source/WebKit/Shared/Cocoa/WKNSURLExtras.h (285547 => 285548)


--- trunk/Source/WebKit/Shared/Cocoa/WKNSURLExtras.h	2021-11-10 01:05:06 UTC (rev 285547)
+++ trunk/Source/WebKit/Shared/Cocoa/WKNSURLExtras.h	2021-11-10 01:09:29 UTC (rev 285548)
@@ -28,5 +28,8 @@
 @interface NSURL (WKExtras)
 
 + (instancetype)_web_URLWithWTFString:(const String&)string;
++ (instancetype)_web_URLWithWTFString:(const String&)string relativeToURL:(NSURL *)baseURL;
 
+- (String)_web_originalDataAsWTFString;
+
 @end

Modified: trunk/Source/WebKit/Shared/Cocoa/WKNSURLExtras.mm (285547 => 285548)


--- trunk/Source/WebKit/Shared/Cocoa/WKNSURLExtras.mm	2021-11-10 01:05:06 UTC (rev 285547)
+++ trunk/Source/WebKit/Shared/Cocoa/WKNSURLExtras.mm	2021-11-10 01:09:29 UTC (rev 285548)
@@ -27,6 +27,9 @@
 #import "WKNSURLExtras.h"
 
 #import <wtf/URL.h>
+#import <wtf/cf/CFURLExtras.h>
+#import <wtf/text/CString.h>
+#import <wtf/text/WTFString.h>
 
 @implementation NSURL (WKExtras)
 
@@ -36,4 +39,18 @@
     return (NSURL *)url;
 }
 
++ (instancetype)_web_URLWithWTFString:(const String&)string relativeToURL:(NSURL *)baseURL
+{
+    URL url { URL { baseURL }, string };
+    return (NSURL *)url;
+}
+
+- (String)_web_originalDataAsWTFString
+{
+    // FIXME: Why is it OK to ignore base URL here?
+    CString originalData;
+    WTF::getURLBytes((__bridge CFURLRef)self, originalData);
+    return String::fromUTF8(originalData);
+}
+
 @end

Modified: trunk/Source/WebKit/Shared/Cocoa/WKNSURLRequest.mm (285547 => 285548)


--- trunk/Source/WebKit/Shared/Cocoa/WKNSURLRequest.mm	2021-11-10 01:05:06 UTC (rev 285547)
+++ trunk/Source/WebKit/Shared/Cocoa/WKNSURLRequest.mm	2021-11-10 01:09:29 UTC (rev 285548)
@@ -37,7 +37,7 @@
 
 - (NSURL *)URL
 {
-    return static_cast<API::URLRequest*>(&self._apiObject)->resourceRequest().url();
+    return [NSURL _web_URLWithWTFString:static_cast<API::URLRequest*>(&self._apiObject)->resourceRequest().url().string()];
 }
 
 #pragma mark NSCopying protocol implementation

Modified: trunk/Source/WebKit/Shared/cf/ArgumentCodersCF.cpp (285547 => 285548)


--- trunk/Source/WebKit/Shared/cf/ArgumentCodersCF.cpp	2021-11-10 01:05:06 UTC (rev 285547)
+++ trunk/Source/WebKit/Shared/cf/ArgumentCodersCF.cpp	2021-11-10 01:09:29 UTC (rev 285548)
@@ -643,7 +643,9 @@
     if (baseURL)
         encoder << baseURL;
 
-    encoder << IPC::DataReference(bytesAsVector(url));
+    WTF::URLCharBuffer urlBytes;
+    WTF::getURLBytes(url, urlBytes);
+    encoder << IPC::DataReference(reinterpret_cast<const uint8_t*>(urlBytes.data()), urlBytes.size());
 }
 
 template void ArgumentCoder<CFURLRef>::encode<Encoder>(Encoder&, CFURLRef);

Modified: trunk/Source/WebKit/UIProcess/API/Cocoa/WKBrowsingContextController.mm (285547 => 285548)


--- trunk/Source/WebKit/UIProcess/API/Cocoa/WKBrowsingContextController.mm	2021-11-10 01:05:06 UTC (rev 285547)
+++ trunk/Source/WebKit/UIProcess/API/Cocoa/WKBrowsingContextController.mm	2021-11-10 01:09:29 UTC (rev 285548)
@@ -60,7 +60,6 @@
 #import <wtf/BlockPtr.h>
 #import <wtf/NeverDestroyed.h>
 #import <wtf/WeakObjCPtr.h>
-#import <wtf/cf/CFURLExtras.h>
 
 NSString * const WKActionIsMainFrameKey = @"WKActionIsMainFrameKey";
 NSString * const WKActionNavigationTypeKey = @"WKActionNavigationTypeKey";
@@ -158,7 +157,7 @@
     if (userData)
         wkUserData = WebKit::ObjCObjectGraph::create(userData);
 
-    _page->loadFile(bytesAsString(bridge_cast(URL)), bytesAsString(bridge_cast(allowedDirectory)), wkUserData.get());
+    _page->loadFile([URL _web_originalDataAsWTFString], [allowedDirectory _web_originalDataAsWTFString], wkUserData.get());
 }
 
 - (void)loadHTMLString:(NSString *)HTMLString baseURL:(NSURL *)baseURL
@@ -173,7 +172,7 @@
         wkUserData = WebKit::ObjCObjectGraph::create(userData);
 
     NSData *data = "" dataUsingEncoding:NSUTF8StringEncoding];
-    _page->loadData({ static_cast<const uint8_t*>(data.bytes), data.length }, "text/html"_s, "UTF-8"_s, bytesAsString(bridge_cast(baseURL)), wkUserData.get());
+    _page->loadData({ static_cast<const uint8_t*>(data.bytes), data.length }, "text/html"_s, "UTF-8"_s, [baseURL _web_originalDataAsWTFString], wkUserData.get());
 }
 
 - (void)loadAlternateHTMLString:(NSString *)string baseURL:(NSURL *)baseURL forUnreachableURL:(NSURL *)unreachableURL
@@ -193,7 +192,7 @@
     if (userData)
         wkUserData = WebKit::ObjCObjectGraph::create(userData);
 
-    _page->loadData({ static_cast<const uint8_t*>(data.bytes), data.length }, MIMEType, encodingName, bytesAsString(bridge_cast(baseURL)), wkUserData.get());
+    _page->loadData({ static_cast<const uint8_t*>(data.bytes), data.length }, MIMEType, encodingName, [baseURL _web_originalDataAsWTFString], wkUserData.get());
 }
 
 - (void)stopLoading
@@ -509,7 +508,7 @@
 
             if (originatingFrame) {
                 actionDictionary = adoptNS([actionDictionary mutableCopy]);
-                [(NSMutableDictionary *)actionDictionary.get() setObject:(NSURL *)WebKit::toImpl(originatingFrame)->url() forKey:WKActionOriginatingFrameURLKey];
+                [(NSMutableDictionary *)actionDictionary.get() setObject:[NSURL _web_URLWithWTFString:WebKit::toImpl(originatingFrame)->url().string()] forKey:WKActionOriginatingFrameURLKey];
             }
             
             [policyDelegate browsingContextController:browsingContext decidePolicyForNavigationAction:actionDictionary.get() decisionHandler:makePolicyDecisionBlock(listener).get()];

Modified: trunk/Source/WebKit/UIProcess/Cocoa/LegacyDownloadClient.mm (285547 => 285548)


--- trunk/Source/WebKit/UIProcess/Cocoa/LegacyDownloadClient.mm	2021-11-10 01:05:06 UTC (rev 285547)
+++ trunk/Source/WebKit/UIProcess/Cocoa/LegacyDownloadClient.mm	2021-11-10 01:09:29 UTC (rev 285548)
@@ -272,7 +272,7 @@
 void LegacyDownloadClient::willSendRequest(DownloadProxy& downloadProxy, WebCore::ResourceRequest&& request, const WebCore::ResourceResponse&, CompletionHandler<void(WebCore::ResourceRequest&&)>&& completionHandler)
 {
     if (m_delegateMethods.downloadDidReceiveServerRedirectToURL)
-        [m_delegate _download:[_WKDownload downloadWithDownload:wrapper(downloadProxy)] didReceiveServerRedirectToURL:request.url()];
+        [m_delegate _download:[_WKDownload downloadWithDownload:wrapper(downloadProxy)] didReceiveServerRedirectToURL:[NSURL _web_URLWithWTFString:request.url().string()]];
 
     completionHandler(WTFMove(request));
 }

Modified: trunk/Source/WebKit/WebProcess/InjectedBundle/API/Cocoa/WKWebProcessPlugInFrame.mm (285547 => 285548)


--- trunk/Source/WebKit/WebProcess/InjectedBundle/API/Cocoa/WKWebProcessPlugInFrame.mm	2021-11-10 01:05:06 UTC (rev 285547)
+++ trunk/Source/WebKit/WebProcess/InjectedBundle/API/Cocoa/WKWebProcessPlugInFrame.mm	2021-11-10 01:09:29 UTC (rev 285548)
@@ -110,7 +110,7 @@
 
 - (NSURL *)URL
 {
-    return _frame->url();
+    return [NSURL _web_URLWithWTFString:_frame->url().string()];
 }
 
 - (NSArray *)childFrames

Modified: trunk/Source/WebKitLegacy/mac/ChangeLog (285547 => 285548)


--- trunk/Source/WebKitLegacy/mac/ChangeLog	2021-11-10 01:05:06 UTC (rev 285547)
+++ trunk/Source/WebKitLegacy/mac/ChangeLog	2021-11-10 01:09:29 UTC (rev 285548)
@@ -1,3 +1,17 @@
+2021-11-09  Commit Queue  <commit-qu...@webkit.org>
+
+        Unreviewed, reverting r285536.
+        https://bugs.webkit.org/show_bug.cgi?id=232915
+
+        causes API test crashes
+
+        Reverted changeset:
+
+        "[CF] Reduce duplication and unneeded buffer allocations and
+        copying in URL code, also remove unused methods and functions"
+        https://bugs.webkit.org/show_bug.cgi?id=232220
+        https://commits.webkit.org/r285536
+
 2021-10-28  Darin Adler  <da...@apple.com>
 
         [CF] Reduce duplication and unneeded buffer allocations and copying in URL code, also remove unused methods and functions

Modified: trunk/Source/WebKitLegacy/mac/Misc/WebNSURLExtras.h (285547 => 285548)


--- trunk/Source/WebKitLegacy/mac/Misc/WebNSURLExtras.h	2021-11-10 01:05:06 UTC (rev 285547)
+++ trunk/Source/WebKitLegacy/mac/Misc/WebNSURLExtras.h	2021-11-10 01:09:29 UTC (rev 285548)
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2005-2021 Apple Inc. All rights reserved.
+ * Copyright (C) 2005-2009, 2014 Apple Inc. All rights reserved.
  *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
@@ -28,23 +28,30 @@
 
 #import <Foundation/Foundation.h>
 
-// FIXME: Consider renaming to _web_ from _webkit_ once identically-named methods are no longer present in Foundation.
+// FIXME: Change method names back to _web_ from _webkit_ when identically-named
+// methods are no longer present in Foundation.
 
 @interface NSURL (WebNSURLExtras)
 
-// Deprecated, as it ignores URL parsing errors.
-// Please use the _webkit_URLWithUserTypedString instead.
+// Deprecated as it ignores URL parsing error.
+// Please use the _webkit_ counterparts.
 + (NSURL *)_web_URLWithUserTypedString:(NSString *)string;
++ (NSURL *)_web_URLWithUserTypedString:(NSString *)string relativeToURL:(NSURL *)URL;
 
+// New SPI.
 // Return value of nil means error in URL parsing.
 + (NSURL *)_webkit_URLWithUserTypedString:(NSString *)string;
++ (NSURL *)_webkit_URLWithUserTypedString:(NSString *)string relativeToURL:(NSURL *)URL;
 
 + (NSURL *)_web_URLWithDataAsString:(NSString *)string;
 + (NSURL *)_web_URLWithDataAsString:(NSString *)string relativeToURL:(NSURL *)baseURL;
 
++ (NSURL *)_web_URLWithData:(NSData *)data;
++ (NSURL *)_web_URLWithData:(NSData *)data relativeToURL:(NSURL *)baseURL;
+
 - (NSData *)_web_originalData;
 - (NSString *)_web_originalDataAsString;
-- (const char*)_web_URLCString;
+- (const char *)_web_URLCString;
 
 - (NSString *)_web_hostString;
 
@@ -71,16 +78,14 @@
 
 - (BOOL)_web_isUserVisibleURL;
 
-// Deprecated as it ignores URL parsing errors.
-// Please use _webkit_decodeHostName instead.
-// Turns funny-looking ASCII form into Unicode, returns self if no decoding needed.
+// Deprecated as it ignores URL parsing error.
+// Please use the _webkit_ counterparts.
+// turns funny-looking ASCII form into Unicode, returns self if no decoding needed, convenient cover
 - (NSString *)_web_decodeHostName;
-
-// Deprecated as it ignores URL parsing errors.
-// Please use the _webkit_encodeHostName instead.
-// Turns Unicode into funny-looking ASCII form, returns self if no encoding needed.
+// turns Unicode into funny-looking ASCII form, returns self if no decoding needed, convenient cover
 - (NSString *)_web_encodeHostName;
 
+// New SPI.
 // Return value of nil means error in URL parsing.
 - (NSString *)_webkit_decodeHostName;
 - (NSString *)_webkit_encodeHostName;

Modified: trunk/Source/WebKitLegacy/mac/Misc/WebNSURLExtras.mm (285547 => 285548)


--- trunk/Source/WebKitLegacy/mac/Misc/WebNSURLExtras.mm	2021-11-10 01:05:06 UTC (rev 285547)
+++ trunk/Source/WebKitLegacy/mac/Misc/WebNSURLExtras.mm	2021-11-10 01:09:29 UTC (rev 285548)
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2005-2021 Apple Inc. All rights reserved.
+ * Copyright (C) 2005, 2007, 2008, 2009 Apple Inc. All rights reserved.
  * Copyright (C) 2006 Alexey Proskuryakov (a...@nypop.com)
  *
  * Redistribution and use in source and binary forms, with or without
@@ -41,38 +41,70 @@
 #import <wtf/Assertions.h>
 #import <wtf/URL.h>
 #import <wtf/cocoa/NSURLExtras.h>
-#import <wtf/cocoa/TypeCastsCocoa.h>
 
+using namespace WebCore;
+using namespace WTF;
+
+#define URL_BYTES_BUFFER_LENGTH 2048
+
 @implementation NSURL (WebNSURLExtras)
 
++ (NSURL *)_web_URLWithUserTypedString:(NSString *)string relativeToURL:(NSURL *)URL
+{
+    return URLWithUserTypedStringDeprecated(string, URL);
+}
+
 + (NSURL *)_web_URLWithUserTypedString:(NSString *)string
 {
-    return WTF::URLWithUserTypedStringDeprecated(string);
+    return URLWithUserTypedStringDeprecated(string, nil);
 }
 
++ (NSURL *)_webkit_URLWithUserTypedString:(NSString *)string relativeToURL:(NSURL *)URL
+{
+    return URLWithUserTypedString(string, URL);
+}
+
 + (NSURL *)_webkit_URLWithUserTypedString:(NSString *)string
 {
-    return WTF::URLWithUserTypedString(string);
+    return URLWithUserTypedString(string, nil);
 }
 
 + (NSURL *)_web_URLWithDataAsString:(NSString *)string
 {
+    if (string == nil) {
+        return nil;
+    }
     return [self _web_URLWithDataAsString:string relativeToURL:nil];
 }
 
 + (NSURL *)_web_URLWithDataAsString:(NSString *)string relativeToURL:(NSURL *)baseURL
 {
-    return WTF::URLWithData([[string _webkit_stringByTrimmingWhitespace] dataUsingEncoding:NSISOLatin1StringEncoding], baseURL);
+    if (string == nil) {
+        return nil;
+    }
+    string = [string _webkit_stringByTrimmingWhitespace];
+    NSData *data = "" dataUsingEncoding:NSISOLatin1StringEncoding];
+    return URLWithData(data, baseURL);
 }
 
++ (NSURL *)_web_URLWithData:(NSData *)data
+{
+    return URLWithData(data, nil);
+}      
+
++ (NSURL *)_web_URLWithData:(NSData *)data relativeToURL:(NSURL *)baseURL
+{
+    return URLWithData(data, baseURL);
+}
+
 - (NSData *)_web_originalData
 {
-    return WTF::originalURLData(self);
+    return originalURLData(self);
 }
 
 - (NSString *)_web_originalDataAsString
 {
-    return adoptNS([[NSString alloc] initWithData:WTF::originalURLData(self) encoding:NSISOLatin1StringEncoding]).autorelease();
+    return adoptNS([[NSString alloc] initWithData:originalURLData(self) encoding:NSISOLatin1StringEncoding]).autorelease();
 }
 
 - (NSString *)_web_userVisibleString
@@ -82,22 +114,22 @@
 
 - (BOOL)_web_isEmpty
 {
-    if (!CFURLGetBaseURL(bridge_cast(self)))
-        return !CFURLGetBytes(bridge_cast(self), nullptr, 0);
-    return ![WTF::originalURLData(self) length];
+    if (!CFURLGetBaseURL((CFURLRef)self))
+        return CFURLGetBytes((CFURLRef)self, NULL, 0) == 0;
+    return [originalURLData(self) length] == 0;
 }
 
-- (const char*)_web_URLCString
+- (const char *)_web_URLCString
 {
     NSMutableData *data = "" data];
-    [data appendData:WTF::originalURLData(self)];
+    [data appendData:originalURLData(self)];
     [data appendBytes:"\0" length:1];
-    return (const char*)[data bytes];
+    return (const char *)[data bytes];
  }
 
 - (NSURL *)_webkit_canonicalize
 {
-    return WebCore::URLByCanonicalizingURL(self);
+    return URLByCanonicalizingURL(self);
 }
 
 - (NSURL *)_webkit_canonicalize_with_wtf
@@ -108,7 +140,7 @@
 
 - (NSURL *)_webkit_URLByRemovingFragment 
 {
-    return WTF::URLByTruncatingOneCharacterBeforeComponent(self, kCFURLComponentFragment);
+    return URLByTruncatingOneCharacterBeforeComponent(self, kCFURLComponentFragment);
 }
 
 - (NSURL *)_web_URLByRemovingUserInfo
@@ -131,6 +163,27 @@
     return [[self _web_originalDataAsString] _webkit_isFileURL];
 }
 
+-(NSData *)_web_schemeSeparatorWithoutColon
+{
+    NSData *result = nil;
+    CFRange rangeWithSeparators;
+    CFRange range = CFURLGetByteRangeForComponent((CFURLRef)self, kCFURLComponentScheme, &rangeWithSeparators);
+    if (rangeWithSeparators.location != kCFNotFound) {
+        NSString *absoluteString = [self absoluteString];
+        NSRange separatorsRange = NSMakeRange(range.location + range.length + 1, rangeWithSeparators.length - range.length - 1);
+        if (separatorsRange.location + separatorsRange.length <= [absoluteString length]) {
+            NSString *slashes = [absoluteString substringWithRange:separatorsRange];
+            result = [slashes dataUsingEncoding:NSISOLatin1StringEncoding];
+        }
+    }
+    return result;
+}
+
+-(NSData *)_web_dataForURLComponentType:(CFURLComponentType)componentType
+{
+    return WTF::dataForURLComponentType(self, componentType);
+}
+
 -(NSData *)_web_schemeData
 {
     return WTF::dataForURLComponentType(self, kCFURLComponentScheme);
@@ -139,11 +192,11 @@
 -(NSData *)_web_hostData
 {
     NSData *result = WTF::dataForURLComponentType(self, kCFURLComponentHost);
-
-    // Take off localhost for file.
-    if ([result _web_isCaseInsensitiveEqualToCString:"localhost"] && [[self _web_schemeData] _web_isCaseInsensitiveEqualToCString:"file"])
-        return nil;
-
+    NSData *scheme = [self _web_schemeData];
+    // Take off localhost for file
+    if ([scheme _web_isCaseInsensitiveEqualToCString:"file"]) {
+        return ([result _web_isCaseInsensitiveEqualToCString:"localhost"]) ? nil : result;
+    }
     return result;
 }
 
@@ -170,7 +223,7 @@
 
 - (BOOL)_web_isUserVisibleURL
 {
-    return WTF::isUserVisibleURL(self);
+    return isUserVisibleURL(self);
 }
 
 - (BOOL)_webkit_isJavaScriptURL
@@ -185,7 +238,7 @@
 
 - (NSString *)_webkit_stringByReplacingValidPercentEscapes
 {
-    return WebCore::decodeURLEscapeSequences(String(self));
+    return decodeURLEscapeSequences(String(self));
 }
 
 - (NSString *)_webkit_scriptIfJavaScriptURL
@@ -198,24 +251,24 @@
 
 - (NSString *)_web_decodeHostName
 {
-    NSString *name = WTF::decodeHostName(self);
+    NSString *name = decodeHostName(self);
     return !name ? self : name;
 }
 
 - (NSString *)_web_encodeHostName
 {
-    NSString *name = WTF::encodeHostName(self);
+    NSString *name = encodeHostName(self);
     return !name ? self : name;
 }
 
 - (NSString *)_webkit_decodeHostName
 {
-    return WTF::decodeHostName(self);
+    return decodeHostName(self);
 }
 
 - (NSString *)_webkit_encodeHostName
 {
-    return WTF::encodeHostName(self);
+    return encodeHostName(self);
 }
 
 -(NSRange)_webkit_rangeOfURLScheme

Modified: trunk/Tools/ChangeLog (285547 => 285548)


--- trunk/Tools/ChangeLog	2021-11-10 01:05:06 UTC (rev 285547)
+++ trunk/Tools/ChangeLog	2021-11-10 01:09:29 UTC (rev 285548)
@@ -1,3 +1,17 @@
+2021-11-09  Commit Queue  <commit-qu...@webkit.org>
+
+        Unreviewed, reverting r285536.
+        https://bugs.webkit.org/show_bug.cgi?id=232915
+
+        causes API test crashes
+
+        Reverted changeset:
+
+        "[CF] Reduce duplication and unneeded buffer allocations and
+        copying in URL code, also remove unused methods and functions"
+        https://bugs.webkit.org/show_bug.cgi?id=232220
+        https://commits.webkit.org/r285536
+
 2021-11-09  Alex Christensen  <achristen...@webkit.org>
 
         Unify build of TestWebKitAPI/Tests/WebKitCocoa

Modified: trunk/Tools/TestWebKitAPI/Tests/WTF/cocoa/URLExtras.mm (285547 => 285548)


--- trunk/Tools/TestWebKitAPI/Tests/WTF/cocoa/URLExtras.mm	2021-11-10 01:05:06 UTC (rev 285547)
+++ trunk/Tools/TestWebKitAPI/Tests/WTF/cocoa/URLExtras.mm	2021-11-10 01:09:29 UTC (rev 285548)
@@ -249,10 +249,10 @@
 
 TEST(WTF_URLExtras, URLExtras_Nil)
 {
-    NSURL *url1 = WTF::URLWithUserTypedString(nil);
+    NSURL *url1 = WTF::URLWithUserTypedString(nil, nil);
     EXPECT_TRUE(url1 == nil);
 
-    NSURL *url2 = WTF::URLWithUserTypedStringDeprecated(nil);
+    NSURL *url2 = WTF::URLWithUserTypedStringDeprecated(nil, nil);
     EXPECT_TRUE(url2 == nil);
 }
 
_______________________________________________
webkit-changes mailing list
webkit-changes@lists.webkit.org
https://lists.webkit.org/mailman/listinfo/webkit-changes

Reply via email to