From 480ceeb859a7ed600c758f0b3781ae89f8689b51 Mon Sep 17 00:00:00 2001 From: Lily Vulcano Date: Thu, 23 Aug 2018 18:00:30 -0700 Subject: [PATCH 01/12] Mojave merge. --- .../CFNotificationCenter.h | 6 +- .../AppServices.subproj/CFUserNotification.c | 50 +- .../AppServices.subproj/CFUserNotification.h | 4 +- CoreFoundation/Base.subproj/CFAvailability.h | 18 +- CoreFoundation/Base.subproj/CFBase.c | 171 +++--- CoreFoundation/Base.subproj/CFBase.h | 11 +- CoreFoundation/Base.subproj/CFByteOrder.h | 4 +- CoreFoundation/Base.subproj/CFFileUtilities.c | 8 +- CoreFoundation/Base.subproj/CFInternal.h | 154 ++--- CoreFoundation/Base.subproj/CFLogUtilities.h | 4 +- CoreFoundation/Base.subproj/CFOverflow.h | 76 +++ CoreFoundation/Base.subproj/CFPlatform.c | 49 +- CoreFoundation/Base.subproj/CFPriv.h | 46 +- CoreFoundation/Base.subproj/CFRuntime.c | 282 +++++----- CoreFoundation/Base.subproj/CFRuntime.h | 4 +- .../Base.subproj/CFRuntime_Internal.h | 159 ++++++ CoreFoundation/Base.subproj/CFSortFunctions.c | 10 +- .../Base.subproj/CFSystemDirectories.c | 4 +- CoreFoundation/Base.subproj/CFUUID.c | 32 +- CoreFoundation/Base.subproj/CFUUID.h | 4 +- CoreFoundation/Base.subproj/CFUtilities.c | 60 +- CoreFoundation/Base.subproj/CFUtilities.h | 4 +- .../Base.subproj/CFWindowsUtilities.c | 4 +- CoreFoundation/Base.subproj/CoreFoundation.h | 4 +- .../Base.subproj/CoreFoundation_Prefix.h | 13 +- .../Base.subproj/DarwinSymbolAliases | 2 +- .../Base.subproj/ForFoundationOnly.h | 123 ++-- .../Base.subproj/ForSwiftFoundationOnly.h | 34 +- CoreFoundation/Collections.subproj/CFArray.c | 16 +- CoreFoundation/Collections.subproj/CFArray.h | 2 +- CoreFoundation/Collections.subproj/CFBag.c | 15 +- CoreFoundation/Collections.subproj/CFBag.h | 4 +- .../Collections.subproj/CFBasicHash.c | 78 +-- .../Collections.subproj/CFBasicHash.h | 4 +- .../CFBasicHashFindBucket.m | 4 +- .../Collections.subproj/CFBinaryHeap.c | 13 +- .../Collections.subproj/CFBinaryHeap.h | 4 +- .../Collections.subproj/CFBitVector.c | 13 +- .../Collections.subproj/CFBitVector.h | 4 +- .../CFCollections_Internal.h | 25 + CoreFoundation/Collections.subproj/CFData.c | 23 +- CoreFoundation/Collections.subproj/CFData.h | 4 +- .../Collections.subproj/CFDictionary.c | 25 +- .../Collections.subproj/CFDictionary.h | 4 +- CoreFoundation/Collections.subproj/CFSet.c | 15 +- CoreFoundation/Collections.subproj/CFSet.h | 4 +- .../Collections.subproj/CFStorage.c | 21 +- .../Collections.subproj/CFStorage.h | 4 +- CoreFoundation/Collections.subproj/CFTree.c | 14 +- CoreFoundation/Collections.subproj/CFTree.h | 4 +- CoreFoundation/Error.subproj/CFError.c | 48 +- CoreFoundation/Error.subproj/CFError.h | 4 +- .../Error.subproj/CFError_Private.h | 4 +- CoreFoundation/Locale.subproj/CFCalendar.c | 13 +- CoreFoundation/Locale.subproj/CFCalendar.h | 4 +- .../Locale.subproj/CFDateFormatter.c | 35 +- .../Locale.subproj/CFDateFormatter.h | 4 +- .../Locale.subproj/CFDateFormatter_Private.h | 4 +- CoreFoundation/Locale.subproj/CFICULogging.h | 8 +- CoreFoundation/Locale.subproj/CFLocale.c | 132 +++-- CoreFoundation/Locale.subproj/CFLocale.h | 4 +- .../Locale.subproj/CFLocaleIdentifier.c | 4 +- .../Locale.subproj/CFLocaleInternal.h | 4 +- CoreFoundation/Locale.subproj/CFLocaleKeys.c | 4 +- .../Locale.subproj/CFLocale_Private.h | 4 +- .../Locale.subproj/CFNumberFormatter.c | 13 +- .../Locale.subproj/CFNumberFormatter.h | 4 +- .../NumberDate.subproj/CFBigNumber.c | 4 +- .../NumberDate.subproj/CFBigNumber.h | 4 +- CoreFoundation/NumberDate.subproj/CFDate.c | 26 +- CoreFoundation/NumberDate.subproj/CFDate.h | 4 +- CoreFoundation/NumberDate.subproj/CFNumber.c | 134 ++--- CoreFoundation/NumberDate.subproj/CFNumber.h | 4 +- .../NumberDate.subproj/CFTimeZone.c | 123 ++-- .../NumberDate.subproj/CFTimeZone.h | 4 +- .../Parsing.subproj/CFBinaryPList.c | 65 +-- .../Parsing.subproj/CFOldStylePList.c | 5 +- .../Parsing.subproj/CFPropertyList.c | 101 ++-- .../Parsing.subproj/CFPropertyList.h | 4 +- .../Parsing.subproj/CFXMLInputStream.c | 4 +- .../Parsing.subproj/CFXMLInputStream.h | 4 +- CoreFoundation/Parsing.subproj/CFXMLNode.c | 13 +- CoreFoundation/Parsing.subproj/CFXMLNode.h | 4 +- CoreFoundation/Parsing.subproj/CFXMLParser.c | 13 +- CoreFoundation/Parsing.subproj/CFXMLParser.h | 2 +- CoreFoundation/Parsing.subproj/CFXMLTree.c | 4 +- CoreFoundation/PlugIn.subproj/CFBundle.c | 40 +- CoreFoundation/PlugIn.subproj/CFBundle.h | 2 +- CoreFoundation/PlugIn.subproj/CFBundlePriv.h | 16 +- .../PlugIn.subproj/CFBundle_Binary.c | 6 +- .../PlugIn.subproj/CFBundle_BinaryTypes.h | 4 +- CoreFoundation/PlugIn.subproj/CFBundle_Grok.c | 10 +- .../PlugIn.subproj/CFBundle_InfoPlist.c | 60 +- .../PlugIn.subproj/CFBundle_Internal.h | 28 +- .../PlugIn.subproj/CFBundle_Locale.c | 59 +- CoreFoundation/PlugIn.subproj/CFBundle_Main.c | 7 +- .../PlugIn.subproj/CFBundle_Resources.c | 10 +- .../PlugIn.subproj/CFBundle_Strings.c | 45 +- CoreFoundation/PlugIn.subproj/CFPlugIn.c | 53 +- CoreFoundation/PlugIn.subproj/CFPlugIn.h | 4 +- CoreFoundation/PlugIn.subproj/CFPlugInCOM.h | 4 +- .../PlugIn.subproj/CFPlugIn_Factory.c | 88 ++- .../PlugIn.subproj/CFPlugIn_Factory.h | 5 +- .../PlugIn.subproj/CFPlugIn_Instance.c | 13 +- .../PlugIn.subproj/CFPlugIn_PlugIn.c | 4 +- .../CFApplicationPreferences.c | 22 +- .../Preferences.subproj/CFPreferences.c | 36 +- .../Preferences.subproj/CFPreferences.h | 6 +- .../CFXMLPreferencesDomain.c | 13 +- CoreFoundation/RunLoop.subproj/CFMachPort.c | 232 ++------ CoreFoundation/RunLoop.subproj/CFMachPort.h | 4 +- .../RunLoop.subproj/CFMachPort_Internal.h | 19 + .../RunLoop.subproj/CFMachPort_Lifetime.c | 293 ++++++++++ .../RunLoop.subproj/CFMachPort_Lifetime.h | 43 ++ .../RunLoop.subproj/CFMessagePort.c | 144 +++-- .../RunLoop.subproj/CFMessagePort.h | 4 +- CoreFoundation/RunLoop.subproj/CFRunLoop.c | 177 +++--- CoreFoundation/RunLoop.subproj/CFRunLoop.h | 4 +- CoreFoundation/RunLoop.subproj/CFSocket.c | 16 +- CoreFoundation/RunLoop.subproj/CFSocket.h | 4 +- .../Stream.subproj/CFConcreteStreams.c | 20 +- .../Stream.subproj/CFSocketStream.c | 4 +- CoreFoundation/Stream.subproj/CFStream.c | 78 ++- CoreFoundation/Stream.subproj/CFStream.h | 319 +++++++++-- .../Stream.subproj/CFStreamAbstract.h | 4 +- .../Stream.subproj/CFStreamInternal.h | 4 +- CoreFoundation/Stream.subproj/CFStreamPriv.h | 16 +- .../String.subproj/CFAttributedString.c | 94 ++-- .../String.subproj/CFAttributedString.h | 2 +- .../String.subproj/CFAttributedStringPriv.h | 25 + CoreFoundation/String.subproj/CFBurstTrie.c | 6 +- CoreFoundation/String.subproj/CFBurstTrie.h | 6 +- .../String.subproj/CFCharacterSet.c | 98 ++-- .../String.subproj/CFCharacterSet.h | 4 +- .../String.subproj/CFCharacterSetPriv.h | 4 +- CoreFoundation/String.subproj/CFRunArray.c | 15 +- CoreFoundation/String.subproj/CFRunArray.h | 6 +- CoreFoundation/String.subproj/CFString.c | 492 ++++++++++------ CoreFoundation/String.subproj/CFString.h | 31 +- .../String.subproj/CFStringDefaultEncoding.h | 4 +- .../String.subproj/CFStringEncodingExt.h | 4 +- .../String.subproj/CFStringEncodings.c | 18 +- .../String.subproj/CFStringScanner.c | 4 +- .../String.subproj/CFStringUtilities.c | 7 +- .../String.subproj/CFString_Internal.h | 22 + .../CFBuiltinConverters.c | 110 ++-- .../StringEncodings.subproj/CFICUConverters.c | 4 +- .../StringEncodings.subproj/CFICUConverters.h | 4 +- .../CFPlatformConverters.c | 34 +- .../CFStringEncodingConverter.c | 52 +- .../CFStringEncodingConverter.h | 15 +- .../CFStringEncodingConverterExt.h | 25 +- .../CFStringEncodingConverterPriv.h | 43 +- .../CFStringEncodingDatabase.c | 14 +- .../CFStringEncodingDatabase.h | 4 +- .../StringEncodings.subproj/CFUniChar.c | 4 +- .../StringEncodings.subproj/CFUniChar.h | 14 +- .../StringEncodings.subproj/CFUniCharPriv.h | 18 +- .../CFUnicodeDecomposition.c | 4 +- .../CFUnicodeDecomposition.h | 5 +- .../CFUnicodePrecomposition.c | 4 +- .../CFUnicodePrecomposition.h | 7 +- CoreFoundation/URL.subproj/CFURL.c | 28 +- CoreFoundation/URL.subproj/CFURL.h | 4 +- CoreFoundation/URL.subproj/CFURL.inc.h | 4 +- CoreFoundation/URL.subproj/CFURLAccess.c | 4 +- CoreFoundation/URL.subproj/CFURLAccess.h | 4 +- CoreFoundation/URL.subproj/CFURLComponents.c | 527 +++++++++++++----- CoreFoundation/URL.subproj/CFURLComponents.h | 36 +- .../URL.subproj/CFURLComponents_Internal.h | 18 +- CoreFoundation/URL.subproj/CFURLPriv.h | 14 +- Foundation.xcodeproj/project.pbxproj | 32 ++ Foundation/NSData.swift | 4 + Foundation/NSPathUtilities.swift | 2 +- Foundation/NSSwiftRuntime.swift | 2 + Foundation/NSURL.swift | 8 +- Foundation/ProcessInfo.swift | 2 +- Foundation/UserDefaults.swift | 7 +- TestFoundation/TestDateFormatter.swift | 2 +- TestFoundation/TestNSString.swift | 40 +- build.py | 8 + 181 files changed, 3839 insertions(+), 2485 deletions(-) create mode 100644 CoreFoundation/Base.subproj/CFOverflow.h create mode 100644 CoreFoundation/Base.subproj/CFRuntime_Internal.h create mode 100644 CoreFoundation/Collections.subproj/CFCollections_Internal.h create mode 100644 CoreFoundation/RunLoop.subproj/CFMachPort_Internal.h create mode 100644 CoreFoundation/RunLoop.subproj/CFMachPort_Lifetime.c create mode 100644 CoreFoundation/RunLoop.subproj/CFMachPort_Lifetime.h create mode 100644 CoreFoundation/String.subproj/CFAttributedStringPriv.h create mode 100644 CoreFoundation/String.subproj/CFString_Internal.h diff --git a/CoreFoundation/AppServices.subproj/CFNotificationCenter.h b/CoreFoundation/AppServices.subproj/CFNotificationCenter.h index b87b54623a..1a96573ac6 100644 --- a/CoreFoundation/AppServices.subproj/CFNotificationCenter.h +++ b/CoreFoundation/AppServices.subproj/CFNotificationCenter.h @@ -1,7 +1,7 @@ /* CFNotificationCenter.h - Copyright (c) 1998-2017, Apple Inc. and the Swift project authors + Copyright (c) 1998-2018, Apple Inc. and the Swift project authors - Portions Copyright (c) 2014-2017, Apple Inc. and the Swift project authors + Portions Copyright (c) 2014-2018, Apple Inc. and the Swift project authors Licensed under Apache License v2.0 with Runtime Library Exception See http://swift.org/LICENSE.txt for license information See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors @@ -37,7 +37,7 @@ CF_EXPORT CFTypeID CFNotificationCenterGetTypeID(void); CF_EXPORT CFNotificationCenterRef CFNotificationCenterGetLocalCenter(void); -#if (TARGET_OS_MAC && !(TARGET_OS_EMBEDDED || TARGET_OS_IPHONE)) || TARGET_OS_WIN32 +#if TARGET_OS_OSX || TARGET_OS_WIN32 CF_EXPORT CFNotificationCenterRef CFNotificationCenterGetDistributedCenter(void); #endif diff --git a/CoreFoundation/AppServices.subproj/CFUserNotification.c b/CoreFoundation/AppServices.subproj/CFUserNotification.c index e6dca66e77..a12d1c4537 100644 --- a/CoreFoundation/AppServices.subproj/CFUserNotification.c +++ b/CoreFoundation/AppServices.subproj/CFUserNotification.c @@ -1,7 +1,7 @@ /* CFUserNotification.c - Copyright (c) 2000-2017, Apple Inc. All rights reserved. + Copyright (c) 2000-2018, Apple Inc. All rights reserved. - Portions Copyright (c) 2014-2017, Apple Inc. and the Swift project authors + Portions Copyright (c) 2014-2018, Apple Inc. and the Swift project authors Licensed under Apache License v2.0 with Runtime Library Exception See http://swift.org/LICENSE.txt for license information See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors @@ -14,6 +14,7 @@ #include #include #include "CFInternal.h" +#include "CFRuntime_Internal.h" #include #include #include @@ -54,13 +55,13 @@ CONST_STRING_DECL(kCFUserNotificationPopUpTitlesKey, "PopUpTitles") CONST_STRING_DECL(kCFUserNotificationTextFieldTitlesKey, "TextFieldTitles") CONST_STRING_DECL(kCFUserNotificationCheckBoxTitlesKey, "CheckBoxTitles") CONST_STRING_DECL(kCFUserNotificationTextFieldValuesKey, "TextFieldValues") +#if TARGET_OS_OSX CONST_STRING_DECL(kCFUserNotificationPopUpSelectionKey, "PopUpSelection") +#endif CONST_STRING_DECL(kCFUserNotificationKeyboardTypesKey, "KeyboardTypes") CONST_STRING_DECL(kCFUserNotificationAlertTopMostKey, "AlertTopMost") // boolean value -static CFTypeID __kCFUserNotificationTypeID = _kCFRuntimeNotATypeID; - struct __CFUserNotification { CFRuntimeBase _base; SInt32 _replyPort; @@ -86,18 +87,13 @@ static CFStringRef __CFUserNotificationCopyDescription(CFTypeRef cf) { #define MAX_PORT_NAME_LENGTH 63 #define NOTIFICATION_PORT_NAME_SUFFIX ".session." #define MESSAGE_TIMEOUT 100 -#if DEPLOYMENT_TARGET_MACOSX -#define NOTIFICATION_PORT_NAME "com.apple.UNCUserNotification" -#elif DEPLOYMENT_TARGET_EMBEDDED -#define NOTIFICATION_PORT_NAME "com.apple.SBUserNotification" -#else -#error Unknown or unspecified DEPLOYMENT_TARGET -#endif +#define NOTIFICATION_PORT_NAME_MAC "com.apple.UNCUserNotification" +#define NOTIFICATION_PORT_NAME_IOS "com.apple.SBUserNotification" static void __CFUserNotificationDeallocate(CFTypeRef cf); -static const CFRuntimeClass __CFUserNotificationClass = { +const CFRuntimeClass __CFUserNotificationClass = { 0, "CFUserNotification", NULL, // init @@ -110,9 +106,7 @@ static const CFRuntimeClass __CFUserNotificationClass = { }; CFTypeID CFUserNotificationGetTypeID(void) { - static dispatch_once_t initOnce = 0; - dispatch_once(&initOnce, ^{ __kCFUserNotificationTypeID = _CFRuntimeRegisterClass(&__CFUserNotificationClass); }); - return __kCFUserNotificationTypeID; + return _kCFRuntimeIDCFUserNotification; } static void __CFUserNotificationDeallocate(CFTypeRef cf) { @@ -122,7 +116,7 @@ static void __CFUserNotificationDeallocate(CFTypeRef cf) { CFRelease(userNotification->_machPort); userNotification->_machPort = NULL; // NOTE: this is still potentially racey and should probably have a CAS (for now this is just a stop-gap to reduce an already very rare crash potential) } else if (MACH_PORT_NULL != userNotification->_replyPort) { - mach_port_destroy(mach_task_self(), userNotification->_replyPort); + mach_port_mod_refs(mach_task_self(), userNotification->_replyPort, MACH_PORT_RIGHT_RECEIVE, -1); } if (userNotification->_sessionID) CFRelease(userNotification->_sessionID); if (userNotification->_responseDictionary) CFRelease(userNotification->_responseDictionary); @@ -187,12 +181,19 @@ static SInt32 _CFUserNotificationSendRequest(CFAllocatorRef allocator, CFStringR mach_msg_base_t *msg = NULL; mach_port_t bootstrapPort = MACH_PORT_NULL, serverPort = MACH_PORT_NULL; CFIndex size; - char namebuffer[MAX_PORT_NAME_LENGTH + 1]; - strlcpy(namebuffer, NOTIFICATION_PORT_NAME, sizeof(namebuffer)); + +#if TARGET_OS_OSX + const char *namebuffer = NOTIFICATION_PORT_NAME_MAC; + const nameLen = sizeof(NOTIFICATION_PORT_NAME_MAC); +#else + const char *namebuffer = NOTIFICATION_PORT_NAME_IOS; + const nameLen = sizeof(NOTIFICATION_PORT_NAME_IOS); +#endif + if (sessionID) { char sessionid[MAX_PORT_NAME_LENGTH + 1]; - CFIndex len = MAX_PORT_NAME_LENGTH - sizeof(NOTIFICATION_PORT_NAME) - sizeof(NOTIFICATION_PORT_NAME_SUFFIX); + CFIndex len = MAX_PORT_NAME_LENGTH - nameLen - sizeof(NOTIFICATION_PORT_NAME_SUFFIX); CFStringGetBytes(sessionID, CFRangeMake(0, CFStringGetLength(sessionID)), kCFStringEncodingUTF8, 0, false, (uint8_t *)sessionid, len, &size); sessionid[len - 1] = '\0'; strlcat(namebuffer, NOTIFICATION_PORT_NAME_SUFFIX, sizeof(namebuffer)); @@ -271,7 +272,9 @@ CFUserNotificationRef CFUserNotificationCreate(CFAllocatorRef allocator, CFTimeI } else { if (dictionary) CFUserNotificationLog(CFDictionaryGetValue(dictionary, kCFUserNotificationAlertHeaderKey), CFDictionaryGetValue(dictionary, kCFUserNotificationAlertMessageKey)); } - if (ERR_SUCCESS != retval && MACH_PORT_NULL != replyPort) mach_port_destroy(mach_task_self(), replyPort); + if (ERR_SUCCESS != retval && MACH_PORT_NULL != replyPort) { + mach_port_mod_refs(mach_task_self(), replyPort, MACH_PORT_RIGHT_RECEIVE, -1); + } if (error) *error = retval; return userNotification; } @@ -290,7 +293,7 @@ static void _CFUserNotificationMachPortCallBack(CFMachPortRef port, void *m, CFI CFMachPortInvalidate(userNotification->_machPort); CFRelease(userNotification->_machPort); userNotification->_machPort = NULL; - mach_port_destroy(mach_task_self(), userNotification->_replyPort); + mach_port_mod_refs(mach_task_self(), userNotification->_replyPort, MACH_PORT_RIGHT_RECEIVE, -1); userNotification->_replyPort = MACH_PORT_NULL; userNotification->_callout(userNotification, responseFlags); } @@ -328,7 +331,7 @@ SInt32 CFUserNotificationReceiveResponse(CFUserNotificationRef userNotification, CFRelease(userNotification->_machPort); userNotification->_machPort = NULL; } - mach_port_destroy(mach_task_self(), userNotification->_replyPort); + mach_port_mod_refs(mach_task_self(), userNotification->_replyPort, MACH_PORT_RIGHT_RECEIVE, -1); userNotification->_replyPort = MACH_PORT_NULL; } CFAllocatorDeallocate(kCFAllocatorSystemDefault, msg); @@ -440,7 +443,8 @@ CF_EXPORT SInt32 CFUserNotificationDisplayAlert(CFTimeInterval timeout, CFOption #undef MAX_STRING_LENGTH #undef MAX_STRING_COUNT -#undef NOTIFICATION_PORT_NAME +#undef NOTIFICATION_PORT_NAME_MAC +#undef NOTIFICATION_PORT_NAME_IOS #undef MESSAGE_TIMEOUT #undef MAX_PORT_NAME_LENGTH #undef NOTIFICATION_PORT_NAME_SUFFIX diff --git a/CoreFoundation/AppServices.subproj/CFUserNotification.h b/CoreFoundation/AppServices.subproj/CFUserNotification.h index 9d01d7b333..1fff5dd024 100644 --- a/CoreFoundation/AppServices.subproj/CFUserNotification.h +++ b/CoreFoundation/AppServices.subproj/CFUserNotification.h @@ -1,7 +1,7 @@ /* CFUserNotification.h - Copyright (c) 2000-2017, Apple Inc. and the Swift project authors + Copyright (c) 2000-2018, Apple Inc. and the Swift project authors - Portions Copyright (c) 2014-2017, Apple Inc. and the Swift project authors + Portions Copyright (c) 2014-2018, Apple Inc. and the Swift project authors Licensed under Apache License v2.0 with Runtime Library Exception See http://swift.org/LICENSE.txt for license information See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors diff --git a/CoreFoundation/Base.subproj/CFAvailability.h b/CoreFoundation/Base.subproj/CFAvailability.h index fcb977d479..b9956c1c17 100644 --- a/CoreFoundation/Base.subproj/CFAvailability.h +++ b/CoreFoundation/Base.subproj/CFAvailability.h @@ -1,7 +1,7 @@ /* CFAvailability.h - Copyright (c) 2013-2017, Apple Inc. and the Swift project authors + Copyright (c) 2013-2018, Apple Inc. and the Swift project authors - Portions Copyright (c) 2014-2017, Apple Inc. and the Swift project authors + Portions Copyright (c) 2014-2018, Apple Inc. and the Swift project authors Licensed under Apache License v2.0 with Runtime Library Exception See http://swift.org/LICENSE.txt for license information See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors @@ -18,7 +18,7 @@ #error Missing header TargetConditionals.h #endif -#if __has_include() && __has_include() && __has_include() +#if __has_include() && __has_include() && __has_include() #include #include // Even if unused, these must remain here for compatibility, because projects rely on them being included. @@ -114,9 +114,11 @@ // Enums and Options #if __has_attribute(enum_extensibility) #define __CF_ENUM_ATTRIBUTES __attribute__((enum_extensibility(open))) +#define __CF_CLOSED_ENUM_ATTRIBUTES __attribute__((enum_extensibility(closed))) #define __CF_OPTIONS_ATTRIBUTES __attribute__((flag_enum,enum_extensibility(open))) #else #define __CF_ENUM_ATTRIBUTES +#define __CF_CLOSED_ENUM_ATTRIBUTES #define __CF_OPTIONS_ATTRIBUTES #endif @@ -124,6 +126,7 @@ #if (__cplusplus && __cplusplus >= 201103L && (__has_extension(cxx_strong_enums) || __has_feature(objc_fixed_enum))) || (!__cplusplus && __has_feature(objc_fixed_enum)) #define __CF_NAMED_ENUM(_type, _name) enum __CF_ENUM_ATTRIBUTES _name : _type _name; enum _name : _type #define __CF_ANON_ENUM(_type) enum __CF_ENUM_ATTRIBUTES : _type +#define CF_CLOSED_ENUM(_type, _name) enum __CF_CLOSED_ENUM_ATTRIBUTES _name : _type _name; enum _name : _type #if (__cplusplus) #define CF_OPTIONS(_type, _name) _type _name; enum __CF_OPTIONS_ATTRIBUTES : _type #else @@ -132,6 +135,7 @@ #else #define __CF_NAMED_ENUM(_type, _name) _type _name; enum #define __CF_ANON_ENUM(_type) enum +#define CF_CLOSED_ENUM(_type, _name) _type _name; enum #define CF_OPTIONS(_type, _name) _type _name; enum #endif @@ -198,6 +202,14 @@ CF_ENUM(CFIndex) { */ #define CF_ERROR_ENUM(...) __CF_ERROR_ENUM_GET_MACRO(__VA_ARGS__, __CF_NAMED_ERROR_ENUM, __CF_ANON_ERROR_ENUM)(__VA_ARGS__) +#ifndef CF_SWIFT_BRIDGED_TYPEDEF +#if __has_attribute(swift_bridged_typedef) +#define CF_SWIFT_BRIDGED_TYPEDEF __attribute__((swift_bridged_typedef)) +#else +#define CF_SWIFT_BRIDGED_TYPEDEF +#endif +#endif + // Extension availability macros #define CF_EXTENSION_UNAVAILABLE(_msg) __OS_EXTENSION_UNAVAILABLE(_msg) #define CF_EXTENSION_UNAVAILABLE_MAC(_msg) __OSX_EXTENSION_UNAVAILABLE(_msg) diff --git a/CoreFoundation/Base.subproj/CFBase.c b/CoreFoundation/Base.subproj/CFBase.c index 0cdb25ed7a..b828085399 100644 --- a/CoreFoundation/Base.subproj/CFBase.c +++ b/CoreFoundation/Base.subproj/CFBase.c @@ -1,7 +1,7 @@ /* CFBase.c - Copyright (c) 1998-2017, Apple Inc. and the Swift project authors + Copyright (c) 1998-2018, Apple Inc. and the Swift project authors - Portions Copyright (c) 2014-2017, Apple Inc. and the Swift project authors + Portions Copyright (c) 2014-2018, Apple Inc. and the Swift project authors Licensed under Apache License v2.0 with Runtime Library Exception See http://swift.org/LICENSE.txt for license information See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors @@ -10,6 +10,7 @@ #include #include "CFInternal.h" +#include "CFRuntime_Internal.h" #if DEPLOYMENT_TARGET_MACOSX || DEPLOYMENT_TARGET_EMBEDDED || DEPLOYMENT_TARGET_EMBEDDED_MINI || DEPLOYMENT_TARGET_LINUX || DEPLOYMENT_TARGET_FREEBSD #include #endif @@ -21,6 +22,8 @@ #include #include +#include "ForFoundationOnly.h" + // -------- -------- -------- -------- -------- -------- -------- -------- struct __CFAllocator { @@ -54,6 +57,10 @@ struct __CFAllocator { CFAllocatorContext _context; }; +CF_INLINE uintptr_t __CFISAForCFAllocator(void) { + return __CFRuntimeObjCClassTable[_kCFRuntimeIDCFAllocator]; +} + CF_INLINE CFAllocatorRetainCallBack __CFAllocatorGetRetainFunction(const CFAllocatorContext *context) { CFAllocatorRetainCallBack retval = NULL; retval = context->retain; @@ -96,7 +103,12 @@ CF_INLINE CFAllocatorPreferredSizeCallBack __CFAllocatorGetPreferredSizeFunction return retval; } -#if DEPLOYMENT_TARGET_MACOSX || DEPLOYMENT_TARGET_EMBEDDED || DEPLOYMENT_TARGET_EMBEDDED_MINI +static const void * const __MallocDefaultZoneInfoPlaceholder = NULL; +#if !TARGET_OS_MAC +#define malloc_default_zone() (NULL) +#endif + +#if TARGET_OS_MAC CF_PRIVATE void __CFAllocatorDeallocate(CFTypeRef cf); @@ -218,19 +230,22 @@ static const struct malloc_introspection_t __CFAllocatorNullZoneIntrospect = { }; static void *__CFAllocatorSystemAllocate(CFIndex size, CFOptionFlags hint, void *info) { - return malloc_zone_malloc(info, size); + malloc_zone_t * const zone = (info == &__MallocDefaultZoneInfoPlaceholder) ? malloc_default_zone() : (malloc_zone_t *)info; + return malloc_zone_malloc(zone, size); } static void *__CFAllocatorSystemReallocate(void *ptr, CFIndex newsize, CFOptionFlags hint, void *info) { - return malloc_zone_realloc(info, ptr, newsize); + malloc_zone_t * const zone = (info == &__MallocDefaultZoneInfoPlaceholder) ? malloc_default_zone() : (malloc_zone_t *)info; + return malloc_zone_realloc(zone, ptr, newsize); } static void __CFAllocatorSystemDeallocate(void *ptr, void *info) { + malloc_zone_t * const zone = (info == &__MallocDefaultZoneInfoPlaceholder) ? malloc_default_zone() : (malloc_zone_t *)info; #if defined(DEBUG) size_t size = malloc_size(ptr); if (size) memset(ptr, 0xCC, size); #endif - malloc_zone_free(info, ptr); + malloc_zone_free(zone, ptr); } #else @@ -272,9 +287,13 @@ static void __CFAllocatorCPPFree(void *ptr, void *info) #endif // C++ -static struct __CFAllocator __kCFAllocatorMalloc = { - INIT_CFRUNTIME_BASE(), -#if DEPLOYMENT_TARGET_MACOSX || DEPLOYMENT_TARGET_EMBEDDED || DEPLOYMENT_TARGET_EMBEDDED_MINI +static _CF_CONSTANT_OBJECT_BACKING struct __CFAllocator __kCFAllocatorSystemDefault; + +DECLARE_STATIC_CLASS_REF(__NSCFType); + +static _CF_CONSTANT_OBJECT_BACKING struct __CFAllocator __kCFAllocatorMalloc = { + INIT_CFRUNTIME_BASE_WITH_CLASS(__NSCFType, _kCFRuntimeIDCFAllocator), +#if TARGET_OS_MAC __CFAllocatorCustomSize, __CFAllocatorCustomMalloc, __CFAllocatorCustomCalloc, @@ -290,7 +309,7 @@ static struct __CFAllocator __kCFAllocatorMalloc = { NULL, NULL, #endif - NULL, // _allocator + &__kCFAllocatorSystemDefault, // _allocator // Using the malloc functions directly is a total cheat, but works (in C) // because the function signatures match in their common prefix of arguments. // This saves us one hop through an adaptor function. @@ -301,9 +320,9 @@ static struct __CFAllocator __kCFAllocatorMalloc = { #endif // __cplusplus }; -static struct __CFAllocator __kCFAllocatorMallocZone = { - INIT_CFRUNTIME_BASE(), -#if DEPLOYMENT_TARGET_MACOSX || DEPLOYMENT_TARGET_EMBEDDED || DEPLOYMENT_TARGET_EMBEDDED_MINI +static _CF_CONSTANT_OBJECT_BACKING struct __CFAllocator __kCFAllocatorMallocZone = { + INIT_CFRUNTIME_BASE_WITH_CLASS(__NSCFType, _kCFRuntimeIDCFAllocator), +#if TARGET_OS_MAC __CFAllocatorCustomSize, __CFAllocatorCustomMalloc, __CFAllocatorCustomCalloc, @@ -319,13 +338,13 @@ static struct __CFAllocator __kCFAllocatorMallocZone = { NULL, NULL, #endif - NULL, // _allocator - {0, NULL, NULL, NULL, NULL, __CFAllocatorSystemAllocate, __CFAllocatorSystemReallocate, __CFAllocatorSystemDeallocate, NULL} + &__kCFAllocatorSystemDefault, // _allocator + {0, (void *)&__MallocDefaultZoneInfoPlaceholder, NULL, NULL, NULL, __CFAllocatorSystemAllocate, __CFAllocatorSystemReallocate, __CFAllocatorSystemDeallocate, NULL} }; -static struct __CFAllocator __kCFAllocatorSystemDefault = { - INIT_CFRUNTIME_BASE(), -#if DEPLOYMENT_TARGET_MACOSX || DEPLOYMENT_TARGET_EMBEDDED || DEPLOYMENT_TARGET_EMBEDDED_MINI +static _CF_CONSTANT_OBJECT_BACKING struct __CFAllocator __kCFAllocatorSystemDefault = { + INIT_CFRUNTIME_BASE_WITH_CLASS(__NSCFType, _kCFRuntimeIDCFAllocator), +#if TARGET_OS_MAC __CFAllocatorCustomSize, __CFAllocatorCustomMalloc, __CFAllocatorCustomCalloc, @@ -341,13 +360,13 @@ static struct __CFAllocator __kCFAllocatorSystemDefault = { NULL, NULL, #endif - NULL, // _allocator - {0, NULL, NULL, NULL, NULL, __CFAllocatorSystemAllocate, __CFAllocatorSystemReallocate, __CFAllocatorSystemDeallocate, NULL} + &__kCFAllocatorSystemDefault, // _allocator + {0, (void *)&__MallocDefaultZoneInfoPlaceholder, NULL, NULL, NULL, __CFAllocatorSystemAllocate, __CFAllocatorSystemReallocate, __CFAllocatorSystemDeallocate, NULL} }; -static struct __CFAllocator __kCFAllocatorNull = { - INIT_CFRUNTIME_BASE(), -#if DEPLOYMENT_TARGET_MACOSX || DEPLOYMENT_TARGET_EMBEDDED || DEPLOYMENT_TARGET_EMBEDDED_MINI +static _CF_CONSTANT_OBJECT_BACKING struct __CFAllocator __kCFAllocatorNull = { + INIT_CFRUNTIME_BASE_WITH_CLASS(__NSCFType, _kCFRuntimeIDCFAllocator), +#if TARGET_OS_MAC __CFAllocatorNullSize, __CFAllocatorNullMalloc, __CFAllocatorNullCalloc, @@ -363,7 +382,7 @@ static struct __CFAllocator __kCFAllocatorNull = { NULL, NULL, #endif - NULL, // _allocator + &__kCFAllocatorSystemDefault, // _allocator {0, NULL, NULL, NULL, NULL, __CFAllocatorNullAllocate, __CFAllocatorNullReallocate, NULL, NULL} }; @@ -416,9 +435,7 @@ CF_PRIVATE void __CFAllocatorDeallocate(CFTypeRef cf) { } } -static CFTypeID __kCFAllocatorTypeID = _kCFRuntimeNotATypeID; - -static const CFRuntimeClass __CFAllocatorClass = { +const CFRuntimeClass __CFAllocatorClass = { 0, "CFAllocator", NULL, // init @@ -431,37 +448,12 @@ static const CFRuntimeClass __CFAllocatorClass = { }; static void _CFAllocatorSetInstanceTypeIDAndIsa(struct __CFAllocator *memory) { - _CFRuntimeSetInstanceTypeID(memory, __kCFAllocatorTypeID); - memory->_base._cfisa = __CFISAForTypeID(__kCFAllocatorTypeID); -} - -CF_PRIVATE void __CFAllocatorInitialize(void) { - static dispatch_once_t initOnce = 0; - dispatch_once(&initOnce, ^{ - __kCFAllocatorTypeID = _CFRuntimeRegisterClass(&__CFAllocatorClass); // initOnce covered - - _CFAllocatorSetInstanceTypeIDAndIsa(&__kCFAllocatorSystemDefault); -#if DEPLOYMENT_TARGET_MACOSX || DEPLOYMENT_TARGET_EMBEDDED || DEPLOYMENT_TARGET_EMBEDDED_MINI - __kCFAllocatorSystemDefault._context.info = malloc_default_zone(); -#endif - __kCFAllocatorSystemDefault._allocator = kCFAllocatorSystemDefault; - - _CFAllocatorSetInstanceTypeIDAndIsa(&__kCFAllocatorMalloc); - __kCFAllocatorMalloc._allocator = kCFAllocatorSystemDefault; - -#if DEPLOYMENT_TARGET_MACOSX || DEPLOYMENT_TARGET_EMBEDDED || DEPLOYMENT_TARGET_EMBEDDED_MINI - _CFAllocatorSetInstanceTypeIDAndIsa(&__kCFAllocatorMallocZone); - __kCFAllocatorMallocZone._allocator = kCFAllocatorSystemDefault; - __kCFAllocatorMallocZone._context.info = malloc_default_zone(); -#endif - - _CFAllocatorSetInstanceTypeIDAndIsa(&__kCFAllocatorNull); - __kCFAllocatorNull._allocator = kCFAllocatorSystemDefault; - }); + _CFRuntimeSetInstanceTypeID(memory, _kCFRuntimeIDCFAllocator); + memory->_base._cfisa = __CFISAForCFAllocator(); } CFTypeID CFAllocatorGetTypeID(void) { - return __kCFAllocatorTypeID; + return _kCFRuntimeIDCFAllocator; } CFAllocatorRef CFAllocatorGetDefault(void) { @@ -472,11 +464,11 @@ void CFAllocatorSetDefault(CFAllocatorRef allocator) { CFAllocatorRef current = __CFGetDefaultAllocator(); #if defined(DEBUG) if (NULL != allocator) { - __CFGenericValidateType(allocator, __kCFAllocatorTypeID); + __CFGenericValidateType(allocator, _kCFRuntimeIDCFAllocator); } #endif #if DEPLOYMENT_TARGET_MACOSX || DEPLOYMENT_TARGET_EMBEDDED || DEPLOYMENT_TARGET_EMBEDDED_MINI - if (allocator && allocator->_base._cfisa != __CFISAForTypeID(__kCFAllocatorTypeID)) { // malloc_zone_t * + if (allocator && allocator->_base._cfisa != __CFISAForCFAllocator()) { // malloc_zone_t * return; // require allocator to this function to be an allocator } #endif @@ -502,7 +494,7 @@ static CFAllocatorRef __CFAllocatorCreate(CFAllocatorRef allocator, CFAllocatorC CFAllocatorAllocateCallBack allocateFunc; void *retainedInfo; #if DEPLOYMENT_TARGET_MACOSX || DEPLOYMENT_TARGET_EMBEDDED || DEPLOYMENT_TARGET_EMBEDDED_MINI - if (allocator && kCFAllocatorUseContext != allocator && allocator->_base._cfisa != __CFISAForTypeID(__kCFAllocatorTypeID)) { // malloc_zone_t * + if (allocator && kCFAllocatorUseContext != allocator && allocator->_base._cfisa != __CFISAForCFAllocator()) { // malloc_zone_t * return NULL; // require allocator to this function to be an allocator } #endif @@ -585,15 +577,15 @@ void *CFAllocatorAllocate(CFAllocatorRef allocator, CFIndex size, CFOptionFlags } #if defined(DEBUG) && (DEPLOYMENT_TARGET_MACOSX || DEPLOYMENT_TARGET_EMBEDDED || DEPLOYMENT_TARGET_EMBEDDED_MINI) - if (allocator->_base._cfisa == __CFISAForTypeID(__kCFAllocatorTypeID)) { - __CFGenericValidateType(allocator, __kCFAllocatorTypeID); + if (allocator->_base._cfisa == __CFISAForCFAllocator()) { + __CFGenericValidateType(allocator, _kCFRuntimeIDCFAllocator); } #else - __CFGenericValidateType(allocator, __kCFAllocatorTypeID); + __CFGenericValidateType(allocator, _kCFRuntimeIDCFAllocator); #endif if (0 == size) return NULL; #if DEPLOYMENT_TARGET_MACOSX || DEPLOYMENT_TARGET_EMBEDDED || DEPLOYMENT_TARGET_EMBEDDED_MINI - if (allocator->_base._cfisa != __CFISAForTypeID(__kCFAllocatorTypeID)) { // malloc_zone_t * + if (allocator->_base._cfisa != __CFISAForCFAllocator()) { // malloc_zone_t * return malloc_zone_malloc((malloc_zone_t *)allocator, size); } #endif @@ -616,15 +608,15 @@ void *CFAllocatorReallocate(CFAllocatorRef allocator, void *ptr, CFIndex newsize } #if defined(DEBUG) && (DEPLOYMENT_TARGET_MACOSX || DEPLOYMENT_TARGET_EMBEDDED || DEPLOYMENT_TARGET_EMBEDDED_MINI) - if (allocator->_base._cfisa == __CFISAForTypeID(__kCFAllocatorTypeID)) { - __CFGenericValidateType(allocator, __kCFAllocatorTypeID); + if (allocator->_base._cfisa == __CFISAForCFAllocator()) { + __CFGenericValidateType(allocator, _kCFRuntimeIDCFAllocator); } #else - __CFGenericValidateType(allocator, __kCFAllocatorTypeID); + __CFGenericValidateType(allocator, _kCFRuntimeIDCFAllocator); #endif if (NULL == ptr && 0 < newsize) { #if DEPLOYMENT_TARGET_MACOSX || DEPLOYMENT_TARGET_EMBEDDED || DEPLOYMENT_TARGET_EMBEDDED_MINI - if (allocator->_base._cfisa != __CFISAForTypeID(__kCFAllocatorTypeID)) { // malloc_zone_t * + if (allocator->_base._cfisa != __CFISAForCFAllocator()) { // malloc_zone_t * return malloc_zone_malloc((malloc_zone_t *)allocator, newsize); } #endif @@ -637,7 +629,7 @@ void *CFAllocatorReallocate(CFAllocatorRef allocator, void *ptr, CFIndex newsize } if (NULL != ptr && 0 == newsize) { #if DEPLOYMENT_TARGET_MACOSX || DEPLOYMENT_TARGET_EMBEDDED || DEPLOYMENT_TARGET_EMBEDDED_MINI - if (allocator->_base._cfisa != __CFISAForTypeID(__kCFAllocatorTypeID)) { // malloc_zone_t * + if (allocator->_base._cfisa != __CFISAForCFAllocator()) { // malloc_zone_t * #if defined(DEBUG) size_t size = malloc_size(ptr); if (size) memset(ptr, 0xCC, size); @@ -654,7 +646,7 @@ void *CFAllocatorReallocate(CFAllocatorRef allocator, void *ptr, CFIndex newsize } if (NULL == ptr && 0 == newsize) return NULL; #if DEPLOYMENT_TARGET_MACOSX || DEPLOYMENT_TARGET_EMBEDDED || DEPLOYMENT_TARGET_EMBEDDED_MINI - if (allocator->_base._cfisa != __CFISAForTypeID(__kCFAllocatorTypeID)) { // malloc_zone_t * + if (allocator->_base._cfisa != __CFISAForCFAllocator()) { // malloc_zone_t * return malloc_zone_realloc((malloc_zone_t *)allocator, ptr, newsize); } #endif @@ -672,14 +664,14 @@ void CFAllocatorDeallocate(CFAllocatorRef allocator, void *ptr) { } #if defined(DEBUG) && (DEPLOYMENT_TARGET_MACOSX || DEPLOYMENT_TARGET_EMBEDDED || DEPLOYMENT_TARGET_EMBEDDED_MINI) - if (allocator->_base._cfisa == __CFISAForTypeID(__kCFAllocatorTypeID)) { - __CFGenericValidateType(allocator, __kCFAllocatorTypeID); + if (allocator->_base._cfisa == __CFISAForCFAllocator()) { + __CFGenericValidateType(allocator, _kCFRuntimeIDCFAllocator); } #else - __CFGenericValidateType(allocator, __kCFAllocatorTypeID); + __CFGenericValidateType(allocator, _kCFRuntimeIDCFAllocator); #endif #if DEPLOYMENT_TARGET_MACOSX || DEPLOYMENT_TARGET_EMBEDDED || DEPLOYMENT_TARGET_EMBEDDED_MINI - if (allocator->_base._cfisa != __CFISAForTypeID(__kCFAllocatorTypeID)) { // malloc_zone_t * + if (allocator->_base._cfisa != __CFISAForCFAllocator()) { // malloc_zone_t * #if defined(DEBUG) size_t size = malloc_size(ptr); if (size) memset(ptr, 0xCC, size); @@ -702,14 +694,14 @@ CFIndex CFAllocatorGetPreferredSizeForSize(CFAllocatorRef allocator, CFIndex siz } #if defined(DEBUG) && (DEPLOYMENT_TARGET_MACOSX || DEPLOYMENT_TARGET_EMBEDDED || DEPLOYMENT_TARGET_EMBEDDED_MINI) - if (allocator->_base._cfisa == __CFISAForTypeID(__kCFAllocatorTypeID)) { - __CFGenericValidateType(allocator, __kCFAllocatorTypeID); + if (allocator->_base._cfisa == __CFISAForCFAllocator()) { + __CFGenericValidateType(allocator, _kCFRuntimeIDCFAllocator); } #else - __CFGenericValidateType(allocator, __kCFAllocatorTypeID); + __CFGenericValidateType(allocator, _kCFRuntimeIDCFAllocator); #endif #if DEPLOYMENT_TARGET_MACOSX || DEPLOYMENT_TARGET_EMBEDDED || DEPLOYMENT_TARGET_EMBEDDED_MINI - if (allocator->_base._cfisa != __CFISAForTypeID(__kCFAllocatorTypeID)) { // malloc_zone_t * + if (allocator->_base._cfisa != __CFISAForCFAllocator()) { // malloc_zone_t * return malloc_good_size(size); } #endif @@ -727,20 +719,20 @@ void CFAllocatorGetContext(CFAllocatorRef allocator, CFAllocatorContext *context } #if defined(DEBUG) && (DEPLOYMENT_TARGET_MACOSX || DEPLOYMENT_TARGET_EMBEDDED || DEPLOYMENT_TARGET_EMBEDDED_MINI) - if (allocator->_base._cfisa == __CFISAForTypeID(__kCFAllocatorTypeID)) { - __CFGenericValidateType(allocator, __kCFAllocatorTypeID); + if (allocator->_base._cfisa == __CFISAForCFAllocator()) { + __CFGenericValidateType(allocator, _kCFRuntimeIDCFAllocator); } #else - __CFGenericValidateType(allocator, __kCFAllocatorTypeID); + __CFGenericValidateType(allocator, _kCFRuntimeIDCFAllocator); #endif CFAssert1(0 == context->version, __kCFLogAssertion, "%s(): context version not initialized to 0", __PRETTY_FUNCTION__); #if DEPLOYMENT_TARGET_MACOSX || DEPLOYMENT_TARGET_EMBEDDED || DEPLOYMENT_TARGET_EMBEDDED_MINI - if (allocator->_base._cfisa != __CFISAForTypeID(__kCFAllocatorTypeID)) { // malloc_zone_t * + if (allocator->_base._cfisa != __CFISAForCFAllocator()) { // malloc_zone_t * return; } #endif context->version = 0; - context->info = allocator->_context.info; + context->info = (allocator->_context.info == &__MallocDefaultZoneInfoPlaceholder) ? (void *)malloc_default_zone() : allocator->_context.info; context->retain = __CFAllocatorGetRetainFunction(&allocator->_context); context->release = __CFAllocatorGetReleaseFunction(&allocator->_context); context->copyDescription = __CFAllocatorGetCopyDescriptionFunction(&allocator->_context); @@ -800,8 +792,10 @@ struct __CFNull { CFRuntimeBase _base; }; -static struct __CFNull __kCFNull = { - INIT_CFRUNTIME_BASE() +DECLARE_STATIC_CLASS_REF(NSNull); + +static struct __CFNull _CF_CONSTANT_OBJECT_BACKING __kCFNull = { + INIT_CFRUNTIME_BASE_WITH_CLASS(NSNull, _kCFRuntimeIDCFNull) }; const CFNullRef kCFNull = &__kCFNull; @@ -817,9 +811,7 @@ static void __CFNullDeallocate(CFTypeRef cf) { CFAssert(false, __kCFLogAssertion, "Deallocated CFNull!"); } -static CFTypeID __kCFNullTypeID = _kCFRuntimeNotATypeID; - -static const CFRuntimeClass __CFNullClass = { +const CFRuntimeClass __CFNullClass = { 0, "CFNull", NULL, // init @@ -832,12 +824,7 @@ static const CFRuntimeClass __CFNullClass = { }; CFTypeID CFNullGetTypeID(void) { - static dispatch_once_t initOnce = 0; - dispatch_once(&initOnce, ^{ - __kCFNullTypeID = _CFRuntimeRegisterClass(&__CFNullClass); // initOnce covered - _CFRuntimeSetInstanceTypeIDAndIsa(&__kCFNull, __kCFNullTypeID); - }); - return __kCFNullTypeID; + return _kCFRuntimeIDCFNull; } void CFCollection_non_gc_storage_error(void) { } diff --git a/CoreFoundation/Base.subproj/CFBase.h b/CoreFoundation/Base.subproj/CFBase.h index 34ca2f80e9..6358493e33 100644 --- a/CoreFoundation/Base.subproj/CFBase.h +++ b/CoreFoundation/Base.subproj/CFBase.h @@ -1,7 +1,7 @@ /* CFBase.h - Copyright (c) 1998-2017, Apple Inc. and the Swift project authors + Copyright (c) 1998-2018, Apple Inc. and the Swift project authors - Portions Copyright (c) 2014-2017, Apple Inc. and the Swift project authors + Portions Copyright (c) 2014-2018, Apple Inc. and the Swift project authors Licensed under Apache License v2.0 with Runtime Library Exception See http://swift.org/LICENSE.txt for license information See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors @@ -139,9 +139,7 @@ #endif #endif #else - #define CF_EXPORT extern - #endif CF_EXTERN_C_BEGIN @@ -682,9 +680,8 @@ CFTypeRef CFMakeCollectable(CFTypeRef cf) CF_AUTOMATED_REFCOUNT_UNAVAILABLE; #if DEPLOYMENT_RUNTIME_SWIFT -#define _CF_SWIFT_RC_PINNED_FLAG 0x1 -#define _CF_CONSTANT_OBJECT_STRONG_RC (_CF_SWIFT_RC_PINNED_FLAG) - +#define _CF_SWIFT_RC_PINNED_FLAG (0x1) +#define _CF_CONSTANT_OBJECT_STRONG_RC ((uintptr_t)_CF_SWIFT_RC_PINNED_FLAG) #endif CF_EXTERN_C_END diff --git a/CoreFoundation/Base.subproj/CFByteOrder.h b/CoreFoundation/Base.subproj/CFByteOrder.h index 79fb412a55..1bd0112595 100644 --- a/CoreFoundation/Base.subproj/CFByteOrder.h +++ b/CoreFoundation/Base.subproj/CFByteOrder.h @@ -1,7 +1,7 @@ /* CFByteOrder.h - Copyright (c) 1995-2017, Apple Inc. and the Swift project authors + Copyright (c) 1995-2018, Apple Inc. and the Swift project authors - Portions Copyright (c) 2014-2017, Apple Inc. and the Swift project authors + Portions Copyright (c) 2014-2018, Apple Inc. and the Swift project authors Licensed under Apache License v2.0 with Runtime Library Exception See http://swift.org/LICENSE.txt for license information See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors diff --git a/CoreFoundation/Base.subproj/CFFileUtilities.c b/CoreFoundation/Base.subproj/CFFileUtilities.c index 984cf1f122..12c69b5271 100644 --- a/CoreFoundation/Base.subproj/CFFileUtilities.c +++ b/CoreFoundation/Base.subproj/CFFileUtilities.c @@ -1,7 +1,7 @@ /* CFFileUtilities.c - Copyright (c) 1999-2017, Apple Inc. and the Swift project authors + Copyright (c) 1999-2018, Apple Inc. and the Swift project authors - Portions Copyright (c) 2014-2017, Apple Inc. and the Swift project authors + Portions Copyright (c) 2014-2018, Apple Inc. and the Swift project authors Licensed under Apache License v2.0 with Runtime Library Exception See http://swift.org/LICENSE.txt for license information See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors @@ -11,11 +11,11 @@ #include "CFInternal.h" #include +#include #include #include #include #include -#include #if DEPLOYMENT_TARGET_WINDOWS #include @@ -1178,7 +1178,6 @@ CF_PRIVATE void _CFIterateDirectory(CFStringRef directoryPath, Boolean appendSla #endif } - #if !DEPLOYMENT_RUNTIME_OBJC // https://specifications.freedesktop.org/basedir-spec/basedir-spec-latest.html @@ -1357,4 +1356,3 @@ CF_PRIVATE CFArrayRef _CFCreateCFArrayByTokenizingString(const char *values, cha } #endif // !DEPLOYMENT_RUNTIME_OBJC - diff --git a/CoreFoundation/Base.subproj/CFInternal.h b/CoreFoundation/Base.subproj/CFInternal.h index ed684cd40a..62d4a94f45 100644 --- a/CoreFoundation/Base.subproj/CFInternal.h +++ b/CoreFoundation/Base.subproj/CFInternal.h @@ -1,7 +1,7 @@ /* CFInternal.h - Copyright (c) 1998-2017, Apple Inc. and the Swift project authors + Copyright (c) 1998-2018, Apple Inc. and the Swift project authors - Portions Copyright (c) 2014-2017, Apple Inc. and the Swift project authors + Portions Copyright (c) 2014-2018, Apple Inc. and the Swift project authors Licensed under Apache License v2.0 with Runtime Library Exception See http://swift.org/LICENSE.txt for license information See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors @@ -82,17 +82,6 @@ #define _CF_RELEASES_ARGUMENT_OBJ #endif -#if DEPLOYMENT_TARGET_WINDOWS - // No C99 support - #define _CF_RESTRICT -#else - #if defined(__cplusplus) - #define _CF_RESTRICT __restrict__ - #else - #define _CF_RESTRICT restrict - #endif -#endif - CF_EXTERN_C_BEGIN #include @@ -105,18 +94,19 @@ CF_EXTERN_C_BEGIN #include #include #include + #if DEPLOYMENT_TARGET_MACOSX || DEPLOYMENT_TARGET_EMBEDDED || DEPLOYMENT_TARGET_EMBEDDED_MINI || DEPLOYMENT_TARGET_LINUX || DEPLOYMENT_TARGET_FREEBSD -#if TARGET_OS_CYGWIN -#else -#if !defined(__linux__) + +#if !TARGET_OS_CYGWIN && !defined(__linux__) #include -#endif -#endif +#endif // !TARGET_OS_CYGWIN && !defined(__linux__) + #include #include #include #include -#endif +#endif // DEPLOYMENT_TARGET_MACOSX || DEPLOYMENT_TARGET_EMBEDDED || DEPLOYMENT_TARGET_EMBEDDED_MINI || DEPLOYMENT_TARGET_LINUX || DEPLOYMENT_TARGET_FREEBSD + #include #if !DEPLOYMENT_RUNTIME_SWIFT && __has_include() @@ -130,6 +120,13 @@ typedef struct os_log_s *os_log_t; #define os_log_create(...) (NULL) #endif +// We want to eventually note that some objects are immortal to the Swift runtime, but this stopgap lets things work while we work to make an ABI for them. +#if DEPLOYMENT_RUNTIME_SWIFT +#define _CF_CONSTANT_OBJECT_BACKING // We don't support this on Swift +#else +#define _CF_CONSTANT_OBJECT_BACKING const +#endif + #if DEPLOYMENT_TARGET_MACOSX && DEPLOYMENT_RUNTIME_SWIFT // This target configuration some how misses the availability macros to let these be defined, so this works-around the missing definitions #ifndef PTHREAD_ERRORCHECK_MUTEX_INITIALIZER @@ -153,10 +150,11 @@ typedef struct os_log_s *os_log_t; #include #if DEPLOYMENT_RUNTIME_SWIFT #include +#include #endif CF_EXPORT const char *_CFProcessName(void); -CF_EXPORT CFStringRef _CFProcessNameString(void); +CF_PRIVATE CFStringRef _CFProcessNameString(void); CF_EXPORT Boolean _CFGetCurrentDirectory(char *path, int maxlen); @@ -190,11 +188,11 @@ CF_PRIVATE CFIndex __CFActiveProcessorCount(void); #define HALT_MSG(str) do { CRSetCrashLogMessage(str); HALT; } while (0) #if defined(DEBUG) - #define CFAssert(cond, prio, desc) do { if (!(cond)) { CFLog(prio, CFSTR(desc)); HALT; } } while (0) - #define CFAssert1(cond, prio, desc, a1) do { if (!(cond)) { CFLog(prio, CFSTR(desc), a1); HALT; } } while (0) - #define CFAssert2(cond, prio, desc, a1, a2) do { if (!(cond)) { CFLog(prio, CFSTR(desc), a1, a2); HALT; } } while (0) - #define CFAssert3(cond, prio, desc, a1, a2, a3) do { if (!(cond)) { CFLog(prio, CFSTR(desc), a1, a2, a3); HALT; } } while (0) - #define CFAssert4(cond, prio, desc, a1, a2, a3, a4) do { if (!(cond)) { CFLog(prio, CFSTR(desc), a1, a2, a3, a4); HALT; } } while (0) + #define CFAssert(cond, prio, desc) do { if (!(cond)) { CFLog(prio, CFSTR(desc)); /* HALT; */ } } while (0) + #define CFAssert1(cond, prio, desc, a1) do { if (!(cond)) { CFLog(prio, CFSTR(desc), a1); /* HALT; */ } } while (0) + #define CFAssert2(cond, prio, desc, a1, a2) do { if (!(cond)) { CFLog(prio, CFSTR(desc), a1, a2); /* HALT; */ } } while (0) + #define CFAssert3(cond, prio, desc, a1, a2, a3) do { if (!(cond)) { CFLog(prio, CFSTR(desc), a1, a2, a3); /* HALT; */ } } while (0) + #define CFAssert4(cond, prio, desc, a1, a2, a3, a4) do { if (!(cond)) { CFLog(prio, CFSTR(desc), a1, a2, a3, a4); /* HALT; */ } } while (0) #else #define CFAssert(cond, prio, desc) do {} while (0) #define CFAssert1(cond, prio, desc, a1) do {} while (0) @@ -279,6 +277,24 @@ static inline void __CFRuntimeSetFlag(CFTypeRef cf, uint8_t n, Boolean flag) { CF_PRIVATE Boolean __CFRuntimeIsConstant(CFTypeRef cf); CF_PRIVATE void __CFRuntimeSetRC(CFTypeRef cf, uint32_t rc); +#if DEPLOYMENT_RUNTIME_SWIFT +#define _CFRUNTIME_BASE_INIT_SWIFT_RETAIN_COUNT ._swift_rc = _CF_CONSTANT_OBJECT_STRONG_RC +#else +#define _CFRUNTIME_BASE_INIT_SWIFT_RETAIN_COUNT +#endif + +// A note on these macros. +// On systems where we have ObjC support (DEPLOYMENT_RUNTIME_OBJC), STATIC_CLASS_REF(…) can statically produce a reference to the ObjC class symbol that ties into this particular type. +// When compiling for Swift Foundation, STATIC_CLASS_REF returns a Swift class. There's a mapping of ObjC name classes to Swift symbols in the header that defines it that should be kept up to date if more constant objects are defined. +// On all other platforms, it returns NULL, which is okay; we only need the type ID if CF is to be used by itself. +#if __LP64__ + #define INIT_CFRUNTIME_BASE_WITH_CLASS(CLASS, TYPEID) { ._cfisa = (uintptr_t)STATIC_CLASS_REF(CLASS) , ._cfinfoa = 0x0000000000000080ULL | ((TYPEID) << 8), _CFRUNTIME_BASE_INIT_SWIFT_RETAIN_COUNT } + #define INIT_CFRUNTIME_BASE_WITH_CLASS_AND_FLAGS(CLASS, TYPEID, FLAGS) { ._cfisa = (uintptr_t)STATIC_CLASS_REF(CLASS) , ._cfinfoa = 0x0000000000000080ULL | ((TYPEID) << 8) | (FLAGS), _CFRUNTIME_BASE_INIT_SWIFT_RETAIN_COUNT } +#else // if !__LP64__ + #define INIT_CFRUNTIME_BASE_WITH_CLASS(CLASS, TYPEID) { ._cfisa = (uintptr_t)STATIC_CLASS_REF(CLASS) , ._cfinfoa = 0x00000080UL | ((TYPEID) << 8), _CFRUNTIME_BASE_INIT_SWIFT_RETAIN_COUNT } + #define INIT_CFRUNTIME_BASE_WITH_CLASS_AND_FLAGS(CLASS, TYPEID, FLAGS) { ._cfisa = (uintptr_t)STATIC_CLASS_REF(CLASS), ._cfinfoa = 0x0000000000000080ULL | ((TYPEID) << 8) | (FLAGS), _CFRUNTIME_BASE_INIT_SWIFT_RETAIN_COUNT } +#endif // __LP64__ + #define __CFBitIsSet(V, N) (((V) & (1UL << (N))) != 0) #define __CFBitSet(V, N) ((V) |= (1UL << (N))) #define __CFBitClear(V, N) ((V) &= ~(1UL << (N))) @@ -308,8 +324,6 @@ enum { }; -#define __kCFAllocatorTypeID_CONST 2 - CF_INLINE CFAllocatorRef __CFGetDefaultAllocator(void) { CFAllocatorRef allocator = (CFAllocatorRef)_CFGetTSD(__CFTSDKeyAllocator); if (NULL == allocator) { @@ -388,7 +402,6 @@ CF_PRIVATE Boolean __CFProcessIsRestricted(void); #define STACK_BUFFER_DECL(T, N, C) T N[C] #endif -#define SAFE_STACK_BUFFER_DEFINE(Type, Name) Type *Name = NULL; BOOL __ ## Name ## WasMallocd = NO; #if DEPLOYMENT_TARGET_WINDOWS #define SAFE_STACK_BUFFER_DECL(Type, Name, Count, Max) Type *Name; BOOL __ ## Name ## WasMallocd = NO; if (sizeof(Type) * Count > Max) { Name = (Type *)malloc((Count) * sizeof(Type)); __ ## Name ## WasMallocd = YES; } else Name = (Count > 0) ? _alloca((Count) * sizeof(Type)) : NULL @@ -398,42 +411,48 @@ CF_PRIVATE Boolean __CFProcessIsRestricted(void); #define SAFE_STACK_BUFFER_DECL(Type, Name, Count, Max) Type *Name; BOOL __ ## Name ## WasMallocd = NO; if (sizeof(Type) * Count > Max) { Name = (Type *)malloc((Count) * sizeof(Type)); __ ## Name ## WasMallocd = YES; } else Name = (Count > 0) ? alloca((Count) * sizeof(Type)) : NULL // Allocate a pre-named stack buffer. Max is the max size (in bytes) before falling over to malloc. +#define SAFE_STACK_BUFFER_DEFINE(Type, Name) Type *Name = NULL; BOOL __ ## Name ## WasMallocd = NO; #define SAFE_STACK_BUFFER_USE(Type, Name, Count, Max) if (sizeof(Type) * Count > Max) { Name = (Type *)malloc((Count) * sizeof(Type)); __ ## Name ## WasMallocd = YES; } else Name = (Count > 0) ? alloca((Count) * sizeof(Type)) : NULL -#endif // DEPLOYMENT_TARGET_MACOSX || DEPLOYMENT_TARGET_EMBEDDED // Be sure to call this before your SAFE_STACK_BUFFER exits scope. #define SAFE_STACK_BUFFER_CLEANUP(Name) if (__ ## Name ## WasMallocd) free(Name) +#endif // DEPLOYMENT_TARGET_MACOSX || DEPLOYMENT_TARGET_EMBEDDED + CF_EXPORT void * __CFConstantStringClassReferencePtr; #if DEPLOYMENT_RUNTIME_SWIFT -#if TARGET_OS_MAC -#define __CFConstantStringClassReference $s15SwiftFoundation19_NSCFConstantStringCN -#else -#define __CFConstantStringClassReference $s10Foundation19_NSCFConstantStringCN -#endif - -CF_EXPORT void *__CFConstantStringClassReference[]; - #if DEPLOYMENT_TARGET_LINUX #define CONST_STRING_SECTION __attribute__((section(".cfstr.data"))) #else #define CONST_STRING_SECTION #endif +#if __BIG_ENDIAN__ +#define _CF_CONST_STR_CFINFOA 0x00000000C8070000 +#else // Little endian: +#define _CF_CONST_STR_CFINFOA 0x07C8 +#endif // __BIG_ENDIAN__ + +#define _CF_CONST_STR_CONTENTS(cStr) {{(uintptr_t)&_CF_CONSTANT_STRING_SWIFT_CLASS, _CF_CONSTANT_OBJECT_STRONG_RC, _CF_CONST_STR_CFINFOA}, (uint8_t *)(cStr), sizeof(cStr) - 1} + #define CONST_STRING_DECL(S, V) \ -const struct __CFConstStr __##S CONST_STRING_SECTION = {{(uintptr_t)&__CFConstantStringClassReference, _CF_CONSTANT_OBJECT_STRONG_RC, 0x000007c8U}, (uint8_t *)(V), sizeof(V) - 1}; \ +_CF_CONSTANT_OBJECT_BACKING struct __CFConstStr __##S CONST_STRING_SECTION = _CF_CONST_STR_CONTENTS(V); \ const CFStringRef S = (CFStringRef)&__##S; +#define STATIC_CONST_STRING_DECL(S, V) \ +static _CF_CONSTANT_OBJECT_BACKING struct __CFConstStr __##S CONST_STRING_SECTION = _CF_CONST_STR_CONTENTS(V); \ +static const CFStringRef S = (CFStringRef)&__##S; + #define PE_CONST_STRING_DECL(S, V) \ -const static struct __CFConstStr __##S CONST_STRING_SECTION = {{(uintptr_t)&__CFConstantStringClassReference, _CF_CONSTANT_OBJECT_STRONG_RC, 0x000007c8U}, (uint8_t *)(V), sizeof(V) - 1}; \ +static _CF_CONSTANT_OBJECT_BACKING struct __CFConstStr __##S CONST_STRING_SECTION = _CF_CONST_STR_CONTENTS(V); \ CF_PRIVATE const CFStringRef S = (CFStringRef)&__##S; - #elif defined(__CONSTANT_CFSTRINGS__) #define CONST_STRING_DECL(S, V) const CFStringRef S = (const CFStringRef)__builtin___CFStringMakeConstantString(V); +#define STATIC_CONST_STRING_DECL(S, V) static const CFStringRef S = (const CFStringRef)__builtin___CFStringMakeConstantString(V); #define PE_CONST_STRING_DECL(S, V) CF_PRIVATE const CFStringRef S = (const CFStringRef)__builtin___CFStringMakeConstantString(V); #else @@ -479,7 +498,7 @@ extern CFTypeRef CFMakeUncollectable(CFTypeRef cf); CF_PRIVATE void _CFRaiseMemoryException(CFStringRef reason); -CF_EXPORT CF_PRIVATE Boolean __CFProphylacticAutofsAccess; +CF_PRIVATE Boolean __CFProphylacticAutofsAccess; CF_EXPORT id __NSDictionary0__; CF_EXPORT id __NSArray0__; @@ -580,30 +599,7 @@ typedef pthread_mutex_t os_unfair_lock; typedef pthread_mutex_t * os_unfair_lock_t; static void os_unfair_lock_lock(os_unfair_lock_t lock) { pthread_mutex_lock(lock); } static void os_unfair_lock_unlock(os_unfair_lock_t lock) { pthread_mutex_unlock(lock); } -#endif - -#if __has_include() -#include -#else - -static _Bool __os_warn_unused(_Bool x) __attribute__((__warn_unused_result__)); -static _Bool __os_warn_unused(_Bool x) { return x; } - -#if __has_builtin(__builtin_add_overflow) && \ - __has_builtin(__builtin_sub_overflow) && \ - __has_builtin(__builtin_mul_overflow) - -#define os_add_overflow(a, b, res) __os_warn_unused(__builtin_add_overflow((a), (b), (res))) -#define os_sub_overflow(a, b, res) __os_warn_unused(__builtin_sub_overflow((a), (b), (res))) -#define os_mul_overflow(a, b, res) __os_warn_unused(__builtin_mul_overflow((a), (b), (res))) - -#else - -#error Missing compiler support for overflow checking - -#endif - -#endif +#endif // __has_include() #if !__HAS_DISPATCH__ @@ -614,8 +610,8 @@ CF_PRIVATE void _CF_dispatch_once(dispatch_once_t *, void (^)(void)); #endif #if DEPLOYMENT_TARGET_MACOSX || DEPLOYMENT_TARGET_EMBEDDED || DEPLOYMENT_TARGET_EMBEDDED_MINI -extern _Atomic(uint8_t) __CF120293; -extern _Atomic(uint8_t) __CF120290; +CF_PRIVATE _Atomic(uint8_t) __CF120293; +CF_PRIVATE _Atomic(uint8_t) __CF120290; extern void __THE_PROCESS_HAS_FORKED_AND_YOU_CANNOT_USE_THIS_COREFOUNDATION_FUNCTIONALITY___YOU_MUST_EXEC__(void); #define CHECK_FOR_FORK() do { __CF120290 = true; if (__CF120293) __THE_PROCESS_HAS_FORKED_AND_YOU_CANNOT_USE_THIS_COREFOUNDATION_FUNCTIONALITY___YOU_MUST_EXEC__(); } while (0) #define CHECK_FOR_FORK_RET(...) do { CHECK_FOR_FORK(); if (__CF120293) return __VA_ARGS__; } while (0) @@ -735,7 +731,20 @@ extern void _CFRuntimeSetInstanceTypeIDAndIsa(CFTypeRef cf, CFTypeID newTypeID); #define CF_SWIFT_CALLV(obj, fn, ...) (0) #endif -extern uintptr_t __CFRuntimeObjCClassTable[]; +#ifndef __has_attribute +#define __has_attribute(...) 0 +#endif + +#if DEPLOYMENT_TARGET_WINDOWS +#define _CF_VISIBILITY_HIDDEN_ATTRIBUTE +#elif __has_attribute(visibility) +#define _CF_VISIBILITY_HIDDEN_ATTRIBUTE __attribute__((visibility("hidden"))) +#else +#define _CF_VISIBILITY_HIDDEN_ATTRIBUTE +#endif + +// an undeclared array length is only valid with extern, but CF_PRIVATE may or may not include extern as part of its expansion. Redefine the visibility attribute so we can explicitly make it an extern declaration. +extern _CF_VISIBILITY_HIDDEN_ATTRIBUTE uintptr_t __CFRuntimeObjCClassTable[]; CF_INLINE uintptr_t __CFISAForTypeID(CFTypeID typeID) { return (typeID < __CFRuntimeClassTableSize) ? __CFRuntimeObjCClassTable[typeID] : 0; @@ -1015,6 +1024,15 @@ enum { __kCFZombieMessagedEvent = 21, }; +#pragma mark - CF Private Globals + +CF_PRIVATE void *__CFAppleLanguages; +CF_PRIVATE uint8_t __CFZombieEnabled; +CF_PRIVATE uint8_t __CFDeallocateZombies; +CF_PRIVATE Boolean __CFInitialized; +CF_PRIVATE _Atomic(bool) __CFMainThreadHasExited; +CF_PRIVATE const CFStringRef __kCFLocaleCollatorID; + CF_EXTERN_C_END #endif /* ! __COREFOUNDATION_CFINTERNAL__ */ diff --git a/CoreFoundation/Base.subproj/CFLogUtilities.h b/CoreFoundation/Base.subproj/CFLogUtilities.h index c293b54810..a6b37cfee1 100644 --- a/CoreFoundation/Base.subproj/CFLogUtilities.h +++ b/CoreFoundation/Base.subproj/CFLogUtilities.h @@ -1,7 +1,7 @@ /* CFLogUtilities.h - Copyright (c) 2004-2017, Apple Inc. and the Swift project authors + Copyright (c) 2004-2018, Apple Inc. and the Swift project authors - Portions Copyright (c) 2014-2017, Apple Inc. and the Swift project authors + Portions Copyright (c) 2014-2018, Apple Inc. and the Swift project authors Licensed under Apache License v2.0 with Runtime Library Exception See http://swift.org/LICENSE.txt for license information See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors diff --git a/CoreFoundation/Base.subproj/CFOverflow.h b/CoreFoundation/Base.subproj/CFOverflow.h new file mode 100644 index 0000000000..3dd5cba289 --- /dev/null +++ b/CoreFoundation/Base.subproj/CFOverflow.h @@ -0,0 +1,76 @@ +/* CFOverflow.h + Copyright (c) 2017-2018, Apple Inc. and the Swift project authors + + Portions Copyright (c) 2017-2018, Apple Inc. and the Swift project authors + Licensed under Apache License v2.0 with Runtime Library Exception + See http://swift.org/LICENSE.txt for license information + See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors +*/ + +#ifndef CFOverflow_h +#define CFOverflow_h + +#if __has_include() +#include +#else + static _Bool __os_warn_unused(_Bool x) __attribute__((__warn_unused_result__)); + static _Bool __os_warn_unused(_Bool x) { return x; } + + #if __has_builtin(__builtin_add_overflow) && \ + __has_builtin(__builtin_sub_overflow) && \ + __has_builtin(__builtin_mul_overflow) + + #define os_add_overflow(a, b, res) __os_warn_unused(__builtin_add_overflow((a), (b), (res))) + #define os_sub_overflow(a, b, res) __os_warn_unused(__builtin_sub_overflow((a), (b), (res))) + #define os_mul_overflow(a, b, res) __os_warn_unused(__builtin_mul_overflow((a), (b), (res))) + + #else + #error Missing compiler support for overflow checking + #endif +#endif // __has_include() + +typedef CF_ENUM(uint8_t, _CFOverflowResult) { + _CFOverflowResultOK = 0, + _CFOverflowResultNegativeParameters, + _CFOverflowResultOverflows, +}; + +// Overflow utilities for positive integers +CF_INLINE _CFOverflowResult _CFPositiveIntegerProductWouldOverflow(CFIndex si_a, CFIndex si_b, CFIndex * /*_Nullable*/ outSum) { + _CFOverflowResult result = _CFOverflowResultOK; + CFIndex sum = 0; + if (si_a < 0 || si_b < 0) { + // we explicitly only implement a subset of the overflow checking, so report failure if out of domain + result = _CFOverflowResultNegativeParameters; + } else { + if (os_mul_overflow(si_a, si_b, &sum)) { + result = _CFOverflowResultOverflows; + } + } + if (outSum) { + *outSum = sum; + } + return result; +} + +CF_INLINE _CFOverflowResult _CFPointerSumWouldOverflow(void const *p, size_t n, void * /*_Nullable*/ * /*_Nullable*/ outSum) { + _CFOverflowResult result = _CFOverflowResultOK; +#if __LP64__ + uint64_t sum = 0; + uint64_t const lhs = (uint64_t)p; + uint64_t const rhs = (uint64_t)n; +#else + uint32_t sum = 0; + uint32_t const lhs = (uint32_t)p; + uint32_t const rhs = (uint32_t)n; +#endif + if (os_add_overflow(lhs, rhs, &sum)) { + result = _CFOverflowResultOverflows; + } + if (outSum) { + *outSum = (void *)sum; + } + return result; +} + +#endif /* CFOverflow_h */ diff --git a/CoreFoundation/Base.subproj/CFPlatform.c b/CoreFoundation/Base.subproj/CFPlatform.c index 39edf0b053..87dd6e1bea 100644 --- a/CoreFoundation/Base.subproj/CFPlatform.c +++ b/CoreFoundation/Base.subproj/CFPlatform.c @@ -1,7 +1,7 @@ /* CFPlatform.c - Copyright (c) 1999-2017, Apple Inc. and the Swift project authors + Copyright (c) 1999-2018, Apple Inc. and the Swift project authors - Portions Copyright (c) 2014-2017, Apple Inc. and the Swift project authors + Portions Copyright (c) 2014-2018, Apple Inc. and the Swift project authors Licensed under Apache License v2.0 with Runtime Library Exception See http://swift.org/LICENSE.txt for license information See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors @@ -123,7 +123,7 @@ const char *_CFProcessPath(void) { #endif #if DEPLOYMENT_TARGET_MACOSX || DEPLOYMENT_TARGET_EMBEDDED || DEPLOYMENT_TARGET_EMBEDDED_MINI -Boolean _CFIsMainThread(void) { +CF_CROSS_PLATFORM_EXPORT Boolean _CFIsMainThread(void) { return pthread_main_np() == 1; } @@ -282,29 +282,28 @@ CF_EXPORT CFStringRef CFCopyUserName(void) { } } #else -#error Dont know how to compute user name on this platform +#error "Please add an implementation for CFCopyUserName() that copies the account username" #endif - if (!result) { + if (!result) result = (CFStringRef)CFRetain(CFSTR("")); - } - return result; } -CF_EXPORT CFStringRef CFCopyFullUserName(void) { +#if DEPLOYMENT_TARGET_ANDROID +#define pw_gecos pw_name +#endif + +CF_CROSS_PLATFORM_EXPORT CFStringRef CFCopyFullUserName(void) { CFStringRef result = NULL; #if DEPLOYMENT_TARGET_MACOSX || DEPLOYMENT_TARGET_EMBEDDED || DEPLOYMENT_TARGET_EMBEDDED_MINI || DEPLOYMENT_TARGET_LINUX || DEPLOYMENT_TARGET_FREEBSD uid_t euid; __CFGetUGIDs(&euid, NULL); struct passwd *upwd = getpwuid(euid ? euid : getuid()); -#if DEPLOYMENT_TARGET_ANDROID -#define pw_gecos pw_name -#endif if (upwd && upwd->pw_gecos) { result = CFStringCreateWithCString(kCFAllocatorSystemDefault, upwd->pw_gecos, kCFPlatformInterfaceStringEncoding); } #else -#error Don't know how to compute full user name on this platform +#error "Please add an implementation for CFCopyFullUserName() that copies the full (display) user name" #endif if (!result) { result = (CFStringRef)CFRetain(CFSTR("")); @@ -313,6 +312,11 @@ CF_EXPORT CFStringRef CFCopyFullUserName(void) { return result; } +#if DEPLOYMENT_TARGET_ANDROID +#undef pw_gecos +#endif + + CFURLRef CFCopyHomeDirectoryURL(void) { #if DEPLOYMENT_TARGET_MACOSX || DEPLOYMENT_TARGET_EMBEDDED || DEPLOYMENT_TARGET_EMBEDDED_MINI || DEPLOYMENT_TARGET_LINUX || DEPLOYMENT_TARGET_FREEBSD return _CFCopyHomeDirURLForUser(NULL, true); @@ -506,6 +510,8 @@ CF_EXPORT CFMutableStringRef _CFCreateApplicationRepositoryPath(CFAllocatorRef a } #endif + + #pragma mark - #pragma mark Thread Functions @@ -604,14 +610,9 @@ CF_PRIVATE void __CFFinalizeWindowsThreadData() { #endif static pthread_key_t __CFTSDIndexKey; -static pthread_once_t __CFTSDIndexKey_once = PTHREAD_ONCE_INIT; - -CF_PRIVATE void __CFTSDInitializeOnce() { - (void)pthread_key_create(&__CFTSDIndexKey, __CFTSDFinalize); -} CF_PRIVATE void __CFTSDInitialize() { - (void)pthread_once(&__CFTSDIndexKey_once, __CFTSDInitializeOnce); + (void)pthread_key_create(&__CFTSDIndexKey, __CFTSDFinalize); } static void __CFTSDSetSpecific(void *arg) { @@ -634,7 +635,8 @@ static void *__CFTSDGetSpecific() { #endif } -CF_PRIVATE _Atomic(bool) __CFMainThreadHasExited; +_Atomic(bool) __CFMainThreadHasExited = false; + static void __CFTSDFinalize(void *arg) { if (pthread_main_np()) { __CFMainThreadHasExited = true; @@ -1354,10 +1356,9 @@ CF_CROSS_PLATFORM_EXPORT int _CFThreadSetName(pthread_t thread, const char *_Non #endif } -CF_CROSS_PLATFORM_EXPORT int _CFThreadGetName(char *_Nonnull buf, int length) { +CF_CROSS_PLATFORM_EXPORT int _CFThreadGetName(char *buf, int length) { #if DEPLOYMENT_TARGET_MACOSX || DEPLOYMENT_TARGET_EMBEDDED || DEPLOYMENT_TARGET_EMBEDDED_MINI return pthread_getname_np(pthread_self(), buf, length); -#elif DEPLOYMENT_TARGET_ANDROID #elif DEPLOYMENT_TARGET_LINUX return pthread_getname_np(pthread_self(), buf, length); #endif @@ -1374,15 +1375,15 @@ CF_EXPORT char **_CFEnviron(void) { #endif } -int _CFOpenFileWithMode(const char *path, int opts, mode_t mode) { +CF_CROSS_PLATFORM_EXPORT int _CFOpenFileWithMode(const char *path, int opts, mode_t mode) { return open(path, opts, mode); } int _CFOpenFile(const char *path, int opts) { return open(path, opts); } -void *_CFReallocf(void *ptr, size_t size) { -#if DEPLOYMENT_TARGET_WINDOWS | DEPLOYMENT_TARGET_LINUX +CF_CROSS_PLATFORM_EXPORT void *_CFReallocf(void *ptr, size_t size) { +#if TARGET_OS_WIN32 | DEPLOYMENT_TARGET_LINUX void *mem = realloc(ptr, size); if (mem == NULL && ptr != NULL && size != 0) { free(ptr); diff --git a/CoreFoundation/Base.subproj/CFPriv.h b/CoreFoundation/Base.subproj/CFPriv.h index bec593c338..bffec48421 100644 --- a/CoreFoundation/Base.subproj/CFPriv.h +++ b/CoreFoundation/Base.subproj/CFPriv.h @@ -1,7 +1,7 @@ /* CFPriv.h - Copyright (c) 1998-2017, Apple Inc. and the Swift project authors + Copyright (c) 1998-2018, Apple Inc. and the Swift project authors - Portions Copyright (c) 2014-2017, Apple Inc. and the Swift project authors + Portions Copyright (c) 2014-2018, Apple Inc. and the Swift project authors Licensed under Apache License v2.0 with Runtime Library Exception See http://swift.org/LICENSE.txt for license information See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors @@ -27,13 +27,26 @@ #include #ifndef CF_CROSS_PLATFORM_EXPORT - #if !DEPLOYMENT_RUNTIME_OBJC - #define CF_CROSS_PLATFORM_EXPORT extern - #else - #define CF_CROSS_PLATFORM_EXPORT static __attribute__((used)) - #endif + #if !DEPLOYMENT_RUNTIME_OBJC + #define CF_CROSS_PLATFORM_EXPORT extern + #else + #define CF_CROSS_PLATFORM_EXPORT static __attribute__((used)) + #endif #endif +#if DEPLOYMENT_TARGET_WINDOWS + // No C99 support + #define _CF_RESTRICT +#else + #if defined(__cplusplus) + #define _CF_RESTRICT __restrict__ + #else + #define _CF_RESTRICT restrict + #endif +#endif + + + #if (TARGET_OS_MAC && !(TARGET_OS_EMBEDDED || TARGET_OS_IPHONE || TARGET_OS_LINUX)) || (TARGET_OS_EMBEDDED || TARGET_OS_IPHONE) #include #include @@ -42,12 +55,9 @@ #include #include #include -#include CF_EXTERN_C_BEGIN -CF_EXPORT intptr_t _CFDoOperation(intptr_t code, intptr_t subcode1, intptr_t subcode2); - CF_EXPORT void _CFRuntimeSetCFMPresent(void *a); CF_EXPORT const char *_CFProcessPath(void); @@ -80,12 +90,14 @@ CF_EXPORT void CFPreferencesFlushCaches(void); + + #if TARGET_OS_WIN32 CF_EXPORT Boolean _CFURLGetWideFileSystemRepresentation(CFURLRef url, Boolean resolveAgainstBase, wchar_t *buffer, CFIndex bufferLength); #endif #if !__LP64__ -#if (TARGET_OS_MAC && !(TARGET_OS_EMBEDDED || TARGET_OS_IPHONE)) || (TARGET_OS_EMBEDDED || TARGET_OS_IPHONE) +#if TARGET_OS_OSX struct FSSpec; CF_EXPORT Boolean _CFGetFSSpecFromURL(CFAllocatorRef alloc, CFURLRef url, struct FSSpec *spec); @@ -159,9 +171,6 @@ CFStringRef CFGetUserName(void); CF_EXPORT CFStringRef CFCopyUserName(void); -CF_EXPORT -CFStringRef CFCopyFullUserName(void); - CF_EXPORT CFURLRef CFCopyHomeDirectoryURLForUser(CFStringRef uName); /* Pass NULL for the current user's home directory */ @@ -248,11 +257,8 @@ CF_EXPORT const CFStringRef _kCFSystemVersionBuildStringKey; // Localized strin CF_EXPORT void CFMergeSortArray(void *list, CFIndex count, CFIndex elementSize, CFComparatorFunction comparator, void *context); CF_EXPORT void CFQSortArray(void *list, CFIndex count, CFIndex elementSize, CFComparatorFunction comparator, void *context); -/* _CFExecutableLinkedOnOrAfter(releaseVersionName) will return YES if the current executable seems to be linked on or after the specified release. Example: If you specify CFSystemVersionPuma (10.1), you will get back true for executables linked on Puma or Jaguar(10.2), but false for those linked on Cheetah (10.0) or any of its software updates (10.0.x). You will also get back false for any app whose version info could not be figured out. - This function caches its results, so no need to cache at call sites. +// For non-Darwin platforms _CFExecutableLinkedOnOrAfter(…) always returns true. - Note that for non-MACH this function always returns true. -*/ typedef CF_ENUM(CFIndex, CFSystemVersion) { CFSystemVersionCheetah = 0, /* 10.0 */ CFSystemVersionPuma = 1, /* 10.1 */ @@ -295,10 +301,6 @@ enum { /* When set, CF encoding conversion engine keeps ASCII compatibility. (i.e. ASCII backslash <-> Unicode backslash in MacJapanese */ CF_EXPORT void _CFStringEncodingSetForceASCIICompatibility(Boolean flag); -extern void __CFSetCharToUniCharFunc(Boolean (*func)(UInt32 flags, UInt8 ch, UniChar *unicodeChar)); -extern UniChar __CFCharToUniCharTable[256]; - - #if defined(CF_INLINE) CF_INLINE const UniChar *CFStringGetCharactersPtrFromInlineBuffer(CFStringInlineBuffer *buf, CFRange desiredRange) { if ((desiredRange.location < 0) || ((desiredRange.location + desiredRange.length) > buf->rangeToBuffer.length)) return NULL; diff --git a/CoreFoundation/Base.subproj/CFRuntime.c b/CoreFoundation/Base.subproj/CFRuntime.c index d2a4d05f92..e62ea7adba 100644 --- a/CoreFoundation/Base.subproj/CFRuntime.c +++ b/CoreFoundation/Base.subproj/CFRuntime.c @@ -1,7 +1,7 @@ /* CFRuntime.c - Copyright (c) 1999-2017, Apple Inc. and the Swift project authors + Copyright (c) 1999-2018, Apple Inc. and the Swift project authors - Portions Copyright (c) 2014-2017, Apple Inc. and the Swift project authors + Portions Copyright (c) 2014-2018, Apple Inc. and the Swift project authors Licensed under Apache License v2.0 with Runtime Library Exception See http://swift.org/LICENSE.txt for license information See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors @@ -11,6 +11,7 @@ #define ENABLE_ZOMBIES 1 #include +#include "CFRuntime_Internal.h" #include "CFInternal.h" #include "CFBasicHash.h" #include @@ -121,8 +122,6 @@ void __CFOAInitialize(void) { } extern void __HALT(void); -static CFTypeID __kCFNotATypeTypeID = _kCFRuntimeNotATypeID; - #if !defined (__cplusplus) static const CFRuntimeClass __CFNotATypeClass = { 0, @@ -136,8 +135,6 @@ static const CFRuntimeClass __CFNotATypeClass = { (void *)__HALT }; -static CFTypeID __kCFTypeTypeID = _kCFRuntimeNotATypeID; - static const CFRuntimeClass __CFTypeClass = { 0, "CFType", @@ -169,8 +166,6 @@ static const CFRuntimeClass __CFNotATypeClass = { SIG6 }; -static CFTypeID __kCFTypeTypeID = _kCFRuntimeNotATypeID; - static const CFRuntimeClass __CFTypeClass = { 0, "CFType", @@ -193,26 +188,83 @@ CF_PRIVATE void objc_terminate(void) { // the lock does not protect most reading of these; we just leak the old table to allow read-only accesses to continue to work static CFLock_t __CFBigRuntimeFunnel = CFLockInit; -CF_PRIVATE CFRuntimeClass * __CFRuntimeClassTable[__CFRuntimeClassTableSize] = {0}; -CF_PRIVATE int32_t __CFRuntimeClassTableCount = 0; +static CFRuntimeClass const * __CFRuntimeClassTable[__CFRuntimeClassTableSize] __attribute__((aligned)) = { + [_kCFRuntimeIDNotAType] = &__CFNotATypeClass, + [_kCFRuntimeIDCFType] = &__CFTypeClass, + [_kCFRuntimeIDCFAllocator] = &__CFAllocatorClass, + [_kCFRuntimeIDCFBasicHash] = &__CFBasicHashClass, + [_kCFRuntimeIDCFBag] = &__CFBagClass, + [_kCFRuntimeIDCFString] = &__CFStringClass, + [_kCFRuntimeIDCFNull] = &__CFNullClass, + [_kCFRuntimeIDCFSet] = &__CFSetClass, + [_kCFRuntimeIDCFDictionary] = &__CFDictionaryClass, + [_kCFRuntimeIDCFArray] = &__CFArrayClass, + [_kCFRuntimeIDCFData] = &__CFDataClass, + [_kCFRuntimeIDCFBoolean] = &__CFBooleanClass, + [_kCFRuntimeIDCFNumber] = &__CFNumberClass, + [_kCFRuntimeIDCFBinaryHeap] = &__CFBinaryHeapClass, + [_kCFRuntimeIDCFBitVector] = &__CFBitVectorClass, + [_kCFRuntimeIDCFUUID] = &__CFUUIDClass, + [_kCFRuntimeIDCFStorage] = &__CFStorageClass, + [_kCFRuntimeIDCFTree] = &__CFTreeClass, + [_kCFRuntimeIDCFError] = &__CFErrorClass, + [_kCFRuntimeIDCFLocale] = &__CFLocaleClass, + [_kCFRuntimeIDCFDateFormatter] = &__CFDateFormatterClass, + [_kCFRuntimeIDCFNumberFormatter] = &__CFNumberFormatterClass, + [_kCFRuntimeIDCFCalendar] = &__CFCalendarClass, + [_kCFRuntimeIDCFDate] = &__CFDateClass, + [_kCFRuntimeIDCFTimeZone] = &__CFTimeZoneClass, + [_kCFRuntimeIDCFKeyedArchiverUID] = &__CFKeyedArchiverUIDClass, + +#if TARGET_OS_OSX + [_kCFRuntimeIDCFXMLParser] = &__CFXMLParserClass, + [_kCFRuntimeIDCFXMLNode] = &__CFXMLNodeClass, +#endif // TARGET_OS_OSX + + [_kCFRuntimeIDCFBundle] = &__CFBundleClass, + [_kCFRuntimeIDCFPFactory] = &__CFPFactoryClass, + [_kCFRuntimeIDCFPlugInInstance] = &__CFPlugInInstanceClass, -CF_PRIVATE uintptr_t __CFRuntimeObjCClassTable[__CFRuntimeClassTableSize] = {0}; + [_kCFRuntimeIDCFPreferencesDomain] = &__CFPreferencesDomainClass, -#if (TARGET_OS_MAC && !(TARGET_OS_EMBEDDED || TARGET_OS_IPHONE) && __x86_64h__) // Match parity with private header -// This must be defined because previous linkages may reference this symbol, however for x86_64h builds this should never be anything but NULL -#undef __CFObjCIsCollectable +#if TARGET_OS_MAC + [_kCFRuntimeIDCFMachPort] = &__CFMachPortClass, #endif -#if !defined(__CFObjCIsCollectable) || __x86_64h__ + + [_kCFRuntimeIDCFMessagePort] = &__CFMessagePortClass, + [_kCFRuntimeIDCFRunLoopMode] = &__CFRunLoopModeClass, + [_kCFRuntimeIDCFRunLoop] = &__CFRunLoopClass, + [_kCFRuntimeIDCFRunLoopSource] = &__CFRunLoopSourceClass, + [_kCFRuntimeIDCFRunLoopObserver] = &__CFRunLoopObserverClass, + [_kCFRuntimeIDCFRunLoopTimer] = &__CFRunLoopTimerClass, + [_kCFRuntimeIDCFSocket] = &__CFSocketClass, + [_kCFRuntimeIDCFReadStream] = &__CFReadStreamClass, + [_kCFRuntimeIDCFWriteStream] = &__CFWriteStreamClass, + [_kCFRuntimeIDCFAttributedString] = &__CFAttributedStringClass, + [_kCFRuntimeIDCFRunArray] = &__CFRunArrayClass, + [_kCFRuntimeIDCFCharacterSet] = &__CFCharacterSetClass, + + + [_kCFRuntimeIDCFURL] = &__CFURLClass, + + + [_kCFRuntimeIDCFURLComponents] = &__CFURLComponentsClass, + +}; + +static int32_t __CFRuntimeClassTableCount = _kCFRuntimeStartingClassID; + +uintptr_t __CFRuntimeObjCClassTable[__CFRuntimeClassTableSize] __attribute__((aligned)) = {0}; + +#if (TARGET_OS_MAC && !TARGET_OS_IPHONE && !__x86_64h__) // Match parity with private header bool (*__CFObjCIsCollectable)(void *) = NULL; -#if __x86_64h__ -#define __CFObjCIsCollectable 0 // allow optimization to cull branches in this file -#endif +#else #endif #if DEPLOYMENT_RUNTIME_SWIFT // The constant string class reference is set at link time to _NSCFConstantString -void *__CFConstantStringClassReferencePtr = &__CFConstantStringClassReference; +void *__CFConstantStringClassReferencePtr = &_CF_CONSTANT_STRING_SWIFT_CLASS; #else #if !__CONSTANT_CFSTRINGS__ || DEPLOYMENT_TARGET_EMBEDDED_MINI // Compiler uses this symbol name; must match compiler built-in decl, so we use 'int' @@ -237,6 +289,7 @@ Boolean _CFIsObjC(CFTypeID typeID, void *obj) { } CFTypeID _CFRuntimeRegisterClass(const CFRuntimeClass * const cls) { + // NOTE: If you are adding a type to CF itself, please use a constant value (see CFRuntime_Internal.h) // className must be pure ASCII string, non-null if ((cls->version & _kCFRuntimeCustomRefCount) && !cls->refcount) { CFLog(kCFLogLevelWarning, CFSTR("*** _CFRuntimeRegisterClass() given inconsistent class '%s'. Program will crash soon."), cls->className); @@ -278,8 +331,8 @@ void _CFRuntimeUnregisterClassWithTypeID(CFTypeID typeID) { #if defined(DEBUG) || defined(ENABLE_ZOMBIES) -CF_PRIVATE uint8_t __CFZombieEnabled = 0; -CF_PRIVATE uint8_t __CFDeallocateZombies = 0; +uint8_t __CFZombieEnabled = 0; +uint8_t __CFDeallocateZombies = 0; extern void __CFZombifyNSObject(void); // from NSObject.m @@ -381,14 +434,14 @@ CFTypeRef _CFRuntimeCreateInstance(CFAllocatorRef allocator, CFTypeID typeID, CF extern void *swift_allocObject(uintptr_t metadata, size_t requiredSize, size_t requiredAlignmentMask); uintptr_t isa = __CFRuntimeObjCClassTable[typeID]; CFIndex size = sizeof(CFRuntimeBase) + extraBytes; - CFRuntimeClass *cls = __CFRuntimeClassTable[typeID]; + const CFRuntimeClass *cls = __CFRuntimeClassTable[typeID]; size_t align = (cls->version & _kCFRuntimeRequiresAlignment) ? cls->requiredAlignment : 16; CFRuntimeBase *memory = (CFRuntimeBase *)swift_allocObject(isa, size, align - 1); // Zero the rest of the memory, starting at cfinfo memset(&memory->_cfinfoa, 0, size - (sizeof(memory->_cfisa) + sizeof(memory->_swift_rc))); - + // Set up the cfinfo struct uint32_t *cfinfop = (uint32_t *)&(memory->_cfinfoa); // The 0x80 means we use the default allocator @@ -398,7 +451,7 @@ CFTypeRef _CFRuntimeCreateInstance(CFAllocatorRef allocator, CFTypeID typeID, CF #else if (__CFRuntimeClassTableSize <= typeID) HALT; CFAssert1(typeID != _kCFRuntimeNotATypeID, __kCFLogAssertion, "%s(): Uninitialized type id", __PRETTY_FUNCTION__); - CFRuntimeClass *cls = __CFRuntimeClassTable[typeID]; + CFRuntimeClass const *cls = __CFRuntimeClassTable[typeID]; if (NULL == cls) { return NULL; } @@ -430,7 +483,7 @@ CFTypeRef _CFRuntimeCreateInstance(CFAllocatorRef allocator, CFTypeID typeID, CF if (NULL == memory) { return NULL; } - memset(memory, 0, size); + memset(memory, 0, size); if (__CFOASafe && category) { __CFSetLastAllocationEventName(memory, (char *)category); } else if (__CFOASafe) { @@ -478,7 +531,7 @@ CFTypeRef _CFRuntimeCreateInstance(CFAllocatorRef allocator, CFTypeID typeID, CF void _CFRuntimeInitStaticInstance(void *ptr, CFTypeID typeID) { CFAssert1(typeID != _kCFRuntimeNotATypeID, __kCFLogAssertion, "%s(): Uninitialized type id", __PRETTY_FUNCTION__); if (__CFRuntimeClassTableSize <= typeID) HALT; - CFRuntimeClass *cfClass = __CFRuntimeClassTable[typeID]; + CFRuntimeClass const *cfClass = __CFRuntimeClassTable[typeID]; Boolean customRC = !!(cfClass->version & _kCFRuntimeCustomRefCount); if (customRC) { CFLog(kCFLogLevelError, CFSTR("*** Cannot initialize a static instance to a class (%s) with custom ref counting"), cfClass->className); @@ -514,9 +567,9 @@ void _CFRuntimeSetInstanceTypeID(CFTypeRef cf, CFTypeID newTypeID) { if (__CFRuntimeClassTableSize <= newTypeID) HALT; __CFInfoType info = ((CFRuntimeBase *)cf)->_cfinfoa; CFTypeID currTypeID = __CFTypeIDFromInfo(info); - CFRuntimeClass *newcfClass = __CFRuntimeClassTable[newTypeID]; + CFRuntimeClass const *newcfClass = __CFRuntimeClassTable[newTypeID]; Boolean newCustomRC = (newcfClass->version & _kCFRuntimeCustomRefCount); - CFRuntimeClass *currcfClass = __CFRuntimeClassTable[currTypeID]; + CFRuntimeClass const *currcfClass = __CFRuntimeClassTable[currTypeID]; Boolean currCustomRC = (currcfClass->version & _kCFRuntimeCustomRefCount); if (currCustomRC || (0 != currTypeID && newCustomRC)) { CFLog(kCFLogLevelError, CFSTR("*** Cannot change the CFTypeID of a %s to a %s due to custom ref counting"), currcfClass->className, newcfClass->className); @@ -540,6 +593,7 @@ CF_PRIVATE void _CFRuntimeSetInstanceTypeIDAndIsa(CFTypeRef cf, CFTypeID newType } +#ifndef __LP64__ enum { __kCFObjectRetainedEvent = 12, __kCFObjectReleasedEvent = 13 @@ -562,7 +616,7 @@ static struct { // uint8_t padding[64 - sizeof(CFBasicHashRef) - sizeof(CFLock_t)]; } __NSRetainCounters[NUM_EXTERN_TABLES]; -CF_EXPORT uintptr_t __CFDoExternRefOperation(uintptr_t op, id obj) { +static uintptr_t __CFDoExternRefOperation(uintptr_t op, id obj) { if (nil == obj) HALT; uintptr_t idx = EXTERN_TABLE_IDX(obj); uintptr_t disguised = DISGUISE(obj); @@ -592,6 +646,7 @@ CF_EXPORT uintptr_t __CFDoExternRefOperation(uintptr_t op, id obj) { } return 0; } +#endif CF_EXPORT CFTypeID CFNumberGetTypeID(void); @@ -605,7 +660,7 @@ CFTypeID __CFGenericTypeID(const void *cf) { } CFTypeID CFTypeGetTypeID(void) { - return __kCFTypeTypeID; + return _kCFRuntimeIDCFType; } CF_PRIVATE void __CFGenericValidateType_(CFTypeRef cf, CFTypeID type, const char *func) { @@ -613,12 +668,12 @@ CF_PRIVATE void __CFGenericValidateType_(CFTypeRef cf, CFTypeID type, const char if (cf && CF_IS_SWIFT(type, (CFSwiftRef)cf)) return; #endif if (cf && CF_IS_OBJC(type, cf)) return; - CFAssert2((cf != NULL) && (NULL != __CFRuntimeClassTable[__CFGenericTypeID_inline(cf)]) && (__kCFNotATypeTypeID != __CFGenericTypeID_inline(cf)) && (__kCFTypeTypeID != __CFGenericTypeID_inline(cf)), __kCFLogAssertion, "%s(): pointer %p is not a CF object", func, cf); \ + CFAssert2((cf != NULL) && (NULL != __CFRuntimeClassTable[__CFGenericTypeID_inline(cf)]) && (_kCFRuntimeIDNotAType != __CFGenericTypeID_inline(cf)) && (_kCFRuntimeIDCFType != __CFGenericTypeID_inline(cf)), __kCFLogAssertion, "%s(): pointer %p is not a CF object", func, cf); \ CFAssert3(__CFGenericTypeID_inline(cf) == type, __kCFLogAssertion, "%s(): pointer %p is not a %s", func, cf, __CFRuntimeClassTable[type]->className); \ } #define __CFGenericAssertIsCF(cf) \ - CFAssert2(cf != NULL && (NULL != __CFRuntimeClassTable[__CFGenericTypeID_inline(cf)]) && (__kCFNotATypeTypeID != __CFGenericTypeID_inline(cf)) && (__kCFTypeTypeID != __CFGenericTypeID_inline(cf)), __kCFLogAssertion, "%s(): pointer %p is not a CF object", __PRETTY_FUNCTION__, cf); + CFAssert2(cf != NULL && (NULL != __CFRuntimeClassTable[__CFGenericTypeID_inline(cf)]) && (_kCFRuntimeIDNotAType != __CFGenericTypeID_inline(cf)) && (_kCFRuntimeIDCFType != __CFGenericTypeID_inline(cf)), __kCFLogAssertion, "%s(): pointer %p is not a CF object", __PRETTY_FUNCTION__, cf); #if DEPLOYMENT_RUNTIME_SWIFT @@ -659,7 +714,7 @@ CFTypeID CFGetTypeID(CFTypeRef cf) { } CFStringRef CFCopyTypeIDDescription(CFTypeID type) { - CFAssert2((NULL != __CFRuntimeClassTable[type]) && __kCFNotATypeTypeID != type && __kCFTypeTypeID != type, __kCFLogAssertion, "%s(): type %lu is not a CF type ID", __PRETTY_FUNCTION__, type); + CFAssert2((NULL != __CFRuntimeClassTable[type]) && _kCFRuntimeIDNotAType != type && _kCFRuntimeIDCFType != type, __kCFLogAssertion, "%s(): type %lu is not a CF type ID", __PRETTY_FUNCTION__, type); return CFStringCreateWithCString(kCFAllocatorSystemDefault, __CFRuntimeClassTable[type]->className, kCFStringEncodingASCII); } @@ -780,7 +835,7 @@ CFIndex CFGetRetainCount(CFTypeRef cf) { __CFInfoType info = atomic_load(&(((CFRuntimeBase *)cf)->_cfinfoa)); if (info & RC_CUSTOM_RC_BIT) { // custom ref counting for object CFTypeID typeID = __CFTypeIDFromInfo(info); - CFRuntimeClass *cfClass = __CFRuntimeClassTable[typeID]; + CFRuntimeClass const *cfClass = __CFRuntimeClassTable[typeID]; uint32_t (*refcount)(intptr_t, CFTypeRef) = cfClass->refcount; if (!refcount || !(cfClass->version & _kCFRuntimeCustomRefCount) || __CFLowRCFromInfo(info) != 0xFF) { HALT; // bogus object @@ -865,6 +920,7 @@ CFHashCode CFHash(CFTypeRef cf) { return (CFHashCode)cf; } + // definition: produces a normally non-NULL debugging description of the object CFStringRef CFCopyDescription(CFTypeRef cf) { if (NULL == cf) return NULL; @@ -891,7 +947,7 @@ extern CFAllocatorRef __CFAllocatorGetAllocator(CFTypeRef); CFAllocatorRef CFGetAllocator(CFTypeRef cf) { if (NULL == cf) return kCFAllocatorSystemDefault; - if (__kCFAllocatorTypeID_CONST == __CFGenericTypeID_inline(cf)) { + if (_kCFRuntimeIDCFAllocator == __CFGenericTypeID_inline(cf)) { return __CFAllocatorGetAllocator(cf); } return __CFGetAllocator(cf); @@ -904,31 +960,20 @@ extern CFTypeID CFTreeGetTypeID(void); extern CFTypeID CFPlugInInstanceGetTypeID(void); extern CFTypeID CFStringTokenizerGetTypeID(void); extern CFTypeID CFStorageGetTypeID(void); -extern void __CFAllocatorInitialize(void); -extern void __CFStringInitialize(void); -extern void __CFNumberInitialize(void); -extern void __CFCharacterSetInitialize(void); -extern void __CFPFactoryInitialize(void); -extern void __CFPlugInInitialize(void); -#if DEPLOYMENT_TARGET_LINUX || DEPLOYMENT_TARGET_MACOSX +#if DEPLOYMENT_TARGET_LINUX || (DEPLOYMENT_TARGET_MACOSX && DEPLOYMENT_RUNTIME_SWIFT) CF_PRIVATE void __CFTSDInitialize(void); #endif #if DEPLOYMENT_TARGET_WINDOWS // From CFPlatform.c -CF_PRIVATE void __CFTSDWindowsInitialize(void); CF_PRIVATE void __CFTSDWindowsCleanup(void); -CF_PRIVATE void __CFFinalizeWindowsThreadData(void); -#endif -extern void __CFStreamInitialize(void); -#if DEPLOYMENT_TARGET_MACOSX || DEPLOYMENT_TARGET_EMBEDDED || DEPLOYMENT_TARGET_WINDOWS -extern void __CFXPreferencesInitialize(void); +CF_PRIVATE void __CFFinalizeWindowsThreadData(); #endif #if DEPLOYMENT_TARGET_MACOSX || DEPLOYMENT_TARGET_EMBEDDED || DEPLOYMENT_TARGET_EMBEDDED_MINI -CF_PRIVATE _Atomic(uint8_t) __CF120290 = false; -CF_PRIVATE _Atomic(uint8_t) __CF120291 = false; -CF_PRIVATE _Atomic(uint8_t) __CF120293 = false; -CF_PRIVATE char * __crashreporter_info__ = NULL; // Keep this symbol, since it was exported and other things may be linking against it, like GraphicsServices.framework on iOS +_Atomic(uint8_t) __CF120290 = false; +static _Atomic(uint8_t) __CF120291 = false; +_Atomic(uint8_t) __CF120293 = false; +char * __crashreporter_info__ = NULL; // Keep this symbol, since it was exported and other things may be linking against it, like GraphicsServices.framework on iOS __asm(".desc ___crashreporter_info__, 0x10"); static void __01121__(void) { @@ -965,7 +1010,7 @@ CF_PRIVATE void __THE_PROCESS_HAS_FORKED_AND_YOU_CANNOT_USE_THIS_COREFOUNDATION_ CF_EXPORT const void *__CFArgStuff; const void *__CFArgStuff = NULL; -CF_PRIVATE void *__CFAppleLanguages = NULL; +void *__CFAppleLanguages = NULL; // do not cache CFFIXED_USER_HOME or HOME, there are situations where they can change @@ -997,15 +1042,6 @@ static struct { {"CFNumberDisableCache", NULL}, {"__CFPREFERENCES_AVOID_DAEMON", NULL}, {"APPLE_FRAMEWORKS_ROOT", NULL}, -#if DEPLOYMENT_RUNTIME_SWIFT - {"HOME", NULL}, - {"XDG_DATA_HOME", NULL}, - {"XDG_CONFIG_HOME", NULL}, - {"XDG_DATA_DIRS", NULL}, - {"XDG_CONFIG_DIRS", NULL}, - {"XDG_CACHE_HOME", NULL}, - {"XDG_RUNTIME_DIR", NULL}, -#endif {NULL, NULL}, // the last one is for optional "COMMAND_MODE" "legacy", do not use this slot, insert before }; @@ -1033,18 +1069,21 @@ CF_PRIVATE Boolean __CFProcessIsRestricted() { // Even though we no longer support GC, we leave this exported symbol to avoid lockstep dependencies. -#undef kCFUseCollectableAllocator +// Match parity with private header +#if (TARGET_OS_MAC && !TARGET_OS_IPHONE && !__x86_64h__) CF_EXPORT bool kCFUseCollectableAllocator; bool kCFUseCollectableAllocator = false; +#endif + -CF_PRIVATE Boolean __CFProphylacticAutofsAccess = false; -CF_PRIVATE Boolean __CFInitializing = 0; -CF_PRIVATE Boolean __CFInitialized = 0; +Boolean __CFProphylacticAutofsAccess = false; +static Boolean __CFInitializing = 0; +Boolean __CFInitialized = 0; -// move the next 2 lines down into the #if below, and make it static, after Foundation gets off this symbol on other platforms +// move the next 2 lines down into the #if below, and make it static, after Foundation gets off this symbol on other platforms. CF_EXPORT pthread_t _CFMainPThread; pthread_t _CFMainPThread = kNilPthreadT; -#if DEPLOYMENT_TARGET_WINDOWS || DEPLOYMENT_TARGET_IPHONESIMULATOR || DEPLOYMENT_TARGET_LINUX +#if DEPLOYMENT_TARGET_WINDOWS || DEPLOYMENT_TARGET_LINUX CF_EXPORT pthread_t _CF_pthread_main_thread_np(void); pthread_t _CF_pthread_main_thread_np(void) { @@ -1067,22 +1106,27 @@ void __CFInitialize(void) { if (!__CFInitialized && !__CFInitializing) { __CFInitializing = 1; -#if DEPLOYMENT_TARGET_WINDOWS || DEPLOYMENT_TARGET_IPHONESIMULATOR +#if DEPLOYMENT_TARGET_WINDOWS if (!pthread_main_np()) HALT; // CoreFoundation must be initialized on the main thread #endif - // move this next line up into the #if above after Foundation gets off this symbol + // move this next line up into the #if above after Foundation gets off this symbol. Also: Stop using _CFMainPThread _CFMainPThread = pthread_self(); #if DEPLOYMENT_TARGET_WINDOWS // Must not call any CF functions __CFTSDWindowsInitialize(); -#elif DEPLOYMENT_TARGET_LINUX || DEPLOYMENT_TARGET_MACOSX +#elif DEPLOYMENT_TARGET_LINUX || (DEPLOYMENT_TARGET_MACOSX && !DEPLOYMENT_RUNTIME_OBJC) __CFTSDInitialize(); #endif __CFProphylacticAutofsAccess = true; for (CFIndex idx = 0; idx < sizeof(__CFEnv) / sizeof(__CFEnv[0]); idx++) { - __CFEnv[idx].value = __CFEnv[idx].name ? getenv(__CFEnv[idx].name) : NULL; + if (__CFEnv[idx].name) { + char *r = NULL; + if ((r = getenv(__CFEnv[idx].name))) { + __CFEnv[idx].value = r; + } + } } #if DEPLOYMENT_TARGET_MACOSX || DEPLOYMENT_TARGET_EMBEDDED || DEPLOYMENT_TARGET_EMBEDDED_MINI @@ -1092,10 +1136,7 @@ void __CFInitialize(void) { #endif - memset(__CFRuntimeClassTable, 0, sizeof(__CFRuntimeClassTable)); - memset(__CFRuntimeObjCClassTable, 0, sizeof(__CFRuntimeObjCClassTable)); - -#if DEPLOYMENT_RUNTIME_SWIFT +#if DEPLOYMENT_RUNTIME_SWIFT extern uintptr_t __CFSwiftGetBaseClass(void); uintptr_t NSCFType = __CFSwiftGetBaseClass(); @@ -1105,13 +1146,6 @@ void __CFInitialize(void) { #endif - /* Here so that two runtime classes get indices 0, 1. */ - __kCFNotATypeTypeID = _CFRuntimeRegisterClass(&__CFNotATypeClass); - __kCFTypeTypeID = _CFRuntimeRegisterClass(&__CFTypeClass); - - /* Here so that __kCFAllocatorTypeID gets index 2. */ - __CFAllocatorInitialize(); - #if DEPLOYMENT_TARGET_MACOSX || DEPLOYMENT_TARGET_EMBEDDED { CFIndex idx, cnt; @@ -1130,77 +1164,30 @@ void __CFInitialize(void) { #endif - CFBasicHashGetTypeID(); - CFBagGetTypeID(); - +#ifndef __LP64__ for (CFIndex idx = 0; idx < NUM_EXTERN_TABLES; idx++) { CFBasicHashCallbacks callbacks = {NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL}; __NSRetainCounters[idx].table = CFBasicHashCreate(kCFAllocatorSystemDefault, kCFBasicHashHasCounts | kCFBasicHashLinearHashing | kCFBasicHashAggressiveGrowth, &callbacks); CFBasicHashSetCapacity(__NSRetainCounters[idx].table, 40); __NSRetainCounters[idx].lock = CFLockInit; } +#endif /*** _CFRuntimeCreateInstance() can finally be called generally after this line. ***/ - __CFRuntimeClassTableCount = 7; - __CFStringInitialize(); // CFString's TypeID must be 0x7, now and forever - - __CFRuntimeClassTableCount = 16; - CFNullGetTypeID(); // See above for hard-coding of this position - CFSetGetTypeID(); // See above for hard-coding of this position - CFDictionaryGetTypeID(); // See above for hard-coding of this position - CFArrayGetTypeID(); // See above for hard-coding of this position - CFDataGetTypeID(); // See above for hard-coding of this position - CFBooleanGetTypeID(); // See above for hard-coding of this position - CFNumberGetTypeID(); // See above for hard-coding of this position - - CFBinaryHeapGetTypeID(); - CFBitVectorGetTypeID(); + CFNumberGetTypeID(); // NB: This does other work + __CFCharacterSetInitialize(); - CFStorageGetTypeID(); - CFErrorGetTypeID(); - CFTreeGetTypeID(); - CFURLGetTypeID(); - _CFURLComponentsGetTypeID(); -#if DEPLOYMENT_TARGET_MACOSX || DEPLOYMENT_TARGET_EMBEDDED || DEPLOYMENT_TARGET_WINDOWS - CFBundleGetTypeID(); - __CFPFactoryInitialize(); -#endif -#if DEPLOYMENT_TARGET_MACOSX || DEPLOYMENT_TARGET_EMBEDDED - __CFPlugInInitialize(); - CFPlugInInstanceGetTypeID(); -#endif - CFUUIDGetTypeID(); -#if (DEPLOYMENT_TARGET_MACOSX || DEPLOYMENT_TARGET_EMBEDDED || DEPLOYMENT_TARGET_EMBEDDED_MINI || DEPLOYMENT_TARGET_WINDOWS) && !DEPLOYMENT_RUNTIME_SWIFT - CFMessagePortGetTypeID(); -#endif -#if (DEPLOYMENT_TARGET_MACOSX || DEPLOYMENT_TARGET_EMBEDDED || DEPLOYMENT_TARGET_EMBEDDED_MINI) && !DEPLOYMENT_RUNTIME_SWIFT - CFMachPortGetTypeID(); -#endif - __CFStreamInitialize(); #if DEPLOYMENT_TARGET_WINDOWS - CFWindowsNamedPipeGetTypeID(); + __CFWindowsNamedPipeInitialize(); #endif - CFDateGetTypeID(); - CFRunLoopGetTypeID(); - CFRunLoopObserverGetTypeID(); - CFRunLoopSourceGetTypeID(); - CFRunLoopTimerGetTypeID(); -#if DEPLOYMENT_TARGET_MACOSX || DEPLOYMENT_TARGET_EMBEDDED || DEPLOYMENT_TARGET_WINDOWS || DEPLOYMENT_TARGET_LINUX - CFTimeZoneGetTypeID(); - CFCalendarGetTypeID(); -#if DEPLOYMENT_TARGET_LINUX - CFTimeZoneGetTypeID(); - CFCalendarGetTypeID(); -#endif -#endif + __CFDateInitialize(); #if DEPLOYMENT_RUNTIME_SWIFT extern void __CFInitializeSwift(void); __CFInitializeSwift(); - __CFNumberInitialize(); /* needs to happen after Swift bridge is initialized */ #endif @@ -1350,7 +1337,6 @@ int DllMain( HINSTANCE hInstance, DWORD dwReason, LPVOID pReserved ) { #if DEPLOYMENT_RUNTIME_SWIFT extern void swift_retain(void *); -extern void swift_release(void *); #endif // For "tryR==true", a return of NULL means "failed". @@ -1365,7 +1351,7 @@ static CFTypeRef _CFRetain(CFTypeRef cf, Boolean tryR) { if (info & RC_CUSTOM_RC_BIT) { if (tryR) return NULL; CFTypeID typeID = __CFTypeIDFromInfo(info); - CFRuntimeClass *cfClass = __CFRuntimeClassTable[typeID]; + CFRuntimeClass const *cfClass = __CFRuntimeClassTable[typeID]; uint32_t (*refcount)(intptr_t, CFTypeRef) = cfClass->refcount; if (!refcount || !(cfClass->version & _kCFRuntimeCustomRefCount) || __CFLowRCFromInfo(info) != 0xFF) { CRSetCrashLogMessage("Detected bogus CFTypeRef"); @@ -1465,6 +1451,10 @@ Boolean _CFIsDeallocating(CFTypeRef cf) { } #endif +#if DEPLOYMENT_RUNTIME_SWIFT +extern void swift_release(void *); +#endif + static void _CFRelease(CFTypeRef CF_RELEASES_ARGUMENT cf) { #if DEPLOYMENT_RUNTIME_SWIFT // We always call through to swift_release, since all CFTypeRefs are at least _NSCFType objects @@ -1480,10 +1470,10 @@ static void _CFRelease(CFTypeRef CF_RELEASES_ARGUMENT cf) { #pragma GCC diagnostic ignored "-Wunused-variable" CFIndex start_rc = __builtin_expect(__CFOASafe, 0) ? CFGetRetainCount(cf) : 0; #pragma GCC diagnostic pop - Boolean isAllocator = (__kCFAllocatorTypeID_CONST == typeID); + Boolean isAllocator = (_kCFRuntimeIDCFAllocator == typeID); if (info & RC_CUSTOM_RC_BIT) { // custom ref counting for object - CFRuntimeClass *cfClass = __CFRuntimeClassTable[typeID]; + CFRuntimeClass const *cfClass = __CFRuntimeClassTable[typeID]; uint32_t (*refcount)(intptr_t, CFTypeRef) = cfClass->refcount; if (!refcount || !(cfClass->version & _kCFRuntimeCustomRefCount) || __CFLowRCFromInfo(info) != 0xFF) { CRSetCrashLogMessage("Detected bogus CFTypeRef"); @@ -1507,7 +1497,7 @@ static void _CFRelease(CFTypeRef CF_RELEASES_ARGUMENT cf) { return; // Constant CFTypeRef } if (1 == rc) { - CFRuntimeClass *cfClass = __CFRuntimeClassTable[typeID]; + CFRuntimeClass const *cfClass = __CFRuntimeClassTable[typeID]; if ((cfClass->version & _kCFRuntimeResourcefulObject) && cfClass->reclaim != NULL) { cfClass->reclaim(cf); } @@ -1580,7 +1570,7 @@ static void _CFRelease(CFTypeRef CF_RELEASES_ARGUMENT cf) { } while (!success); if (whack) { - CFRuntimeClass *cfClass = __CFRuntimeClassTable[typeID]; + CFRuntimeClass const *cfClass = __CFRuntimeClassTable[typeID]; if ((cfClass->version & _kCFRuntimeResourcefulObject) && cfClass->reclaim != NULL) { cfClass->reclaim(cf); } @@ -1631,7 +1621,7 @@ static void _CFRelease(CFTypeRef CF_RELEASES_ARGUMENT cf) { Boolean usesSystemDefaultAllocator = true; if (!__CFRuntimeGetFlag(cf, 7)) { - allocator = CFGetAllocator(cf); + allocator = CFGetAllocator(cf); usesSystemDefaultAllocator = _CFAllocatorIsSystemDefault(allocator); } @@ -1642,7 +1632,7 @@ static void _CFRelease(CFTypeRef CF_RELEASES_ARGUMENT cf) { if (kCFAllocatorSystemDefault != allocator) { CFRelease(allocator); - } + } } #endif } @@ -1655,7 +1645,6 @@ struct _CFSwiftBridge __CFSwiftBridge = { { NULL } }; CF_CROSS_PLATFORM_EXPORT void _CFDeinit(CFTypeRef cf) { __CFInfoType info = atomic_load(&(((CFRuntimeBase *)cf)->_cfinfoa)); CFTypeID typeID = __CFTypeIDFromInfo(info); - CFRuntimeClass *cfClass = __CFRuntimeClassTable[typeID]; void (*func)(CFTypeRef) = __CFRuntimeClassTable[typeID]->finalize; if (NULL != func) { func(cf); @@ -1694,7 +1683,7 @@ const char *_NSPrintForDebugger(void *cf) { return result; } } - + CFHashCode __CFHashDouble(double d) { return _CFHashDouble(d); } @@ -1716,7 +1705,6 @@ void _CFSwiftRelease(void *_Nullable t) { #endif -#undef __kCFAllocatorTypeID_CONST #undef __CFGenericAssertIsCF diff --git a/CoreFoundation/Base.subproj/CFRuntime.h b/CoreFoundation/Base.subproj/CFRuntime.h index 13b044c260..6318834e60 100644 --- a/CoreFoundation/Base.subproj/CFRuntime.h +++ b/CoreFoundation/Base.subproj/CFRuntime.h @@ -1,7 +1,7 @@ /* CFRuntime.h - Copyright (c) 1999-2017, Apple Inc. All rights reserved. + Copyright (c) 1999-2018, Apple Inc. All rights reserved. - Portions Copyright (c) 2014-2017, Apple Inc. and the Swift project authors + Portions Copyright (c) 2014-2018, Apple Inc. and the Swift project authors Licensed under Apache License v2.0 with Runtime Library Exception See http://swift.org/LICENSE.txt for license information See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors diff --git a/CoreFoundation/Base.subproj/CFRuntime_Internal.h b/CoreFoundation/Base.subproj/CFRuntime_Internal.h new file mode 100644 index 0000000000..ce0c20f039 --- /dev/null +++ b/CoreFoundation/Base.subproj/CFRuntime_Internal.h @@ -0,0 +1,159 @@ +// +// CFRuntime_Internal.h +// CoreFoundation +// +// Created by Tony Parker on 4/21/18. +// + +#ifndef CFRuntime_Internal_h +#define CFRuntime_Internal_h + +#include + +// Note: Platform differences leave us with some holes in the table, but that's ok. + +enum { + _kCFRuntimeIDNotAType = 0, + _kCFRuntimeIDCFType = 1, + _kCFRuntimeIDCFAllocator = 2, + _kCFRuntimeIDCFBasicHash = 3, + _kCFRuntimeIDCFBag = 4, + _kCFRuntimeIDCFString = 7, + _kCFRuntimeIDCFNull = 16, + _kCFRuntimeIDCFSet = 17, + _kCFRuntimeIDCFDictionary = 18, + _kCFRuntimeIDCFArray = 19, + _kCFRuntimeIDCFData = 20, + _kCFRuntimeIDCFBoolean = 21, + _kCFRuntimeIDCFNumber = 22, + _kCFRuntimeIDCFBinaryHeap = 23, + _kCFRuntimeIDCFBitVector = 24, + _kCFRuntimeIDCFCharacterSet = 25, + _kCFRuntimeIDCFStorage = 26, + _kCFRuntimeIDCFError = 27, + _kCFRuntimeIDCFTree = 28, + _kCFRuntimeIDCFURL = 29, + _kCFRuntimeIDCFURLComponents = 30, + _kCFRuntimeIDCFBundle = 31, + _kCFRuntimeIDCFPFactory = 32, + _kCFRuntimeIDCFPlugInInstance = 33, + _kCFRuntimeIDCFUUID = 34, + _kCFRuntimeIDCFMessagePort = 35, +#if TARGET_OS_MAC + _kCFRuntimeIDCFMachPort = 36, +#endif + _kCFRuntimeIDCFReadStream = 38, + _kCFRuntimeIDCFWriteStream = 39, + _kCFRuntimeIDCFKeyedArchiverUID = 41, + _kCFRuntimeIDCFDate = 42, + _kCFRuntimeIDCFRunLoop = 43, + _kCFRuntimeIDCFRunLoopMode = 44, + _kCFRuntimeIDCFRunLoopObserver = 45, + _kCFRuntimeIDCFRunLoopSource = 46, + _kCFRuntimeIDCFRunLoopTimer = 47, + _kCFRuntimeIDCFTimeZone = 48, + _kCFRuntimeIDCFCalendar = 49, + _kCFRuntimeIDCFPreferencesDomain = 50, +#if TARGET_OS_WIN32 + _kCFRuntimeIDCFWindowsNamedPipe = 51, +#endif + + // After this point, the values were never hard-coded into __CFInitialize. + + _kCFRuntimeIDCFNotificationCenter = 52, + _kCFRuntimeIDCFPasteboard = 53, + _kCFRuntimeIDCFUserNotification = 54, + _kCFRuntimeIDCFLocale = 55, + _kCFRuntimeIDCFDateFormatter = 56, + _kCFRuntimeIDCFNumberFormatter = 57, +#if TARGET_OS_OSX || DEPLOYMENT_RUNTIME_SWIFT + _kCFRuntimeIDCFXMLParser = 58, + _kCFRuntimeIDCFXMLNode = 59, +#endif + _kCFRuntimeIDCFFileDescriptor = 60, + _kCFRuntimeIDCFSocket = 61, + _kCFRuntimeIDCFAttributedString = 62, + _kCFRuntimeIDCFRunArray = 63, + // If you are adding a new value, it goes below this line. + + // Stuff not in CF goes here. This value should be one more than the last one above. + _kCFRuntimeStartingClassID +}; + +CF_PRIVATE const CFRuntimeClass __CFAllocatorClass; +CF_PRIVATE const CFRuntimeClass __CFBasicHashClass; +CF_PRIVATE const CFRuntimeClass __CFBagClass; +CF_PRIVATE const CFRuntimeClass __CFStringClass; +CF_PRIVATE const CFRuntimeClass __CFNullClass; +CF_PRIVATE const CFRuntimeClass __CFSetClass; +CF_PRIVATE const CFRuntimeClass __CFDictionaryClass; +CF_PRIVATE const CFRuntimeClass __CFArrayClass; +CF_PRIVATE const CFRuntimeClass __CFDataClass; +CF_PRIVATE const CFRuntimeClass __CFBooleanClass; +CF_PRIVATE const CFRuntimeClass __CFNumberClass; +CF_PRIVATE const CFRuntimeClass __CFBinaryHeapClass; +CF_PRIVATE const CFRuntimeClass __CFBitVectorClass; +CF_PRIVATE const CFRuntimeClass __CFCharacterSetClass; +CF_PRIVATE const CFRuntimeClass __CFStorageClass; +CF_PRIVATE const CFRuntimeClass __CFErrorClass; +CF_PRIVATE const CFRuntimeClass __CFTreeClass; +CF_PRIVATE const CFRuntimeClass __CFURLClass; +CF_PRIVATE const CFRuntimeClass __CFURLComponentsClass; +CF_PRIVATE const CFRuntimeClass __CFBundleClass; +CF_PRIVATE const CFRuntimeClass __CFPlugInInstanceClass; + + +CF_PRIVATE const CFRuntimeClass __CFPasteboardClass; +CF_PRIVATE const CFRuntimeClass __CFUserNotificationClass; +CF_PRIVATE const CFRuntimeClass __CFUUIDClass; +CF_PRIVATE const CFRuntimeClass __CFLocaleClass; +CF_PRIVATE const CFRuntimeClass __CFDateFormatterClass; +CF_PRIVATE const CFRuntimeClass __CFNumberFormatterClass; +CF_PRIVATE const CFRuntimeClass __CFCalendarClass; +CF_PRIVATE const CFRuntimeClass __CFDateClass; +CF_PRIVATE const CFRuntimeClass __CFTimeZoneClass; +CF_PRIVATE const CFRuntimeClass __CFDateClass; +CF_PRIVATE const CFRuntimeClass __CFKeyedArchiverUIDClass; +CF_PRIVATE const CFRuntimeClass __CFXMLParserClass; +CF_PRIVATE const CFRuntimeClass __CFXMLNodeClass; +CF_PRIVATE const CFRuntimeClass __CFPFactoryClass; + +CF_PRIVATE const CFRuntimeClass __CFPreferencesDomainClass; + +CF_PRIVATE const CFRuntimeClass __CFMachPortClass; + + +#if (TARGET_OS_MAC || TARGET_OS_WIN32 || DEPLOYMENT_RUNTIME_SWIFT) +CF_PRIVATE const CFRuntimeClass __CFMessagePortClass; +#endif +CF_PRIVATE const CFRuntimeClass __CFRunLoopModeClass; +CF_PRIVATE const CFRuntimeClass __CFRunLoopClass; +CF_PRIVATE const CFRuntimeClass __CFRunLoopSourceClass; +CF_PRIVATE const CFRuntimeClass __CFRunLoopObserverClass; +CF_PRIVATE const CFRuntimeClass __CFRunLoopTimerClass; +CF_PRIVATE const CFRuntimeClass __CFSocketClass; +CF_PRIVATE const CFRuntimeClass __CFReadStreamClass; +CF_PRIVATE const CFRuntimeClass __CFWriteStreamClass; +CF_PRIVATE const CFRuntimeClass __CFAttributedStringClass; +CF_PRIVATE const CFRuntimeClass __CFRunArrayClass; +#if TARGET_OS_WIN32 +CF_PRIVATE const CFRuntimeClass __CFWindowsNamedPipeClass; +#endif +CF_PRIVATE const CFRuntimeClass __CFTimeZoneClass; +CF_PRIVATE const CFRuntimeClass __CFCalendarClass; + +#pragma mark - Private initialiers to run at process start time + +CF_PRIVATE void __CFDateInitialize(void); +CF_PRIVATE void __CFCharacterSetInitialize(void); + +#if TARGET_OS_WIN32 +CF_PRIVATE void __CFTSDWindowsInitialize(void); +CF_PRIVATE void __CFWindowsNamedPipeInitialize(void); +#endif + +#if TARGET_OS_MAC || TARGET_OS_IPHONE || TARGET_OS_WIN32 +CF_PRIVATE void __CFXPreferencesInitialize(void); +#endif + +#endif /* CFRuntime_Internal_h */ diff --git a/CoreFoundation/Base.subproj/CFSortFunctions.c b/CoreFoundation/Base.subproj/CFSortFunctions.c index 88781c1619..0bac93d933 100644 --- a/CoreFoundation/Base.subproj/CFSortFunctions.c +++ b/CoreFoundation/Base.subproj/CFSortFunctions.c @@ -1,7 +1,7 @@ /* CFSortFunctions.c - Copyright (c) 1999-2017, Apple Inc. and the Swift project authors + Copyright (c) 1999-2018, Apple Inc. and the Swift project authors - Portions Copyright (c) 2014-2017, Apple Inc. and the Swift project authors + Portions Copyright (c) 2014-2018, Apple Inc. and the Swift project authors Licensed under Apache License v2.0 with Runtime Library Exception See http://swift.org/LICENSE.txt for license information See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors @@ -16,8 +16,8 @@ #include #else #define DISPATCH_APPLY_CURRENT_ROOT_QUEUE ((dispatch_queue_t _Nonnull)0) -#endif -#endif +#endif // (DEPLOYMENT_TARGET_MACOSX || DEPLOYMENT_TARGET_EMBEDDED) && __has_include() +#endif // __HAS_DISPATCH__ #include "CFLogUtilities.h" #include "CFInternal.h" @@ -52,8 +52,6 @@ enum { #define __checkint_int64_mul(x, y, err) (x * y) #define __checkint_uint64_add(x, y, err) (x + y) -#define __checkint_int32_mul(x,y,err) (x * y) -#define __checkint_uint32_add(x,y,err) (x + y) #endif diff --git a/CoreFoundation/Base.subproj/CFSystemDirectories.c b/CoreFoundation/Base.subproj/CFSystemDirectories.c index c3d6a4dbf2..145907bfa2 100644 --- a/CoreFoundation/Base.subproj/CFSystemDirectories.c +++ b/CoreFoundation/Base.subproj/CFSystemDirectories.c @@ -1,7 +1,7 @@ /* CFSystemDirectories.c - Copyright (c) 1997-2017, Apple Inc. and the Swift project authors + Copyright (c) 1997-2018, Apple Inc. and the Swift project authors - Portions Copyright (c) 2014-2017, Apple Inc. and the Swift project authors + Portions Copyright (c) 2014-2018, Apple Inc. and the Swift project authors Licensed under Apache License v2.0 with Runtime Library Exception See http://swift.org/LICENSE.txt for license information See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors diff --git a/CoreFoundation/Base.subproj/CFUUID.c b/CoreFoundation/Base.subproj/CFUUID.c index c302c6e1a2..80f2badfe2 100644 --- a/CoreFoundation/Base.subproj/CFUUID.c +++ b/CoreFoundation/Base.subproj/CFUUID.c @@ -1,7 +1,7 @@ /* CFUUID.c - Copyright (c) 1999-2017, Apple Inc. and the Swift project authors + Copyright (c) 1999-2018, Apple Inc. and the Swift project authors - Portions Copyright (c) 2014-2017, Apple Inc. and the Swift project authors + Portions Copyright (c) 2014-2018, Apple Inc. and the Swift project authors Licensed under Apache License v2.0 with Runtime Library Exception See http://swift.org/LICENSE.txt for license information See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors @@ -10,24 +10,22 @@ #include #include "CFInternal.h" +#include "CFRuntime_Internal.h" -#if __HAS_DISPATCH__ -#include +#if __has_include() +#include static CFMutableDictionaryRef _uniquedUUIDs = NULL; +static os_unfair_lock _uniquedUUIDsLock = OS_UNFAIR_LOCK_INIT; + CF_INLINE void LOCKED(dispatch_block_t work) { - static dispatch_once_t guard; - static dispatch_queue_t CFUUIDGlobalDataLock; - dispatch_once(&guard, ^{ - dispatch_queue_attr_t dqattr = dispatch_queue_attr_make_with_qos_class(DISPATCH_QUEUE_SERIAL, qos_class_main(), 0); - CFUUIDGlobalDataLock = dispatch_queue_create("com.apple.CFUUID", dqattr); - }); - dispatch_sync(CFUUIDGlobalDataLock, work); + os_unfair_lock_lock_with_options(&_uniquedUUIDsLock, OS_UNFAIR_LOCK_DATA_SYNCHRONIZATION); + work(); + os_unfair_lock_unlock(&_uniquedUUIDsLock); } #else -// Platforms without dispatch - +// Platforms without unfair lock static CFMutableDictionaryRef _uniquedUUIDs = NULL; static CFLock_t _uniquedUUIDsLock = CFLockInit; @@ -95,9 +93,7 @@ static CFStringRef __CFUUIDCopyFormattingDescription(CFTypeRef cf, CFDictionaryR return CFUUIDCreateString(CFGetAllocator(cf), (CFUUIDRef)cf); } -static CFTypeID __kCFUUIDTypeID = _kCFRuntimeNotATypeID; - -static const CFRuntimeClass __CFUUIDClass = { +const CFRuntimeClass __CFUUIDClass = { 0, "CFUUID", NULL, // init @@ -110,9 +106,7 @@ static const CFRuntimeClass __CFUUIDClass = { }; CFTypeID CFUUIDGetTypeID(void) { - static dispatch_once_t initOnce; - dispatch_once(&initOnce, ^{ __kCFUUIDTypeID = _CFRuntimeRegisterClass(&__CFUUIDClass); }); - return __kCFUUIDTypeID; + return _kCFRuntimeIDCFUUID; } static CFUUIDRef __CFUUIDCreateWithBytesPrimitive(CFAllocatorRef allocator, CFUUIDBytes bytes, Boolean isConst) { diff --git a/CoreFoundation/Base.subproj/CFUUID.h b/CoreFoundation/Base.subproj/CFUUID.h index f951bb4e12..2ca4357028 100644 --- a/CoreFoundation/Base.subproj/CFUUID.h +++ b/CoreFoundation/Base.subproj/CFUUID.h @@ -1,7 +1,7 @@ /* CFUUID.h - Copyright (c) 1999-2017, Apple Inc. and the Swift project authors + Copyright (c) 1999-2018, Apple Inc. and the Swift project authors - Portions Copyright (c) 2014-2017, Apple Inc. and the Swift project authors + Portions Copyright (c) 2014-2018, Apple Inc. and the Swift project authors Licensed under Apache License v2.0 with Runtime Library Exception See http://swift.org/LICENSE.txt for license information See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors diff --git a/CoreFoundation/Base.subproj/CFUtilities.c b/CoreFoundation/Base.subproj/CFUtilities.c index 4fb8d1a30e..77d083598b 100644 --- a/CoreFoundation/Base.subproj/CFUtilities.c +++ b/CoreFoundation/Base.subproj/CFUtilities.c @@ -1,7 +1,7 @@ /* CFUtilities.c - Copyright (c) 1998-2017, Apple Inc. and the Swift project authors + Copyright (c) 1998-2018, Apple Inc. and the Swift project authors - Portions Copyright (c) 2014-2017, Apple Inc. and the Swift project authors + Portions Copyright (c) 2014-2018, Apple Inc. and the Swift project authors Licensed under Apache License v2.0 with Runtime Library Exception See http://swift.org/LICENSE.txt for license information See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors @@ -11,6 +11,7 @@ #include #include "CFInternal.h" #include "CFLocaleInternal.h" +#include "CFBundle_Internal.h" #include #if DEPLOYMENT_TARGET_MACOSX || DEPLOYMENT_TARGET_EMBEDDED || DEPLOYMENT_TARGET_WINDOWS #include @@ -55,7 +56,9 @@ #include #include #include +#include #endif + #if DEPLOYMENT_TARGET_LINUX || DEPLOYMENT_TARGET_FREEBSD #include #include @@ -64,8 +67,13 @@ #endif -#if !defined(CF_HAVE_HW_CONFIG_COMMPAGE) && defined(_COMM_PAGE_LOGICAL_CPUS) && defined(_COMM_PAGE_PHYSICAL_CPUS) && defined(_COMM_PAGE_ACTIVE_CPUS) + + + +#if !defined(CF_HAVE_HW_CONFIG_COMMPAGE) && defined(_COMM_PAGE_LOGICAL_CPUS) && defined(_COMM_PAGE_PHYSICAL_CPUS) && defined(_COMM_PAGE_ACTIVE_CPUS) && !__has_feature(address_sanitizer) #define CF_HAVE_HW_CONFIG_COMMPAGE 1 +#else +#define CF_HAVE_HW_CONFIG_COMMPAGE 0 #endif CF_PRIVATE os_log_t _CFOSLog(void) { @@ -482,7 +490,7 @@ CF_PRIVATE uint64_t __CFMemorySize() { #endif return memsize; } - + #if TARGET_OS_MAC static uid_t _CFGetSVUID(BOOL *successful) { uid_t uid = -1; @@ -531,7 +539,7 @@ typedef struct _ugids { } ugids; CF_PRIVATE void __CFGetUGIDs(uid_t *euid, gid_t *egid) { - ugids(^lookup)() = ^{ + ugids(^lookup)(void) = ^{ ugids ids; #if 1 && (DEPLOYMENT_TARGET_MACOSX || DEPLOYMENT_TARGET_EMBEDDED || DEPLOYMENT_TARGET_EMBEDDED_MINI) if (0 != pthread_getugid_np(&ids._euid, &ids._egid)) @@ -564,13 +572,13 @@ CF_EXPORT void _CFGetUGIDs(uid_t *euid, gid_t *egid) { __CFGetUGIDs(euid, egid); } -CF_EXPORT uid_t _CFGetEUID(void) { +CF_EXPORT uid_t _CFGetEUID() { uid_t euid; __CFGetUGIDs(&euid, NULL); return euid; } -CF_EXPORT uid_t _CFGetEGID(void) { +CF_EXPORT uid_t _CFGetEGID() { uid_t egid; __CFGetUGIDs(NULL, &egid); return egid; @@ -751,8 +759,6 @@ static bool also_do_stderr(const _cf_logging_style style) { return result; } -extern char *__CFBundleMainID; - static void _populateBanner(char **banner, char **time, char **thread, int *bannerLen) { double dummy; CFAbsoluteTime at = CFAbsoluteTimeGetCurrent(); @@ -874,7 +880,7 @@ static void __CFLogCStringLegacy(int32_t lev, const char *message, size_t length asl_set(msg, "CFLog Local Time", time); // not to be documented, not public API asl_set(msg, "CFLog Thread", thread); // not to be documented, not public API asl_set(msg, "ReadUID", uid); - static const char *levstr[] = {"0", "1", "2", "3", "4", "5", "6", "7"}; + static const char * const levstr[] = {"0", "1", "2", "3", "4", "5", "6", "7"}; asl_set(msg, ASL_KEY_LEVEL, levstr[lev]); asl_set(msg, ASL_KEY_MSG, message); asl_send(asl, msg); @@ -1065,22 +1071,23 @@ kern_return_t _CFDiscorporateMemoryMaterialize(CFDiscorporateMemory *hm) { #endif #if DEPLOYMENT_TARGET_MACOSX - -#define SUDDEN_TERMINATION_ENABLE_VPROC 1 - -#if SUDDEN_TERMINATION_ENABLE_VPROC - static os_unfair_lock __CFProcessKillingLock = OS_UNFAIR_LOCK_INIT; static CFIndex __CFProcessKillingDisablingCount = 1; static Boolean __CFProcessKillingWasTurnedOn = false; +#endif void _CFSuddenTerminationDisable(void) { +#if DEPLOYMENT_TARGET_MACOSX os_unfair_lock_lock(&__CFProcessKillingLock); __CFProcessKillingDisablingCount++; os_unfair_lock_unlock(&__CFProcessKillingLock); +#else + // Do nothing +#endif } void _CFSuddenTerminationEnable(void) { +#if DEPLOYMENT_TARGET_MACOSX // In our model the first call of _CFSuddenTerminationEnable() that does not balance a previous call of _CFSuddenTerminationDisable() actually enables sudden termination so we have to keep a count that's almost redundant with vproc's. os_unfair_lock_lock(&__CFProcessKillingLock); __CFProcessKillingDisablingCount--; @@ -1089,34 +1096,41 @@ void _CFSuddenTerminationEnable(void) { } else { } os_unfair_lock_unlock(&__CFProcessKillingLock); +#else + // Do nothing +#endif } void _CFSuddenTerminationExitIfTerminationEnabled(int exitStatus) { +#if DEPLOYMENT_TARGET_MACOSX // This is for when the caller wants to try to exit quickly if possible but not automatically exit the process when it next becomes clean, because quitting might still be cancelled by the user. os_unfair_lock_lock(&__CFProcessKillingLock); os_unfair_lock_unlock(&__CFProcessKillingLock); +#else + // Elsewhere, sudden termination is always disabled +#endif } void _CFSuddenTerminationExitWhenTerminationEnabled(int exitStatus) { +#if DEPLOYMENT_TARGET_MACOSX // The user has had their final opportunity to cancel quitting. Exit as soon as the process is clean. Same carefulness as in _CFSuddenTerminationExitIfTerminationEnabled(). os_unfair_lock_lock(&__CFProcessKillingLock); if (__CFProcessKillingWasTurnedOn) { } os_unfair_lock_unlock(&__CFProcessKillingLock); +#else + // Elsewhere, sudden termination is always disabled +#endif } size_t _CFSuddenTerminationDisablingCount(void) { +#if DEPLOYMENT_TARGET_MACOSX return (__CFProcessKillingWasTurnedOn ? 0 : 1); -} - #else - -//The non-vproc implementation is present in the commit history, but long ago began failing to compile and nobody noticed. If you need to resurrect it, start there. -#error Building with vproc sudden termination API disabled. - -#endif - + // Elsewhere, sudden termination is always disabled + return 1; #endif +} #pragma mark File Reading diff --git a/CoreFoundation/Base.subproj/CFUtilities.h b/CoreFoundation/Base.subproj/CFUtilities.h index 6429fdcf45..dfc866b60a 100644 --- a/CoreFoundation/Base.subproj/CFUtilities.h +++ b/CoreFoundation/Base.subproj/CFUtilities.h @@ -1,7 +1,7 @@ /* CFUtilities.h - Copyright (c) 2005-2017, Apple Inc. and the Swift project authors + Copyright (c) 2005-2018, Apple Inc. and the Swift project authors - Portions Copyright (c) 2014-2017, Apple Inc. and the Swift project authors + Portions Copyright (c) 2014-2018, Apple Inc. and the Swift project authors Licensed under Apache License v2.0 with Runtime Library Exception See http://swift.org/LICENSE.txt for license information See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors diff --git a/CoreFoundation/Base.subproj/CFWindowsUtilities.c b/CoreFoundation/Base.subproj/CFWindowsUtilities.c index 83872c349b..b180c59126 100644 --- a/CoreFoundation/Base.subproj/CFWindowsUtilities.c +++ b/CoreFoundation/Base.subproj/CFWindowsUtilities.c @@ -1,8 +1,8 @@ /* CFWindowsUtilities.c - Copyright (c) 2008-2017, Apple Inc. and the Swift project authors + Copyright (c) 2008-2018, Apple Inc. and the Swift project authors - Portions Copyright (c) 2014-2017, Apple Inc. and the Swift project authors + Portions Copyright (c) 2014-2018, Apple Inc. and the Swift project authors Licensed under Apache License v2.0 with Runtime Library Exception See http://swift.org/LICENSE.txt for license information See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors diff --git a/CoreFoundation/Base.subproj/CoreFoundation.h b/CoreFoundation/Base.subproj/CoreFoundation.h index ec012f8131..9d34c4ab80 100644 --- a/CoreFoundation/Base.subproj/CoreFoundation.h +++ b/CoreFoundation/Base.subproj/CoreFoundation.h @@ -1,7 +1,7 @@ /* CoreFoundation.h - Copyright (c) 1998-2017, Apple Inc. and the Swift project authors + Copyright (c) 1998-2018, Apple Inc. and the Swift project authors - Portions Copyright (c) 2014-2017, Apple Inc. and the Swift project authors + Portions Copyright (c) 2014-2018, Apple Inc. and the Swift project authors Licensed under Apache License v2.0 with Runtime Library Exception See http://swift.org/LICENSE.txt for license information See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors diff --git a/CoreFoundation/Base.subproj/CoreFoundation_Prefix.h b/CoreFoundation/Base.subproj/CoreFoundation_Prefix.h index 59b7a70afa..34b35e5aa7 100644 --- a/CoreFoundation/Base.subproj/CoreFoundation_Prefix.h +++ b/CoreFoundation/Base.subproj/CoreFoundation_Prefix.h @@ -1,7 +1,7 @@ /* CoreFoundation_Prefix.h - Copyright (c) 2005-2017, Apple Inc. and the Swift project authors + Copyright (c) 2005-2018, Apple Inc. and the Swift project authors - Portions Copyright (c) 2014-2017, Apple Inc. and the Swift project authors + Portions Copyright (c) 2014-2018, Apple Inc. and the Swift project authors Licensed under Apache License v2.0 with Runtime Library Exception See http://swift.org/LICENSE.txt for license information See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors @@ -453,15 +453,12 @@ CF_EXPORT int64_t OSAtomicAdd64Barrier( int64_t __theAmount, volatile int64_t *_ #endif #if !defined(CF_PRIVATE) -#define CF_PRIVATE __attribute__((__visibility__("hidden"))) +#define CF_PRIVATE __attribute__((__visibility__("hidden"))) extern #endif + // [FIXED_35517899] We can't currently support this, but would like to leave things annotated #if !defined(CF_TEST_PRIVATE) -#ifdef UNIT_TEST -#define CF_TEST_PRIVATE -#else -#define CF_TEST_PRIVATE __attribute__((__visibility__("hidden"))) extern -#endif +#define CF_TEST_PRIVATE CF_PRIVATE #endif #if DEPLOYMENT_TARGET_LINUX || DEPLOYMENT_TARGET_WINDOWS diff --git a/CoreFoundation/Base.subproj/DarwinSymbolAliases b/CoreFoundation/Base.subproj/DarwinSymbolAliases index 4ca887db4a..0c8f4828ca 100644 --- a/CoreFoundation/Base.subproj/DarwinSymbolAliases +++ b/CoreFoundation/Base.subproj/DarwinSymbolAliases @@ -1,7 +1,7 @@ # This is specific to Swift open source; Foundation's NSCFConstantString is used as our constant string class reference -__TMC15SwiftFoundation19_NSCFConstantString ___CFConstantStringClassReference +_$s15SwiftFoundation19_NSCFConstantStringCN ___CFConstantStringClassReference _kCFCalendarIdentifierBuddhist _kCFBuddhistCalendar _kCFCalendarIdentifierChinese _kCFChineseCalendar diff --git a/CoreFoundation/Base.subproj/ForFoundationOnly.h b/CoreFoundation/Base.subproj/ForFoundationOnly.h index 20c9ca9f55..2fe51d2435 100644 --- a/CoreFoundation/Base.subproj/ForFoundationOnly.h +++ b/CoreFoundation/Base.subproj/ForFoundationOnly.h @@ -1,7 +1,7 @@ /* ForFoundationOnly.h - Copyright (c) 1998-2017, Apple Inc. and the Swift project authors + Copyright (c) 1998-2018, Apple Inc. and the Swift project authors - Portions Copyright (c) 2014-2017, Apple Inc. and the Swift project authors + Portions Copyright (c) 2014-2018, Apple Inc. and the Swift project authors Licensed under Apache License v2.0 with Runtime Library Exception See http://swift.org/LICENSE.txt for license information See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors @@ -23,6 +23,7 @@ #include #include #include +#include #include #include #include @@ -79,8 +80,6 @@ CF_EXPORT const CFStringRef _kCFBundleRawInfoPlistURLKey; CF_EXPORT const CFStringRef _kCFBundleNumericVersionKey; CF_EXPORT const CFStringRef _kCFBundleResourcesFileMappedKey; CF_EXPORT const CFStringRef _kCFBundleAllowMixedLocalizationsKey; -CF_EXPORT const CFStringRef _kCFBundleInitialPathKey; -CF_EXPORT const CFStringRef _kCFBundleResolvedPathKey; CF_EXPORT const CFStringRef _kCFBundlePrincipalClassKey; #if __BLOCKS__ @@ -102,8 +101,6 @@ _CF_EXPORT_SCOPE_END _CF_EXPORT_SCOPE_BEGIN -extern void _CFPreferencesPurgeDomainCache(void); - typedef struct { void *_Null_unspecified (*_Null_unspecified createDomain)(CFAllocatorRef _Nullable allocator, CFTypeRef context); void (*_Null_unspecified freeDomain)(CFAllocatorRef _Nullable allocator, CFTypeRef context, void *domain); @@ -112,61 +109,18 @@ typedef struct { Boolean (*_Null_unspecified synchronize)(CFTypeRef context, void *domain); void (*_Null_unspecified getKeysAndValues)(CFAllocatorRef _Nullable alloc, CFTypeRef context, void *domain, void *_Null_unspecified * _Null_unspecified buf[_Null_unspecified], CFIndex *numKeyValuePairs); CFDictionaryRef _Null_unspecified (*_Null_unspecified copyDomainDictionary)(CFTypeRef context, void *domain); - /* HACK - see comment on _CFPreferencesDomainSetIsWorldReadable(), below */ + /* HACK - this is to work around the fact that individual domains lose the information about their user/host/app triplet at creation time. We should find a better way to propogate this information. */ void (*setIsWorldReadable)(CFTypeRef context, void *domain, Boolean isWorldReadable); } _CFPreferencesDomainCallBacks; -CF_EXPORT CFAllocatorRef __CFPreferencesAllocator(void); -CF_EXPORT const _CFPreferencesDomainCallBacks __kCFVolatileDomainCallBacks; -CF_EXPORT const _CFPreferencesDomainCallBacks __kCFXMLPropertyListDomainCallBacks; - typedef struct CF_BRIDGED_MUTABLE_TYPE(id) __CFPreferencesDomain * CFPreferencesDomainRef; -CF_EXPORT CFPreferencesDomainRef _CFPreferencesDomainCreate(CFTypeRef context, const _CFPreferencesDomainCallBacks *callBacks); -CF_EXPORT CFPreferencesDomainRef _CFPreferencesStandardDomain(CFStringRef domainName, CFStringRef userName, CFStringRef hostName); - -CF_EXPORT CFTypeRef _CFPreferencesDomainCreateValueForKey(CFPreferencesDomainRef domain, CFStringRef key); -CF_EXPORT void _CFPreferencesDomainSet(CFPreferencesDomainRef domain, CFStringRef key, CFTypeRef _Nullable value); -CF_EXPORT Boolean _CFPreferencesDomainSynchronize(CFPreferencesDomainRef domain); - -CF_EXPORT CFArrayRef _Nullable _CFPreferencesCreateDomainList(CFStringRef userName, CFStringRef hostName); -CF_EXPORT Boolean _CFSynchronizeDomainCache(void); - -CF_EXPORT void _CFPreferencesDomainSetDictionary(CFPreferencesDomainRef domain, CFDictionaryRef dict); -CF_EXPORT CFDictionaryRef _CFPreferencesDomainDeepCopyDictionary(CFPreferencesDomainRef domain); -CF_EXPORT Boolean _CFPreferencesDomainExists(CFStringRef domainName, CFStringRef userName, CFStringRef hostName); - -/* HACK - this is to work around the fact that individual domains lose the information about their user/host/app triplet at creation time. We should find a better way to propogate this information. REW, 1/13/00 */ -CF_EXPORT void _CFPreferencesDomainSetIsWorldReadable(CFPreferencesDomainRef domain, Boolean isWorldReadable); - typedef struct { CFMutableArrayRef _search; // the search list; an array of _CFPreferencesDomains CFMutableDictionaryRef _dictRep; // Mutable; a collapsed view of the search list, expressed as a single dictionary CFStringRef _appName; } _CFApplicationPreferences; -CF_EXPORT _CFApplicationPreferences *_Nullable _CFStandardApplicationPreferences(CFStringRef appName); -CF_EXPORT _CFApplicationPreferences *_CFApplicationPreferencesCreateWithUser(CFStringRef userName, CFStringRef appName); -CF_EXPORT void _CFDeallocateApplicationPreferences(_CFApplicationPreferences *self); -CF_EXPORT CFTypeRef _CFApplicationPreferencesCreateValueForKey(_CFApplicationPreferences *prefs, CFStringRef key); -CF_EXPORT void _CFApplicationPreferencesSet(_CFApplicationPreferences *self, CFStringRef defaultName, CFTypeRef value); -CF_EXPORT void _CFApplicationPreferencesRemove(_CFApplicationPreferences *self, CFStringRef defaultName); -CF_EXPORT Boolean _CFApplicationPreferencesSynchronize(_CFApplicationPreferences *self); -CF_EXPORT void _CFApplicationPreferencesUpdate(_CFApplicationPreferences *self); // same as updateDictRep -CF_EXPORT CFDictionaryRef _CFApplicationPreferencesCopyRepresentation3(_CFApplicationPreferences *self, CFDictionaryRef hint, CFDictionaryRef insertion, CFPreferencesDomainRef afterDomain); -CF_EXPORT CFDictionaryRef _CFApplicationPreferencesCopyRepresentationWithHint(_CFApplicationPreferences *self, CFDictionaryRef hint); // same as dictRep -CF_EXPORT void _CFApplicationPreferencesSetStandardSearchList(_CFApplicationPreferences *appPreferences); -CF_EXPORT void _CFApplicationPreferencesSetCacheForApp(_CFApplicationPreferences *appPrefs, CFStringRef appName); -CF_EXPORT void _CFApplicationPreferencesAddSuitePreferences(_CFApplicationPreferences *appPrefs, CFStringRef suiteName); -CF_EXPORT void _CFApplicationPreferencesRemoveSuitePreferences(_CFApplicationPreferences *appPrefs, CFStringRef suiteName); - -CF_EXPORT void _CFApplicationPreferencesAddDomain(_CFApplicationPreferences *self, CFPreferencesDomainRef domain, Boolean addAtTop); -CF_EXPORT Boolean _CFApplicationPreferencesContainsDomain(_CFApplicationPreferences *self, CFPreferencesDomainRef domain); -CF_EXPORT void _CFApplicationPreferencesRemoveDomain(_CFApplicationPreferences *self, CFPreferencesDomainRef domain); - -CF_EXPORT CFTypeRef _Nullable _CFApplicationPreferencesSearchDownToDomain(_CFApplicationPreferences *self, CFPreferencesDomainRef stopper, CFStringRef key); - - _CF_EXPORT_SCOPE_END @@ -304,7 +258,7 @@ CF_EXPORT Boolean __CFStringDecodeByteStream3(const UInt8 *bytes, CFIndex len, C /* Convert single byte to Unicode; assumes one-to-one correspondence (that is, can only be used with 1-byte encodings). You can use the function if it's not NULL. */ -CF_EXPORT Boolean (*__CFCharToUniCharFunc)(UInt32 flags, UInt8 ch, UniChar *unicodeChar); +CF_EXPORT CFStringEncodingCheapEightBitToUnicodeProc __CFCharToUniCharFunc; /* Character class functions UnicodeData-2_1_5.txt */ @@ -348,8 +302,8 @@ CF_EXPORT void _CFStringAppendFormatAndArgumentsAux(CFMutableStringRef outputStr CF_EXPORT CFStringRef _CFStringCreateWithFormatAndArgumentsAux(CFAllocatorRef _Nullable alloc, CFStringRef _Nonnull (*_Nullable copyDescFunc)(void *, const void *loc), CFDictionaryRef _Nullable formatOptions, CFStringRef format, va_list arguments); CF_EXPORT void _CFStringAppendFormatAndArgumentsAux2(CFMutableStringRef outputString, CFStringRef _Nonnull (*_Nullable copyDescFunc)(void *, const void *loc), CFStringRef _Nonnull (*_Nullable contextDescFunc)(void *, const void *, const void *, bool, bool *), CFDictionaryRef _Nullable formatOptions, CFStringRef formatString, va_list args); -CF_EXPORT CFStringRef _CFStringCreateWithFormatAndArgumentsAux2(CFAllocatorRef _Nullable alloc, CFStringRef _Nonnull (*_Nullable copyDescFunc)(void *, const void *loc), CFStringRef _Nonnull (*_Nullable contextDescFunc)(void *, const void *, const void *, bool, bool *), CFDictionaryRef _Nullable formatOptions, CFStringRef format, va_list arguments); -CF_EXPORT CFStringRef CFStringCreateStringWithValidatedFormat(CFAllocatorRef alloc, CFDictionaryRef formatOptions, CFStringRef validFormatSpecifiers, CFStringRef format, va_list arguments, CFErrorRef *errorPtr) API_AVAILABLE(macos(10.13), ios(11.0), watchos(4.0), tvos(11.0)); +CF_EXPORT CFStringRef _Nullable _CFStringCreateWithFormatAndArgumentsAux2(CFAllocatorRef _Nullable alloc, CFStringRef _Nonnull (*_Nullable copyDescFunc)(void *, const void *loc), CFStringRef _Nonnull (*_Nullable contextDescFunc)(void *, const void *, const void *, bool, bool *), CFDictionaryRef _Nullable formatOptions, CFStringRef format, va_list arguments); +CF_EXPORT CFStringRef _Nullable CFStringCreateStringWithValidatedFormat(CFAllocatorRef alloc, CFDictionaryRef formatOptions, CFStringRef validFormatSpecifiers, CFStringRef format, va_list arguments, CFErrorRef *errorPtr) API_AVAILABLE(macos(10.13), ios(11.0), watchos(4.0), tvos(11.0)); /* For NSString (and NSAttributedString) usage, mutate with isMutable check */ @@ -435,16 +389,13 @@ CF_EXPORT CFTypeRef _CFPropertyListCreateFromXMLString(CFAllocatorRef _Nullable // ---- Sudden Termination material ---------------------------------------- -#if DEPLOYMENT_TARGET_MACOSX - CF_EXPORT void _CFSuddenTerminationDisable(void); CF_EXPORT void _CFSuddenTerminationEnable(void); + CF_EXPORT void _CFSuddenTerminationExitIfTerminationEnabled(int exitStatus); CF_EXPORT void _CFSuddenTerminationExitWhenTerminationEnabled(int exitStatus); CF_EXPORT size_t _CFSuddenTerminationDisablingCount(void); -#endif - // ---- Thread-specific data -------------------------------------------- // Get some thread specific data from a pre-assigned slot. @@ -568,6 +519,7 @@ CF_EXPORT CFStringRef _CFErrorCreateLocalizedDescription(CFErrorRef err); CF_EXPORT CFStringRef _CFErrorCreateLocalizedFailureReason(CFErrorRef err); CF_EXPORT CFStringRef _CFErrorCreateLocalizedRecoverySuggestion(CFErrorRef err); CF_EXPORT CFStringRef _CFErrorCreateDebugDescription(CFErrorRef err); +CF_EXPORT CFStringRef _CFErrorCreateRedactedDescription(CFErrorRef err); CF_EXPORT void *__CFURLReservedPtr(CFURLRef url); CF_EXPORT void __CFURLSetReservedPtr(CFURLRef url, void *_Nullable ptr); @@ -641,13 +593,6 @@ CF_EXPORT _CFStringFileSystemRepresentationError _CFStringGetFileSystemRepresent -CF_EXPORT CFIndex __CFProcessorCount(void); -CF_EXPORT uint64_t __CFMemorySize(void); -CF_EXPORT CFStringRef _CFProcessNameString(void); -CF_EXPORT CFIndex __CFActiveProcessorCount(void); -CF_EXPORT CFDictionaryRef __CFGetEnvironment(void); -CF_EXPORT int32_t __CFGetPid(void); -CF_EXPORT int32_t __CFGetPid(void); CF_EXPORT CFTimeInterval CFGetSystemUptime(void); CF_EXPORT CFStringRef CFCopySystemVersionString(void); CF_EXPORT CFDictionaryRef _CFCopySystemVersionDictionary(void); @@ -657,7 +602,7 @@ CF_EXPORT Boolean _CFCalendarComposeAbsoluteTimeV(CFCalendarRef calendar, /* out CF_EXPORT Boolean _CFCalendarDecomposeAbsoluteTimeV(CFCalendarRef calendar, CFAbsoluteTime at, const char *componentDesc, int32_t *_Nonnull * _Nonnull vector, int32_t count); CF_EXPORT Boolean _CFCalendarAddComponentsV(CFCalendarRef calendar, /* inout */ CFAbsoluteTime *atp, CFOptionFlags options, const char *componentDesc, int32_t *vector, int32_t count); CF_EXPORT Boolean _CFCalendarGetComponentDifferenceV(CFCalendarRef calendar, CFAbsoluteTime startingAT, CFAbsoluteTime resultAT, CFOptionFlags options, const char *componentDesc, int32_t *_Nonnull * _Nonnull vector, int32_t count); -CF_EXPORT Boolean _CFCalendarIsWeekend(CFCalendarRef calendar, CFAbsoluteTime at); +CF_CROSS_PLATFORM_EXPORT Boolean _CFCalendarIsWeekend(CFCalendarRef calendar, CFAbsoluteTime at); typedef struct { CFTimeInterval onsetTime; @@ -666,7 +611,7 @@ typedef struct { CFIndex end; } _CFCalendarWeekendRange; -CF_EXPORT Boolean _CFCalendarGetNextWeekend(CFCalendarRef calendar, _CFCalendarWeekendRange *range); +CF_CROSS_PLATFORM_EXPORT Boolean _CFCalendarGetNextWeekend(CFCalendarRef calendar, _CFCalendarWeekendRange *range); CF_CROSS_PLATFORM_EXPORT Boolean _CFLocaleInit(CFLocaleRef locale, CFStringRef identifier); @@ -676,11 +621,6 @@ CF_CROSS_PLATFORM_EXPORT Boolean _CFCharacterSetInitWithCharactersInRange(CFMuta CF_CROSS_PLATFORM_EXPORT Boolean _CFCharacterSetInitWithCharactersInString(CFMutableCharacterSetRef cset, CFStringRef theString); CF_CROSS_PLATFORM_EXPORT Boolean _CFCharacterSetInitMutable(CFMutableCharacterSetRef cset); CF_CROSS_PLATFORM_EXPORT Boolean _CFCharacterSetInitWithBitmapRepresentation(CFMutableCharacterSetRef cset, CFDataRef theData); -CF_EXPORT CFIndex __CFCharDigitValue(UniChar ch); - -CF_EXPORT int _CFOpenFileWithMode(const char *path, int opts, mode_t mode); -CF_EXPORT int _CFOpenFile(const char *path, int opts); -CF_EXPORT void *_CFReallocf(void *ptr, size_t size); // The following functions can be used when you know for certain that the types involved are not objc types. For Foundation Only! CF_EXPORT Boolean _CFNonObjCEqual(CFTypeRef cf1, CFTypeRef cf2); @@ -712,6 +652,47 @@ CF_EXPORT void (*__cf_tsanWriteFunction)(void *, void *, void *); CF_EXPORT void *_CFCreateArrayStorage(size_t numPointers, Boolean zeroed, size_t *actualNumPointers); + +#if DEPLOYMENT_RUNTIME_SWIFT +// --- Static class references for Swift use; implements {DECLARE_,}STATIC_CLASS_REF. + +#if TARGET_OS_MAC +#define STATIC_CLASS_PREFIX $s15SwiftFoundation +#else +#define STATIC_CLASS_PREFIX $s10Foundation +#endif + +#define STATIC_CLASS_NAME_LENGTH_LOOKUP___NSCFType 10 +#define STATIC_CLASS_NAME_LOOKUP___NSCFType __NSCFTypeCN + +#define STATIC_CLASS_NAME_LENGTH_LOOKUP_NSNull 6 +#define STATIC_CLASS_NAME_LOOKUP_NSNull NSNullCN + +#define STATIC_CLASS_NAME_LENGTH_LOOKUP___NSCFBoolean 13 +#define STATIC_CLASS_NAME_LOOKUP___NSCFBoolean __NSCFBooleanCN + +#define STATIC_CLASS_NAME_LENGTH_LOOKUP___NSCFNumber 8 +#define STATIC_CLASS_NAME_LOOKUP___NSCFNumber NSNumberCN + +#define STATIC_CLASS_NAME_CONCAT_INNER(x,y) x ## y +#define STATIC_CLASS_NAME_CONCAT(x,y) STATIC_CLASS_NAME_CONCAT_INNER(x,y) + +#define STATIC_CLASS_NAME_LOOKUP(CLASSNAME) STATIC_CLASS_NAME_CONCAT(STATIC_CLASS_NAME_LOOKUP_, CLASSNAME) +#define STATIC_CLASS_NAME_LENGTH_LOOKUP(CLASSNAME) STATIC_CLASS_NAME_CONCAT(STATIC_CLASS_NAME_LENGTH_LOOKUP_, CLASSNAME) + +#define STATIC_CLASS_NAME(CLASSNAME) STATIC_CLASS_NAME_CONCAT(STATIC_CLASS_NAME_LENGTH_LOOKUP(CLASSNAME), STATIC_CLASS_NAME_LOOKUP(CLASSNAME)) + +#define DECLARE_STATIC_CLASS_REF(CLASSNAME) extern void STATIC_CLASS_NAME_CONCAT(STATIC_CLASS_PREFIX, STATIC_CLASS_NAME(CLASSNAME)) +#define STATIC_CLASS_REF(CLASSNAME) &(STATIC_CLASS_NAME_CONCAT(STATIC_CLASS_PREFIX, STATIC_CLASS_NAME(CLASSNAME))) + +#else // if !DEPLOYMENT_RUNTIME_SWIFT + +// We don't need static class refs if CF is used standalone, as there's no Swift or ObjC runtime to interoperate with. +#define STATIC_CLASS_REF(...) NULL + +#endif + + _CF_EXPORT_SCOPE_END #endif /* ! __COREFOUNDATION_FORFOUNDATIONONLY__ */ diff --git a/CoreFoundation/Base.subproj/ForSwiftFoundationOnly.h b/CoreFoundation/Base.subproj/ForSwiftFoundationOnly.h index 85b0b88715..e5f5ebf005 100644 --- a/CoreFoundation/Base.subproj/ForSwiftFoundationOnly.h +++ b/CoreFoundation/Base.subproj/ForSwiftFoundationOnly.h @@ -239,6 +239,10 @@ struct _NSNumberBridge { bool (*_Nonnull _getValue)(CFTypeRef number, void *value, CFNumberType type); }; +struct _NSDataBridge { + _Nonnull CFTypeRef (*_Nonnull copy)(CFTypeRef obj); +}; + struct _CFSwiftBridge { struct _NSObjectBridge NSObject; struct _NSArrayBridge NSArray; @@ -254,6 +258,7 @@ struct _CFSwiftBridge { struct _NSCharacterSetBridge NSCharacterSet; struct _NSMutableCharacterSetBridge NSMutableCharacterSet; struct _NSNumberBridge NSNumber; + struct _NSDataBridge NSData; }; CF_EXPORT struct _CFSwiftBridge __CFSwiftBridge; @@ -283,6 +288,12 @@ CF_EXPORT void _cf_uuid_unparse_lower(const _cf_uuid_t _Nonnull uu, _cf_uuid_str CF_EXPORT void _cf_uuid_unparse_upper(const _cf_uuid_t _Nonnull uu, _cf_uuid_string_t _Nonnull out); +CF_PRIVATE CFStringRef _CFProcessNameString(void); +CF_PRIVATE CFIndex __CFProcessorCount(void); +CF_PRIVATE uint64_t __CFMemorySize(void); +CF_PRIVATE CFIndex __CFActiveProcessorCount(void); +CF_CROSS_PLATFORM_EXPORT CFStringRef CFCopyFullUserName(void); + extern CFWriteStreamRef _CFWriteStreamCreateFromFileDescriptor(CFAllocatorRef alloc, int fd); #if !__COREFOUNDATION_FORFOUNDATIONONLY__ typedef const struct __CFKeyedArchiverUID * CFKeyedArchiverUIDRef; @@ -302,7 +313,7 @@ CF_EXPORT char *_Nullable *_Nonnull _CFEnviron(void); CF_EXPORT void CFLog1(CFLogLevel lev, CFStringRef message); -CF_EXPORT Boolean _CFIsMainThread(void); +CF_CROSS_PLATFORM_EXPORT Boolean _CFIsMainThread(void); CF_EXPORT pthread_t _CFMainPThread; CF_EXPORT CFHashCode __CFHashDouble(double d); @@ -315,11 +326,7 @@ CF_EXPORT _CFThreadSpecificKey _CFThreadSpecificKeyCreate(void); typedef pthread_attr_t _CFThreadAttributes; typedef pthread_t _CFThreadRef; -#if defined(__cplusplus) -CF_EXPORT _CFThreadRef _CFThreadCreate(const _CFThreadAttributes attrs, void *_Nullable (* _Nonnull startfn)(void *_Nullable), void *__restrict__ _Nullable context); -#else -CF_EXPORT _CFThreadRef _CFThreadCreate(const _CFThreadAttributes attrs, void *_Nullable (* _Nonnull startfn)(void *_Nullable), void *restrict _Nullable context); -#endif +CF_EXPORT _CFThreadRef _CFThreadCreate(const _CFThreadAttributes attrs, void *_Nullable (* _Nonnull startfn)(void *_Nullable), void *_CF_RESTRICT _Nullable context); CF_CROSS_PLATFORM_EXPORT int _CFThreadSetName(pthread_t thread, const char *_Nonnull name); CF_CROSS_PLATFORM_EXPORT int _CFThreadGetName(char *_Nonnull buf, int length); @@ -328,9 +335,9 @@ CF_EXPORT Boolean _CFCharacterSetIsLongCharacterMember(CFCharacterSetRef theSet, CF_EXPORT CFCharacterSetRef _CFCharacterSetCreateCopy(CFAllocatorRef alloc, CFCharacterSetRef theSet); CF_EXPORT CFMutableCharacterSetRef _CFCharacterSetCreateMutableCopy(CFAllocatorRef alloc, CFCharacterSetRef theSet); -CF_EXPORT _Nullable CFErrorRef CFReadStreamCopyError(CFReadStreamRef stream); +CF_EXPORT _Nullable CFErrorRef CFReadStreamCopyError(CFReadStreamRef _Null_unspecified stream); -CF_EXPORT _Nullable CFErrorRef CFWriteStreamCopyError(CFWriteStreamRef stream); +CF_EXPORT _Nullable CFErrorRef CFWriteStreamCopyError(CFWriteStreamRef _Null_unspecified stream); CF_CROSS_PLATFORM_EXPORT Boolean _CFBundleSupportsFHSBundles(void); @@ -357,6 +364,7 @@ CF_EXPORT CFStringRef _CFXDGCreateCacheDirectoryPath(void); /// a single base directory relative to which user-specific runtime files and other file objects should be placed. This directory is defined by the environment variable $XDG_RUNTIME_DIR. CF_EXPORT CFStringRef _CFXDGCreateRuntimeDirectoryPath(void); +CF_CROSS_PLATFORM_EXPORT void __CFURLComponentsDeallocate(CFTypeRef cf); typedef struct { void *_Nonnull memory; @@ -404,6 +412,16 @@ static inline _Bool _withStackOrHeapBuffer(size_t amount, void (__attribute__((n return true; } +#pragma mark - Character Set + +CF_CROSS_PLATFORM_EXPORT CFIndex __CFCharDigitValue(UniChar ch); + +#pragma mark - File Functions + +CF_CROSS_PLATFORM_EXPORT int _CFOpenFileWithMode(const char *path, int opts, mode_t mode); +CF_CROSS_PLATFORM_EXPORT void *_CFReallocf(void *ptr, size_t size); +CF_CROSS_PLATFORM_EXPORT int _CFOpenFile(const char *path, int opts); + static inline int _direntNameLength(struct dirent *entry) { #ifdef _D_EXACT_NAMLEN // defined on Linux return _D_EXACT_NAMLEN(entry); diff --git a/CoreFoundation/Collections.subproj/CFArray.c b/CoreFoundation/Collections.subproj/CFArray.c index 987799831f..1fc0d200ca 100644 --- a/CoreFoundation/Collections.subproj/CFArray.c +++ b/CoreFoundation/Collections.subproj/CFArray.c @@ -1,7 +1,7 @@ /* CFArray.c - Copyright (c) 1998-2017, Apple Inc. and the Swift project authors + Copyright (c) 1998-2018, Apple Inc. and the Swift project authors - Portions Copyright (c) 2014-2017, Apple Inc. and the Swift project authors + Portions Copyright (c) 2014-2018, Apple Inc. and the Swift project authors Licensed under Apache License v2.0 with Runtime Library Exception See http://swift.org/LICENSE.txt for license information See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors @@ -11,6 +11,7 @@ #include #include #include "CFInternal.h" +#include "CFRuntime_Internal.h" #include #define CF_ARRAY_ALWAYS_BRIDGE 0 @@ -86,6 +87,7 @@ CF_INLINE void __CFArraySetCount(CFArrayRef array, CFIndex v) { CF_INLINE struct __CFArrayBucket *__CFArrayGetBucketsPtr(CFArrayRef array) { switch (__CFArrayGetType(array)) { case __kCFArrayImmutable: + // TODO: Refactor the following to just get the custom callbacks value directly, or refactor helper function return (struct __CFArrayBucket *)((uint8_t *)array + __CFArrayGetSizeOfType(__CFRuntimeGetValue(array, 6, 0))); case __kCFArrayDeque: { struct __CFArrayDeque *deque = (struct __CFArrayDeque *)array->_store; @@ -276,9 +278,7 @@ static void __CFArrayDeallocate(CFTypeRef cf) { END_MUTATION(array); } -static CFTypeID __kCFArrayTypeID = _kCFRuntimeNotATypeID; - -static const CFRuntimeClass __CFArrayClass = { +const CFRuntimeClass __CFArrayClass = { _kCFRuntimeScannedObject, "CFArray", NULL, // init @@ -291,11 +291,7 @@ static const CFRuntimeClass __CFArrayClass = { }; CFTypeID CFArrayGetTypeID(void) { - static dispatch_once_t initOnce; - dispatch_once(&initOnce, ^{ - __kCFArrayTypeID = _CFRuntimeRegisterClass(&__CFArrayClass); - }); - return __kCFArrayTypeID; + return _kCFRuntimeIDCFArray; } static CFArrayRef __CFArrayInit(CFAllocatorRef allocator, UInt32 flags, CFIndex capacity, const CFArrayCallBacks *callBacks) { diff --git a/CoreFoundation/Collections.subproj/CFArray.h b/CoreFoundation/Collections.subproj/CFArray.h index 6ce9b1e000..0741982093 100644 --- a/CoreFoundation/Collections.subproj/CFArray.h +++ b/CoreFoundation/Collections.subproj/CFArray.h @@ -1,5 +1,5 @@ /* CFArray.h - Copyright (c) 1998-2017, Apple Inc. All rights reserved. + Copyright (c) 1998-2018, Apple Inc. All rights reserved. */ /*! diff --git a/CoreFoundation/Collections.subproj/CFBag.c b/CoreFoundation/Collections.subproj/CFBag.c index b8ca20fbb0..9fa2c4518e 100644 --- a/CoreFoundation/Collections.subproj/CFBag.c +++ b/CoreFoundation/Collections.subproj/CFBag.c @@ -1,7 +1,7 @@ /* CFBag.c - Copyright (c) 1998-2017, Apple Inc. and the Swift project authors + Copyright (c) 1998-2018, Apple Inc. and the Swift project authors - Portions Copyright (c) 2014-2017, Apple Inc. and the Swift project authors + Portions Copyright (c) 2014-2018, Apple Inc. and the Swift project authors Licensed under Apache License v2.0 with Runtime Library Exception See http://swift.org/LICENSE.txt for license information See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors @@ -15,6 +15,7 @@ #include #include "CFInternal.h" +#include "CFRuntime_Internal.h" #include "CFBasicHash.h" #include @@ -89,9 +90,7 @@ static void __CFBagDeallocate(CFTypeRef cf) { __CFBasicHashDeallocate((CFBasicHashRef)cf); } -static CFTypeID __kCFBagTypeID = _kCFRuntimeNotATypeID; - -static const CFRuntimeClass __CFBagClass = { +const CFRuntimeClass __CFBagClass = { _kCFRuntimeScannedObject, "CFBag", NULL, // init @@ -104,11 +103,7 @@ static const CFRuntimeClass __CFBagClass = { }; CFTypeID CFBagGetTypeID(void) { - static dispatch_once_t initOnce; - dispatch_once(&initOnce, ^{ - __kCFBagTypeID = _CFRuntimeRegisterClass(&__CFBagClass); - }); - return __kCFBagTypeID; + return _kCFRuntimeIDCFBag; } diff --git a/CoreFoundation/Collections.subproj/CFBag.h b/CoreFoundation/Collections.subproj/CFBag.h index 82f87af56e..f562e71e00 100644 --- a/CoreFoundation/Collections.subproj/CFBag.h +++ b/CoreFoundation/Collections.subproj/CFBag.h @@ -1,7 +1,7 @@ /* CFBag.h - Copyright (c) 1998-2017, Apple Inc. and the Swift project authors + Copyright (c) 1998-2018, Apple Inc. and the Swift project authors - Portions Copyright (c) 2014-2017, Apple Inc. and the Swift project authors + Portions Copyright (c) 2014-2018, Apple Inc. and the Swift project authors Licensed under Apache License v2.0 with Runtime Library Exception See http://swift.org/LICENSE.txt for license information See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors diff --git a/CoreFoundation/Collections.subproj/CFBasicHash.c b/CoreFoundation/Collections.subproj/CFBasicHash.c index f4a192dfb7..2731b0b993 100644 --- a/CoreFoundation/Collections.subproj/CFBasicHash.c +++ b/CoreFoundation/Collections.subproj/CFBasicHash.c @@ -1,21 +1,23 @@ /* CFBasicHash.m - Copyright (c) 2008-2017, Apple Inc. and the Swift project authors + Copyright (c) 2008-2018, Apple Inc. and the Swift project authors - Portions Copyright (c) 2014-2017, Apple Inc. and the Swift project authors + Portions Copyright (c) 2014-2018, Apple Inc. and the Swift project authors Licensed under Apache License v2.0 with Runtime Library Exception See http://swift.org/LICENSE.txt for license information See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors Responsibility: Christopher Kane */ -#include "CFBasicHash.h" -#include -#include -#include -#include +#import "CFBasicHash.h" +#import +#import "CFRuntime_Internal.h" +#import +#import +#import #if __HAS_DISPATCH__ -#include +#import #endif +#import "CFOverflow.h" #if DEPLOYMENT_TARGET_MACOSX || DEPLOYMENT_TARGET_EMBEDDED #define __SetLastAllocationEventName(A, B) do { if (__CFOASafe && (A)) __CFSetLastAllocationEventName(A, B); } while (0) @@ -258,11 +260,19 @@ static const uintptr_t __CFBasicHashPrimitiveRoots[64] = { }; CF_INLINE void *__CFBasicHashAllocateMemory(CFConstBasicHashRef ht, CFIndex count, CFIndex elem_size, Boolean strong, Boolean compactable) { - return CFAllocatorAllocate(CFGetAllocator(ht), count * elem_size, 0); + CFIndex memorySize; + if (os_mul_overflow(count, elem_size, &memorySize)) { + HALT_MSG("overflow while growing CFBasicHash"); + } + return CFAllocatorAllocate(CFGetAllocator(ht), memorySize, 0); } CF_INLINE void *__CFBasicHashAllocateMemory2(CFAllocatorRef allocator, CFIndex count, CFIndex elem_size, Boolean strong, Boolean compactable) { - return CFAllocatorAllocate(allocator, count * elem_size, 0); + CFIndex memorySize; + if (os_mul_overflow(count, elem_size, &memorySize)) { + HALT_MSG("overflow while growing CFBasicHash"); + } + return CFAllocatorAllocate(allocator, memorySize, 0); } #define __CFBasicHashSubABZero 0xa7baadb1 @@ -379,69 +389,69 @@ CF_INLINE Boolean __CFBasicHashHasHashCache(CFConstBasicHashRef ht) { } CF_INLINE uintptr_t __CFBasicHashImportValue(CFConstBasicHashRef ht, uintptr_t stack_value) { - uintptr_t (*func)(CFAllocatorRef, uintptr_t) = (uintptr_t (*)(CFAllocatorRef, uintptr_t))CFBasicHashGetPtrAtIndex(ht->bits.__vret); + void * (*func)(CFAllocatorRef, void *) = (void * (*)(CFAllocatorRef, void *))CFBasicHashGetPtrAtIndex(ht->bits.__vret); if (!func || ht->bits.null_rc) return stack_value; CFAllocatorRef alloc = __CFGetAllocator(ht); - return func(alloc, stack_value); + return (uintptr_t)func(alloc, (void *)stack_value); } CF_INLINE uintptr_t __CFBasicHashImportKey(CFConstBasicHashRef ht, uintptr_t stack_key) { - uintptr_t (*func)(CFAllocatorRef, uintptr_t) = (uintptr_t (*)(CFAllocatorRef, uintptr_t))CFBasicHashGetPtrAtIndex(ht->bits.__kret); + void * (*func)(CFAllocatorRef, void *) = (void * (*)(CFAllocatorRef, void *))CFBasicHashGetPtrAtIndex(ht->bits.__kret); if (!func || ht->bits.null_rc) return stack_key; CFAllocatorRef alloc = __CFGetAllocator(ht); - return func(alloc, stack_key); + return (uintptr_t)func(alloc, (void *)stack_key); } CF_INLINE void __CFBasicHashEjectValue(CFConstBasicHashRef ht, uintptr_t stack_value) { - void (*func)(CFAllocatorRef, uintptr_t) = (void (*)(CFAllocatorRef, uintptr_t))CFBasicHashGetPtrAtIndex(ht->bits.__vrel); + void (*func)(CFAllocatorRef, void *) = (void (*)(CFAllocatorRef, void *))CFBasicHashGetPtrAtIndex(ht->bits.__vrel); if (!func || ht->bits.null_rc) return; CFAllocatorRef alloc = __CFGetAllocator(ht); - func(alloc, stack_value); + func(alloc, (void *)stack_value); } CF_INLINE void __CFBasicHashEjectKey(CFConstBasicHashRef ht, uintptr_t stack_key) { - void (*func)(CFAllocatorRef, uintptr_t) = (void (*)(CFAllocatorRef, uintptr_t))CFBasicHashGetPtrAtIndex(ht->bits.__krel); + void (*func)(CFAllocatorRef, void *) = (void (*)(CFAllocatorRef, void *))CFBasicHashGetPtrAtIndex(ht->bits.__krel); if (!func || ht->bits.null_rc) return; CFAllocatorRef alloc = __CFGetAllocator(ht); - func(alloc, stack_key); + func(alloc, (void *)stack_key); } CF_INLINE CFStringRef __CFBasicHashDescValue(CFConstBasicHashRef ht, uintptr_t stack_value) CF_RETURNS_RETAINED { - CFStringRef (*func)(uintptr_t) = (CFStringRef (*)(uintptr_t))CFBasicHashGetPtrAtIndex(ht->bits.__vdes); + CFStringRef (*func)(void *) = (CFStringRef (*)(void *))CFBasicHashGetPtrAtIndex(ht->bits.__vdes); if (!func) return CFStringCreateWithFormat(kCFAllocatorSystemDefault, NULL, CFSTR("<%p>"), (void *)stack_value); - return func(stack_value); + return func((void *)stack_value); } CF_INLINE CFStringRef __CFBasicHashDescKey(CFConstBasicHashRef ht, uintptr_t stack_key) CF_RETURNS_RETAINED { - CFStringRef (*func)(uintptr_t) = (CFStringRef (*)(uintptr_t))CFBasicHashGetPtrAtIndex(ht->bits.__kdes); + CFStringRef (*func)(void *) = (CFStringRef (*)(void *))CFBasicHashGetPtrAtIndex(ht->bits.__kdes); if (!func) return CFStringCreateWithFormat(kCFAllocatorSystemDefault, NULL, CFSTR("<%p>"), (void *)stack_key); - return func(stack_key); + return func((void *)stack_key); } CF_INLINE Boolean __CFBasicHashTestEqualValue(CFConstBasicHashRef ht, uintptr_t stack_value_a, uintptr_t stack_value_b) { - Boolean (*func)(uintptr_t, uintptr_t) = (Boolean (*)(uintptr_t, uintptr_t))CFBasicHashGetPtrAtIndex(ht->bits.__vequ); + Boolean (*func)(void *, void *) = (Boolean (*)(void *, void *))CFBasicHashGetPtrAtIndex(ht->bits.__vequ); if (!func) return (stack_value_a == stack_value_b); - return func(stack_value_a, stack_value_b); + return func((void *)stack_value_a, (void *)stack_value_b); } CF_INLINE Boolean __CFBasicHashTestEqualKey(CFConstBasicHashRef ht, uintptr_t in_coll_key, uintptr_t stack_key) { COCOA_HASHTABLE_TEST_EQUAL(ht, in_coll_key, stack_key); - Boolean (*func)(uintptr_t, uintptr_t) = (Boolean (*)(uintptr_t, uintptr_t))CFBasicHashGetPtrAtIndex(ht->bits.__kequ); + Boolean (*func)(void *, void *) = (Boolean (*)(void *, void *))CFBasicHashGetPtrAtIndex(ht->bits.__kequ); if (!func) return (in_coll_key == stack_key); - return func(in_coll_key, stack_key); + return func((void *)in_coll_key, (void *)stack_key); } CF_INLINE CFHashCode __CFBasicHashHashKey(CFConstBasicHashRef ht, uintptr_t stack_key) { - CFHashCode (*func)(uintptr_t) = (CFHashCode (*)(uintptr_t))CFBasicHashGetPtrAtIndex(ht->bits.__khas); - CFHashCode hash_code = func ? func(stack_key) : stack_key; + CFHashCode (*func)(void *) = (CFHashCode (*)(void *))CFBasicHashGetPtrAtIndex(ht->bits.__khas); + CFHashCode hash_code = func ? func((void *)stack_key) : stack_key; COCOA_HASHTABLE_HASH_KEY(ht, stack_key, hash_code); return hash_code; } CF_INLINE uintptr_t __CFBasicHashGetIndirectKey(CFConstBasicHashRef ht, uintptr_t coll_key) { - uintptr_t (*func)(uintptr_t) = (uintptr_t (*)(uintptr_t))CFBasicHashGetPtrAtIndex(ht->bits.__kget); + void * (*func)(void *) = (void * (*)(void *))CFBasicHashGetPtrAtIndex(ht->bits.__kget); if (!func) return coll_key; - return func(coll_key); + return (uintptr_t)func((void *)coll_key); } CF_INLINE CFBasicHashValue *__CFBasicHashGetValues(CFConstBasicHashRef ht) { @@ -1526,9 +1536,7 @@ CF_PRIVATE void __CFBasicHashDeallocate(CFTypeRef cf) { #endif } -static CFTypeID __kCFBasicHashTypeID = _kCFRuntimeNotATypeID; - -static const CFRuntimeClass __CFBasicHashClass = { +const CFRuntimeClass __CFBasicHashClass = { _kCFRuntimeScannedObject, "CFBasicHash", NULL, // init @@ -1541,9 +1549,7 @@ static const CFRuntimeClass __CFBasicHashClass = { }; CF_PRIVATE CFTypeID CFBasicHashGetTypeID(void) { - static dispatch_once_t initOnce; - dispatch_once(&initOnce, ^{ __kCFBasicHashTypeID = _CFRuntimeRegisterClass(&__CFBasicHashClass); }); - return __kCFBasicHashTypeID; + return _kCFRuntimeIDCFBasicHash; } CF_PRIVATE CFBasicHashRef CFBasicHashCreate(CFAllocatorRef allocator, CFOptionFlags flags, const CFBasicHashCallbacks *cb) { diff --git a/CoreFoundation/Collections.subproj/CFBasicHash.h b/CoreFoundation/Collections.subproj/CFBasicHash.h index 90ec452e85..e2648fb128 100644 --- a/CoreFoundation/Collections.subproj/CFBasicHash.h +++ b/CoreFoundation/Collections.subproj/CFBasicHash.h @@ -1,7 +1,7 @@ /* CFBasicHash.h - Copyright (c) 2008-2017, Apple Inc. and the Swift project authors + Copyright (c) 2008-2018, Apple Inc. and the Swift project authors - Portions Copyright (c) 2014-2017, Apple Inc. and the Swift project authors + Portions Copyright (c) 2014-2018, Apple Inc. and the Swift project authors Licensed under Apache License v2.0 with Runtime Library Exception See http://swift.org/LICENSE.txt for license information See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors diff --git a/CoreFoundation/Collections.subproj/CFBasicHashFindBucket.m b/CoreFoundation/Collections.subproj/CFBasicHashFindBucket.m index 2d8f8eb1ba..b85f3bd727 100644 --- a/CoreFoundation/Collections.subproj/CFBasicHashFindBucket.m +++ b/CoreFoundation/Collections.subproj/CFBasicHashFindBucket.m @@ -1,7 +1,7 @@ /* CFBasicHashFindBucket.m - Copyright (c) 2009-2017, Apple Inc. and the Swift project authors + Copyright (c) 2009-2018, Apple Inc. and the Swift project authors - Portions Copyright (c) 2014-2017, Apple Inc. and the Swift project authors + Portions Copyright (c) 2014-2018, Apple Inc. and the Swift project authors Licensed under Apache License v2.0 with Runtime Library Exception See http://swift.org/LICENSE.txt for license information See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors diff --git a/CoreFoundation/Collections.subproj/CFBinaryHeap.c b/CoreFoundation/Collections.subproj/CFBinaryHeap.c index 1fa621f494..1ec0c325a4 100644 --- a/CoreFoundation/Collections.subproj/CFBinaryHeap.c +++ b/CoreFoundation/Collections.subproj/CFBinaryHeap.c @@ -1,7 +1,7 @@ /* CFBinaryHeap.c - Copyright (c) 1998-2017, Apple Inc. and the Swift project authors + Copyright (c) 1998-2018, Apple Inc. and the Swift project authors - Portions Copyright (c) 2014-2017, Apple Inc. and the Swift project authors + Portions Copyright (c) 2014-2018, Apple Inc. and the Swift project authors Licensed under Apache License v2.0 with Runtime Library Exception See http://swift.org/LICENSE.txt for license information See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors @@ -11,6 +11,7 @@ #include #include #include "CFInternal.h" +#include "CFRuntime_Internal.h" const CFBinaryHeapCallBacks kCFStringBinaryHeapCallBacks = {0, __CFTypeCollectionRetain, __CFTypeCollectionRelease, CFCopyDescription, (CFComparisonResult (*)(const void *, const void *, void *))CFStringCompare}; @@ -161,9 +162,7 @@ static void __CFBinaryHeapDeallocate(CFTypeRef cf) { } } -static CFTypeID __kCFBinaryHeapTypeID = _kCFRuntimeNotATypeID; - -static const CFRuntimeClass __CFBinaryHeapClass = { +const CFRuntimeClass __CFBinaryHeapClass = { _kCFRuntimeScannedObject, "CFBinaryHeap", NULL, // init @@ -176,9 +175,7 @@ static const CFRuntimeClass __CFBinaryHeapClass = { }; CFTypeID CFBinaryHeapGetTypeID(void) { - static dispatch_once_t initOnce; - dispatch_once(&initOnce, ^{ __kCFBinaryHeapTypeID = _CFRuntimeRegisterClass(&__CFBinaryHeapClass); }); - return __kCFBinaryHeapTypeID; + return _kCFRuntimeIDCFBinaryHeap; } static CFBinaryHeapRef __CFBinaryHeapInit(CFAllocatorRef allocator, UInt32 flags, CFIndex capacity, const void **values, CFIndex numValues, const CFBinaryHeapCallBacks *callBacks, const CFBinaryHeapCompareContext *compareContext) { diff --git a/CoreFoundation/Collections.subproj/CFBinaryHeap.h b/CoreFoundation/Collections.subproj/CFBinaryHeap.h index aaec0f542d..8583735079 100644 --- a/CoreFoundation/Collections.subproj/CFBinaryHeap.h +++ b/CoreFoundation/Collections.subproj/CFBinaryHeap.h @@ -1,7 +1,7 @@ /* CFBinaryHeap.h - Copyright (c) 1998-2017, Apple Inc. and the Swift project authors + Copyright (c) 1998-2018, Apple Inc. and the Swift project authors - Portions Copyright (c) 2014-2017, Apple Inc. and the Swift project authors + Portions Copyright (c) 2014-2018, Apple Inc. and the Swift project authors Licensed under Apache License v2.0 with Runtime Library Exception See http://swift.org/LICENSE.txt for license information See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors diff --git a/CoreFoundation/Collections.subproj/CFBitVector.c b/CoreFoundation/Collections.subproj/CFBitVector.c index fa50220b9d..5f7f078f57 100644 --- a/CoreFoundation/Collections.subproj/CFBitVector.c +++ b/CoreFoundation/Collections.subproj/CFBitVector.c @@ -1,7 +1,7 @@ /* CFBitVector.c - Copyright (c) 1998-2017, Apple Inc. and the Swift project authors + Copyright (c) 1998-2018, Apple Inc. and the Swift project authors - Portions Copyright (c) 2014-2017, Apple Inc. and the Swift project authors + Portions Copyright (c) 2014-2018, Apple Inc. and the Swift project authors Licensed under Apache License v2.0 with Runtime Library Exception See http://swift.org/LICENSE.txt for license information See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors @@ -10,6 +10,7 @@ #include #include "CFInternal.h" +#include "CFRuntime_Internal.h" #include /* The bucket type must be unsigned, at least one byte in size, and @@ -189,9 +190,7 @@ static void __CFBitVectorDeallocate(CFTypeRef cf) { if (bv->_buckets) CFAllocatorDeallocate(allocator, bv->_buckets); } -static CFTypeID __kCFBitVectorTypeID = _kCFRuntimeNotATypeID; - -static const CFRuntimeClass __CFBitVectorClass = { +const CFRuntimeClass __CFBitVectorClass = { _kCFRuntimeScannedObject, "CFBitVector", NULL, // init @@ -204,9 +203,7 @@ static const CFRuntimeClass __CFBitVectorClass = { }; CFTypeID CFBitVectorGetTypeID(void) { - static dispatch_once_t initOnce; - dispatch_once(&initOnce, ^{ __kCFBitVectorTypeID = _CFRuntimeRegisterClass(&__CFBitVectorClass); }); - return __kCFBitVectorTypeID; + return _kCFRuntimeIDCFBitVector; } static CFMutableBitVectorRef __CFBitVectorInit(CFAllocatorRef allocator, CFOptionFlags flags, CFIndex capacity, const uint8_t *bytes, CFIndex numBits) CF_RETURNS_RETAINED { diff --git a/CoreFoundation/Collections.subproj/CFBitVector.h b/CoreFoundation/Collections.subproj/CFBitVector.h index 2e91d84fc3..5eb49915f6 100644 --- a/CoreFoundation/Collections.subproj/CFBitVector.h +++ b/CoreFoundation/Collections.subproj/CFBitVector.h @@ -1,7 +1,7 @@ /* CFBitVector.h - Copyright (c) 1998-2017, Apple Inc. and the Swift project authors + Copyright (c) 1998-2018, Apple Inc. and the Swift project authors - Portions Copyright (c) 2014-2017, Apple Inc. and the Swift project authors + Portions Copyright (c) 2014-2018, Apple Inc. and the Swift project authors Licensed under Apache License v2.0 with Runtime Library Exception See http://swift.org/LICENSE.txt for license information See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors diff --git a/CoreFoundation/Collections.subproj/CFCollections_Internal.h b/CoreFoundation/Collections.subproj/CFCollections_Internal.h new file mode 100644 index 0000000000..12780ace1d --- /dev/null +++ b/CoreFoundation/Collections.subproj/CFCollections_Internal.h @@ -0,0 +1,25 @@ +/* CFCollections_Internal.h + Copyright (c) 1998-2018, Apple Inc. and the Swift project authors + + Portions Copyright (c) 2014-2018, Apple Inc. and the Swift project authors + Licensed under Apache License v2.0 with Runtime Library Exception + See http://swift.org/LICENSE.txt for license information + See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors +*/ + +#if !defined(__COREFOUNDATION_CFCOLLECTIONS_INTERNAL__) +#define __COREFOUNDATION_CFCOLLECTIONS_INTERNAL__ + +#include +#include +#include "CFInternal.h" + +CF_EXTERN_C_BEGIN +CF_ASSUME_NONNULL_BEGIN + +CF_PRIVATE void CFDictionaryApply(CFDictionaryRef theDict, void (^block)(const void * _Nullable key, const void * _Nullable value, Boolean *stop)); + +CF_ASSUME_NONNULL_END +CF_EXTERN_C_END + +#endif /* __COREFOUNDATION_CFCOLLECTIONS_INTERNAL__ */ diff --git a/CoreFoundation/Collections.subproj/CFData.c b/CoreFoundation/Collections.subproj/CFData.c index 54620d3f27..cdd305007f 100644 --- a/CoreFoundation/Collections.subproj/CFData.c +++ b/CoreFoundation/Collections.subproj/CFData.c @@ -1,7 +1,7 @@ /* CFData.c - Copyright (c) 1998-2017, Apple Inc. and the Swift project authors + Copyright (c) 1998-2018, Apple Inc. and the Swift project authors - Portions Copyright (c) 2014-2017, Apple Inc. and the Swift project authors + Portions Copyright (c) 2014-2018, Apple Inc. and the Swift project authors Licensed under Apache License v2.0 with Runtime Library Exception See http://swift.org/LICENSE.txt for license information See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors @@ -11,6 +11,7 @@ #include #include #include "CFInternal.h" +#include "CFRuntime_Internal.h" #include @@ -86,6 +87,9 @@ typedef enum { kCFMutable = 0x3 /* changeable and variable capacity */ } _CFDataMutableVariety; +#define __CFGenericValidateMutability(variety) \ + CFAssert1((variety != kCFFixedMutable && variety != kCFMutable), __kCFLogAssertion, "%s(): variety is not mutable", __PRETTY_FUNCTION__); + CF_INLINE Boolean __CFDataIsMutable(CFDataRef data) { return __CFRuntimeGetFlag(data, __kCFMutable); } @@ -307,9 +311,7 @@ static void __CFDataDeallocate(CFTypeRef cf) { } } -static CFTypeID __kCFDataTypeID = _kCFRuntimeNotATypeID; - -static const CFRuntimeClass __CFDataClass = { +const CFRuntimeClass __CFDataClass = { _kCFRuntimeScannedObject, "CFData", NULL, // init @@ -322,19 +324,16 @@ static const CFRuntimeClass __CFDataClass = { }; CFTypeID CFDataGetTypeID(void) { - static dispatch_once_t initOnce; - dispatch_once(&initOnce, ^{ __kCFDataTypeID = _CFRuntimeRegisterClass(&__CFDataClass); }); - return __kCFDataTypeID; + return _kCFRuntimeIDCFData; } void _CFDataInit(CFMutableDataRef memory, CFOptionFlags variety, CFIndex capacity, const uint8_t *bytes, CFIndex length, Boolean noCopy) { Boolean isMutable = ((variety & __kCFMutableMask) != 0); Boolean isGrowable = ((variety & __kCFGrowableMask) != 0); - Boolean isDontDeallocate = ((variety & __kCFDontDeallocate) != 0); __CFDataSetNumBytesUsed(memory, 0); __CFDataSetLength(memory, 0); - __CFDataSetDontDeallocate(memory, isDontDeallocate); + __CFDataSetDontDeallocate(memory, true); if (isMutable && isGrowable) { __CFDataSetCapacity(memory, __CFDataRoundUpCapacity(1)); @@ -376,6 +375,7 @@ static Boolean __CFDataShouldUseAllocator(CFAllocatorRef allocator) { // that there should be no deallocator, and the bytes should be copied. static CFMutableDataRef __CFDataInit(CFAllocatorRef allocator, _CFDataMutableVariety variety, CFIndex capacity, const uint8_t *bytes, CFIndex length, CFAllocatorRef bytesDeallocator) CF_RETURNS_RETAINED { CFMutableDataRef memory; + __CFGenericValidateMutability(variety); CFAssert2(0 <= capacity, __kCFLogAssertion, "%s(): capacity (%ld) cannot be less than zero", __PRETTY_FUNCTION__, capacity); CFAssert3(kCFFixedMutable != variety || length <= capacity, __kCFLogAssertion, "%s(): for kCFFixedMutable type, capacity (%ld) must be greater than or equal to number of initial elements (%ld)", __PRETTY_FUNCTION__, capacity, length); CFAssert2(0 <= length, __kCFLogAssertion, "%s(): length (%ld) cannot be less than zero", __PRETTY_FUNCTION__, length); @@ -460,7 +460,7 @@ CFDataRef CFDataCreateCopy(CFAllocatorRef allocator, CFDataRef data) { Boolean allowRetain = true; if (allowRetain) { CF_OBJC_FUNCDISPATCHV(CFDataGetTypeID(), CFDataRef, (NSData *)data, copy); - CF_SWIFT_FUNCDISPATCHV(CFDataGetTypeID(), CFDataRef, (CFSwiftRef)data, NSObject.copyWithZone, NULL); + CF_SWIFT_FUNCDISPATCHV(CFDataGetTypeID(), CFDataRef, (CFSwiftRef)data, NSData.copy); // If the data isn't mutable... if (!__CFDataIsMutable(data)) { @@ -840,6 +840,7 @@ CFRange CFDataFind(CFDataRef data, CFDataRef dataToFind, CFRange searchRange, CF } #undef __CFDataValidateRange +#undef __CFGenericValidateMutability #undef INLINE_BYTES_THRESHOLD #undef CFDATA_MAX_SIZE #undef REVERSE_BUFFER diff --git a/CoreFoundation/Collections.subproj/CFData.h b/CoreFoundation/Collections.subproj/CFData.h index 2d8edd4533..2ae4012796 100644 --- a/CoreFoundation/Collections.subproj/CFData.h +++ b/CoreFoundation/Collections.subproj/CFData.h @@ -1,7 +1,7 @@ /* CFData.h - Copyright (c) 1998-2017, Apple Inc. and the Swift project authors + Copyright (c) 1998-2018, Apple Inc. and the Swift project authors - Portions Copyright (c) 2014-2017, Apple Inc. and the Swift project authors + Portions Copyright (c) 2014-2018, Apple Inc. and the Swift project authors Licensed under Apache License v2.0 with Runtime Library Exception See http://swift.org/LICENSE.txt for license information See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors diff --git a/CoreFoundation/Collections.subproj/CFDictionary.c b/CoreFoundation/Collections.subproj/CFDictionary.c index f82c32e5e5..a8ad71c927 100644 --- a/CoreFoundation/Collections.subproj/CFDictionary.c +++ b/CoreFoundation/Collections.subproj/CFDictionary.c @@ -1,7 +1,7 @@ /* CFDictionary.c - Copyright (c) 1998-2017, Apple Inc. and the Swift project authors + Copyright (c) 1998-2018, Apple Inc. and the Swift project authors - Portions Copyright (c) 2014-2017, Apple Inc. and the Swift project authors + Portions Copyright (c) 2014-2018, Apple Inc. and the Swift project authors Licensed under Apache License v2.0 with Runtime Library Exception See http://swift.org/LICENSE.txt for license information See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors @@ -17,6 +17,7 @@ #include "CFInternal.h" #include "CFBasicHash.h" #include +#include "CFRuntime_Internal.h" #define CFDictionary 0 @@ -89,9 +90,7 @@ static void __CFDictionaryDeallocate(CFTypeRef cf) { __CFBasicHashDeallocate((CFBasicHashRef)cf); } -static CFTypeID __kCFDictionaryTypeID = _kCFRuntimeNotATypeID; - -static const CFRuntimeClass __CFDictionaryClass = { +const CFRuntimeClass __CFDictionaryClass = { _kCFRuntimeScannedObject, "CFDictionary", NULL, // init @@ -104,11 +103,7 @@ static const CFRuntimeClass __CFDictionaryClass = { }; CFTypeID CFDictionaryGetTypeID(void) { - static dispatch_once_t initOnce; - dispatch_once(&initOnce, ^{ - __kCFDictionaryTypeID = _CFRuntimeRegisterClass(&__CFDictionaryClass); - }); - return __kCFDictionaryTypeID; + return _kCFRuntimeIDCFDictionary; } @@ -442,6 +437,16 @@ void CFDictionaryApplyFunction(CFHashRef hc, CFDictionaryApplierFunction applier }); } +CF_PRIVATE void CFDictionaryApply(CFHashRef hc, void (^block)(const void *key, const void *value, Boolean *stop)) { + __CFGenericValidateType(hc, CFDictionaryGetTypeID()); + CFBasicHashApply((CFBasicHashRef)hc, ^(CFBasicHashBucket bkt) { + Boolean stop = false; + block((const_any_pointer_t)bkt.weak_key, (const_any_pointer_t)bkt.weak_value, &stop); + if (stop) return (Boolean)false; + return (Boolean)true; + }); +} + // This function is for Foundation's benefit; no one else should use it. CF_EXPORT unsigned long _CFDictionaryFastEnumeration(CFHashRef hc, struct __objcFastEnumerationStateEquivalent *state, void *stackbuffer, unsigned long count) { if (CF_IS_SWIFT(CFDictionaryGetTypeID(), hc)) return 0; diff --git a/CoreFoundation/Collections.subproj/CFDictionary.h b/CoreFoundation/Collections.subproj/CFDictionary.h index 94035c0db7..575affb9d8 100644 --- a/CoreFoundation/Collections.subproj/CFDictionary.h +++ b/CoreFoundation/Collections.subproj/CFDictionary.h @@ -1,7 +1,7 @@ /* CFDictionary.h - Copyright (c) 1998-2017, Apple Inc. and the Swift project authors + Copyright (c) 1998-2018, Apple Inc. and the Swift project authors - Portions Copyright (c) 2014-2017, Apple Inc. and the Swift project authors + Portions Copyright (c) 2014-2018, Apple Inc. and the Swift project authors Licensed under Apache License v2.0 with Runtime Library Exception See http://swift.org/LICENSE.txt for license information See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors diff --git a/CoreFoundation/Collections.subproj/CFSet.c b/CoreFoundation/Collections.subproj/CFSet.c index 7ff89cf54a..afca65e1ae 100644 --- a/CoreFoundation/Collections.subproj/CFSet.c +++ b/CoreFoundation/Collections.subproj/CFSet.c @@ -1,7 +1,7 @@ /* CFSet.c - Copyright (c) 1998-2017, Apple Inc. and the Swift project authors + Copyright (c) 1998-2018, Apple Inc. and the Swift project authors - Portions Copyright (c) 2014-2017, Apple Inc. and the Swift project authors + Portions Copyright (c) 2014-2018, Apple Inc. and the Swift project authors Licensed under Apache License v2.0 with Runtime Library Exception See http://swift.org/LICENSE.txt for license information See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors @@ -17,6 +17,7 @@ #include "CFInternal.h" #include "CFBasicHash.h" #include +#include "CFRuntime_Internal.h" #define CFDictionary 0 @@ -89,9 +90,7 @@ static void __CFSetDeallocate(CFTypeRef cf) { __CFBasicHashDeallocate((CFBasicHashRef)cf); } -static CFTypeID __kCFSetTypeID = _kCFRuntimeNotATypeID; - -static const CFRuntimeClass __CFSetClass = { +const CFRuntimeClass __CFSetClass = { _kCFRuntimeScannedObject, "CFSet", NULL, // init @@ -104,11 +103,7 @@ static const CFRuntimeClass __CFSetClass = { }; CFTypeID CFSetGetTypeID(void) { - static dispatch_once_t initOnce; - dispatch_once(&initOnce, ^{ - __kCFSetTypeID = _CFRuntimeRegisterClass(&__CFSetClass); - }); - return __kCFSetTypeID; + return _kCFRuntimeIDCFSet; } diff --git a/CoreFoundation/Collections.subproj/CFSet.h b/CoreFoundation/Collections.subproj/CFSet.h index b22d81557a..a9c0c34766 100644 --- a/CoreFoundation/Collections.subproj/CFSet.h +++ b/CoreFoundation/Collections.subproj/CFSet.h @@ -1,7 +1,7 @@ /* CFSet.h - Copyright (c) 1998-2017, Apple Inc. and the Swift project authors + Copyright (c) 1998-2018, Apple Inc. and the Swift project authors - Portions Copyright (c) 2014-2017, Apple Inc. and the Swift project authors + Portions Copyright (c) 2014-2018, Apple Inc. and the Swift project authors Licensed under Apache License v2.0 with Runtime Library Exception See http://swift.org/LICENSE.txt for license information See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors diff --git a/CoreFoundation/Collections.subproj/CFStorage.c b/CoreFoundation/Collections.subproj/CFStorage.c index 5729821b59..273b3a84b7 100644 --- a/CoreFoundation/Collections.subproj/CFStorage.c +++ b/CoreFoundation/Collections.subproj/CFStorage.c @@ -1,7 +1,7 @@ /* CFStorage.c - Copyright (c) 1999-2017, Apple Inc. All rights reserved. + Copyright (c) 1999-2018, Apple Inc. All rights reserved. - Portions Copyright (c) 2014-2017, Apple Inc. and the Swift project authors + Portions Copyright (c) 2014-2018, Apple Inc. and the Swift project authors Licensed under Apache License v2.0 with Runtime Library Exception See http://swift.org/LICENSE.txt for license information See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors @@ -32,11 +32,14 @@ #include #include "CFInternal.h" +#include "CFRuntime_Internal.h" #if __HAS_DISPATCH__ #include #endif #if DEPLOYMENT_TARGET_WINDOWS +// No C99 support +#define restrict // Replace bzero #define bzero(dst, size) ZeroMemory(dst, size) @@ -242,7 +245,7 @@ static inline void __CFStorageSetChild(CFStorageNode *parentNode, CFIndex childI *((void **)&parentNode->info.notLeaf.child[childIndex]) = newChild; } -static inline void __CFStorageGetChildren(const CFStorageNode *parent, CFStorageNode ** _CF_RESTRICT resultArray, bool shouldRetain, bool shouldFreeze) { +static inline void __CFStorageGetChildren(const CFStorageNode *parent, CFStorageNode ** restrict resultArray, bool shouldRetain, bool shouldFreeze) { ASSERT(! parent->isLeaf); CFIndex i; for (i=0; i < 3; i++) { @@ -270,7 +273,7 @@ CF_INLINE void __CFStorageSetCache(CFStorageRef storage, CFStorageNode *node, CF /* Gets the location for the specified absolute loc from the cached info. Returns NULL if the location is not in the cache. */ -CF_INLINE uint8_t *__CFStorageGetFromCache(CFStorageRef storage, CFIndex loc, CFRange * _CF_RESTRICT validConsecutiveValueRange, bool requireUnfrozenNode) { +CF_INLINE uint8_t *__CFStorageGetFromCache(CFStorageRef storage, CFIndex loc, CFRange * restrict validConsecutiveValueRange, bool requireUnfrozenNode) { CFStorageNode * const cachedNode = storage->cacheNode; /* It's important we read from this field no more than once, for thread safety with other concurrent reads; that is why the field is marked volatile. */ if (! cachedNode) return NULL; /* No cache */ @@ -305,7 +308,7 @@ CF_INLINE uint8_t *__CFStorageGetFromCache(CFStorageRef storage, CFIndex loc, CF relativeByteNum (not optional, for performance reasons) returns the relative byte number of the specified byte in the child. Don't call with leaf nodes! */ -CF_INLINE CFStorageNode *__CFStorageFindChild(const CFStorageNode * _CF_RESTRICT node, CFIndex byteNum, bool forInsertionOrDeletion, CFIndex * _CF_RESTRICT childNum, CFIndex * _CF_RESTRICT relativeByteNum) { +CF_INLINE CFStorageNode *__CFStorageFindChild(const CFStorageNode * restrict node, CFIndex byteNum, bool forInsertionOrDeletion, CFIndex * restrict childNum, CFIndex * restrict relativeByteNum) { if (forInsertionOrDeletion) byteNum--; /* If for insertion, we do <= checks, not <, so this accomplishes the same thing */ CFStorageNode *result; result = node->info.notLeaf.child[0]; @@ -1065,9 +1068,7 @@ static void __CFStorageDeallocate(CFTypeRef cf) { __CFStorageClearRootNode(storage); } -static CFTypeID __kCFStorageTypeID = _kCFRuntimeNotATypeID; - -static const CFRuntimeClass __CFStorageClass = { +const CFRuntimeClass __CFStorageClass = { _kCFRuntimeScannedObject, "CFStorage", NULL, // init @@ -1168,9 +1169,7 @@ CFStorageRef CFStorageCreateWithSubrange(CFStorageRef mutStorage, CFRange range) } CFTypeID CFStorageGetTypeID(void) { - static dispatch_once_t initOnce; - dispatch_once(&initOnce, ^{ __kCFStorageTypeID = _CFRuntimeRegisterClass(&__CFStorageClass); }); - return __kCFStorageTypeID; + return _kCFRuntimeIDCFStorage; } CFIndex CFStorageGetCount(CFStorageRef storage) { diff --git a/CoreFoundation/Collections.subproj/CFStorage.h b/CoreFoundation/Collections.subproj/CFStorage.h index d35868b3d3..ac267d85eb 100644 --- a/CoreFoundation/Collections.subproj/CFStorage.h +++ b/CoreFoundation/Collections.subproj/CFStorage.h @@ -1,7 +1,7 @@ /* CFStorage.h - Copyright (c) 1999-2017, Apple Inc. and the Swift project authors + Copyright (c) 1999-2018, Apple Inc. and the Swift project authors - Portions Copyright (c) 2014-2017, Apple Inc. and the Swift project authors + Portions Copyright (c) 2014-2018, Apple Inc. and the Swift project authors Licensed under Apache License v2.0 with Runtime Library Exception See http://swift.org/LICENSE.txt for license information See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors diff --git a/CoreFoundation/Collections.subproj/CFTree.c b/CoreFoundation/Collections.subproj/CFTree.c index 0b2e42c431..de5ddeb1f1 100644 --- a/CoreFoundation/Collections.subproj/CFTree.c +++ b/CoreFoundation/Collections.subproj/CFTree.c @@ -1,7 +1,7 @@ /* CFTree.c - Copyright (c) 1998-2017, Apple Inc. and the Swift project authors + Copyright (c) 1998-2018, Apple Inc. and the Swift project authors - Portions Copyright (c) 2014-2017, Apple Inc. and the Swift project authors + Portions Copyright (c) 2014-2018, Apple Inc. and the Swift project authors Licensed under Apache License v2.0 with Runtime Library Exception See http://swift.org/LICENSE.txt for license information See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors @@ -10,6 +10,7 @@ #include #include "CFInternal.h" +#include "CFRuntime_Internal.h" #include struct __CFTreeCallBacks { @@ -99,10 +100,7 @@ static void __CFTreeDeallocate(CFTypeRef cf) { } } - -static CFTypeID __kCFTreeTypeID = _kCFRuntimeNotATypeID; - -static const CFRuntimeClass __CFTreeClass = { +const CFRuntimeClass __CFTreeClass = { _kCFRuntimeScannedObject, "CFTree", NULL, // init @@ -115,9 +113,7 @@ static const CFRuntimeClass __CFTreeClass = { }; CFTypeID CFTreeGetTypeID(void) { - static dispatch_once_t initOnce; - dispatch_once(&initOnce, ^{ __kCFTreeTypeID = _CFRuntimeRegisterClass(&__CFTreeClass); }); - return __kCFTreeTypeID; + return _kCFRuntimeIDCFTree; } CFTreeRef CFTreeCreate(CFAllocatorRef allocator, const CFTreeContext *context) { diff --git a/CoreFoundation/Collections.subproj/CFTree.h b/CoreFoundation/Collections.subproj/CFTree.h index 7aaf4f1bcc..ce5694dd31 100644 --- a/CoreFoundation/Collections.subproj/CFTree.h +++ b/CoreFoundation/Collections.subproj/CFTree.h @@ -1,7 +1,7 @@ /* CFTree.h - Copyright (c) 1998-2017, Apple Inc. and the Swift project authors + Copyright (c) 1998-2018, Apple Inc. and the Swift project authors - Portions Copyright (c) 2014-2017, Apple Inc. and the Swift project authors + Portions Copyright (c) 2014-2018, Apple Inc. and the Swift project authors Licensed under Apache License v2.0 with Runtime Library Exception See http://swift.org/LICENSE.txt for license information See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors diff --git a/CoreFoundation/Error.subproj/CFError.c b/CoreFoundation/Error.subproj/CFError.c index 8a9b2133a9..108f1bd627 100644 --- a/CoreFoundation/Error.subproj/CFError.c +++ b/CoreFoundation/Error.subproj/CFError.c @@ -1,7 +1,7 @@ /* CFError.c - Copyright (c) 2006-2017, Apple Inc. and the Swift project authors + Copyright (c) 2006-2018, Apple Inc. and the Swift project authors - Portions Copyright (c) 2014-2017, Apple Inc. and the Swift project authors + Portions Copyright (c) 2014-2018, Apple Inc. and the Swift project authors Licensed under Apache License v2.0 with Runtime Library Exception See http://swift.org/LICENSE.txt for license information See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors @@ -11,6 +11,7 @@ #include #include #include "CFInternal.h" +#include "CFRuntime_Internal.h" #include #include #if DEPLOYMENT_TARGET_MACOSX || DEPLOYMENT_TARGET_EMBEDDED @@ -19,6 +20,7 @@ + #if DEPLOYMENT_RUNTIME_SWIFT // We don't have the right memory management semantics to handle storing Swift blocks right now #define USES_CALLBACK_BLOCKS 0 @@ -142,10 +144,7 @@ static void __CFErrorDeallocate(CFTypeRef cf) { CFRelease(err->userInfo); } - -static CFTypeID __kCFErrorTypeID = _kCFRuntimeNotATypeID; - -static const CFRuntimeClass __CFErrorClass = { +const CFRuntimeClass __CFErrorClass = { 0, "CFError", NULL, // init @@ -158,9 +157,7 @@ static const CFRuntimeClass __CFErrorClass = { }; CFTypeID CFErrorGetTypeID(void) { - static dispatch_once_t initOnce; - dispatch_once(&initOnce, ^{ __kCFErrorTypeID = _CFRuntimeRegisterClass(&__CFErrorClass); }); - return __kCFErrorTypeID; + return _kCFRuntimeIDCFError; } @@ -241,7 +238,13 @@ CFStringRef _CFErrorCreateLocalizedDescription(CFErrorRef err) { if (localizedDesc) return localizedDesc; // If a we have kCFErrorLocalizedFailureKey, use it, in conjunction with kCFErrorLocalizedFailureReasonKey if we have that, otherwise by itself +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wunguarded-availability-new" + CFStringRef failure = (keyLookupFunc)(err, kCFErrorLocalizedFailureKey); + +#pragma clang diagnostic pop + if (failure) { CFStringRef reason = _CFErrorCopyUserInfoKey(err, kCFErrorLocalizedFailureReasonKey); // This can come from userInfo or callback if (reason) { @@ -340,7 +343,8 @@ static void userInfoKeyValueShow(const void *key, const void *value, void *ctxt) CFStringAppendFormat(context->result, NULL, CFSTR("%@=%p {"), key, value); _CFErrorFormatDebugDescriptionAux((CFErrorRef)value, context); CFStringAppend(context->result, CFSTR("}, ")); - } else { + } + else { CFStringAppendFormat(context->result, NULL, CFSTR("%@=%@, "), key, value); } } @@ -392,6 +396,7 @@ CFStringRef _CFErrorCreateDebugDescription(CFErrorRef err) { + /**** CFError API/SPI ****/ /* Note that there are two entry points for creating CFErrors. This one does it with a presupplied userInfo dictionary. @@ -615,3 +620,26 @@ static void __CFErrorSetCallBackForDomainNoLock(CFStringRef domainName, CFErrorU } } +// !!! This function can go away after 10.13/iOS 11 +void CFErrorSetCallBackForDomain(CFStringRef domainName, CFErrorUserInfoKeyCallBack callBack) { + // Since we have replaced the callback functionality with a callback block functionality, we now register (legacy) callback functions embedded in a block which autoreleases the result + CFErrorUserInfoKeyCallBackBlock block = (!callBack) ? NULL : ^(CFErrorRef err, CFStringRef key){ + CFTypeRef result = callBack(err, key); +#if !DEPLOYMENT_RUNTIME_SWIFT + if (result) CFAutorelease(result); +#endif + return result; + }; + CFErrorSetCallBackBlockForDomain(domainName, block); +} + +// !!! This function can go away after 10.13/iOS 11 +CFErrorUserInfoKeyCallBack CFErrorGetCallBackForDomain(CFStringRef domainName) { + // Since there were no callers other than CF, removed as of 10.11/iOS9 + // Otherwise would have had to have separate tables for callback functions and blocks + return NULL; +} + + + + diff --git a/CoreFoundation/Error.subproj/CFError.h b/CoreFoundation/Error.subproj/CFError.h index 8f36f41efc..7cd3ebb077 100644 --- a/CoreFoundation/Error.subproj/CFError.h +++ b/CoreFoundation/Error.subproj/CFError.h @@ -1,7 +1,7 @@ /* CFError.h - Copyright (c) 2006-2017, Apple Inc. and the Swift project authors + Copyright (c) 2006-2018, Apple Inc. and the Swift project authors - Portions Copyright (c) 2014-2017, Apple Inc. and the Swift project authors + Portions Copyright (c) 2014-2018, Apple Inc. and the Swift project authors Licensed under Apache License v2.0 with Runtime Library Exception See http://swift.org/LICENSE.txt for license information See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors diff --git a/CoreFoundation/Error.subproj/CFError_Private.h b/CoreFoundation/Error.subproj/CFError_Private.h index db4eaf3dfd..c7649d2150 100644 --- a/CoreFoundation/Error.subproj/CFError_Private.h +++ b/CoreFoundation/Error.subproj/CFError_Private.h @@ -1,7 +1,7 @@ /* CFError_Private.h - Copyright (c) 2006-2017, Apple Inc. and the Swift project authors + Copyright (c) 2006-2018, Apple Inc. and the Swift project authors - Portions Copyright (c) 2014-2017, Apple Inc. and the Swift project authors + Portions Copyright (c) 2014-2018, Apple Inc. and the Swift project authors Licensed under Apache License v2.0 with Runtime Library Exception See http://swift.org/LICENSE.txt for license information See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors diff --git a/CoreFoundation/Locale.subproj/CFCalendar.c b/CoreFoundation/Locale.subproj/CFCalendar.c index d2f13c8642..4e7b7b6c57 100644 --- a/CoreFoundation/Locale.subproj/CFCalendar.c +++ b/CoreFoundation/Locale.subproj/CFCalendar.c @@ -1,7 +1,7 @@ /* CFCalendar.c - Copyright (c) 2004-2017, Apple Inc. and the Swift project authors + Copyright (c) 2004-2018, Apple Inc. and the Swift project authors - Portions Copyright (c) 2014-2017, Apple Inc. and the Swift project authors + Portions Copyright (c) 2014-2018, Apple Inc. and the Swift project authors Licensed under Apache License v2.0 with Runtime Library Exception See http://swift.org/LICENSE.txt for license information See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors @@ -14,6 +14,7 @@ #include #include "CFInternal.h" #include "CFPriv.h" +#include "CFRuntime_Internal.h" #include #define BUFFER_SIZE 512 @@ -52,9 +53,7 @@ static void __CFCalendarDeallocate(CFTypeRef cf) { if (calendar->_cal) ucal_close(calendar->_cal); } -static CFTypeID __kCFCalendarTypeID = _kCFRuntimeNotATypeID; - -static const CFRuntimeClass __CFCalendarClass = { +const CFRuntimeClass __CFCalendarClass = { 0, "CFCalendar", NULL, // init @@ -67,9 +66,7 @@ static const CFRuntimeClass __CFCalendarClass = { }; CFTypeID CFCalendarGetTypeID(void) { - static dispatch_once_t initOnce; - dispatch_once(&initOnce, ^{ __kCFCalendarTypeID = _CFRuntimeRegisterClass(&__CFCalendarClass); }); - return __kCFCalendarTypeID; + return _kCFRuntimeIDCFCalendar; } CF_PRIVATE UCalendar *__CFCalendarCreateUCalendar(CFStringRef calendarID, CFStringRef localeID, CFTimeZoneRef tz) { diff --git a/CoreFoundation/Locale.subproj/CFCalendar.h b/CoreFoundation/Locale.subproj/CFCalendar.h index 920701958f..75fbf7c98d 100644 --- a/CoreFoundation/Locale.subproj/CFCalendar.h +++ b/CoreFoundation/Locale.subproj/CFCalendar.h @@ -1,7 +1,7 @@ /* CFCalendar.h - Copyright (c) 2004-2017, Apple Inc. and the Swift project authors + Copyright (c) 2004-2018, Apple Inc. and the Swift project authors - Portions Copyright (c) 2014-2017, Apple Inc. and the Swift project authors + Portions Copyright (c) 2014-2018, Apple Inc. and the Swift project authors Licensed under Apache License v2.0 with Runtime Library Exception See http://swift.org/LICENSE.txt for license information See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors diff --git a/CoreFoundation/Locale.subproj/CFDateFormatter.c b/CoreFoundation/Locale.subproj/CFDateFormatter.c index 260f0a99a1..2f825ae087 100644 --- a/CoreFoundation/Locale.subproj/CFDateFormatter.c +++ b/CoreFoundation/Locale.subproj/CFDateFormatter.c @@ -1,7 +1,7 @@ /* CFDateFormatter.c - Copyright (c) 2002-2017, Apple Inc. and the Swift project authors + Copyright (c) 2002-2018, Apple Inc. and the Swift project authors - Portions Copyright (c) 2014-2017, Apple Inc. and the Swift project authors + Portions Copyright (c) 2014-2018, Apple Inc. and the Swift project authors Licensed under Apache License v2.0 with Runtime Library Exception See http://swift.org/LICENSE.txt for license information See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors @@ -18,6 +18,7 @@ #include #include "CFPriv.h" #include "CFInternal.h" +#include "CFRuntime_Internal.h" #include "CFLocaleInternal.h" #include "CFICULogging.h" #include @@ -66,7 +67,7 @@ static Boolean useTemplatePatternGenerator(CFLocaleRef locale, void(^work)(UDate if (CFStringGetCString(ln, buffer, BUFFER_SIZE, kCFStringEncodingASCII)) localeName = buffer; } - static void (^flushCache)(void) = ^{ + void (^flushCache)(void) = ^{ __cficu_udatpg_close(ptg); ptg = NULL; free((void *)ptgLocaleName); @@ -642,13 +643,14 @@ static void __ResetUDateFormat(CFDateFormatterRef df, Boolean goingToHaveCustomF } if (!wantRelative && df->_property._HasCustomFormat == kCFBooleanTrue) { CFIndex cnt = CFStringGetLength(df->_format); - STACK_BUFFER_DECL(UChar, ubuffer, cnt); + SAFE_STACK_BUFFER_DECL(UChar, ubuffer, cnt, 256); const UChar *ustr = (UChar *)CFStringGetCharactersPtr((CFStringRef)df->_format); if (NULL == ustr) { CFStringGetCharacters(df->_format, CFRangeMake(0, cnt), (UniChar *)ubuffer); ustr = ubuffer; } __cficu_udat_applyPattern(icudf, false, ustr, cnt); + SAFE_STACK_BUFFER_CLEANUP(ubuffer); } CFStringRef calident = (CFStringRef)CFLocaleGetValue(df->_locale, kCFLocaleCalendarIdentifierKey); @@ -712,7 +714,7 @@ static void __ResetUDateFormat(CFDateFormatterRef df, Boolean goingToHaveCustomF CFIndex cnt = CFStringGetLength(formatString); CFAssert1(cnt <= 1024, __kCFLogAssertion, "%s(): format string too long", __PRETTY_FUNCTION__); if (cnt <= 1024) { - STACK_BUFFER_DECL(UChar, ubuffer, cnt); + SAFE_STACK_BUFFER_DECL(UChar, ubuffer, cnt, 256); const UChar *ustr = (UChar *)CFStringGetCharactersPtr((CFStringRef)formatString); if (NULL == ustr) { CFStringGetCharacters(formatString, CFRangeMake(0, cnt), (UniChar *)ubuffer); @@ -725,6 +727,7 @@ static void __ResetUDateFormat(CFDateFormatterRef df, Boolean goingToHaveCustomF if (df->_format) CFRelease(df->_format); df->_format = (CFStringRef)CFStringCreateCopy(CFGetAllocator(df), formatString); } + SAFE_STACK_BUFFER_CLEANUP(ubuffer); } CFRelease(formatString); CFRelease(newFormat); @@ -746,9 +749,7 @@ static void __ResetUDateFormat(CFDateFormatterRef df, Boolean goingToHaveCustomF RESET_PROPERTY(_FormattingContext, kCFDateFormatterFormattingContextKey); } -static CFTypeID __kCFDateFormatterTypeID = _kCFRuntimeNotATypeID; - -static const CFRuntimeClass __CFDateFormatterClass = { +const CFRuntimeClass __CFDateFormatterClass = { 0, "CFDateFormatter", NULL, // init @@ -761,9 +762,7 @@ static const CFRuntimeClass __CFDateFormatterClass = { }; CFTypeID CFDateFormatterGetTypeID(void) { - static dispatch_once_t initOnce; - dispatch_once(&initOnce, ^{ __kCFDateFormatterTypeID = _CFRuntimeRegisterClass(&__CFDateFormatterClass); }); - return __kCFDateFormatterTypeID; + return _kCFRuntimeIDCFDateFormatter; } static CFDateFormatterRef __SetUpCFDateFormatter(CFAllocatorRef allocator, CFLocaleRef locale, CFDateFormatterStyle dateStyle, CFDateFormatterStyle timeStyle, CFBooleanRef calculateISO8601) { @@ -899,8 +898,14 @@ static CFMutableStringRef __createISO8601FormatString(CFISO8601DateFormatOptions BOOL useColonSeparatorInTime = (options & kCFISO8601DateFormatWithColonSeparatorInTime) == kCFISO8601DateFormatWithColonSeparatorInTime; BOOL useColonSeparatorInTimeZone = (options & kCFISO8601DateFormatWithColonSeparatorInTimeZone) == kCFISO8601DateFormatWithColonSeparatorInTimeZone; BOOL internetDateTime = (options & kCFISO8601DateFormatWithInternetDateTime) == kCFISO8601DateFormatWithInternetDateTime; + +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wunguarded-availability-new" + BOOL includeFractionalSecs = (options & kCFISO8601DateFormatWithFractionalSeconds) == kCFISO8601DateFormatWithFractionalSeconds; +#pragma clang diagnostic pop + if (internetDateTime) { // Check for dashes if (useDashSeparator == NO) { @@ -1297,7 +1302,7 @@ static CFStringRef __CFDateFormatterCreateForcedString(CFDateFormatterRef format #if __HAS_APPLE_ICU__ Boolean success = useTemplatePatternGenerator(formatter->_locale, ^(UDateTimePatternGenerator *ptg) { CFIndex cnt = CFStringGetLength(inString); - STACK_BUFFER_DECL(UChar, ubuffer, cnt); + SAFE_STACK_BUFFER_DECL(UChar, ubuffer, cnt, 256); const UChar *ustr = (UChar *)CFStringGetCharactersPtr(inString); if (NULL == ustr) { CFStringGetCharacters(inString, CFRangeMake(0, cnt), (UniChar *)ubuffer); @@ -1318,6 +1323,7 @@ static CFStringRef __CFDateFormatterCreateForcedString(CFDateFormatterRef format } free(largerBuffer); } + SAFE_STACK_BUFFER_CLEANUP(ubuffer); }); #else Boolean success = false; @@ -1359,7 +1365,7 @@ void CFDateFormatterSetFormat(CFDateFormatterRef formatter, CFStringRef formatSt __ResetUDateFormat(formatter, true); // the "true" results in: if you set a custom format string, you don't get relative date formatting } - STACK_BUFFER_DECL(UChar, ubuffer, cnt); + SAFE_STACK_BUFFER_DECL(UChar, ubuffer, cnt, 256); const UChar *ustr = (UChar *)CFStringGetCharactersPtr((CFStringRef)formatString); if (NULL == ustr) { CFStringGetCharacters(formatString, CFRangeMake(0, cnt), (UniChar *)ubuffer); @@ -1373,6 +1379,7 @@ void CFDateFormatterSetFormat(CFDateFormatterRef formatter, CFStringRef formatSt formatter->_format = (CFStringRef)CFStringCreateCopy(CFGetAllocator(formatter), formatString); formatter->_property._HasCustomFormat = kCFBooleanTrue; } + SAFE_STACK_BUFFER_CLEANUP(ubuffer); } if (formatString) CFRelease(formatString); } @@ -1517,7 +1524,7 @@ static UDate __CFDateFormatterCorrectTimeToARangeAroundCurrentDate(UCalendar *ca } } else { if (period < INT_MAX && futureMax > period) { - futureRange.location = 1; + futureRange.location = 1, futureRange.length = futureMax - period; } if (pastMin <= 0) { diff --git a/CoreFoundation/Locale.subproj/CFDateFormatter.h b/CoreFoundation/Locale.subproj/CFDateFormatter.h index dc3942f7db..0b3b6624bb 100644 --- a/CoreFoundation/Locale.subproj/CFDateFormatter.h +++ b/CoreFoundation/Locale.subproj/CFDateFormatter.h @@ -1,7 +1,7 @@ /* CFDateFormatter.h - Copyright (c) 2003-2017, Apple Inc. and the Swift project authors + Copyright (c) 2003-2018, Apple Inc. and the Swift project authors - Portions Copyright (c) 2014-2017, Apple Inc. and the Swift project authors + Portions Copyright (c) 2014-2018, Apple Inc. and the Swift project authors Licensed under Apache License v2.0 with Runtime Library Exception See http://swift.org/LICENSE.txt for license information See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors diff --git a/CoreFoundation/Locale.subproj/CFDateFormatter_Private.h b/CoreFoundation/Locale.subproj/CFDateFormatter_Private.h index ae2a982734..5454c9cb96 100644 --- a/CoreFoundation/Locale.subproj/CFDateFormatter_Private.h +++ b/CoreFoundation/Locale.subproj/CFDateFormatter_Private.h @@ -1,7 +1,7 @@ /* CFDateFormatter_Private.h - Copyright (c) 2015-2017, Apple Inc. and the Swift project authors + Copyright (c) 2015-2018, Apple Inc. and the Swift project authors - Portions Copyright (c) 2014-2017, Apple Inc. and the Swift project authors + Portions Copyright (c) 2014-2018, Apple Inc. and the Swift project authors Licensed under Apache License v2.0 with Runtime Library Exception See http://swift.org/LICENSE.txt for license information See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors diff --git a/CoreFoundation/Locale.subproj/CFICULogging.h b/CoreFoundation/Locale.subproj/CFICULogging.h index fae3e29416..1b35f9ff42 100644 --- a/CoreFoundation/Locale.subproj/CFICULogging.h +++ b/CoreFoundation/Locale.subproj/CFICULogging.h @@ -1,8 +1,8 @@ /* CFICULogging.h - Copyright (c) 2008-2017, Apple Inc. and the Swift project authors + Copyright (c) 2008-2018, Apple Inc. and the Swift project authors - Portions Copyright (c) 2014-2017, Apple Inc. and the Swift project authors + Portions Copyright (c) 2014-2018, Apple Inc. and the Swift project authors Licensed under Apache License v2.0 with Runtime Library Exception See http://swift.org/LICENSE.txt for license information See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors @@ -22,6 +22,10 @@ #include #include +#if !DEPLOYMENT_RUNTIME_SWIFT && __has_include() +#include +#endif + // ucal diff --git a/CoreFoundation/Locale.subproj/CFLocale.c b/CoreFoundation/Locale.subproj/CFLocale.c index 78b072a8df..ec52965166 100644 --- a/CoreFoundation/Locale.subproj/CFLocale.c +++ b/CoreFoundation/Locale.subproj/CFLocale.c @@ -1,7 +1,7 @@ /* CFLocale.c - Copyright (c) 2002-2017, Apple Inc. and the Swift project authors + Copyright (c) 2002-2018, Apple Inc. and the Swift project authors - Portions Copyright (c) 2014-2017, Apple Inc. and the Swift project authors + Portions Copyright (c) 2014-2018, Apple Inc. and the Swift project authors Licensed under Apache License v2.0 with Runtime Library Exception See http://swift.org/LICENSE.txt for license information See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors @@ -10,7 +10,6 @@ // Note the header file is in the OpenSource set (stripped to almost nothing), but not the .c file -#include #include #include #include @@ -20,8 +19,10 @@ #include #include #include "CFInternal.h" +#include "CFRuntime_Internal.h" #include "CFBundle_Internal.h" #include "CFLocaleInternal.h" +#include #if DEPLOYMENT_TARGET_MACOSX || DEPLOYMENT_TARGET_EMBEDDED || DEPLOYMENT_TARGET_WINDOWS || DEPLOYMENT_TARGET_LINUX || DEPLOYMENT_TARGET_FREEBSD #include // ICU locales #include // ICU locale data @@ -35,6 +36,15 @@ #include #if U_ICU_VERSION_MAJOR_NUM > 53 && __has_include() #include + +extern int32_t +uameasfmt_getUnitsForUsage( const char* locale, + const char* category, + const char* usage, + UAMeasureUnit* units, + int32_t unitsCapacity, + UErrorCode* status ); + #endif #endif #include @@ -64,13 +74,13 @@ CF_PRIVATE CFCalendarRef _CFCalendarCreateCoWWithIdentifier(CFStringRef identifi CONST_STRING_DECL(kCFLocaleCurrentLocaleDidChangeNotification, "kCFLocaleCurrentLocaleDidChangeNotification") -static const char *kCalendarKeyword = "calendar"; -static const char *kCollationKeyword = "collation"; +static const char * const kCalendarKeyword = "calendar"; +static const char * const kCollationKeyword = "collation"; #define kMaxICUNameSize 1024 typedef struct __CFLocale *CFMutableLocaleRef; -PE_CONST_STRING_DECL(__kCFLocaleCollatorID, "locale:collator id") +CONST_STRING_DECL(__kCFLocaleCollatorID, "locale:collator id") enum { @@ -231,9 +241,7 @@ static void __CFLocaleDeallocate(CFTypeRef cf) { if (NULL != locale->_prefs) CFRelease(locale->_prefs); } -static CFTypeID __kCFLocaleTypeID = _kCFRuntimeNotATypeID; - -static const CFRuntimeClass __CFLocaleClass = { +const CFRuntimeClass __CFLocaleClass = { 0, "CFLocale", NULL, // init @@ -248,7 +256,6 @@ static const CFRuntimeClass __CFLocaleClass = { CFTypeID CFLocaleGetTypeID(void) { static dispatch_once_t initOnce; dispatch_once(&initOnce, ^{ - __kCFLocaleTypeID = _CFRuntimeRegisterClass(&__CFLocaleClass); // initOnce covered for (CFIndex idx = 0; idx < __kCFLocaleKeyTableCount; idx++) { // table fixup to workaround compiler/language limitations __CFLocaleKeyTable[idx].key = *((CFStringRef *)__CFLocaleKeyTable[idx].key); @@ -257,7 +264,7 @@ CFTypeID CFLocaleGetTypeID(void) { } } }); - return __kCFLocaleTypeID; + return _kCFRuntimeIDCFLocale; } CFLocaleRef CFLocaleGetSystem(void) { @@ -282,17 +289,12 @@ CFLocaleRef CFLocaleGetSystem(void) { return locale; } -extern CFDictionaryRef __CFXPreferencesCopyCurrentApplicationState(void); +extern CFDictionaryRef __CFXPreferencesCopyCurrentApplicationStateWithDeadlockAvoidance(Boolean * /* _Nonnull */outWouldDeadlock); static _Atomic(CFLocaleRef) _CFLocaleCurrent_ = NULL; CF_INLINE CFLocaleRef _cachedCurrentLocale() { -#if DEPLOYMENT_RUNTIME_SWIFT - CFLocaleRef loc = atomic_load_explicit(&_CFLocaleCurrent_, memory_order_relaxed); - return loc ? CFRetain(loc) : NULL; -#else return atomic_load_explicit(&_CFLocaleCurrent_, memory_order_relaxed); -#endif } static void _setCachedCurrentLocale(CFLocaleRef newLocale) { @@ -300,16 +302,11 @@ static void _setCachedCurrentLocale(CFLocaleRef newLocale) { } -#if DEPLOYMENT_TARGET_MACOSX -// Specify a default locale on Mac for Swift -#if DEPLOYMENT_RUNTIME_SWIFT -#define FALLBACK_LOCALE_NAME CFSTR("en_US") -#else +#if DEPLOYMENT_TARGET_MACOSX && !DEPLOYMENT_RUNTIME_SWIFT #define FALLBACK_LOCALE_NAME CFSTR("") -#endif /* DEPLOYMENT_RUNTIME_SWIFT */ #elif DEPLOYMENT_TARGET_EMBEDDED || DEPLOYMENT_TARGET_EMBEDDED_MINI #define FALLBACK_LOCALE_NAME CFSTR("en_US") -#elif DEPLOYMENT_TARGET_WINDOWS || DEPLOYMENT_TARGET_LINUX || DEPLOYMENT_TARGET_FREEBSD +#elif DEPLOYMENT_TARGET_WINDOWS || DEPLOYMENT_TARGET_LINUX || DEPLOYMENT_TARGET_FREEBSD || DEPLOYMENT_RUNTIME_SWIFT #define FALLBACK_LOCALE_NAME CFSTR("en_US") #endif @@ -543,11 +540,55 @@ CFStringRef _CFLocaleCreateLocaleIdentiferByReplacingLanguageCodeAndScriptCode(C #if DEPLOYMENT_TARGET_MACOSX || DEPLOYMENT_TARGET_EMBEDDED || DEPLOYMENT_TARGET_WINDOWS static CFArrayRef _CFLocaleCopyPreferredLanguagesFromPrefs(CFArrayRef languagesArray); + +/// Creates a new locale identifier by identifying the most preferred localization (using `availableLocalizations` and `preferredLanguages`) and then creating a locale based on the most preferred localization, while retaining any relevant attributes from `preferredLocaleID`, e.g. if `availableLocalizations` is `[ "en", "fr", "de" ]`, `preferredLanguages` is `[ "ar-AE", "en-AE" ]`, `preferredLocaleID` is `ar_AE@numbers=arab;calendar=islamic-civil`, it will return `en_AE@calendar=islamic-civil`, i.e. the language will be matched to `en` since that’s the only available localization that matches, `calendar` will be retained since it’s language-agnostic, but `numbers` will be discarded because the `arab` numbering system is not valid for `en`. +static CFStringRef _CFLocaleCreateLocaleIdentifierForAvailableLocalizations(CFArrayRef availableLocalizations, CFArrayRef preferredLanguages, CFStringRef preferredLocaleID) { + CFStringRef result = NULL; + if (availableLocalizations && CFArrayGetCount(availableLocalizations) > 0 && + preferredLanguages && CFArrayGetCount(preferredLanguages) > 0 && + preferredLocaleID && CFStringGetLength(preferredLocaleID) > 0) + { + CFArrayRef canonicalizedPreferredLanguages = _CFLocaleCopyPreferredLanguagesFromPrefs(preferredLanguages); + + // Combine `availableLocalizations` with `preferredLanguages` to get `preferredLocalizations`, whose #0 object indicates the localization that the app is current launched in. + CFArrayRef preferredLocalizations = NULL; { + // Since `availableLocalizations` can contains legacy lproj names such as `English`, `French`, etc. we need to canonicalize these into language identifiers such as `en`, `fr`, etc. Otherwise the logic that later compares these to language identifiers will fail. () + CFArrayRef canonicalizedAvailableLocalizations = _CFLocaleCopyPreferredLanguagesFromPrefs(availableLocalizations); + if (canonicalizedAvailableLocalizations) { + preferredLocalizations = CFBundleCopyLocalizationsForPreferences(canonicalizedAvailableLocalizations, canonicalizedPreferredLanguages); + CFRelease(canonicalizedAvailableLocalizations); + } + } + + if (preferredLocalizations && CFArrayGetCount(preferredLocalizations) > 0) { + // If we didn't find an overlap, we go with the preferred locale of the bundle. + CFStringRef preferredLocalization = CFArrayGetValueAtIndex(preferredLocalizations, 0); + if (preferredLocalization) { + // The goal here is to preserve all of the overrides present in the value stored in AppleLocale (e.g. "@calendar=buddhist") + CFStringRef preferredLocaleLanguageID = _CFLocaleCopyLanguageIdentifierWithScriptCodeForLocaleIdentifier(preferredLocaleID); + CFStringRef preferredLocalizationLanguageID = _CFLocaleCopyLanguageIdentifierWithScriptCodeForLocaleIdentifier(preferredLocalization); + if (preferredLocaleLanguageID && preferredLocalizationLanguageID) { + if (CFEqual(preferredLocaleLanguageID, preferredLocalizationLanguageID)) { + result = CFRetain(preferredLocaleID); + } else { + result = _CFLocaleCreateLocaleIdentiferByReplacingLanguageCodeAndScriptCode(preferredLocalization, preferredLocaleID); + } + } + if (preferredLocaleLanguageID) { CFRelease(preferredLocaleLanguageID); } + if (preferredLocalizationLanguageID) { CFRelease(preferredLocalizationLanguageID); } + } + + } + if (preferredLocalizations) { CFRelease(preferredLocalizations); } + if (canonicalizedPreferredLanguages) CFRelease(canonicalizedPreferredLanguages); + } + return result; +} #endif static CFLocaleRef _CFLocaleCopyCurrentGuts(CFStringRef name, Boolean useCache, CFDictionaryRef overridePrefs, Boolean disableBundleMatching) { /* - NOTE: calling any CFPreferences function, or any function which calls into a CFPreferences function, *except* for __CFXPreferencesCopyCurrentApplicationState, will deadlock. This is because in apps linked against older SDKs, this function is called from inside CFPreferences, with locks held, via CFPrefsCompatibilitySource. + NOTE: calling any CFPreferences function, or any function which calls into a CFPreferences function, *except* for __CFXPreferencesCopyCurrentApplicationStateWithDeadlockAvoidance (and accepting backstop values if its outparam is false), will deadlock. This is because CFPreferences calls os_log_*, which calls -descriptionWithLocale:, which calls CFLocaleCopyCurrent. */ CFStringRef ident = NULL; @@ -582,6 +623,10 @@ static CFLocaleRef _CFLocaleCopyCurrentGuts(CFStringRef name, Boolean useCache, CFRelease(ident); } if (cached) { +#if DEPLOYMENT_RUNTIME_SWIFT + CFRetain(cached); // In Swift, this object isn't immortal and needs to be correctly memory-managed. +#endif + return cached; } } @@ -596,11 +641,15 @@ static CFLocaleRef _CFLocaleCopyCurrentGuts(CFStringRef name, Boolean useCache, if (ident) CFRelease(ident); return NULL; } -#if !DEPLOYMENT_RUNTIME_SWIFT if (useCache) { - __CFRuntimeSetRC((CFTypeRef)locale, 0); //make immortal - } + // Make this object immortal: +#if !DEPLOYMENT_RUNTIME_SWIFT + __CFRuntimeSetRC((CFTypeRef)locale, 0); +#else + // Swift does not support immortal objects yet; add an unbalanced retain instead. + CFRetain((CFTypeRef)locale); #endif + } __CFLocaleSetType(locale, __kCFLocaleUser); if (NULL == ident) ident = (CFStringRef)CFRetain(FALLBACK_LOCALE_NAME); locale->_identifier = ident; @@ -1081,7 +1130,7 @@ _CFLocaleCalendarDirection _CFLocaleGetCalendarDirection(void) { #endif } -#if DEPLOYMENT_TARGET_MACOSX || DEPLOYMENT_TARGET_EMBEDDED || DEPLOYMENT_TARGET_WINDOWS || DEPLOYMENT_TARGET_LINUX +#if DEPLOYMENT_TARGET_MACOSX || DEPLOYMENT_TARGET_EMBEDDED || DEPLOYMENT_TARGET_WINDOWS static CFArrayRef _CFLocaleCopyPreferredLanguagesFromPrefs(CFArrayRef languagesArray) { CFMutableArrayRef newArray = CFArrayCreateMutable(kCFAllocatorSystemDefault, 0, &kCFTypeArrayCallBacks); if (languagesArray && (CFArrayGetTypeID() == CFGetTypeID(languagesArray))) { @@ -1101,7 +1150,7 @@ static CFArrayRef _CFLocaleCopyPreferredLanguagesFromPrefs(CFArrayRef languagesA #endif CFArrayRef CFLocaleCopyPreferredLanguages(void) { -#if DEPLOYMENT_TARGET_MACOSX || DEPLOYMENT_TARGET_EMBEDDED || DEPLOYMENT_TARGET_WINDOWS || DEPLOYMENT_TARGET_LINUX +#if DEPLOYMENT_TARGET_MACOSX || DEPLOYMENT_TARGET_EMBEDDED || DEPLOYMENT_TARGET_WINDOWS CFArrayRef languagesArray = (CFArrayRef)CFPreferencesCopyAppValue(CFSTR("AppleLanguages"), kCFPreferencesCurrentApplication); CFArrayRef result = _CFLocaleCopyPreferredLanguagesFromPrefs(languagesArray); if (languagesArray) CFRelease(languagesArray); @@ -1429,20 +1478,16 @@ static bool __CFLocaleCopyCollatorID(CFLocaleRef locale, bool user, CFTypeRef *c } #if DEPLOYMENT_TARGET_MACOSX || DEPLOYMENT_TARGET_EMBEDDED -static CONST_STRING_DECL(_metricUnitsKey, "AppleMetricUnits"); -static CONST_STRING_DECL(_measurementUnitsKey, "AppleMeasurementUnits"); -static CONST_STRING_DECL(_measurementUnitsCentimeters, "Centimeters"); -static CONST_STRING_DECL(_measurementUnitsInches, "Inches"); -static CONST_STRING_DECL(_temperatureUnitKey, "AppleTemperatureUnit"); +STATIC_CONST_STRING_DECL(_metricUnitsKey, "AppleMetricUnits"); +STATIC_CONST_STRING_DECL(_measurementUnitsKey, "AppleMeasurementUnits"); +STATIC_CONST_STRING_DECL(_measurementUnitsCentimeters, "Centimeters"); +STATIC_CONST_STRING_DECL(_measurementUnitsInches, "Inches"); +STATIC_CONST_STRING_DECL(_temperatureUnitKey, "AppleTemperatureUnit"); static bool __CFLocaleGetMeasurementSystemForPreferences(CFTypeRef metricPref, CFTypeRef measurementPref, UMeasurementSystem *outMeasurementSystem) { if (metricPref || measurementPref) { if (metricPref == kCFBooleanTrue && measurementPref && CFEqual(measurementPref, _measurementUnitsInches)) { -#if U_ICU_VERSION_MAJOR_NUM >= 55 *outMeasurementSystem = UMS_UK; -#else - return false; -#endif } else if (metricPref == kCFBooleanFalse) { *outMeasurementSystem = UMS_US; } else { @@ -1481,6 +1526,10 @@ static CFStringRef _CFLocaleGetTemperatureUnitName(bool celsius) { #endif #if DEPLOYMENT_TARGET_MACOSX || DEPLOYMENT_TARGET_EMBEDDED || DEPLOYMENT_TARGET_WINDOWS || DEPLOYMENT_TARGET_LINUX + +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wunguarded-availability-new" + static CFStringRef __CFLocaleGetMeasurementSystemName(UMeasurementSystem measurementSystem) { switch (measurementSystem) { case UMS_US: @@ -1505,15 +1554,16 @@ static bool __CFLocaleGetMeasurementSystemForName(CFStringRef name, UMeasuremen *outMeasurementSystem = UMS_US; return true; } -#if U_ICU_VERSION_MAJOR_NUM >= 55 if (CFEqual(name, kCFLocaleMeasurementSystemUK)) { *outMeasurementSystem = UMS_UK; return true; } -#endif } return false; } + +#pragma clang diagnostic pop + #endif #if DEPLOYMENT_TARGET_MACOSX || DEPLOYMENT_TARGET_EMBEDDED || DEPLOYMENT_TARGET_WINDOWS || DEPLOYMENT_TARGET_LINUX diff --git a/CoreFoundation/Locale.subproj/CFLocale.h b/CoreFoundation/Locale.subproj/CFLocale.h index a7d2139c5c..ff6acdf33e 100644 --- a/CoreFoundation/Locale.subproj/CFLocale.h +++ b/CoreFoundation/Locale.subproj/CFLocale.h @@ -1,7 +1,7 @@ /* CFLocale.h - Copyright (c) 2002-2017, Apple Inc. and the Swift project authors + Copyright (c) 2002-2018, Apple Inc. and the Swift project authors - Portions Copyright (c) 2014-2017, Apple Inc. and the Swift project authors + Portions Copyright (c) 2014-2018, Apple Inc. and the Swift project authors Licensed under Apache License v2.0 with Runtime Library Exception See http://swift.org/LICENSE.txt for license information See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors diff --git a/CoreFoundation/Locale.subproj/CFLocaleIdentifier.c b/CoreFoundation/Locale.subproj/CFLocaleIdentifier.c index ee41444d17..f97bd79294 100644 --- a/CoreFoundation/Locale.subproj/CFLocaleIdentifier.c +++ b/CoreFoundation/Locale.subproj/CFLocaleIdentifier.c @@ -1,8 +1,8 @@ /* CFLocaleIdentifier.c - Copyright (c) 2002-2017, Apple Inc. and the Swift project authors + Copyright (c) 2002-2018, Apple Inc. and the Swift project authors - Portions Copyright (c) 2014-2017, Apple Inc. and the Swift project authors + Portions Copyright (c) 2014-2018, Apple Inc. and the Swift project authors Licensed under Apache License v2.0 with Runtime Library Exception See http://swift.org/LICENSE.txt for license information See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors diff --git a/CoreFoundation/Locale.subproj/CFLocaleInternal.h b/CoreFoundation/Locale.subproj/CFLocaleInternal.h index ebeffe286c..ff4ccad0ba 100644 --- a/CoreFoundation/Locale.subproj/CFLocaleInternal.h +++ b/CoreFoundation/Locale.subproj/CFLocaleInternal.h @@ -1,8 +1,8 @@ /* CFLocaleInternal.h - Copyright (c) 2008-2017, Apple Inc. and the Swift project authors + Copyright (c) 2008-2018, Apple Inc. and the Swift project authors - Portions Copyright (c) 2014-2017, Apple Inc. and the Swift project authors + Portions Copyright (c) 2014-2018, Apple Inc. and the Swift project authors Licensed under Apache License v2.0 with Runtime Library Exception See http://swift.org/LICENSE.txt for license information See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors diff --git a/CoreFoundation/Locale.subproj/CFLocaleKeys.c b/CoreFoundation/Locale.subproj/CFLocaleKeys.c index d908c8cf2b..64a4a0b32b 100644 --- a/CoreFoundation/Locale.subproj/CFLocaleKeys.c +++ b/CoreFoundation/Locale.subproj/CFLocaleKeys.c @@ -1,7 +1,7 @@ /* CFLocaleKeys.c - Copyright (c) 2008-2017, Apple Inc. and the Swift project authors + Copyright (c) 2008-2018, Apple Inc. and the Swift project authors - Portions Copyright (c) 2014-2017, Apple Inc. and the Swift project authors + Portions Copyright (c) 2014-2018, Apple Inc. and the Swift project authors Licensed under Apache License v2.0 with Runtime Library Exception See http://swift.org/LICENSE.txt for license information See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors diff --git a/CoreFoundation/Locale.subproj/CFLocale_Private.h b/CoreFoundation/Locale.subproj/CFLocale_Private.h index d449665578..05139bf136 100644 --- a/CoreFoundation/Locale.subproj/CFLocale_Private.h +++ b/CoreFoundation/Locale.subproj/CFLocale_Private.h @@ -1,7 +1,7 @@ /* CFLocale_Private.h - Copyright (c) 2016-2017, Apple Inc. and the Swift project authors + Copyright (c) 2016-2018, Apple Inc. and the Swift project authors - Portions Copyright (c) 2014-2017, Apple Inc. and the Swift project authors + Portions Copyright (c) 2014-2018, Apple Inc. and the Swift project authors Licensed under Apache License v2.0 with Runtime Library Exception See http://swift.org/LICENSE.txt for license information See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors diff --git a/CoreFoundation/Locale.subproj/CFNumberFormatter.c b/CoreFoundation/Locale.subproj/CFNumberFormatter.c index 8076fbb9d0..5d459483f8 100644 --- a/CoreFoundation/Locale.subproj/CFNumberFormatter.c +++ b/CoreFoundation/Locale.subproj/CFNumberFormatter.c @@ -1,7 +1,7 @@ /* CFNumberFormatter.c - Copyright (c) 2002-2017, Apple Inc. and the Swift project authors + Copyright (c) 2002-2018, Apple Inc. and the Swift project authors - Portions Copyright (c) 2014-2017, Apple Inc. and the Swift project authors + Portions Copyright (c) 2014-2018, Apple Inc. and the Swift project authors Licensed under Apache License v2.0 with Runtime Library Exception See http://swift.org/LICENSE.txt for license information See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors @@ -12,6 +12,7 @@ #include #include #include "CFInternal.h" +#include "CFRuntime_Internal.h" #include "CFLocaleInternal.h" #include "CFICULogging.h" #include @@ -56,9 +57,7 @@ static void __CFNumberFormatterDeallocate(CFTypeRef cf) { if (formatter->_zeroSym) CFRelease(formatter->_zeroSym); } -static CFTypeID __kCFNumberFormatterTypeID = _kCFRuntimeNotATypeID; - -static const CFRuntimeClass __CFNumberFormatterClass = { +const CFRuntimeClass __CFNumberFormatterClass = { 0, "CFNumberFormatter", NULL, // init @@ -71,9 +70,7 @@ static const CFRuntimeClass __CFNumberFormatterClass = { }; CFTypeID CFNumberFormatterGetTypeID(void) { - static dispatch_once_t initOnce; - dispatch_once(&initOnce, ^{ __kCFNumberFormatterTypeID = _CFRuntimeRegisterClass(&__CFNumberFormatterClass); }); - return __kCFNumberFormatterTypeID; + return _kCFRuntimeIDCFNumberFormatter; } CFNumberFormatterRef CFNumberFormatterCreate(CFAllocatorRef allocator, CFLocaleRef locale, CFNumberFormatterStyle style) { diff --git a/CoreFoundation/Locale.subproj/CFNumberFormatter.h b/CoreFoundation/Locale.subproj/CFNumberFormatter.h index cca3177200..33520238ae 100644 --- a/CoreFoundation/Locale.subproj/CFNumberFormatter.h +++ b/CoreFoundation/Locale.subproj/CFNumberFormatter.h @@ -1,7 +1,7 @@ /* CFNumberFormatter.h - Copyright (c) 2003-2017, Apple Inc. and the Swift project authors + Copyright (c) 2003-2018, Apple Inc. and the Swift project authors - Portions Copyright (c) 2014-2017, Apple Inc. and the Swift project authors + Portions Copyright (c) 2014-2018, Apple Inc. and the Swift project authors Licensed under Apache License v2.0 with Runtime Library Exception See http://swift.org/LICENSE.txt for license information See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors diff --git a/CoreFoundation/NumberDate.subproj/CFBigNumber.c b/CoreFoundation/NumberDate.subproj/CFBigNumber.c index 453bbbb044..a515854d0e 100644 --- a/CoreFoundation/NumberDate.subproj/CFBigNumber.c +++ b/CoreFoundation/NumberDate.subproj/CFBigNumber.c @@ -1,7 +1,7 @@ /* CFBigNumber.c - Copyright (c) 2012-2017, Apple Inc. and the Swift project authors + Copyright (c) 2012-2018, Apple Inc. and the Swift project authors - Portions Copyright (c) 2014-2017, Apple Inc. and the Swift project authors + Portions Copyright (c) 2014-2018, Apple Inc. and the Swift project authors Licensed under Apache License v2.0 with Runtime Library Exception See http://swift.org/LICENSE.txt for license information See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors diff --git a/CoreFoundation/NumberDate.subproj/CFBigNumber.h b/CoreFoundation/NumberDate.subproj/CFBigNumber.h index 48c4d4dd93..751e478a24 100644 --- a/CoreFoundation/NumberDate.subproj/CFBigNumber.h +++ b/CoreFoundation/NumberDate.subproj/CFBigNumber.h @@ -1,7 +1,7 @@ /* CFBigNumber.h - Copyright (c) 2012-2017, Apple Inc. and the Swift project authors + Copyright (c) 2012-2018, Apple Inc. and the Swift project authors - Portions Copyright (c) 2014-2017, Apple Inc. and the Swift project authors + Portions Copyright (c) 2014-2018, Apple Inc. and the Swift project authors Licensed under Apache License v2.0 with Runtime Library Exception See http://swift.org/LICENSE.txt for license information See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors diff --git a/CoreFoundation/NumberDate.subproj/CFDate.c b/CoreFoundation/NumberDate.subproj/CFDate.c index 823e8f7b02..94588c2180 100644 --- a/CoreFoundation/NumberDate.subproj/CFDate.c +++ b/CoreFoundation/NumberDate.subproj/CFDate.c @@ -1,7 +1,7 @@ /* CFDate.c - Copyright (c) 1998-2017, Apple Inc. and the Swift project authors + Copyright (c) 1998-2018, Apple Inc. and the Swift project authors - Portions Copyright (c) 2014-2017, Apple Inc. and the Swift project authors + Portions Copyright (c) 2014-2018, Apple Inc. and the Swift project authors Licensed under Apache License v2.0 with Runtime Library Exception See http://swift.org/LICENSE.txt for license information See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors @@ -15,6 +15,7 @@ #include #include #include "CFInternal.h" +#include "CFRuntime_Internal.h" #include #if __HAS_DISPATCH__ @@ -40,7 +41,8 @@ const CFTimeInterval kCFAbsoluteTimeIntervalSince1970 = 978307200.0L; const CFTimeInterval kCFAbsoluteTimeIntervalSince1904 = 3061152000.0L; -CF_PRIVATE double __CFTSRRate = 0.0; +CF_PRIVATE double __CFTSRRate; +double __CFTSRRate = 0.0; static double __CF1_TSRRate = 0.0; CF_PRIVATE uint64_t __CFTimeIntervalToTSR(CFTimeInterval ti) { @@ -130,9 +132,7 @@ static CFStringRef __CFDateCopyDescription(CFTypeRef cf) { return CFStringCreateWithFormat(CFGetAllocator(date), NULL, CFSTR("{time = %0.09g}"), cf, CFGetAllocator(date), date->_time); } -static CFTypeID __kCFDateTypeID = _kCFRuntimeNotATypeID; - -static const CFRuntimeClass __CFDateClass = { +const CFRuntimeClass __CFDateClass = { 0, "CFDate", NULL, // init @@ -144,11 +144,7 @@ static const CFRuntimeClass __CFDateClass = { __CFDateCopyDescription }; -CFTypeID CFDateGetTypeID(void) { - static dispatch_once_t initOnce; - dispatch_once(&initOnce, ^{ - __kCFDateTypeID = _CFRuntimeRegisterClass(&__CFDateClass); - +CF_PRIVATE void __CFDateInitialize(void) { #if DEPLOYMENT_TARGET_MACOSX || DEPLOYMENT_TARGET_EMBEDDED || DEPLOYMENT_TARGET_EMBEDDED_MINI struct mach_timebase_info info; mach_timebase_info(&info); @@ -171,8 +167,10 @@ CFTypeID CFDateGetTypeID(void) { #else #error Unable to initialize date #endif - }); - return __kCFDateTypeID; +} + +CFTypeID CFDateGetTypeID(void) { + return _kCFRuntimeIDCFDate; } CFDateRef CFDateCreate(CFAllocatorRef allocator, CFAbsoluteTime at) { @@ -225,7 +223,7 @@ CF_INLINE double __CFDoubleMod(double d, int32_t modulus) { #define INVALID_MONTH_RESULT (0xffff) #define CHECK_BOUNDS(month, array) ((month) >= 0 && (month) < (sizeof(array) / sizeof(*(array)))) -#define ASSERT_VALID_MONTH(month) do { if (!((month) >= 1 && (month) <= 12)) { os_log_error(OS_LOG_DEFAULT, "Month %d is out of bounds", (int)month); /* HALT */ } } while(0) +#define ASSERT_VALID_MONTH(month) do { if (!((month) >= 1 && (month) <= 12)) { /* os_log_error(OS_LOG_DEFAULT, "Month %d is out of bounds", (int)month); HALT */ } } while(0) static const uint8_t daysInMonth[16] = {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31, 0, 0, 0}; static const uint16_t daysBeforeMonth[16] = {INVALID_MONTH_RESULT, 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365, INVALID_MONTH_RESULT, INVALID_MONTH_RESULT}; diff --git a/CoreFoundation/NumberDate.subproj/CFDate.h b/CoreFoundation/NumberDate.subproj/CFDate.h index ba303b65e6..07a33c580a 100644 --- a/CoreFoundation/NumberDate.subproj/CFDate.h +++ b/CoreFoundation/NumberDate.subproj/CFDate.h @@ -1,7 +1,7 @@ /* CFDate.h - Copyright (c) 1998-2017, Apple Inc. and the Swift project authors + Copyright (c) 1998-2018, Apple Inc. and the Swift project authors - Portions Copyright (c) 2014-2017, Apple Inc. and the Swift project authors + Portions Copyright (c) 2014-2018, Apple Inc. and the Swift project authors Licensed under Apache License v2.0 with Runtime Library Exception See http://swift.org/LICENSE.txt for license information See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors diff --git a/CoreFoundation/NumberDate.subproj/CFNumber.c b/CoreFoundation/NumberDate.subproj/CFNumber.c index 6c542da8a7..6a9bde1e19 100644 --- a/CoreFoundation/NumberDate.subproj/CFNumber.c +++ b/CoreFoundation/NumberDate.subproj/CFNumber.c @@ -1,7 +1,7 @@ /* CFNumber.c - Copyright (c) 1999-2017, Apple Inc. and the Swift project authors + Copyright (c) 1999-2018, Apple Inc. and the Swift project authors - Portions Copyright (c) 2014-2017, Apple Inc. and the Swift project authors + Portions Copyright (c) 2014-2018, Apple Inc. and the Swift project authors Licensed under Apache License v2.0 with Runtime Library Exception See http://swift.org/LICENSE.txt for license information See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors @@ -10,6 +10,7 @@ #include #include "CFInternal.h" +#include "CFRuntime_Internal.h" #include #include #include @@ -85,13 +86,15 @@ struct __CFBoolean { CFRuntimeBase _base; }; -static struct __CFBoolean __kCFBooleanTrue = { - INIT_CFRUNTIME_BASE() +DECLARE_STATIC_CLASS_REF(__NSCFBoolean); + +static _CF_CONSTANT_OBJECT_BACKING struct __CFBoolean __kCFBooleanTrue = { + INIT_CFRUNTIME_BASE_WITH_CLASS(__NSCFBoolean, _kCFRuntimeIDCFBoolean) }; const CFBooleanRef kCFBooleanTrue = &__kCFBooleanTrue; -static struct __CFBoolean __kCFBooleanFalse = { - INIT_CFRUNTIME_BASE() +static _CF_CONSTANT_OBJECT_BACKING struct __CFBoolean __kCFBooleanFalse = { + INIT_CFRUNTIME_BASE_WITH_CLASS(__NSCFBoolean, _kCFRuntimeIDCFBoolean) }; const CFBooleanRef kCFBooleanFalse = &__kCFBooleanFalse; @@ -114,9 +117,7 @@ static void __CFBooleanDeallocate(CFTypeRef cf) { CFAssert(false, __kCFLogAssertion, "Deallocated CFBoolean!"); } -static CFTypeID __kCFBooleanTypeID = _kCFRuntimeNotATypeID; - -static const CFRuntimeClass __CFBooleanClass = { +const CFRuntimeClass __CFBooleanClass = { 0, "CFBoolean", NULL, // init @@ -129,13 +130,7 @@ static const CFRuntimeClass __CFBooleanClass = { }; CFTypeID CFBooleanGetTypeID(void) { - static dispatch_once_t initOnce; - dispatch_once(&initOnce, ^{ - __kCFBooleanTypeID = _CFRuntimeRegisterClass(&__CFBooleanClass); // initOnce covered - _CFRuntimeSetInstanceTypeIDAndIsa(&__kCFBooleanTrue, __kCFBooleanTypeID); - _CFRuntimeSetInstanceTypeIDAndIsa(&__kCFBooleanFalse, __kCFBooleanTypeID); - }); - return __kCFBooleanTypeID; + return _kCFRuntimeIDCFBoolean; } Boolean CFBooleanGetValue(CFBooleanRef boolean) { @@ -169,6 +164,11 @@ typedef union { int64_t bits; } Float64Bits; +typedef union { + Float32Bits _32; + Float64Bits _64; +} FloatBits; + static const Float32Bits floatZeroBits = {.floatValue = 0.0f}; static const Float32Bits floatOneBits = {.floatValue = 1.0f}; @@ -380,7 +380,7 @@ static void cvtFloat64ToSInt128(CFSInt128Struct *out, const Float64 *in) { struct __CFNumber { CFRuntimeBase _base; - uint64_t _pad; // need this space here for the constant objects + FloatBits _bits; // need this space here for the constant objects /* 0 or 8 more bytes allocated here */ }; @@ -389,39 +389,48 @@ struct __CFNumber { Bits 4..0: CFNumber type */ +DECLARE_STATIC_CLASS_REF(__NSCFNumber); + // Note: The isa for these things is fixed up later -static struct __CFNumber __kCFNumberNaN = { - INIT_CFRUNTIME_BASE(), 0ULL +static _CF_CONSTANT_OBJECT_BACKING struct __CFNumber __kCFNumberNaN = { + INIT_CFRUNTIME_BASE_WITH_CLASS_AND_FLAGS(__NSCFNumber, _kCFRuntimeIDCFNumber, kCFNumberFloat64CanonicalTypeIndex), + { ._64.bits = BITSFORDOUBLENAN } }; const CFNumberRef kCFNumberNaN = &__kCFNumberNaN; -static struct __CFNumber __kCFNumberNegativeInfinity = { - INIT_CFRUNTIME_BASE(), 0ULL +static _CF_CONSTANT_OBJECT_BACKING struct __CFNumber __kCFNumberNegativeInfinity = { + INIT_CFRUNTIME_BASE_WITH_CLASS_AND_FLAGS(__NSCFNumber, _kCFRuntimeIDCFNumber, kCFNumberFloat64CanonicalTypeIndex), + { ._64.bits = BITSFORDOUBLENEGINF } }; const CFNumberRef kCFNumberNegativeInfinity = &__kCFNumberNegativeInfinity; -static struct __CFNumber __kCFNumberPositiveInfinity = { - INIT_CFRUNTIME_BASE(), 0ULL +static _CF_CONSTANT_OBJECT_BACKING struct __CFNumber __kCFNumberPositiveInfinity = { + INIT_CFRUNTIME_BASE_WITH_CLASS_AND_FLAGS(__NSCFNumber, _kCFRuntimeIDCFNumber, kCFNumberFloat64CanonicalTypeIndex), + { ._64.bits = BITSFORDOUBLEPOSINF } }; const CFNumberRef kCFNumberPositiveInfinity = &__kCFNumberPositiveInfinity; -static struct __CFNumber __kCFNumberFloat32Zero = { - INIT_CFRUNTIME_BASE(), 0ULL +static _CF_CONSTANT_OBJECT_BACKING struct __CFNumber __kCFNumberFloat32Zero = { + INIT_CFRUNTIME_BASE_WITH_CLASS_AND_FLAGS(__NSCFNumber, _kCFRuntimeIDCFNumber, kCFNumberFloat32CanonicalTypeIndex), + { ._32.floatValue = 0.0f } }; static const CFNumberRef kCFNumberFloat32Zero = &__kCFNumberFloat32Zero; -static struct __CFNumber __kCFNumberFloat32One = { - INIT_CFRUNTIME_BASE(), 0ULL +static _CF_CONSTANT_OBJECT_BACKING struct __CFNumber __kCFNumberFloat32One = { + INIT_CFRUNTIME_BASE_WITH_CLASS_AND_FLAGS(__NSCFNumber, _kCFRuntimeIDCFNumber, kCFNumberFloat32CanonicalTypeIndex), + { ._32.floatValue = 1.0f } }; static const CFNumberRef kCFNumberFloat32One = &__kCFNumberFloat32One; -static struct __CFNumber __kCFNumberFloat64Zero = { - INIT_CFRUNTIME_BASE(), 0ULL +static _CF_CONSTANT_OBJECT_BACKING struct __CFNumber __kCFNumberFloat64Zero = { + INIT_CFRUNTIME_BASE_WITH_CLASS_AND_FLAGS(__NSCFNumber, _kCFRuntimeIDCFNumber, kCFNumberFloat64CanonicalTypeIndex), + { ._64.floatValue = 0.0f } }; static const CFNumberRef kCFNumberFloat64Zero = &__kCFNumberFloat64Zero; -static struct __CFNumber __kCFNumberFloat64One = { - INIT_CFRUNTIME_BASE(), 0ULL +static _CF_CONSTANT_OBJECT_BACKING struct __CFNumber __kCFNumberFloat64One = { + INIT_CFRUNTIME_BASE_WITH_CLASS_AND_FLAGS(__NSCFNumber, _kCFRuntimeIDCFNumber, kCFNumberFloat64CanonicalTypeIndex), + { ._64.floatValue = 1.0f } }; static const CFNumberRef kCFNumberFloat64One = &__kCFNumberFloat64One; @@ -497,7 +506,7 @@ CF_INLINE CFNumberType __CFNumberGetType(CFNumberRef num) { static Boolean __CFNumberGetValue(CFNumberRef number, CFNumberType type, void *valuePtr) { type = __CFNumberTypeTable[type].canonicalType; CFNumberType ntype = __CFNumberGetType(number); - const void *data = &(number->_pad); + const void *data = &(number->_bits._64.bits); Boolean floatBit = __CFNumberTypeTable[ntype].floatBit; Boolean storageBit = __CFNumberTypeTable[ntype].storageBit; switch (type) { @@ -689,7 +698,7 @@ static Boolean __CFNumberGetValue(CFNumberRef number, CFNumberType type, void *v static Boolean __CFNumberGetValueCompat(CFNumberRef number, CFNumberType type, void *valuePtr) { type = __CFNumberTypeTable[type].canonicalType; CFNumberType ntype = __CFNumberGetType(number); - const void *data = &(number->_pad); + const void *data = &(number->_bits._64.bits); switch (type) { case kCFNumberSInt8Type: if (__CFNumberTypeTable[ntype].floatBit) { @@ -970,7 +979,6 @@ static CFHashCode __CFNumberHash(CFTypeRef cf) { return h; } -static CFTypeID __kCFNumberTypeID = _kCFRuntimeNotATypeID; enum { kCFNumberCachingEnabled = 0, @@ -979,7 +987,7 @@ enum { }; static char __CFNumberCaching = kCFNumberCachingEnabled; -static const CFRuntimeClass __CFNumberClass = { +const CFRuntimeClass __CFNumberClass = { 0, "CFNumber", NULL, // init @@ -992,56 +1000,16 @@ static const CFRuntimeClass __CFNumberClass = { }; -CF_PRIVATE void __CFNumberInitialize(void) { - _CFRuntimeSetInstanceTypeIDAndIsa(&__kCFNumberNaN, __kCFNumberTypeID); - __CFRuntimeSetNumberType(&__kCFNumberNaN, kCFNumberFloat64Type); - __kCFNumberNaN._pad = BITSFORDOUBLENAN; - - _CFRuntimeSetInstanceTypeIDAndIsa(& __kCFNumberNegativeInfinity, __kCFNumberTypeID); - __CFRuntimeSetNumberType(&__kCFNumberNegativeInfinity, kCFNumberFloat64Type); - __kCFNumberNegativeInfinity._pad = BITSFORDOUBLENEGINF; - - _CFRuntimeSetInstanceTypeIDAndIsa(& __kCFNumberPositiveInfinity, __kCFNumberTypeID); - __CFRuntimeSetNumberType(&__kCFNumberPositiveInfinity, kCFNumberFloat64Type); - __kCFNumberPositiveInfinity._pad = BITSFORDOUBLEPOSINF; - - _CFRuntimeSetInstanceTypeIDAndIsa(& __kCFNumberFloat32Zero, __kCFNumberTypeID); - __CFRuntimeSetNumberType(&__kCFNumberFloat32Zero, kCFNumberFloat32Type); - __kCFNumberFloat32Zero._pad = BITSFORFLOATZERO; - - _CFRuntimeSetInstanceTypeIDAndIsa(& __kCFNumberFloat32One, __kCFNumberTypeID); - __CFRuntimeSetNumberType(&__kCFNumberFloat32One, kCFNumberFloat32Type); - __kCFNumberFloat32One._pad = BITSFORFLOATONE; -#if __BIG_ENDIAN__ - __kCFNumberFloat32One._pad = __kCFNumberFloat32One._pad << 32; -#endif - - _CFRuntimeSetInstanceTypeIDAndIsa(& __kCFNumberFloat64Zero, __kCFNumberTypeID); - __CFRuntimeSetNumberType(&__kCFNumberFloat64Zero, kCFNumberFloat64Type); - __kCFNumberFloat64Zero._pad = BITSFORDOUBLEZERO; - - _CFRuntimeSetInstanceTypeIDAndIsa(& __kCFNumberFloat64One, __kCFNumberTypeID); - __CFRuntimeSetNumberType(&__kCFNumberFloat64One, kCFNumberFloat64Type); - __kCFNumberFloat64One._pad = BITSFORDOUBLEONE; -#if DEPLOYMENT_RUNTIME_SWIFT - _CFRuntimeSetInstanceTypeIDAndIsa(&__kCFBooleanTrue, __kCFBooleanTypeID); - _CFRuntimeSetInstanceTypeIDAndIsa(&__kCFBooleanFalse, __kCFBooleanTypeID); -#endif -} - CFTypeID CFNumberGetTypeID(void) { + // TODO: Move other work out of here static dispatch_once_t initOnce; dispatch_once(&initOnce, ^{ - __kCFNumberTypeID = _CFRuntimeRegisterClass(&__CFNumberClass); // initOnce covered -#if !DEPLOYMENT_RUNTIME_SWIFT - __CFNumberInitialize(); -#endif const char *caching = __CFgetenv("CFNumberDisableCache"); // "all" to disable caching and tagging; anything else to disable caching; nothing to leave both enabled if (caching) __CFNumberCaching = (!strcmp(caching, "all")) ? kCFNumberCachingFullyDisabled : kCFNumberCachingDisabled; // initial state above is kCFNumberCachingEnabled }); - return __kCFNumberTypeID; + return _kCFRuntimeIDCFNumber; } #define MinCachedInt (-1) @@ -1057,11 +1025,11 @@ static inline void __CFNumberInit(CFNumberRef result, CFNumberType type, const v case kCFNumberSInt8Type: value = (uint64_t)(int64_t)*(int8_t *)valuePtr; goto smallVal; case kCFNumberSInt16Type: value = (uint64_t)(int64_t)*(int16_t *)valuePtr; goto smallVal; case kCFNumberSInt32Type: value = (uint64_t)(int64_t)*(int32_t *)valuePtr; goto smallVal; - smallVal: memmove((void *)&result->_pad, &value, 8); break; - case kCFNumberSInt64Type: memmove((void *)&result->_pad, valuePtr, 8); break; - case kCFNumberSInt128Type: memmove((void *)&result->_pad, valuePtr, 16); break; - case kCFNumberFloat32Type: memmove((void *)&result->_pad, valuePtr, 4); break; - case kCFNumberFloat64Type: memmove((void *)&result->_pad, valuePtr, 8); break; + smallVal: memmove((void *)&result->_bits._64.bits, &value, 8); break; + case kCFNumberSInt64Type: memmove((void *)&result->_bits._64.bits, valuePtr, 8); break; + case kCFNumberSInt128Type: memmove((void *)&result->_bits._64.bits, valuePtr, 16); break; + case kCFNumberFloat32Type: memmove((void *)&result->_bits._64.bits, valuePtr, 4); break; + case kCFNumberFloat64Type: memmove((void *)&result->_bits._64.bits, valuePtr, 8); break; } } @@ -1180,7 +1148,7 @@ static CFNumberRef _CFNumberCreate(CFAllocatorRef allocator, CFNumberType type, // for a value to be cached, we already have the value handy if (NotToBeCached != valToBeCached) { - memmove((void *)&result->_pad, &valToBeCached, 8); + memmove((void *)&result->_bits._64.bits, &valToBeCached, 8); // Put this in the cache unless the cache is already filled (by another thread). If we do put it in the cache, retain it an extra time for the cache. // Note that we don't bother freeing this result and returning the cached value if the cache was filled, since cached CFNumbers are not guaranteed unique. // Barrier assures that the number that is placed in the cache is properly formed. diff --git a/CoreFoundation/NumberDate.subproj/CFNumber.h b/CoreFoundation/NumberDate.subproj/CFNumber.h index 95f7756209..1a77a0d8e1 100644 --- a/CoreFoundation/NumberDate.subproj/CFNumber.h +++ b/CoreFoundation/NumberDate.subproj/CFNumber.h @@ -1,7 +1,7 @@ /* CFNumber.h - Copyright (c) 1999-2017, Apple Inc. and the Swift project authors + Copyright (c) 1999-2018, Apple Inc. and the Swift project authors - Portions Copyright (c) 2014-2017, Apple Inc. and the Swift project authors + Portions Copyright (c) 2014-2018, Apple Inc. and the Swift project authors Licensed under Apache License v2.0 with Runtime Library Exception See http://swift.org/LICENSE.txt for license information See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors diff --git a/CoreFoundation/NumberDate.subproj/CFTimeZone.c b/CoreFoundation/NumberDate.subproj/CFTimeZone.c index 57ebeb6274..68b1953b18 100644 --- a/CoreFoundation/NumberDate.subproj/CFTimeZone.c +++ b/CoreFoundation/NumberDate.subproj/CFTimeZone.c @@ -1,7 +1,7 @@ /* CFTimeZone.c - Copyright (c) 1998-2017, Apple Inc. and the Swift project authors + Copyright (c) 1998-2018, Apple Inc. and the Swift project authors - Portions Copyright (c) 2014-2017, Apple Inc. and the Swift project authors + Portions Copyright (c) 2014-2018, Apple Inc. and the Swift project authors Licensed under Apache License v2.0 with Runtime Library Exception See http://swift.org/LICENSE.txt for license information See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors @@ -14,6 +14,7 @@ #include #include #include "CFInternal.h" +#include "CFRuntime_Internal.h" #include #include #include @@ -33,12 +34,9 @@ #endif #if DEPLOYMENT_TARGET_MACOSX || DEPLOYMENT_TARGET_EMBEDDED #include -#define MACOS_TZDIR1 "/usr/share/zoneinfo/" // 10.12 and earlier -#define MACOS_TZDIR2 "/var/db/timezone/zoneinfo/" // 10.13 onwards - #elif DEPLOYMENT_TARGET_LINUX || DEPLOYMENT_TARGET_FREEBSD #ifndef TZDIR -#define TZDIR "/usr/share/zoneinfo/" /* Time zone object file directory */ +#define TZDIR "/usr/share/zoneinfo" /* Time zone object file directory */ #endif /* !defined TZDIR */ #ifndef TZDEFAULT @@ -59,9 +57,16 @@ struct tzhead { #include +#if DEPLOYMENT_TARGET_MACOSX || DEPLOYMENT_TARGET_EMBEDDED || DEPLOYMENT_TARGET_LINUX || DEPLOYMENT_TARGET_FREEBSD +#define TZZONELINK TZDEFAULT +#define TZZONEINFO TZDIR "/" +#elif DEPLOYMENT_TARGET_WINDOWS static CFStringRef __tzZoneInfo = NULL; static char *__tzDir = NULL; static void __InitTZStrings(void); +#else +#error Unknown or unspecified DEPLOYMENT_TARGET +#endif CONST_STRING_DECL(kCFTimeZoneSystemTimeZoneDidChangeNotification, "kCFTimeZoneSystemTimeZoneDidChangeNotification") @@ -143,9 +148,13 @@ static CFMutableArrayRef __CFCopyWindowsTimeZoneList() { #elif DEPLOYMENT_TARGET_MACOSX || DEPLOYMENT_TARGET_EMBEDDED || DEPLOYMENT_TARGET_WINDOWS || DEPLOYMENT_TARGET_LINUX || DEPLOYMENT_TARGET_FREEBSD static CFMutableArrayRef __CFCopyRecursiveDirectoryList() { CFMutableArrayRef result = CFArrayCreateMutable(kCFAllocatorSystemDefault, 0, &kCFTypeArrayCallBacks); +#if DEPLOYMENT_TARGET_WINDOWS if (!__tzDir) __InitTZStrings(); if (!__tzDir) return result; int fd = open(__tzDir, O_RDONLY); +#else + int fd = open(TZDIR "/zone.tab", O_RDONLY); +#endif for (; 0 <= fd;) { uint8_t buffer[4096]; @@ -440,9 +449,7 @@ static void __CFTimeZoneDeallocate(CFTypeRef cf) { if (NULL != tz->_periods) CFAllocatorDeallocate(allocator, tz->_periods); } -static CFTypeID __kCFTimeZoneTypeID = _kCFRuntimeNotATypeID; - -static const CFRuntimeClass __CFTimeZoneClass = { +const CFRuntimeClass __CFTimeZoneClass = { 0, "CFTimeZone", NULL, // init @@ -455,9 +462,7 @@ static const CFRuntimeClass __CFTimeZoneClass = { }; CFTypeID CFTimeZoneGetTypeID(void) { - static dispatch_once_t initOnce; - dispatch_once(&initOnce, ^{ __kCFTimeZoneTypeID = _CFRuntimeRegisterClass(&__CFTimeZoneClass); }); - return __kCFTimeZoneTypeID; + return _kCFRuntimeIDCFTimeZone; } #if DEPLOYMENT_TARGET_WINDOWS @@ -696,50 +701,6 @@ static void __InitTZStrings(void) { } __CFUnlock(&__CFTZDirLock); } - -#elif DEPLOYMENT_TARGET_MACOSX || DEPLOYMENT_TARGET_EMBEDDED -static void __InitTZStrings(void) { - static dispatch_once_t initOnce = 0; - - dispatch_once(&initOnce, ^{ - unsigned int major = 0, minor = 0, patch = 0; - - CFDictionaryRef dict = _CFCopySystemVersionDictionary(); - if (dict) { - CFStringRef version = CFDictionaryGetValue(dict, _kCFSystemVersionProductVersionKey); - if (version) { - const char *cStr = CFStringGetCStringPtr(version, kCFStringEncodingASCII); - if (cStr) { - if (sscanf(cStr, "%u.%u.%u", &major, &minor, &patch) != 3) { - major = 0; - minor = 0; - patch = 0; - } - } - } - CFRelease(dict); - } - - // Timezone files moved in High Sierra(10.13) - if (major == 10 && minor < 13) { - // older versions - __tzZoneInfo = CFSTR(MACOS_TZDIR1); - __tzDir = MACOS_TZDIR1 "zone.tab"; - } else { - __tzZoneInfo = CFSTR(MACOS_TZDIR2); - __tzDir = MACOS_TZDIR2 "zone.tab"; - } - }); -} - -#elif DEPLOYMENT_TARGET_LINUX || DEPLOYMENT_TARGET_FREEBSD -static void __InitTZStrings(void) { - __tzZoneInfo = CFSTR(TZDIR); - __tzDir = TZDIR "zone.tab"; -} - -#else -#error Unknown or unspecified DEPLOYMENT_TARGET #endif static CFTimeZoneRef __CFTimeZoneCreateSystem(void) { @@ -784,16 +745,11 @@ static CFTimeZoneRef __CFTimeZoneCreateSystem(void) { CFRelease(name); if (result) return result; } - - if (!__tzZoneInfo) __InitTZStrings(); - ret = readlink(TZDEFAULT, linkbuf, sizeof(linkbuf)); - if (__tzZoneInfo && (0 < ret)) { + ret = readlink(TZZONELINK, linkbuf, sizeof(linkbuf)); + if (0 < ret) { linkbuf[ret] = '\0'; - const char *tzZoneInfo = CFStringGetCStringPtr(__tzZoneInfo, kCFStringEncodingASCII); - size_t zoneInfoDirLen = CFStringGetLength(__tzZoneInfo); - if (strncmp(linkbuf, tzZoneInfo, zoneInfoDirLen) == 0) { - name = CFStringCreateWithBytes(kCFAllocatorSystemDefault, (uint8_t *)linkbuf + zoneInfoDirLen, - strlen(linkbuf) - zoneInfoDirLen + 1, kCFStringEncodingUTF8, false); + if (strncmp(linkbuf, TZZONEINFO, sizeof(TZZONEINFO) - 1) == 0) { + name = CFStringCreateWithBytes(kCFAllocatorSystemDefault, (uint8_t *)linkbuf + sizeof(TZZONEINFO) - 1, strlen(linkbuf) - sizeof(TZZONEINFO) + 1, kCFStringEncodingUTF8, false); } else { name = CFStringCreateWithBytes(kCFAllocatorSystemDefault, (uint8_t *)linkbuf, strlen(linkbuf), kCFStringEncodingUTF8, false); } @@ -813,15 +769,6 @@ static CFTimeZoneRef __CFTimeZoneCreateSystem(void) { CFRelease(name); if (result) return result; } -#if DEPLOYMENT_TARGET_ANDROID - // Timezone database by name not available on Android. - // Approximate with gmtoff - could be general default. - struct tm info; - time_t now = time(NULL); - if (NULL != localtime_r(&now, &info)) { - return CFTimeZoneCreateWithTimeIntervalFromGMT(kCFAllocatorSystemDefault, info.tm_gmtoff); - } -#endif return CFTimeZoneCreateWithTimeIntervalFromGMT(kCFAllocatorSystemDefault, 0.0); } @@ -891,7 +838,6 @@ void CFTimeZoneSetDefault(CFTimeZoneRef tz) { } static CFDictionaryRef __CFTimeZoneCopyCompatibilityDictionary(void); -static Boolean __nameStringOK(CFStringRef name); CFArrayRef CFTimeZoneCopyKnownNames(void) { CFArrayRef tzs; @@ -907,7 +853,7 @@ CFArrayRef CFTimeZoneCopyKnownNames(void) { CFIndex idx; for (idx = CFArrayGetCount(list); idx--; ) { CFStringRef item = (CFStringRef)CFArrayGetValueAtIndex(list, idx); - if (CFDictionaryContainsKey(dict, item) || !__nameStringOK(item)) { + if (CFDictionaryContainsKey(dict, item)) { CFArrayRemoveValueAtIndex(list, idx); } } @@ -1013,6 +959,8 @@ void CFTimeZoneSetAbbreviationDictionary(CFDictionaryRef dict) { __CFTimeZoneUnlockGlobal(); } +#if DEPLOYMENT_RUNTIME_SWIFT + CF_INLINE const UChar *STRING_to_UTF16(CFStringRef S) { // UTF16String CFIndex length = CFStringGetLength((CFStringRef)S); UChar *buffer = (UChar *)malloc((length + 1) * sizeof(UChar)); @@ -1182,12 +1130,12 @@ Boolean _CFTimeZoneInit(CFTimeZoneRef timeZone, CFStringRef name, CFDataRef data CFIndex length; Boolean result = false; +#if DEPLOYMENT_TARGET_WINDOWS if (!__tzZoneInfo) __InitTZStrings(); if (!__tzZoneInfo) return NULL; -#if DEPLOYMENT_TARGET_WINDOWS baseURL = CFURLCreateWithFileSystemPath(kCFAllocatorSystemDefault, __tzZoneInfo, kCFURLWindowsPathStyle, true); #else - baseURL = CFURLCreateWithFileSystemPath(kCFAllocatorSystemDefault, __tzZoneInfo, kCFURLPOSIXPathStyle, true); + baseURL = CFURLCreateWithFileSystemPath(kCFAllocatorSystemDefault, CFSTR(TZZONEINFO), kCFURLPOSIXPathStyle, true); #endif if (tryAbbrev) { CFDictionaryRef abbrevs = CFTimeZoneCopyAbbreviationDictionary(); @@ -1208,9 +1156,15 @@ Boolean _CFTimeZoneInit(CFTimeZoneRef timeZone, CFStringRef name, CFDataRef data CFStringRef mapping = CFDictionaryGetValue(dict, name); if (mapping) { name = mapping; +#if DEPLOYMENT_TARGET_WINDOWS } else if (CFStringHasPrefix(name, __tzZoneInfo)) { CFMutableStringRef unprefixed = CFStringCreateMutableCopy(kCFAllocatorSystemDefault, CFStringGetLength(name), name); CFStringDelete(unprefixed, CFRangeMake(0, CFStringGetLength(__tzZoneInfo))); +#else + } else if (CFStringHasPrefix(name, CFSTR(TZZONEINFO))) { + CFMutableStringRef unprefixed = CFStringCreateMutableCopy(kCFAllocatorSystemDefault, CFStringGetLength(name), name); + CFStringDelete(unprefixed, CFRangeMake(0, sizeof(TZZONEINFO))); +#endif mapping = CFDictionaryGetValue(dict, unprefixed); if (mapping) { name = mapping; @@ -1242,6 +1196,7 @@ Boolean _CFTimeZoneInit(CFTimeZoneRef timeZone, CFStringRef name, CFDataRef data } return false; } +#endif CFTimeZoneRef CFTimeZoneCreate(CFAllocatorRef allocator, CFStringRef name, CFDataRef data) { // assert: (NULL != name && NULL != data); @@ -1382,12 +1337,12 @@ CFTimeZoneRef CFTimeZoneCreateWithName(CFAllocatorRef allocator, CFStringRef nam void *bytes; CFIndex length; +#if DEPLOYMENT_TARGET_WINDOWS if (!__tzZoneInfo) __InitTZStrings(); if (!__tzZoneInfo) return NULL; -#if DEPLOYMENT_TARGET_WINDOWS baseURL = CFURLCreateWithFileSystemPath(kCFAllocatorSystemDefault, __tzZoneInfo, kCFURLWindowsPathStyle, true); #else - baseURL = CFURLCreateWithFileSystemPath(kCFAllocatorSystemDefault, __tzZoneInfo, kCFURLPOSIXPathStyle, true); + baseURL = CFURLCreateWithFileSystemPath(kCFAllocatorSystemDefault, CFSTR(TZZONEINFO), kCFURLPOSIXPathStyle, true); #endif if (tryAbbrev) { CFDictionaryRef abbrevs = CFTimeZoneCopyAbbreviationDictionary(); @@ -1408,9 +1363,15 @@ CFTimeZoneRef CFTimeZoneCreateWithName(CFAllocatorRef allocator, CFStringRef nam CFStringRef mapping = CFDictionaryGetValue(dict, name); if (mapping) { name = mapping; +#if DEPLOYMENT_TARGET_WINDOWS } else if (CFStringHasPrefix(name, __tzZoneInfo)) { CFMutableStringRef unprefixed = CFStringCreateMutableCopy(kCFAllocatorSystemDefault, CFStringGetLength(name), name); CFStringDelete(unprefixed, CFRangeMake(0, CFStringGetLength(__tzZoneInfo))); +#else + } else if (CFStringHasPrefix(name, CFSTR(TZZONEINFO))) { + CFMutableStringRef unprefixed = CFStringCreateMutableCopy(kCFAllocatorSystemDefault, CFStringGetLength(name), name); + CFStringDelete(unprefixed, CFRangeMake(0, sizeof(TZZONEINFO))); +#endif mapping = CFDictionaryGetValue(dict, unprefixed); if (mapping) { name = mapping; @@ -1585,4 +1546,6 @@ static CFDictionaryRef __CFTimeZoneCopyCompatibilityDictionary(void) { return dict; } +#undef TZZONEINFO +#undef TZZONELINK diff --git a/CoreFoundation/NumberDate.subproj/CFTimeZone.h b/CoreFoundation/NumberDate.subproj/CFTimeZone.h index 4207f4559e..e4beab8095 100644 --- a/CoreFoundation/NumberDate.subproj/CFTimeZone.h +++ b/CoreFoundation/NumberDate.subproj/CFTimeZone.h @@ -1,7 +1,7 @@ /* CFTimeZone.h - Copyright (c) 1998-2017, Apple Inc. and the Swift project authors + Copyright (c) 1998-2018, Apple Inc. and the Swift project authors - Portions Copyright (c) 2014-2017, Apple Inc. and the Swift project authors + Portions Copyright (c) 2014-2018, Apple Inc. and the Swift project authors Licensed under Apache License v2.0 with Runtime Library Exception See http://swift.org/LICENSE.txt for license information See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors diff --git a/CoreFoundation/Parsing.subproj/CFBinaryPList.c b/CoreFoundation/Parsing.subproj/CFBinaryPList.c index adf3a24e7f..2d8eb2ac10 100644 --- a/CoreFoundation/Parsing.subproj/CFBinaryPList.c +++ b/CoreFoundation/Parsing.subproj/CFBinaryPList.c @@ -1,7 +1,7 @@ /* CFBinaryPList.c - Copyright (c) 2000-2017, Apple Inc. and the Swift project authors + Copyright (c) 2000-2018, Apple Inc. and the Swift project authors - Portions Copyright (c) 2014-2017, Apple Inc. and the Swift project authors + Portions Copyright (c) 2014-2018, Apple Inc. and the Swift project authors Licensed under Apache License v2.0 with Runtime Library Exception See http://swift.org/LICENSE.txt for license information See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors @@ -26,6 +26,7 @@ #include #include #include "CFInternal.h" +#include "CFRuntime_Internal.h" #include typedef struct { @@ -100,9 +101,7 @@ static CFStringRef __CFKeyedArchiverUIDCopyFormattingDescription(CFTypeRef cf, C return CFStringCreateWithFormat(kCFAllocatorSystemDefault, NULL, CFSTR("@%u@"), uid->_value); } -static CFTypeID __kCFKeyedArchiverUIDTypeID = _kCFRuntimeNotATypeID; - -static const CFRuntimeClass __CFKeyedArchiverUIDClass = { +const CFRuntimeClass __CFKeyedArchiverUIDClass = { 0, "CFKeyedArchiverUID", NULL, // init @@ -115,9 +114,7 @@ static const CFRuntimeClass __CFKeyedArchiverUIDClass = { }; CFTypeID _CFKeyedArchiverUIDGetTypeID(void) { - static dispatch_once_t initOnce; - dispatch_once(&initOnce, ^{ __kCFKeyedArchiverUIDTypeID = _CFRuntimeRegisterClass(&__CFKeyedArchiverUIDClass); }); - return __kCFKeyedArchiverUIDTypeID; + return _kCFRuntimeIDCFKeyedArchiverUID; } CFKeyedArchiverUIDRef _CFKeyedArchiverUIDCreate(CFAllocatorRef allocator, uint32_t value) { @@ -264,28 +261,6 @@ TRAILER */ -static CFTypeID stringtype = -1, datatype = -1, numbertype = -1, datetype = -1; -static CFTypeID booltype = -1, nulltype = -1, dicttype = -1, arraytype = -1; -static CFTypeID uuidtype = -1, urltype = -1, osettype = -1, settype = -1; - -static void initStatics() { - static dispatch_once_t once; - dispatch_once(&once, ^{ - stringtype = CFStringGetTypeID(); - datatype = CFDataGetTypeID(); - numbertype = CFNumberGetTypeID(); - booltype = CFBooleanGetTypeID(); - datetype = CFDateGetTypeID(); - dicttype = CFDictionaryGetTypeID(); - arraytype = CFArrayGetTypeID(); - settype = CFSetGetTypeID(); - nulltype = CFNullGetTypeID(); - uuidtype = CFUUIDGetTypeID(); - urltype = CFURLGetTypeID(); - osettype = -1; - }); -} - static void _appendInt(__CFBinaryPlistWriteBuffer *buf, uint64_t bigint, Boolean dryRun) { uint8_t marker; uint8_t *bytes; @@ -417,14 +392,14 @@ static Boolean _appendObject(__CFBinaryPlistWriteBuffer *buf, CFTypeRef obj, CFD uint64_t refnum; CFIndex idx2; CFTypeID type = CFGetTypeID(obj); - if (stringtype == type) { + if (_kCFRuntimeIDCFString == type) { _appendString(buf, (CFStringRef)obj, dryRun); - } else if (numbertype == type) { + } else if (_kCFRuntimeIDCFNumber == type) { _appendNumber(buf, (CFNumberRef)obj, dryRun); - } else if (booltype == type) { + } else if (_kCFRuntimeIDCFBoolean == type) { uint8_t marker = CFBooleanGetValue((CFBooleanRef)obj) ? kCFBinaryPlistMarkerTrue : kCFBinaryPlistMarkerFalse; bufferWrite(buf, &marker, 1, dryRun); - } else if (datatype == type) { + } else if (_kCFRuntimeIDCFData == type) { CFIndex count = CFDataGetLength((CFDataRef)obj); uint8_t marker = (uint8_t)(kCFBinaryPlistMarkerData | (count < 15 ? count : 0xf)); bufferWrite(buf, &marker, 1, dryRun); @@ -432,13 +407,13 @@ static Boolean _appendObject(__CFBinaryPlistWriteBuffer *buf, CFTypeRef obj, CFD _appendInt(buf, (uint64_t)count, dryRun); } bufferWrite(buf, CFDataGetBytePtr((CFDataRef)obj), count, dryRun); - } else if (datetype == type) { + } else if (_kCFRuntimeIDCFDate == type) { CFSwappedFloat64 swapped; uint8_t marker = kCFBinaryPlistMarkerDate; bufferWrite(buf, &marker, 1, dryRun); swapped = CFConvertFloat64HostToSwapped(CFDateGetAbsoluteTime((CFDateRef)obj)); bufferWrite(buf, (uint8_t *)&swapped, sizeof(swapped), dryRun); - } else if (dicttype == type) { + } else if (_kCFRuntimeIDCFDictionary == type) { CFIndex count = CFDictionaryGetCount((CFDictionaryRef)obj); uint8_t marker = (uint8_t)(kCFBinaryPlistMarkerDict | (count < 15 ? count : 0xf)); bufferWrite(buf, &marker, 1, dryRun); @@ -465,7 +440,7 @@ static Boolean _appendObject(__CFBinaryPlistWriteBuffer *buf, CFTypeRef obj, CFD } } if (list != buffer) CFAllocatorDeallocate(kCFAllocatorSystemDefault, list); - } else if (arraytype == type) { + } else if (_kCFRuntimeIDCFArray == type) { CFIndex count = CFArrayGetCount((CFArrayRef)obj); CFPropertyListRef *list, buffer[256]; uint8_t marker = (uint8_t)(kCFBinaryPlistMarkerArray | (count < 15 ? count : 0xf)); @@ -507,7 +482,7 @@ static void _flattenPlist(CFPropertyListRef plist, CFMutableArrayRef objlist, CF // Do not unique dictionaries or arrays, because: they // are slow to compare, and have poor hash codes. // Uniquing bools is unnecessary. - if (stringtype == type || numbertype == type || datetype == type || datatype == type) { + if (_kCFRuntimeIDCFString == type || _kCFRuntimeIDCFNumber == type || _kCFRuntimeIDCFDate == type || _kCFRuntimeIDCFData == type) { CFIndex before = CFSetGetCount(uniquingset); CFSetAddValue(uniquingset, plist); CFIndex after = CFSetGetCount(uniquingset); @@ -523,7 +498,7 @@ static void _flattenPlist(CFPropertyListRef plist, CFMutableArrayRef objlist, CF refnum = CFArrayGetCount(objlist); CFArrayAppendValue(objlist, plist); CFDictionaryAddValue(objtable, plist, (const void *)(uintptr_t)refnum); - if (dicttype == type) { + if (_kCFRuntimeIDCFDictionary == type) { CFIndex count = CFDictionaryGetCount((CFDictionaryRef)plist); STACK_BUFFER_DECL(CFPropertyListRef, buffer, count <= 128 ? count * 2 : 1); CFPropertyListRef *list = (count <= 128) ? buffer : (CFPropertyListRef *)CFAllocatorAllocate(kCFAllocatorSystemDefault, 2 * count * sizeof(CFTypeRef), 0); @@ -532,7 +507,7 @@ static void _flattenPlist(CFPropertyListRef plist, CFMutableArrayRef objlist, CF _flattenPlist(list[idx], objlist, objtable, uniquingset); } if (list != buffer) CFAllocatorDeallocate(kCFAllocatorSystemDefault, list); - } else if (arraytype == type) { + } else if (_kCFRuntimeIDCFArray == type) { CFIndex count = CFArrayGetCount((CFArrayRef)plist); STACK_BUFFER_DECL(CFPropertyListRef, buffer, count <= 256 ? count : 1); CFPropertyListRef *list = (count <= 256) ? buffer : (CFPropertyListRef *)CFAllocatorAllocate(kCFAllocatorSystemDefault, count * sizeof(CFTypeRef), 0); @@ -579,8 +554,6 @@ CF_PRIVATE CFIndex __CFBinaryPlistWriteOrPresize(CFPropertyListRef plist, CFType //If we're actually serializing, rather than just pre-sizing, we have to have something to serialize into. CFAssert(stream || sizeOnly, __kCFLogAssertion, "Passing NULL for the stream argument to __CFBinaryPlistWriteOrPresize is only valid if sizeOnly is true"); - initStatics(); - /* This is exactly the same as a CFDictionary with NULL callbacks, except that it has the "aggressive growth" flag set, since we're not keeping it around. Radar 21883482 */ @@ -765,8 +738,6 @@ CF_INLINE uint64_t _getSizedInt(const uint8_t *data, uint8_t valSize) { bool __CFBinaryPlistGetTopLevelInfo(const uint8_t *databytes, uint64_t datalen, uint8_t *marker, uint64_t *offset, CFBinaryPlistTrailer *trailer) { CFBinaryPlistTrailer trail; - initStatics(); - if (!databytes || datalen < sizeof(trail) + 8 + 1) FAIL_FALSE; // Tiger and earlier will parse "bplist00" // Leopard will parse "bplist00" or "bplist01" @@ -854,7 +825,7 @@ bool __CFBinaryPlistGetTopLevelInfo(const uint8_t *databytes, uint64_t datalen, CF_INLINE Boolean _plistIsPrimitive(CFPropertyListRef pl) { CFTypeID type = CFGetTypeID(pl); - if (dicttype == type || arraytype == type || settype == type || osettype == type) FAIL_FALSE; + if (_kCFRuntimeIDCFDictionary == type || _kCFRuntimeIDCFArray == type || _kCFRuntimeIDCFSet == type) FAIL_FALSE; return true; } @@ -1030,7 +1001,7 @@ CFSetRef __CFBinaryPlistCopyTopLevelKeys(CFAllocatorRef allocator, const uint8_t // Unlike in __CFBinaryPlistGetOffsetForValueFromDictionary3, we're accumulating keys, so we go through the CFObjectRef case always. CFPropertyListRef keyInData = NULL; if (!(__CFBinaryPlistCreateObjectFiltered(databytes, datalen, off, trailer, allocator, kCFPropertyListImmutable, NULL, NULL, 0, NULL, &keyInData) && - CFGetTypeID(keyInData) == stringtype)) { + CFGetTypeID(keyInData) == _kCFRuntimeIDCFString)) { bad = true; if (keyInData) { // we're not storing keyInData in the buffer, so we need to free it now; buffered keys are cleaned below @@ -1099,7 +1070,7 @@ bool __CFBinaryPlistGetOffsetForValueFromDictionary3(const uint8_t *databytes, u // For short keys (15 bytes or less) in ASCII form, we can do a quick comparison check // We get the pointer or copy the buffer here, outside of the loop CFIndex stringKeyLen = -1; - if (CFGetTypeID(key) == stringtype) { + if (CFGetTypeID(key) == _kCFRuntimeIDCFString) { stringKeyLen = CFStringGetLength((CFStringRef)key); } diff --git a/CoreFoundation/Parsing.subproj/CFOldStylePList.c b/CoreFoundation/Parsing.subproj/CFOldStylePList.c index a3ab78c192..0fc99b69cb 100644 --- a/CoreFoundation/Parsing.subproj/CFOldStylePList.c +++ b/CoreFoundation/Parsing.subproj/CFOldStylePList.c @@ -1,7 +1,7 @@ /* CFOldStylePList.c - Copyright (c) 1999-2017, Apple Inc. and the Swift project authors + Copyright (c) 1999-2018, Apple Inc. and the Swift project authors - Portions Copyright (c) 2014-2017, Apple Inc. and the Swift project authors + Portions Copyright (c) 2014-2018, Apple Inc. and the Swift project authors Licensed under Apache License v2.0 with Runtime Library Exception See http://swift.org/LICENSE.txt for license information See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors @@ -18,6 +18,7 @@ #include #include +#include "CFOverflow.h" // // Old NeXT-style property lists diff --git a/CoreFoundation/Parsing.subproj/CFPropertyList.c b/CoreFoundation/Parsing.subproj/CFPropertyList.c index e45afdc3c0..f833eeddc6 100644 --- a/CoreFoundation/Parsing.subproj/CFPropertyList.c +++ b/CoreFoundation/Parsing.subproj/CFPropertyList.c @@ -1,7 +1,7 @@ /* CFPropertyList.c - Copyright (c) 1999-2017, Apple Inc. and the Swift project authors + Copyright (c) 1999-2018, Apple Inc. and the Swift project authors - Portions Copyright (c) 2014-2017, Apple Inc. and the Swift project authors + Portions Copyright (c) 2014-2018, Apple Inc. and the Swift project authors Licensed under Apache License v2.0 with Runtime Library Exception See http://swift.org/LICENSE.txt for license information See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors @@ -19,6 +19,7 @@ #include #include #include "CFInternal.h" +#include "CFRuntime_Internal.h" #include #include #include @@ -32,6 +33,7 @@ #include #include +#include "CFOverflow.h" CF_EXPORT CFNumberType _CFNumberGetType2(CFNumberRef number); @@ -93,24 +95,6 @@ CF_EXPORT CFNumberType _CFNumberGetType2(CFNumberRef number); // Used to reference an old-style plist parser error inside of a more general XML error #define CFPropertyListOldStyleParserErrorKey CFSTR("kCFPropertyListOldStyleParsingError") -static CFTypeID stringtype, datatype, numbertype, datetype; -static CFTypeID booltype, nulltype, dicttype, arraytype, settype; - -static void initStatics() { - static dispatch_once_t once; - dispatch_once(&once, ^{ - stringtype = CFStringGetTypeID(); - datatype = CFDataGetTypeID(); - numbertype = CFNumberGetTypeID(); - booltype = CFBooleanGetTypeID(); - datetype = CFDateGetTypeID(); - dicttype = CFDictionaryGetTypeID(); - arraytype = CFArrayGetTypeID(); - settype = CFSetGetTypeID(); - nulltype = CFNullGetTypeID(); - }); -} - CF_PRIVATE CFErrorRef __CFPropertyListCreateError(CFIndex code, CFStringRef debugString, ...) { va_list argList; CFErrorRef error = NULL; @@ -179,12 +163,12 @@ static void __CFPropertyListIsDictPlistAux(const void *key, const void *value, v if (!ctx->answer) return; if (!key && ctx->error && !*(ctx->error)) *(ctx->error) = (CFStringRef)CFRetain(CFSTR("property list dictionaries cannot contain NULL keys")); if (!value && ctx->error && !*(ctx->error)) *(ctx->error) = (CFStringRef)CFRetain(CFSTR("property list dictionaries cannot contain NULL values")); - if (stringtype != CFGetTypeID(key) && ctx->error && !*(ctx->error)) { + if (_kCFRuntimeIDCFString != CFGetTypeID(key) && ctx->error && !*(ctx->error)) { CFStringRef desc = CFCopyTypeIDDescription(CFGetTypeID(key)); *(ctx->error) = CFStringCreateWithFormat(kCFAllocatorSystemDefault, NULL, CFSTR("property list dictionaries may only have keys which are CFStrings, not '%@'"), desc); CFRelease(desc); } - ctx->answer = key && value && (stringtype == CFGetTypeID(key)) && __CFPropertyListIsValidAux(value, true, ctx->set, ctx->format, ctx->error); + ctx->answer = key && value && (_kCFRuntimeIDCFString == CFGetTypeID(key)) && __CFPropertyListIsValidAux(value, true, ctx->set, ctx->format, ctx->error); } static bool __CFPropertyListIsValidAux(CFPropertyListRef plist, bool recursive, CFMutableSetRef set, CFPropertyListFormat format, CFStringRef *error) { @@ -193,16 +177,16 @@ static bool __CFPropertyListIsValidAux(CFPropertyListRef plist, bool recursive, return false; } CFTypeID type = CFGetTypeID(plist); - if (stringtype == type) return true; - if (datatype == type) return true; + if (_kCFRuntimeIDCFString == type) return true; + if (_kCFRuntimeIDCFData == type) return true; if (kCFPropertyListOpenStepFormat != format) { - if (booltype == type) return true; - if (numbertype == type) return true; - if (datetype == type) return true; + if (_kCFRuntimeIDCFBoolean == type) return true; + if (_kCFRuntimeIDCFNumber == type) return true; + if (_kCFRuntimeIDCFDate == type) return true; if (_CFKeyedArchiverUIDGetTypeID() == type) return true; } - if (!recursive && arraytype == type) return true; - if (!recursive && dicttype == type) return true; + if (!recursive && _kCFRuntimeIDCFArray == type) return true; + if (!recursive && _kCFRuntimeIDCFDictionary == type) return true; // at any one invocation of this function, set should contain the objects in the "path" down to this object. For the outermost invocation it can be NULL. Boolean createdSet = false; @@ -214,13 +198,13 @@ static bool __CFPropertyListIsValidAux(CFPropertyListRef plist, bool recursive, return false; } Boolean result = false; - if (arraytype == type) { + if (_kCFRuntimeIDCFArray == type) { struct context ctx = {true, set, format, error}; CFSetAddValue(set, plist); CFArrayApplyFunction((CFArrayRef)plist, CFRangeMake(0, CFArrayGetCount((CFArrayRef)plist)), __CFPropertyListIsArrayPlistAux, &ctx); CFSetRemoveValue(set, plist); result = ctx.answer; - } else if (dicttype == type) { + } else if (_kCFRuntimeIDCFDictionary == type) { struct context ctx = {true, set, format, error}; CFSetAddValue(set, plist); CFDictionaryApplyFunction((CFDictionaryRef)plist, __CFPropertyListIsDictPlistAux, &ctx); @@ -240,7 +224,6 @@ static bool __CFPropertyListIsValidAux(CFPropertyListRef plist, bool recursive, } static Boolean _CFPropertyListIsValidWithErrorString(CFPropertyListRef plist, CFPropertyListFormat format, CFStringRef *error) { - initStatics(); CFAssert1(plist != NULL, __kCFLogAssertion, "%s(): NULL is not a property list", __PRETTY_FUNCTION__); return __CFPropertyListIsValidAux(plist, true, NULL, format, error); } @@ -512,7 +495,7 @@ extern CFStringRef __CFNumberCopyFormattingDescriptionAsFloat64(CFTypeRef cf); static void _CFAppendXML0(CFTypeRef object, UInt32 indentation, CFMutableDataRef xmlString) { UInt32 typeID = CFGetTypeID(object); _appendIndents(indentation, xmlString); - if (typeID == stringtype) { + if (typeID == _kCFRuntimeIDCFString) { _plistAppendUTF8CString(xmlString, "<"); _plistAppendCharacters(xmlString, CFXMLPlistTagsUnicode[STRING_IX], STRING_TAG_LENGTH); _plistAppendUTF8CString(xmlString, ">"); @@ -550,7 +533,7 @@ static void _CFAppendXML0(CFTypeRef object, UInt32 indentation, CFMutableDataRef _plistAppendUTF8CString(xmlString, "\n"); - } else if (typeID == arraytype) { + } else if (typeID == _kCFRuntimeIDCFArray) { UInt32 i, count = CFArrayGetCount((CFArrayRef)object); if (count == 0) { _plistAppendUTF8CString(xmlString, "<"); @@ -568,7 +551,7 @@ static void _CFAppendXML0(CFTypeRef object, UInt32 indentation, CFMutableDataRef _plistAppendUTF8CString(xmlString, "\n"); - } else if (typeID == dicttype) { + } else if (typeID == _kCFRuntimeIDCFDictionary) { UInt32 i, count = CFDictionaryGetCount((CFDictionaryRef)object); CFMutableArrayRef keyArray; if (count == 0) { @@ -604,7 +587,7 @@ static void _CFAppendXML0(CFTypeRef object, UInt32 indentation, CFMutableDataRef _plistAppendUTF8CString(xmlString, "\n"); - } else if (typeID == datatype) { + } else if (typeID == _kCFRuntimeIDCFData) { _plistAppendUTF8CString(xmlString, "<"); _plistAppendCharacters(xmlString, CFXMLPlistTagsUnicode[DATA_IX], DATA_TAG_LENGTH); _plistAppendUTF8CString(xmlString, ">\n"); @@ -613,7 +596,7 @@ static void _CFAppendXML0(CFTypeRef object, UInt32 indentation, CFMutableDataRef _plistAppendUTF8CString(xmlString, "\n"); - } else if (typeID == datetype) { + } else if (typeID == _kCFRuntimeIDCFDate) { // YYYY '-' MM '-' DD 'T' hh ':' mm ':' ss 'Z' int32_t y = 0, M = 0, d = 0, H = 0, m = 0, s = 0; CFAbsoluteTime at = CFDateGetAbsoluteTime((CFDateRef)object); @@ -655,7 +638,7 @@ if (date.year != y || date.month != M || date.day != d || date.hour != H || date _plistAppendUTF8CString(xmlString, "\n"); - } else if (typeID == numbertype) { + } else if (typeID == _kCFRuntimeIDCFNumber) { if (CFNumberIsFloatType((CFNumberRef)object)) { _plistAppendUTF8CString(xmlString, "<"); _plistAppendCharacters(xmlString, CFXMLPlistTagsUnicode[REAL_IX], REAL_TAG_LENGTH); @@ -677,7 +660,7 @@ if (date.year != y || date.month != M || date.day != d || date.hour != H || date _plistAppendCharacters(xmlString, CFXMLPlistTagsUnicode[INTEGER_IX], INTEGER_TAG_LENGTH); _plistAppendUTF8CString(xmlString, ">\n"); } - } else if (typeID == booltype) { + } else if (typeID == _kCFRuntimeIDCFBoolean) { if (CFBooleanGetValue((CFBooleanRef)object)) { _plistAppendUTF8CString(xmlString, "<"); _plistAppendCharacters(xmlString, CFXMLPlistTagsUnicode[TRUE_IX], TRUE_TAG_LENGTH); @@ -709,7 +692,6 @@ static void _CFGenerateXMLPropertyListToData(CFMutableDataRef xml, CFTypeRef pro #pragma mark Exported Creation Functions CFDataRef _CFPropertyListCreateXMLData(CFAllocatorRef allocator, CFPropertyListRef propertyList, Boolean checkValidPlist) { - initStatics(); CFMutableDataRef xml; CFAssert1(propertyList != NULL, __kCFLogAssertion, "%s(): Cannot be called with a NULL property list", __PRETTY_FUNCTION__); if (checkValidPlist && !CFPropertyListIsValid(propertyList, kCFPropertyListXMLFormat_v1_0)) { @@ -730,7 +712,6 @@ CF_EXPORT CFDataRef _CFPropertyListCreateXMLDataWithExtras(CFAllocatorRef alloca } Boolean CFPropertyListIsValid(CFPropertyListRef plist, CFPropertyListFormat format) { - initStatics(); CFAssert1(plist != NULL, __kCFLogAssertion, "%s(): NULL is not a property list", __PRETTY_FUNCTION__); return __CFPropertyListIsValidAux(plist, true, NULL, format, NULL); #if defined(DEBUG) @@ -1565,7 +1546,7 @@ static Boolean parseDictTag(_CFXMLPlistParseInfo *pInfo, CFTypeRef *out) { CFIndex cnt = CFDictionaryGetCount(dict); if (1 == cnt) { CFTypeRef val = CFDictionaryGetValue(dict, CFSTR("CF$UID")); - if (val && CFGetTypeID(val) == numbertype) { + if (val && CFGetTypeID(val) == _kCFRuntimeIDCFNumber) { CFTypeRef uid; uint32_t v; CFNumberGetValue((CFNumberRef)val, kCFNumberSInt32Type, &v); @@ -2395,7 +2376,6 @@ static Boolean __savePlistData(CFDataRef data, CFOptionFlags opt) { // If the data is from a converted string, then originalString is non-NULL. If originalString is NULL, then pass in guessedEncoding. // keyPaths is a set of CFStrings, ':'-separated paths static Boolean _CFPropertyListCreateFromUTF8Data(CFAllocatorRef allocator, CFDataRef xmlData, CFIndex skipBytes, CFStringRef originalString, CFStringEncoding guessedEncoding, CFOptionFlags option, CFErrorRef *outError, Boolean allowNewTypes, CFPropertyListFormat *format, CFSetRef keyPaths, CFTypeRef *out, Boolean doXML, Boolean doOpenStep) { - initStatics(); CFAssert1(xmlData != NULL, __kCFLogAssertion, "%s(): NULL data not allowed", __PRETTY_FUNCTION__); @@ -2518,7 +2498,6 @@ static CFDataRef _createUTF8DataFromString(CFAllocatorRef allocator, CFStringRef // Set topLevelKeys to a set of top level keys to decode. If NULL, all keys are decoded. If the top level object is not a dictionary, all objects are decoded. If the plist is not XML, all objects are decoded. static Boolean _CFPropertyListCreateWithData(CFAllocatorRef allocator, CFDataRef data, CFOptionFlags option, CFErrorRef *outError, Boolean allowNewTypes, CFPropertyListFormat *format, CFSetRef topLevelKeys, CFTypeRef *out) { - initStatics(); CFStringEncoding encoding; // we support the restriction of the kinds of parses we will try @@ -2618,7 +2597,6 @@ CFTypeRef _CFPropertyListCreateFromXMLStringError(CFAllocatorRef allocator, CFSt } CFTypeRef _CFPropertyListCreateFromXMLString(CFAllocatorRef allocator, CFStringRef xmlString, CFOptionFlags option, CFStringRef *errorString, Boolean allowNewTypes, CFPropertyListFormat *format) { - initStatics(); if (errorString) *errorString = NULL; CFErrorRef error = NULL; CFTypeRef result = _CFPropertyListCreateFromXMLStringError(allocator, xmlString, option, &error, allowNewTypes, format); @@ -2666,8 +2644,6 @@ CF_PRIVATE bool __CFBinaryPlistCreateObjectFiltered(const uint8_t *databytes, ui // Returns a subset of the property list, only including the key paths in the CFSet. bool _CFPropertyListCreateFiltered(CFAllocatorRef allocator, CFDataRef data, CFOptionFlags option, CFSetRef keyPaths, CFPropertyListRef *value, CFErrorRef *error) { - initStatics(); - if (!keyPaths || !data) { return false; } @@ -2717,8 +2693,6 @@ bool _CFPropertyListCreateFiltered(CFAllocatorRef allocator, CFDataRef data, CFO */ bool _CFPropertyListCreateSingleValue(CFAllocatorRef allocator, CFDataRef data, CFOptionFlags option, CFStringRef keyPath, CFPropertyListRef *value, CFErrorRef *error) { - initStatics(); - if (!keyPath || CFStringGetLength(keyPath) == 0) { return false; } @@ -2791,10 +2765,10 @@ bool _CFPropertyListCreateSingleValue(CFAllocatorRef allocator, CFDataRef data, for (CFIndex i = 0; i < CFArrayGetCount(keyPathArray); i++) { CFStringRef oneKey = (CFStringRef)CFArrayGetValueAtIndex(keyPathArray, i); SInt32 intValue = CFStringGetIntValue(oneKey); - if (((intValue == 0 && CFStringCompare(CFSTR("0"), oneKey, 0) != kCFCompareEqualTo) || intValue == INT_MAX || intValue == INT_MIN) && nextObject && CFGetTypeID((CFTypeRef)nextObject) == dicttype) { + if (((intValue == 0 && CFStringCompare(CFSTR("0"), oneKey, 0) != kCFCompareEqualTo) || intValue == INT_MAX || intValue == INT_MIN) && nextObject && CFGetTypeID((CFTypeRef)nextObject) == _kCFRuntimeIDCFDictionary) { // Treat as a string key into a dictionary nextObject = (CFPropertyListRef)CFDictionaryGetValue((CFDictionaryRef)nextObject, oneKey); - } else if (nextObject && CFGetTypeID((CFTypeRef)nextObject) == arraytype) { + } else if (nextObject && CFGetTypeID((CFTypeRef)nextObject) == _kCFRuntimeIDCFArray) { // Treat as integer index into an array nextObject = (CFPropertyListRef)CFArrayGetValueAtIndex((CFArrayRef)nextObject, intValue); } else { @@ -2855,7 +2829,7 @@ CFSetRef _CFPropertyListCopyTopLevelKeys(CFAllocatorRef allocator, CFDataRef dat const CFPropertyListRef plist = CFPropertyListCreateWithData(allocator, data, option, NULL, outError); if (plist) { const CFTypeID type = CFGetTypeID(plist); - if (type != dicttype) { + if (type != _kCFRuntimeIDCFDictionary) { if (outError) { *outError = __CFPropertyListCreateError(kCFPropertyListReadCorruptError, CFSTR("Cannot copy top-level keys for plist with non-dictionary root object")); } @@ -2888,7 +2862,6 @@ CFSetRef _CFPropertyListCopyTopLevelKeys(CFAllocatorRef allocator, CFDataRef dat // Legacy CFTypeRef _CFPropertyListCreateFromXMLData(CFAllocatorRef allocator, CFDataRef xmlData, CFOptionFlags option, CFStringRef *errorString, Boolean allowNewTypes, CFPropertyListFormat *format) { - initStatics(); CFTypeRef out = NULL; if (errorString) *errorString = NULL; CFErrorRef error = NULL; @@ -2901,7 +2874,6 @@ CFTypeRef _CFPropertyListCreateFromXMLData(CFAllocatorRef allocator, CFDataRef x } CFPropertyListRef CFPropertyListCreateWithData(CFAllocatorRef allocator, CFDataRef data, CFOptionFlags options, CFPropertyListFormat *format, CFErrorRef *error) { - initStatics(); CFAssert1(data != NULL, __kCFLogAssertion, "%s(): NULL data not allowed", __PRETTY_FUNCTION__); CFAssert2(options == kCFPropertyListImmutable || options == kCFPropertyListMutableContainers || options == kCFPropertyListMutableContainersAndLeaves, __kCFLogAssertion, "%s(): Unrecognized option %lu", __PRETTY_FUNCTION__, options); CFPropertyListRef out = NULL; @@ -2910,7 +2882,6 @@ CFPropertyListRef CFPropertyListCreateWithData(CFAllocatorRef allocator, CFDataR } CFPropertyListRef CFPropertyListCreateFromXMLData(CFAllocatorRef allocator, CFDataRef xmlData, CFOptionFlags option, CFStringRef *errorString) { - initStatics(); if (errorString) *errorString = NULL; CFErrorRef error = NULL; CFPropertyListRef result = CFPropertyListCreateWithData(allocator, xmlData, option, NULL, &error); @@ -2922,7 +2893,6 @@ CFPropertyListRef CFPropertyListCreateFromXMLData(CFAllocatorRef allocator, CFDa } CFDataRef CFPropertyListCreateData(CFAllocatorRef allocator, CFPropertyListRef propertyList, CFPropertyListFormat format, CFOptionFlags options, CFErrorRef *error) { - initStatics(); CFAssert1(format != kCFPropertyListOpenStepFormat, __kCFLogAssertion, "%s(): kCFPropertyListOpenStepFormat not supported for writing", __PRETTY_FUNCTION__); CFAssert2(format == kCFPropertyListXMLFormat_v1_0 || format == kCFPropertyListBinaryFormat_v1_0, __kCFLogAssertion, "%s(): Unrecognized option %ld", __PRETTY_FUNCTION__, format); CFAssert1(propertyList != NULL, __kCFLogAssertion, "%s(): Cannot be called with a NULL property list", __PRETTY_FUNCTION__); @@ -2962,7 +2932,6 @@ CFDataRef CFPropertyListCreateData(CFAllocatorRef allocator, CFPropertyListRef p } CFIndex CFPropertyListWrite(CFPropertyListRef propertyList, CFWriteStreamRef stream, CFPropertyListFormat format, CFOptionFlags options, CFErrorRef *error) { - initStatics(); CFAssert1(stream != NULL, __kCFLogAssertion, "%s(): NULL stream not allowed", __PRETTY_FUNCTION__); CFAssert1(format != kCFPropertyListOpenStepFormat, __kCFLogAssertion, "%s(): kCFPropertyListOpenStepFormat not supported for writing", __PRETTY_FUNCTION__); CFAssert2(format == kCFPropertyListXMLFormat_v1_0 || format == kCFPropertyListBinaryFormat_v1_0, __kCFLogAssertion, "%s(): Unrecognized option %ld", __PRETTY_FUNCTION__, format); @@ -3030,7 +2999,6 @@ CFIndex CFPropertyListWrite(CFPropertyListRef propertyList, CFWriteStreamRef str } CFIndex CFPropertyListWriteToStream(CFPropertyListRef propertyList, CFWriteStreamRef stream, CFPropertyListFormat format, CFStringRef *errorString) { - initStatics(); if (errorString) *errorString = NULL; CFErrorRef error = NULL; @@ -3096,7 +3064,6 @@ static bool __convertReadStreamToBytes(CFReadStreamRef stream, CFIndex max, uint } CFPropertyListRef CFPropertyListCreateWithStream(CFAllocatorRef allocator, CFReadStreamRef stream, CFIndex streamLength, CFOptionFlags mutabilityOption, CFPropertyListFormat *format, CFErrorRef *error) { - initStatics(); CFAssert1(stream != NULL, __kCFLogAssertion, "%s(): NULL stream not allowed", __PRETTY_FUNCTION__); CFAssert1(CFReadStreamGetTypeID() == CFGetTypeID(stream), __kCFLogAssertion, "%s(): stream argument is not a read stream", __PRETTY_FUNCTION__); @@ -3139,7 +3106,6 @@ CFPropertyListRef CFPropertyListCreateWithStream(CFAllocatorRef allocator, CFRea } CFPropertyListRef CFPropertyListCreateFromStream(CFAllocatorRef allocator, CFReadStreamRef stream, CFIndex length, CFOptionFlags mutabilityOption, CFPropertyListFormat *format, CFStringRef *errorString) { - initStatics(); if (errorString) *errorString = NULL; CFErrorRef error = NULL; CFPropertyListRef result = CFPropertyListCreateWithStream(allocator, stream, length, mutabilityOption, format, &error); @@ -3196,7 +3162,6 @@ static CFMutableArrayRef _arrayDeepMutableCopy(CFAllocatorRef allocator, CFArray } CFPropertyListRef CFPropertyListCreateDeepCopy(CFAllocatorRef allocator, CFPropertyListRef propertyList, CFOptionFlags mutabilityOption) { - initStatics(); CFPropertyListRef result = NULL; CFAssert1(propertyList != NULL, __kCFLogAssertion, "%s(): cannot copy a NULL property list", __PRETTY_FUNCTION__); __CFAssertIsPList(propertyList); @@ -3204,7 +3169,7 @@ CFPropertyListRef CFPropertyListCreateDeepCopy(CFAllocatorRef allocator, CFPrope if (!CFPropertyListIsValid(propertyList, kCFPropertyListBinaryFormat_v1_0)) return NULL; CFTypeID typeID = CFGetTypeID(propertyList); - if (typeID == dicttype) { + if (typeID == _kCFRuntimeIDCFDictionary) { CFDictionaryRef dict = (CFDictionaryRef)propertyList; Boolean isMutable = (mutabilityOption != kCFPropertyListImmutable); CFIndex count = CFDictionaryGetCount(dict); @@ -3248,32 +3213,32 @@ CFPropertyListRef CFPropertyListCreateDeepCopy(CFAllocatorRef allocator, CFPrope } free_cftype_array(keys); } - } else if (typeID == arraytype) { + } else if (typeID == _kCFRuntimeIDCFArray) { if (mutabilityOption == kCFPropertyListImmutable) { result = _arrayDeepImmutableCopy(allocator, (CFArrayRef)propertyList, mutabilityOption); } else { result = _arrayDeepMutableCopy(allocator, (CFArrayRef)propertyList, mutabilityOption); } - } else if (typeID == datatype) { + } else if (typeID == _kCFRuntimeIDCFData) { if (mutabilityOption == kCFPropertyListMutableContainersAndLeaves) { result = CFDataCreateMutableCopy(allocator, 0, (CFDataRef)propertyList); } else { result = CFDataCreateCopy(allocator, (CFDataRef)propertyList); } - } else if (typeID == numbertype) { + } else if (typeID == _kCFRuntimeIDCFNumber) { // Warning - this will break if byteSize is ever greater than 128 uint8_t bytes[128]; CFNumberType numType = _CFNumberGetType2((CFNumberRef)propertyList); CFNumberGetValue((CFNumberRef)propertyList, numType, (void *)bytes); result = CFNumberCreate(allocator, numType, (void *)bytes); - } else if (typeID == booltype) { + } else if (typeID == _kCFRuntimeIDCFBoolean) { // Booleans are immutable & shared instances CFRetain(propertyList); result = propertyList; - } else if (typeID == datetype) { + } else if (typeID == _kCFRuntimeIDCFDate) { // Dates are immutable result = CFDateCreate(allocator, CFDateGetAbsoluteTime((CFDateRef)propertyList)); - } else if (typeID == stringtype) { + } else if (typeID == _kCFRuntimeIDCFString) { if (mutabilityOption == kCFPropertyListMutableContainersAndLeaves) { result = CFStringCreateMutableCopy(allocator, 0, (CFStringRef)propertyList); } else { diff --git a/CoreFoundation/Parsing.subproj/CFPropertyList.h b/CoreFoundation/Parsing.subproj/CFPropertyList.h index bd785bd0d4..f5483c5018 100644 --- a/CoreFoundation/Parsing.subproj/CFPropertyList.h +++ b/CoreFoundation/Parsing.subproj/CFPropertyList.h @@ -1,7 +1,7 @@ /* CFPropertyList.h - Copyright (c) 1998-2017, Apple Inc. and the Swift project authors + Copyright (c) 1998-2018, Apple Inc. and the Swift project authors - Portions Copyright (c) 2014-2017, Apple Inc. and the Swift project authors + Portions Copyright (c) 2014-2018, Apple Inc. and the Swift project authors Licensed under Apache License v2.0 with Runtime Library Exception See http://swift.org/LICENSE.txt for license information See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors diff --git a/CoreFoundation/Parsing.subproj/CFXMLInputStream.c b/CoreFoundation/Parsing.subproj/CFXMLInputStream.c index c3c7932790..ae266ff762 100644 --- a/CoreFoundation/Parsing.subproj/CFXMLInputStream.c +++ b/CoreFoundation/Parsing.subproj/CFXMLInputStream.c @@ -1,7 +1,7 @@ /* CFXMLInputStream.c - Copyright (c) 1999-2017, Apple Inc. and the Swift project authors + Copyright (c) 1999-2018, Apple Inc. and the Swift project authors - Portions Copyright (c) 2014-2017, Apple Inc. and the Swift project authors + Portions Copyright (c) 2014-2018, Apple Inc. and the Swift project authors Licensed under Apache License v2.0 with Runtime Library Exception See http://swift.org/LICENSE.txt for license information See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors diff --git a/CoreFoundation/Parsing.subproj/CFXMLInputStream.h b/CoreFoundation/Parsing.subproj/CFXMLInputStream.h index a37d284bd9..828793fdae 100644 --- a/CoreFoundation/Parsing.subproj/CFXMLInputStream.h +++ b/CoreFoundation/Parsing.subproj/CFXMLInputStream.h @@ -1,7 +1,7 @@ /* CFXMLInputStream.h - Copyright (c) 2000-2017, Apple Inc. and the Swift project authors + Copyright (c) 2000-2018, Apple Inc. and the Swift project authors - Portions Copyright (c) 2014-2017, Apple Inc. and the Swift project authors + Portions Copyright (c) 2014-2018, Apple Inc. and the Swift project authors Licensed under Apache License v2.0 with Runtime Library Exception See http://swift.org/LICENSE.txt for license information See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors diff --git a/CoreFoundation/Parsing.subproj/CFXMLNode.c b/CoreFoundation/Parsing.subproj/CFXMLNode.c index 25b33fc6ab..f7a73ad1ff 100644 --- a/CoreFoundation/Parsing.subproj/CFXMLNode.c +++ b/CoreFoundation/Parsing.subproj/CFXMLNode.c @@ -1,7 +1,7 @@ /* CFXMLNode.c - Copyright (c) 1998-2017, Apple Inc. and the Swift project authors + Copyright (c) 1998-2018, Apple Inc. and the Swift project authors - Portions Copyright (c) 2014-2017, Apple Inc. and the Swift project authors + Portions Copyright (c) 2014-2018, Apple Inc. and the Swift project authors Licensed under Apache License v2.0 with Runtime Library Exception See http://swift.org/LICENSE.txt for license information See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors @@ -11,6 +11,7 @@ #include #include #include "CFInternal.h" +#include "CFRuntime_Internal.h" #include "CFXMLInputStream.h" CF_INLINE Boolean _nullSafeCFEqual(CFTypeRef cf1, CFTypeRef cf2) { @@ -191,9 +192,7 @@ static void __CFXMLNodeDeallocate(CFTypeRef cf) { } } -static CFTypeID __kCFXMLNodeTypeID = _kCFRuntimeNotATypeID; - -static const CFRuntimeClass __CFXMLNodeClass = { +const CFRuntimeClass __CFXMLNodeClass = { 0, "CFXMLNode", NULL, // init @@ -206,9 +205,7 @@ static const CFRuntimeClass __CFXMLNodeClass = { }; CFTypeID CFXMLNodeGetTypeID(void) { - static dispatch_once_t initOnce; - dispatch_once(&initOnce, ^{ __kCFXMLNodeTypeID = _CFRuntimeRegisterClass(&__CFXMLNodeClass); }); - return __kCFXMLNodeTypeID; + return _kCFRuntimeIDCFXMLNode; } CFXMLNodeRef CFXMLNodeCreateCopy(CFAllocatorRef alloc, CFXMLNodeRef origNode) { diff --git a/CoreFoundation/Parsing.subproj/CFXMLNode.h b/CoreFoundation/Parsing.subproj/CFXMLNode.h index 5e120de807..b770abe1cc 100644 --- a/CoreFoundation/Parsing.subproj/CFXMLNode.h +++ b/CoreFoundation/Parsing.subproj/CFXMLNode.h @@ -1,7 +1,7 @@ /* CFXMLNode.h - Copyright (c) 1998-2017, Apple Inc. and the Swift project authors + Copyright (c) 1998-2018, Apple Inc. and the Swift project authors - Portions Copyright (c) 2014-2017, Apple Inc. and the Swift project authors + Portions Copyright (c) 2014-2018, Apple Inc. and the Swift project authors Licensed under Apache License v2.0 with Runtime Library Exception See http://swift.org/LICENSE.txt for license information See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors diff --git a/CoreFoundation/Parsing.subproj/CFXMLParser.c b/CoreFoundation/Parsing.subproj/CFXMLParser.c index 50e41b6e57..e847a5b778 100644 --- a/CoreFoundation/Parsing.subproj/CFXMLParser.c +++ b/CoreFoundation/Parsing.subproj/CFXMLParser.c @@ -1,5 +1,5 @@ /* CFXMLParser.c - Copyright (c) 1999-2017, Apple Inc. All rights reserved. + Copyright (c) 1999-2018, Apple Inc. All rights reserved. Responsibility: David Smith */ @@ -8,6 +8,7 @@ #include "CFXMLInputStream.h" #include "CFUniChar.h" #include "CFInternal.h" +#include "CFRuntime_Internal.h" #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wdeprecated-declarations" @@ -52,9 +53,7 @@ static void __CFXMLParserDeallocate(CFTypeRef cf) { } } -static CFTypeID __kCFXMLParserTypeID = _kCFRuntimeNotATypeID; - -static const CFRuntimeClass __CFXMLParserClass = { +const CFRuntimeClass __CFXMLParserClass = { 0, "CFXMLParser", NULL, // init @@ -67,9 +66,7 @@ static const CFRuntimeClass __CFXMLParserClass = { }; CFTypeID CFXMLParserGetTypeID(void) { - static dispatch_once_t initOnce; - dispatch_once(&initOnce, ^{ __kCFXMLParserTypeID = _CFRuntimeRegisterClass(&__CFXMLParserClass); }); - return __kCFXMLParserTypeID; + return _kCFRuntimeIDCFXMLParser; } void CFXMLParserGetContext(CFXMLParserRef parser, CFXMLParserContext *context) { @@ -771,7 +768,7 @@ static Boolean parseExternalID(CFXMLParserRef parser, Boolean alsoAcceptPublicID [82] NotationDecl ::= '' */ static Boolean parseNotationDeclaration(CFXMLParserRef parser) { - static UniChar notationString[8] = {'N', 'O', 'T', 'A', 'T', 'I', 'O', 'N'}; + static UniChar const notationString[8] = {'N', 'O', 'T', 'A', 'T', 'I', 'O', 'N'}; Boolean report = *(parser->top) && !(parser->options & kCFXMLParserSkipMetaData); CFXMLNotationInfo notationData = {{NULL, NULL}}; CFStringRef name; diff --git a/CoreFoundation/Parsing.subproj/CFXMLParser.h b/CoreFoundation/Parsing.subproj/CFXMLParser.h index e7baa76454..df8150884e 100644 --- a/CoreFoundation/Parsing.subproj/CFXMLParser.h +++ b/CoreFoundation/Parsing.subproj/CFXMLParser.h @@ -1,5 +1,5 @@ /* CFXMLParser.h - Copyright (c) 1998-2017, Apple Inc. All rights reserved. + Copyright (c) 1998-2018, Apple Inc. All rights reserved. */ /* CFXMLParser is deprecated as of Mac OS X 10.8. The suggested replacements are the Foundation classes NSXMLParser and NSXMLDocument, or the libxml2 library. */ diff --git a/CoreFoundation/Parsing.subproj/CFXMLTree.c b/CoreFoundation/Parsing.subproj/CFXMLTree.c index 405596601d..e4374fd659 100644 --- a/CoreFoundation/Parsing.subproj/CFXMLTree.c +++ b/CoreFoundation/Parsing.subproj/CFXMLTree.c @@ -1,7 +1,7 @@ /* CFXMLTree.c - Copyright (c) 1999-2017, Apple Inc. and the Swift project authors + Copyright (c) 1999-2018, Apple Inc. and the Swift project authors - Portions Copyright (c) 2014-2017, Apple Inc. and the Swift project authors + Portions Copyright (c) 2014-2018, Apple Inc. and the Swift project authors Licensed under Apache License v2.0 with Runtime Library Exception See http://swift.org/LICENSE.txt for license information See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors diff --git a/CoreFoundation/PlugIn.subproj/CFBundle.c b/CoreFoundation/PlugIn.subproj/CFBundle.c index c6b9d16b1d..a07923f98d 100644 --- a/CoreFoundation/PlugIn.subproj/CFBundle.c +++ b/CoreFoundation/PlugIn.subproj/CFBundle.c @@ -1,7 +1,7 @@ /* CFBundle.c - Copyright (c) 1999-2017, Apple Inc. and the Swift project authors + Copyright (c) 1999-2018, Apple Inc. and the Swift project authors - Portions Copyright (c) 2014-2017, Apple Inc. and the Swift project authors + Portions Copyright (c) 2014-2018, Apple Inc. and the Swift project authors Licensed under Apache License v2.0 with Runtime Library Exception See http://swift.org/LICENSE.txt for license information See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors @@ -17,6 +17,7 @@ #include #include #include "CFInternal.h" +#include "CFRuntime_Internal.h" #include #include "CFBundle_BinaryTypes.h" #include @@ -118,9 +119,6 @@ CONST_STRING_DECL(_kCFBundleCFMLoadAsBundleKey, "CFBundleCFMLoadAsBundle") // Keys used by NSBundle for loaded Info plists. CONST_STRING_DECL(_kCFBundlePrincipalClassKey, "NSPrincipalClass") - -static CFTypeID __kCFBundleTypeID = _kCFRuntimeNotATypeID; - static pthread_mutex_t CFBundleGlobalDataLock = PTHREAD_MUTEX_INITIALIZER; static CFMutableDictionaryRef _bundlesByIdentifier = NULL; @@ -164,7 +162,7 @@ static Boolean _CFBundleURLIsForFHSInstalledBundle(CFURLRef bundleURL) { } #endif // !DEPLOYMENT_RUNTIME_OBJC && !DEPLOYMENT_TARGET_WINDOWS && !DEPLOYMENT_TARGET_ANDROID -Boolean _CFBundleSupportsFHSBundles() { +CF_CROSS_PLATFORM_EXPORT Boolean _CFBundleSupportsFHSBundles() { #if !DEPLOYMENT_RUNTIME_OBJC && !DEPLOYMENT_TARGET_WINDOWS && !DEPLOYMENT_TARGET_ANDROID return true; #else @@ -172,6 +170,8 @@ Boolean _CFBundleSupportsFHSBundles() { #endif } +#pragma mark - + CF_PRIVATE os_log_t _CFBundleResourceLogger(void) { static os_log_t _log; static dispatch_once_t onceToken; @@ -252,6 +252,10 @@ static void _CFBundleAddToTables(CFBundleRef bundle) { if (newVersion >= existingVersion) break; } CFArrayInsertValueAtIndex(bundlesWithThisID, i, bundle); + + // We've encountered a bundle with this ID already. + // Output some additional info here. It may not be an error (adding a newer version of a bundle is supported), so use os_log_debug. + os_log_debug(_CFBundleResourceLogger(), "More than one bundle with the same identifier has been added: %{public}@", bundlesWithThisID); } else { CFArrayCallBacks nonRetainingArrayCallbacks = kCFTypeArrayCallBacks; nonRetainingArrayCallbacks.retain = NULL; @@ -467,13 +471,21 @@ CF_EXPORT void _CFBundleFlushBundleCaches(CFBundleRef bundle) { _CFBundleFlushBundleCachesAlreadyLocked(bundle, false); } +#if !(__OBJC__ || __OBJC2__) +static void _CFBundleArrayApplyFlushBundleCaches(const void *value, void *unusedContext) { + _CFBundleFlushBundleCachesAlreadyLocked((CFBundleRef)value, true); +} +#endif + CF_PRIVATE void _CFBundleFlushAllBundleCaches(void) { pthread_mutex_lock(&CFBundleGlobalDataLock); - CFIndex count = CFArrayGetCount(_allBundles); - for (CFIndex idx = 0; idx < count; idx++) { - CFBundleRef bundle = (CFBundleRef)CFArrayGetValueAtIndex(_allBundles, idx); - _CFBundleFlushBundleCachesAlreadyLocked(bundle, true); +#if __OBJC__ || __OBJC2__ + for (id value in (id)_allBundles) { + _CFBundleFlushBundleCachesAlreadyLocked((CFBundleRef)value, true); } +#else + CFArrayApplyFunction(_allBundles, CFRangeMake(0, CFArrayGetCount(_allBundles)), &_CFBundleArrayApplyFlushBundleCaches, NULL); +#endif pthread_mutex_unlock(&CFBundleGlobalDataLock); } @@ -618,7 +630,7 @@ static void __CFBundleDeallocate(CFTypeRef cf) { pthread_mutex_destroy(&(bundle->_bundleLoadingLock)); } -static const CFRuntimeClass __CFBundleClass = { +const CFRuntimeClass __CFBundleClass = { _kCFRuntimeScannedObject, "CFBundle", NULL, // init @@ -634,11 +646,11 @@ static const CFRuntimeClass __CFBundleClass = { CF_PRIVATE void _CFBundleResourcesInitialize(void); CFTypeID CFBundleGetTypeID(void) { - static dispatch_once_t initOnce; - dispatch_once(&initOnce, ^{ __kCFBundleTypeID = _CFRuntimeRegisterClass(&__CFBundleClass); _CFBundleResourcesInitialize(); }); - return __kCFBundleTypeID; + return _kCFRuntimeIDCFBundle; } +// TODO: Remove this SPI, it appears no one is using it +// Remove _CFBundleGetExistingBundleWithBundleURL CFBundleRef _CFBundleGetExistingBundleWithBundleURL(CFURLRef bundleURL) { CFBundleRef bundle = NULL; char buff[CFMaxPathSize]; diff --git a/CoreFoundation/PlugIn.subproj/CFBundle.h b/CoreFoundation/PlugIn.subproj/CFBundle.h index a7af6bab63..e7577c3630 100644 --- a/CoreFoundation/PlugIn.subproj/CFBundle.h +++ b/CoreFoundation/PlugIn.subproj/CFBundle.h @@ -1,5 +1,5 @@ /* CFBundle.h - Copyright (c) 1999-2017, Apple Inc. All rights reserved. + Copyright (c) 1999-2018, Apple Inc. All rights reserved. */ #if !defined(__COREFOUNDATION_CFBUNDLE__) diff --git a/CoreFoundation/PlugIn.subproj/CFBundlePriv.h b/CoreFoundation/PlugIn.subproj/CFBundlePriv.h index 1cb1b12a0d..3892daec5d 100644 --- a/CoreFoundation/PlugIn.subproj/CFBundlePriv.h +++ b/CoreFoundation/PlugIn.subproj/CFBundlePriv.h @@ -1,7 +1,7 @@ /* CFBundlePriv.h - Copyright (c) 1999-2017, Apple Inc. and the Swift project authors + Copyright (c) 1999-2018, Apple Inc. and the Swift project authors - Portions Copyright (c) 2014-2017, Apple Inc. and the Swift project authors + Portions Copyright (c) 2014-2018, Apple Inc. and the Swift project authors Licensed under Apache License v2.0 with Runtime Library Exception See http://swift.org/LICENSE.txt for license information See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors @@ -249,6 +249,15 @@ void _CFBundleSetupXPCBootstrap(xpc_object_t bootstrap) API_AVAILABLE(macos(10.1 #endif +/* SPI for AppKit usage only, they should be only used in limited secnarios of the application load lifecycle */ + +CF_EXPORT +Boolean _CFBundleAddResourceURL(CFBundleRef bundle, CFURLRef url) API_AVAILABLE(macos(10.11), ios(9.0), watchos(2.0), tvos(9.0)); + +CF_EXPORT +Boolean _CFBundleRemoveResourceURL(CFBundleRef bundle, CFURLRef url) API_AVAILABLE(macos(10.11), ios(9.0), watchos(2.0), tvos(9.0)); + + /* CFString & Localization Debug Utilities */ CF_EXPORT @@ -287,9 +296,6 @@ CFURLRef _CFBundleCopySharedFrameworksURL(CFBundleRef bundle); // deprecated in CF_EXPORT CFURLRef _CFBundleCopySharedSupportURL(CFBundleRef bundle); // deprecated in favor of CFBundleCopySharedSupportURL -CF_EXPORT -CFURLRef _CFBundleCopyBuiltInPlugInsURL(CFBundleRef bundle); // deprecated in favor of CFBundleCopyBuiltInPlugInsURL - CF_EXPORT CFURLRef _CFBundleCopyResourceURLForLanguage(CFBundleRef bundle, CFStringRef resourceName, CFStringRef resourceType, CFStringRef subDirName, CFStringRef language); // deprecated in favor of CFBundleCopyResourceURLForLocalization diff --git a/CoreFoundation/PlugIn.subproj/CFBundle_Binary.c b/CoreFoundation/PlugIn.subproj/CFBundle_Binary.c index 2cd602dac7..8e8253e284 100644 --- a/CoreFoundation/PlugIn.subproj/CFBundle_Binary.c +++ b/CoreFoundation/PlugIn.subproj/CFBundle_Binary.c @@ -1,7 +1,7 @@ /* CFBundle_Binary.c - Copyright (c) 1999-2017, Apple Inc. and the Swift project authors + Copyright (c) 1999-2018, Apple Inc. and the Swift project authors - Portions Copyright (c) 2014-2017, Apple Inc. and the Swift project authors + Portions Copyright (c) 2014-2018, Apple Inc. and the Swift project authors Licensed under Apache License v2.0 with Runtime Library Exception See http://swift.org/LICENSE.txt for license information See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors @@ -680,7 +680,7 @@ static void *_CFBundleDlfcnGetSymbolByNameWithSearch(CFBundleRef bundle, CFStrin #if !defined(BINARY_SUPPORT_DYLD) #if TARGET_OS_CYGWIN static CFStringRef _CFBundleDlfcnCopyLoadedImagePathForPointer(void *p) { -// Cygwin does not support dladdr() + // Cygwin does not support dladdr() return NULL; } #else diff --git a/CoreFoundation/PlugIn.subproj/CFBundle_BinaryTypes.h b/CoreFoundation/PlugIn.subproj/CFBundle_BinaryTypes.h index 5465f2f7a9..ad4a470f6e 100644 --- a/CoreFoundation/PlugIn.subproj/CFBundle_BinaryTypes.h +++ b/CoreFoundation/PlugIn.subproj/CFBundle_BinaryTypes.h @@ -1,7 +1,7 @@ /* CFBundle_BinaryTypes.h - Copyright (c) 1999-2017, Apple Inc. and the Swift project authors + Copyright (c) 1999-2018, Apple Inc. and the Swift project authors - Portions Copyright (c) 2014-2017, Apple Inc. and the Swift project authors + Portions Copyright (c) 2014-2018, Apple Inc. and the Swift project authors Licensed under Apache License v2.0 with Runtime Library Exception See http://swift.org/LICENSE.txt for license information See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors diff --git a/CoreFoundation/PlugIn.subproj/CFBundle_Grok.c b/CoreFoundation/PlugIn.subproj/CFBundle_Grok.c index 77485b5996..970e3e97d7 100644 --- a/CoreFoundation/PlugIn.subproj/CFBundle_Grok.c +++ b/CoreFoundation/PlugIn.subproj/CFBundle_Grok.c @@ -1,7 +1,7 @@ /* CFBundle_Grok.c - Copyright (c) 1999-2017, Apple Inc. and the Swift project authors + Copyright (c) 1999-2018, Apple Inc. and the Swift project authors - Portions Copyright (c) 2014-2017, Apple Inc. and the Swift project authors + Portions Copyright (c) 2014-2018, Apple Inc. and the Swift project authors Licensed under Apache License v2.0 with Runtime Library Exception See http://swift.org/LICENSE.txt for license information See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors @@ -82,7 +82,7 @@ static const uint32_t __CFBundleMagicNumbersArray[] = { }; // string, with groups of 5 characters being 1 element in the array -static const char * __CFBundleExtensionsArray = +static const char * const __CFBundleExtensionsArray = "mach\0" "mach\0" "mach\0" "mach\0" "mach\0" "mach\0" "pef\0\0" "pef\0\0" "elf\0\0" "jpeg\0" "tiff\0" "tiff\0" "gif\0\0" "png\0\0" "icns\0" "ico\0\0" "rtf\0\0" "pdf\0\0" "ra\0\0\0""rm\0\0\0""au\0\0\0""au\0\0\0""iff\0\0" "riff\0" @@ -92,8 +92,8 @@ static const char * __CFBundleExtensionsArray = "ttf\0\0" "ttf\0\0" "otf\0\0" "dwg\0\0" "dgn\0\0" "dgn\0\0" "wrl\0\0" "xcf\0\0" "cpx\0\0" "dwf\0\0" "bom\0\0" "lit\0\0" "rtfd\0" "caf\0\0" "cin\0\0" "exr\0\0"; -static const char * __CFBundleOOExtensionsArray = "sxc\0\0" "sxd\0\0" "sxg\0\0" "sxi\0\0" "sxm\0\0" "sxw\0\0"; -static const char * __CFBundleODExtensionsArray = "odc\0\0" "odf\0\0" "odg\0\0" "oth\0\0" "odi\0\0" "odm\0\0" "odp\0\0" "ods\0\0" "odt\0\0"; +static const char * const __CFBundleOOExtensionsArray = "sxc\0\0" "sxd\0\0" "sxg\0\0" "sxi\0\0" "sxm\0\0" "sxw\0\0"; +static const char * const __CFBundleODExtensionsArray = "odc\0\0" "odf\0\0" "odg\0\0" "oth\0\0" "odi\0\0" "odm\0\0" "odp\0\0" "ods\0\0" "odt\0\0"; #define EXTENSION_LENGTH 5 #define NUM_EXTENSIONS 64 diff --git a/CoreFoundation/PlugIn.subproj/CFBundle_InfoPlist.c b/CoreFoundation/PlugIn.subproj/CFBundle_InfoPlist.c index dd14abc4fe..e48c6857bf 100644 --- a/CoreFoundation/PlugIn.subproj/CFBundle_InfoPlist.c +++ b/CoreFoundation/PlugIn.subproj/CFBundle_InfoPlist.c @@ -1,7 +1,7 @@ /* CFBundle_InfoPlist.c - Copyright (c) 2012-2017, Apple Inc. and the Swift project authors + Copyright (c) 2012-2018, Apple Inc. and the Swift project authors - Portions Copyright (c) 2014-2017, Apple Inc. and the Swift project authors + Portions Copyright (c) 2014-2018, Apple Inc. and the Swift project authors Licensed under Apache License v2.0 with Runtime Library Exception See http://swift.org/LICENSE.txt for license information See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors @@ -15,20 +15,17 @@ #include #include -#if DEPLOYMENT_TARGET_MACOSX || DEPLOYMENT_TARGET_EMBEDDED || DEPLOYMENT_TARGET_LINUX || DEPLOYMENT_TARGET_EMBEDDED_MINI || DEPLOYMENT_TARGET_FREEBSD -#if TARGET_OS_CYGWIN -#else +#if (DEPLOYMENT_TARGET_MACOSX || DEPLOYMENT_TARGET_EMBEDDED || DEPLOYMENT_TARGET_LINUX || DEPLOYMENT_TARGET_EMBEDDED_MINI || DEPLOYMENT_TARGET_FREEBSD) && !TARGET_OS_CYGWIN #include #if !TARGET_OS_ANDROID #include #endif #include #endif -#endif // The following strings are initialized 'later' (i.e., not at static initialization time) because static init time is too early for CFSTR to work, on platforms without constant CF strings -#if !__CONSTANT_STRINGS__ +#if !__CONSTANT_CFSTRINGS__ #define _CFBundleNumberOfPlatforms 7 static CFStringRef _CFBundleSupportedPlatforms[_CFBundleNumberOfPlatforms] = { NULL, NULL, NULL, NULL, NULL, NULL, NULL }; @@ -55,18 +52,33 @@ CF_PRIVATE void _CFBundleResourcesInitialize() { #if DEPLOYMENT_TARGET_EMBEDDED || DEPLOYMENT_TARGET_EMBEDDED_MINI // On iOS, we only support one platform #define _CFBundleNumberOfPlatforms 1 -static CFStringRef _CFBundleSupportedPlatforms[_CFBundleNumberOfPlatforms] = { CFSTR("iphoneos") }; +static const CFStringRef _CFBundleSupportedPlatforms[_CFBundleNumberOfPlatforms] = { CFSTR("iphoneos") }; #else // On other platforms, we support the following platforms #define _CFBundleNumberOfPlatforms 7 -static CFStringRef _CFBundleSupportedPlatforms[_CFBundleNumberOfPlatforms] = { CFSTR("iphoneos"), CFSTR("macos"), CFSTR("windows"), CFSTR("linux"), CFSTR("freebsd"), CFSTR("solaris"), CFSTR("hpux") }; +STATIC_CONST_STRING_DECL(_CFBundleSupportedPlatform_iphoneos, "iphoneos"); +STATIC_CONST_STRING_DECL(_CFBundleSupportedPlatform_macos, "macos"); +STATIC_CONST_STRING_DECL(_CFBundleSupportedPlatform_windows, "windows"); +STATIC_CONST_STRING_DECL(_CFBundleSupportedPlatform_linux, "linux"); +STATIC_CONST_STRING_DECL(_CFBundleSupportedPlatform_freebsd, "freebsd"); +STATIC_CONST_STRING_DECL(_CFBundleSupportedPlatform_solaris, "solaris"); +STATIC_CONST_STRING_DECL(_CFBundleSupportedPlatform_hpux, "hpux"); +static const CFStringRef _CFBundleSupportedPlatforms[_CFBundleNumberOfPlatforms] = { + _CFBundleSupportedPlatform_iphoneos, + _CFBundleSupportedPlatform_macos, + _CFBundleSupportedPlatform_windows, + _CFBundleSupportedPlatform_linux, + _CFBundleSupportedPlatform_freebsd, + _CFBundleSupportedPlatform_solaris, + _CFBundleSupportedPlatform_hpux, +}; #endif #define _CFBundleNumberOfProducts 3 -static CFStringRef _CFBundleSupportedProducts[_CFBundleNumberOfProducts] = { CFSTR("iphone"), CFSTR("ipod"), CFSTR("ipad") }; +static const CFStringRef _CFBundleSupportedProducts[_CFBundleNumberOfProducts] = { _CFBundleiPhoneDeviceName, _CFBundleiPodDeviceName, _CFBundleiPadDeviceName }; #define _CFBundleNumberOfiPhoneOSPlatformProducts 3 -static CFStringRef _CFBundleSupportediPhoneOSPlatformProducts[_CFBundleNumberOfiPhoneOSPlatformProducts] = { CFSTR("iphone"), CFSTR("ipod"), CFSTR("ipad") }; +static const CFStringRef _CFBundleSupportediPhoneOSPlatformProducts[_CFBundleNumberOfiPhoneOSPlatformProducts] = { _CFBundleiPhoneDeviceName, _CFBundleiPodDeviceName, _CFBundleiPadDeviceName }; CF_PRIVATE void _CFBundleResourcesInitialize() { } #endif @@ -102,9 +114,9 @@ CF_EXPORT CFStringRef _CFGetProductName(void) { // We only honor the classic suffix if it is one of two preset values. Otherwise we fall back to the result of sysctlbyname. const char *classicSuffix = __CFgetenv("CLASSIC_SUFFIX"); if (classicSuffix && strncmp(classicSuffix, "iphone", strlen("iphone")) == 0) { - _cfBundlePlatform = CFSTR("iphone"); + _cfBundlePlatform = _CFBundleiPhoneDeviceName; } else if (classicSuffix && strncmp(classicSuffix, "ipad", strlen("ipad")) == 0) { - _cfBundlePlatform = CFSTR("ipad"); + _cfBundlePlatform = _CFBundleiPadDeviceName; } else { char buffer[256]; memset(buffer, 0, sizeof(buffer)); @@ -112,18 +124,18 @@ CF_EXPORT CFStringRef _CFGetProductName(void) { int ret = sysctlbyname("hw.machine", buffer, &buflen, NULL, 0); if (0 == ret || (-1 == ret && ENOMEM == errno)) { if (6 <= buflen && 0 == memcmp(buffer, "iPhone", 6)) { - _cfBundlePlatform = CFSTR("iphone"); + _cfBundlePlatform = _CFBundleiPhoneDeviceName; } else if (4 <= buflen && 0 == memcmp(buffer, "iPod", 4)) { - _cfBundlePlatform = CFSTR("ipod"); + _cfBundlePlatform = _CFBundleiPodDeviceName; } else if (4 <= buflen && 0 == memcmp(buffer, "iPad", 4)) { - _cfBundlePlatform = CFSTR("ipad"); + _cfBundlePlatform = _CFBundleiPadDeviceName; } else { const char *env = __CFgetenv("SIMULATOR_LEGACY_ASSET_SUFFIX"); if (env) { if (0 == strcmp(env, "iphone")) { - _cfBundlePlatform = CFSTR("iphone"); + _cfBundlePlatform = _CFBundleiPhoneDeviceName; } else if (0 == strcmp(env, "ipad")) { - _cfBundlePlatform = CFSTR("ipad"); + _cfBundlePlatform = _CFBundleiPadDeviceName; } else { // fallback, unrecognized SIMULATOR_LEGACY_ASSET_SUFFIX } @@ -133,7 +145,7 @@ CF_EXPORT CFStringRef _CFGetProductName(void) { } } } - if (!_cfBundlePlatform) _cfBundlePlatform = CFSTR("iphone"); // fallback + if (!_cfBundlePlatform) _cfBundlePlatform = _CFBundleiPhoneDeviceName; // fallback } return _cfBundlePlatform; #endif @@ -145,8 +157,8 @@ CF_PRIVATE CFStringRef _CFBundleGetProductNameSuffix(void) { // Not dispatch once, because this can be reset (by a rare API call). If a race happens, it just leaks one string. if (!_cfBundlePlatformSuffix) { CFStringRef productName = _CFGetProductName(); - if (CFEqual(productName, CFSTR("ipod"))) { - productName = CFSTR("iphone"); + if (CFEqual(productName, _CFBundleiPodDeviceName)) { + productName = _CFBundleiPhoneDeviceName; } _cfBundlePlatformSuffix = CFStringCreateWithFormat(kCFAllocatorSystemDefault, NULL, CFSTR("~%@"), productName); } @@ -179,7 +191,7 @@ CF_PRIVATE CFStringRef _CFBundleGetPlatformNameSuffix(void) { // All new-style bundles will have these extensions. CF_EXPORT CFStringRef _CFGetPlatformName(void) { -#if DEPLOYMENT_TARGET_MACOSX +#if DEPLOYMENT_TARGET_MACOSX return _CFBundleMacOSXPlatformName; #elif DEPLOYMENT_TARGET_EMBEDDED || DEPLOYMENT_TARGET_EMBEDDED_MINI return _CFBundleiPhoneOSPlatformName; @@ -193,7 +205,7 @@ CF_EXPORT CFStringRef _CFGetPlatformName(void) { #if TARGET_OS_CYGWIN return _CFBundleCygwinPlatformName; #else - return _CFBundleLinuxPlatformName; + return _CFBundleLinuxPlatformName; #endif #elif DEPLOYMENT_TARGET_FREEBSD return _CFBundleFreeBSDPlatformName; @@ -213,7 +225,7 @@ CF_EXPORT CFStringRef _CFGetAlternatePlatformName(void) { #if TARGET_OS_CYGWIN return CFSTR("Cygwin"); #else - return CFSTR("Linux"); + return CFSTR("Linux"); #endif #elif DEPLOYMENT_TARGET_FREEBSD return CFSTR("FreeBSD"); diff --git a/CoreFoundation/PlugIn.subproj/CFBundle_Internal.h b/CoreFoundation/PlugIn.subproj/CFBundle_Internal.h index b94a9aeb18..93c973086a 100644 --- a/CoreFoundation/PlugIn.subproj/CFBundle_Internal.h +++ b/CoreFoundation/PlugIn.subproj/CFBundle_Internal.h @@ -1,7 +1,7 @@ /* CFBundle_Internal.h - Copyright (c) 1999-2017, Apple Inc. and the Swift project authors + Copyright (c) 1999-2018, Apple Inc. and the Swift project authors - Portions Copyright (c) 2014-2017, Apple Inc. and the Swift project authors + Portions Copyright (c) 2014-2018, Apple Inc. and the Swift project authors Licensed under Apache License v2.0 with Runtime Library Exception See http://swift.org/LICENSE.txt for license information See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors @@ -34,13 +34,13 @@ CF_EXTERN_C_BEGIN #if !DEPLOYMENT_RUNTIME_OBJC && !DEPLOYMENT_TARGET_WINDOWS && !DEPLOYMENT_TARGET_ANDROID #if DEPLOYMENT_TARGET_LINUX || DEPLOYMENT_TARGET_FREEBSD - #define _CFBundleFHSSharedLibraryFilenamePrefix CFSTR("lib") - #define _CFBundleFHSSharedLibraryFilenameSuffix CFSTR(".so") +#define _CFBundleFHSSharedLibraryFilenamePrefix CFSTR("lib") +#define _CFBundleFHSSharedLibraryFilenameSuffix CFSTR(".so") #elif DEPLOYMENT_TARGET_MACOSX || DEPLOYMENT_TARGET_EMBEDDED || DEPLOYMENT_TARGET_EMBEDDED_MINI - #define _CFBundleFHSSharedLibraryFilenamePrefix CFSTR("lib") - #define _CFBundleFHSSharedLibraryFilenameSuffix CFSTR(".dylib") +#define _CFBundleFHSSharedLibraryFilenamePrefix CFSTR("lib") +#define _CFBundleFHSSharedLibraryFilenameSuffix CFSTR(".dylib") #else // a non-covered DEPLOYMENT_TARGET… - #error Disable FHS bundles or specify shared library prefixes and suffixes for this platform. +#error Disable FHS bundles or specify shared library prefixes and suffixes for this platform. #endif // DEPLOYMENT_TARGET_… #endif // !DEPLOYMENT_RUNTIME_OBJC && !DEPLOYMENT_TARGET_WINDOWS && !DEPLOYMENT_TARGET_ANDROID @@ -52,6 +52,9 @@ CF_EXTERN_C_BEGIN #define CFBundleExecutableLoadError 3587 #define CFBundleExecutableLinkError 3588 +CF_PRIVATE char *__CFBundleMainID; + + CF_INLINE uint32_t _CFBundleSwapInt32Conditional(uint32_t arg, Boolean swap) {return swap ? CFSwapInt32(arg) : arg;} CF_INLINE uint32_t _CFBundleSwapInt64Conditional(uint64_t arg, Boolean swap) {return swap ? CFSwapInt64(arg) : arg;} @@ -77,7 +80,7 @@ struct __CFBundle { CFURLRef _url; -#if !DEPLOYMENT_RUNTIME_OBJC && !DEPLOYMENT_TARGET_WINDOWS +#if !DEPLOYMENT_RUNTIME_OBJC && !DEPLOYMENT_TARGET_WINDOWS && !DEPLOYMENT_TARGET_ANDROID Boolean _isFHSInstalledBundle; #endif @@ -160,7 +163,7 @@ CF_PRIVATE SInt32 _CFBundleCurrentArchitecture(void); CF_PRIVATE Boolean _CFBundleGetObjCImageInfo(CFBundleRef bundle, uint32_t *objcVersion, uint32_t *objcFlags); #if defined(BINARY_SUPPORT_DYLD) -CF_PRIVATE CFMutableDictionaryRef _CFBundleCreateInfoDictFromMainExecutable(); +CF_PRIVATE CFMutableDictionaryRef _CFBundleCreateInfoDictFromMainExecutable(void); CF_PRIVATE Boolean _CFBundleGrokObjCImageInfoFromMainExecutable(uint32_t *objcVersion, uint32_t *objcFlags); #endif @@ -355,6 +358,13 @@ extern void _CFPlugInRemoveFactory(CFPlugInRef plugIn, _CFPFactoryRef factory); #define _CFBundleLinuxPlatformNameSuffix CFSTR("-linux") #define _CFBundleFreeBSDPlatformNameSuffix CFSTR("-freebsd") +STATIC_CONST_STRING_DECL(_CFBundleMacDeviceName, "mac"); +STATIC_CONST_STRING_DECL(_CFBundleiPhoneDeviceName, "iphone"); +STATIC_CONST_STRING_DECL(_CFBundleiPodDeviceName, "ipod"); +STATIC_CONST_STRING_DECL(_CFBundleiPadDeviceName, "ipad"); +STATIC_CONST_STRING_DECL(_CFBundleAppleWatchDeviceName, "applewatch"); +STATIC_CONST_STRING_DECL(_CFBundleAppleTVDeviceName, "appletv"); + CF_PRIVATE CFStringRef _CFBundleGetProductNameSuffix(void); CF_PRIVATE CFStringRef _CFBundleGetPlatformNameSuffix(void); diff --git a/CoreFoundation/PlugIn.subproj/CFBundle_Locale.c b/CoreFoundation/PlugIn.subproj/CFBundle_Locale.c index 021cf1fdd5..36a2b641bc 100644 --- a/CoreFoundation/PlugIn.subproj/CFBundle_Locale.c +++ b/CoreFoundation/PlugIn.subproj/CFBundle_Locale.c @@ -1,7 +1,7 @@ /* CFBundle_Locale.c - Copyright (c) 1999-2017, Apple Inc. and the Swift project authors + Copyright (c) 1999-2018, Apple Inc. and the Swift project authors - Portions Copyright (c) 2014-2017, Apple Inc. and the Swift project authors + Portions Copyright (c) 2014-2018, Apple Inc. and the Swift project authors Licensed under Apache License v2.0 with Runtime Library Exception See http://swift.org/LICENSE.txt for license information See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors @@ -11,6 +11,7 @@ #include "CFBundle_Internal.h" + #include #if __HAS_APPLE_ICU__ @@ -113,7 +114,7 @@ static const char * const __CFBundleLanguageNamesArray[] = { #define LANGUAGE_NAME_LENGTH 13 // string, with groups of 3 characters being 1 element in the array of abbreviations -const char * __CFBundleLanguageAbbreviationsArray = +const char * const __CFBundleLanguageAbbreviationsArray = "en\0" "fr\0" "de\0" "it\0" "nl\0" "sv\0" "es\0" "da\0" "pt\0" "nb\0" "he\0" "ja\0" "ar\0" "fi\0" "el\0" "is\0" "mt\0" "tr\0" "hr\0" "zh\0" "ur\0" "hi\0" "th\0" "ko\0" @@ -393,27 +394,9 @@ static CFArrayRef _CFBundleCopyLProjDirectoriesForURL(CFAllocatorRef allocator, return (CFArrayRef)result; } -/* This function returns: - 1. The predefined localizations in the Info.plist (CFBundleLocalizations) - 2. Additionally, the .lproj directories inside the bundle - 3. Additionally, the development region of the bundle (CFBundleDevelopmentRegion) -- although if it's already in #1, or #2, we don't append it again - 4. As an ultimate fallback, an empty array - - This doesn't attempt to include a list of localizations supported by a bundle by way of a fallback path; e.g., if the bundle has en_GB then we do not include en_IN (which falls back to en_GB if not present). - - Since the result of this is "typically passed as a parameter to either the CFBundleCopyPreferredLocalizationsFromArray or CFBundleCopyLocalizationsForPreferences function", those other functions will take into account the user prefs and pick the right lproj. -*/ -CF_EXPORT CFArrayRef CFBundleCopyBundleLocalizations(CFBundleRef bundle) { +// Only called from CFBundleCopyBundleLocalizations below +static CFArrayRef _copyBundleLocalizationsFromResources(CFBundleRef bundle) { CFArrayRef result = NULL; - - __CFLock(&bundle->_lock); - if (bundle->_lookedForLocalizations) { - result = (CFArrayRef)CFRetain(bundle->_localizations); - __CFUnlock(&bundle->_lock); - return result; - } - __CFUnlock(&bundle->_lock); - CFDictionaryRef infoDict = CFBundleGetInfoDictionary(bundle); if (infoDict) { CFArrayRef predefinedLocalizations = (CFArrayRef)CFDictionaryGetValue(infoDict, kCFBundleLocalizationsKey); @@ -475,6 +458,34 @@ CF_EXPORT CFArrayRef CFBundleCopyBundleLocalizations(CFBundleRef bundle) { result = CFArrayCreate(CFGetAllocator(bundle), NULL, 0, &kCFTypeArrayCallBacks); } } + return result; +} + +/* This function returns: + 1. The predefined localizations in the Info.plist (CFBundleLocalizations) + 2. Additionally, the .lproj directories inside the bundle + 3. Additionally, the development region of the bundle (CFBundleDevelopmentRegion) -- although if it's already in #1, or #2, we don't append it again + 4. As an ultimate fallback, an empty array + + This doesn't attempt to include a list of localizations supported by a bundle by way of a fallback path; e.g., if the bundle has en_GB then we do not include en_IN (which falls back to en_GB if not present). + + Since the result of this is "typically passed as a parameter to either the CFBundleCopyPreferredLocalizationsFromArray or CFBundleCopyLocalizationsForPreferences function", those other functions will take into account the user prefs and pick the right lproj. +*/ +CF_EXPORT CFArrayRef CFBundleCopyBundleLocalizations(CFBundleRef bundle) { + CFArrayRef result = NULL; + + __CFLock(&bundle->_lock); + if (bundle->_lookedForLocalizations) { + result = (CFArrayRef)CFRetain(bundle->_localizations); + __CFUnlock(&bundle->_lock); + return result; + } + __CFUnlock(&bundle->_lock); + + + if (!result) { + result = _copyBundleLocalizationsFromResources(bundle); + } // Cache the result. __CFLock(&bundle->_lock); @@ -517,8 +528,6 @@ CF_EXPORT CFArrayRef CFBundleCopyLocalizationsForURL(CFURLRef url) { return result; } -extern void *__CFAppleLanguages; - diff --git a/CoreFoundation/PlugIn.subproj/CFBundle_Main.c b/CoreFoundation/PlugIn.subproj/CFBundle_Main.c index a980d30888..38b4dbcbcf 100644 --- a/CoreFoundation/PlugIn.subproj/CFBundle_Main.c +++ b/CoreFoundation/PlugIn.subproj/CFBundle_Main.c @@ -1,5 +1,5 @@ /* CFBundle_Main.c - Copyright (c) 1999-2017, Apple Inc. and the Swift project authors + Copyright (c) 1999-2018, Apple Inc. and the Swift project authors Portions Copyright (c) 2014-2017, Apple Inc. and the Swift project authors Licensed under Apache License v2.0 with Runtime Library Exception @@ -23,7 +23,7 @@ static Boolean _initedMainBundle = false; static CFBundleRef _mainBundle = NULL; static char __CFBundleMainID__[1026] = {0}; -CF_PRIVATE char *__CFBundleMainID = __CFBundleMainID__; +char *__CFBundleMainID = __CFBundleMainID__; static pthread_mutex_t _mainBundleLock = PTHREAD_MUTEX_INITIALIZER; #pragma mark - @@ -40,7 +40,8 @@ static void _CFBundleInitializeMainBundleInfoDictionaryAlreadyLocked(CFStringRef if (executableName) CFRelease(executableName); } #if defined(BINARY_SUPPORT_DYLD) - if (_mainBundle->_binaryType == __CFBundleDYLDExecutableBinary) { + // We can fall into this case when the executable is sandboxed enough that it can't read its own executable file. We can still attempt to get the info dictionary from the main executable though. _CFBundleCreateInfoDictFromMainExecutable will correctly handle a case where the section does not exist. + if (_mainBundle->_binaryType == __CFBundleDYLDExecutableBinary || _mainBundle->_binaryType == __CFBundleUnreadableBinary) { if (_mainBundle->_infoDict) CFRelease(_mainBundle->_infoDict); _mainBundle->_infoDict = (CFDictionaryRef)_CFBundleCreateInfoDictFromMainExecutable(); } diff --git a/CoreFoundation/PlugIn.subproj/CFBundle_Resources.c b/CoreFoundation/PlugIn.subproj/CFBundle_Resources.c index 5f666749b0..554fb7c895 100644 --- a/CoreFoundation/PlugIn.subproj/CFBundle_Resources.c +++ b/CoreFoundation/PlugIn.subproj/CFBundle_Resources.c @@ -1,7 +1,7 @@ /* CFBundle_Resources.c - Copyright (c) 1999-2017, Apple Inc. and the Swift project authors + Copyright (c) 1999-2018, Apple Inc. and the Swift project authors - Portions Copyright (c) 2014-2017, Apple Inc. and the Swift project authors + Portions Copyright (c) 2014-2018, Apple Inc. and the Swift project authors Licensed under Apache License v2.0 with Runtime Library Exception See http://swift.org/LICENSE.txt for license information See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors @@ -300,7 +300,7 @@ CF_EXPORT CFStringRef _CFBundleGetCurrentPlatform(void) { #if TARGET_OS_CYGWIN return CFSTR("Cygwin"); #else - return CFSTR("Linux"); + return CFSTR("Linux"); #endif #elif DEPLOYMENT_TARGET_FREEBSD return CFSTR("FreeBSD"); @@ -322,7 +322,7 @@ CF_PRIVATE CFStringRef _CFBundleGetPlatformExecutablesSubdirectoryName(void) { #if TARGET_OS_CYGWIN return CFSTR("Cygwin"); #else - return CFSTR("Linux"); + return CFSTR("Linux"); #endif #elif DEPLOYMENT_TARGET_FREEBSD return CFSTR("FreeBSD"); @@ -1234,7 +1234,6 @@ CF_EXPORT CFTypeRef _CFBundleCopyFindResources(CFBundleRef bundle, CFURLRef bund return returnValue; } -// for foundation use only! // Note: content must be on disk and pinned before invoking this method CF_EXPORT Boolean _CFBundleAddResourceURL(CFBundleRef bundle, CFURLRef url) { CFBundleRef resourceBundle = CFBundleCreate(kCFAllocatorSystemDefault, url); @@ -1255,7 +1254,6 @@ CF_EXPORT Boolean _CFBundleAddResourceURL(CFBundleRef bundle, CFURLRef url) { return true; } -// for foundation use only! // Note: Content must not be unpinned until this method returns CF_EXPORT Boolean _CFBundleRemoveResourceURL(CFBundleRef bundle, CFURLRef url) { Boolean result = false; diff --git a/CoreFoundation/PlugIn.subproj/CFBundle_Strings.c b/CoreFoundation/PlugIn.subproj/CFBundle_Strings.c index ea3906e90e..3671837a05 100644 --- a/CoreFoundation/PlugIn.subproj/CFBundle_Strings.c +++ b/CoreFoundation/PlugIn.subproj/CFBundle_Strings.c @@ -1,7 +1,7 @@ /* CFBundle_Strings.c - Copyright (c) 1999-2017, Apple Inc. and the Swift project authors + Copyright (c) 1999-2018, Apple Inc. and the Swift project authors - Portions Copyright (c) 2014-2017, Apple Inc. and the Swift project authors + Portions Copyright (c) 2014-2018, Apple Inc. and the Swift project authors Licensed under Apache License v2.0 with Runtime Library Exception See http://swift.org/LICENSE.txt for license information See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors @@ -9,6 +9,8 @@ */ #include "CFBundle_Internal.h" +#include "CFCollections_Internal.h" + #if DEPLOYMENT_TARGET_MACOSX #endif @@ -19,16 +21,16 @@ #pragma mark - #pragma mark Localized Strings -typedef struct { - CFDictionaryRef localizedFormatStringsTable; - CFMutableDictionaryRef result; -} VariableWidthStringContext; +static void __CFStringsDictMergeApplyFunction(const void *key, const void *value, void *context) { + CFDictionarySetValue((CFMutableDictionaryRef)context, key, value); +} CF_EXPORT CFStringRef CFBundleCopyLocalizedString(CFBundleRef bundle, CFStringRef key, CFStringRef value, CFStringRef tableName) { return CFBundleCopyLocalizedStringForLocalization(bundle, key, value, tableName, NULL); } + static CFStringRef _copyStringFromTable(CFBundleRef bundle, CFStringRef tableName, CFStringRef key, CFStringRef localizationName) { // Check the cache first. If it's not there, populate the cache and check again. @@ -92,30 +94,35 @@ static CFStringRef _copyStringFromTable(CFBundleRef bundle, CFStringRef tableNam CFDictionaryRef stringsDictTable = (CFDictionaryRef)CFPropertyListCreateWithData(CFGetAllocator(bundle), tableData, kCFPropertyListImmutable, NULL, &error); CFRelease(tableData); - if (stringsDictTable && CFDictionaryGetTypeID() != CFGetTypeID(stringsDictTable)) { - os_log_error(_CFBundleLocalizedStringLogger(), "Unable to load .stringsdict file: %@ / %@: Top-level object was not a dictionary", bundle, tableName); - CFRelease(stringsDictTable); - stringsDictTable = NULL; - } else if (!stringsDictTable && error) { + if (!stringsDictTable && error) { os_log_error(_CFBundleLocalizedStringLogger(), "Unable to load .stringsdict file: %@ / %@: %@", bundle, tableName, error); CFRelease(error); error = NULL; - } - - // Post-process the strings table - if (stringsDictTable) { + } else if (stringsDictTable && CFDictionaryGetTypeID() != CFGetTypeID(stringsDictTable)) { + os_log_error(_CFBundleLocalizedStringLogger(), "Unable to load .stringsdict file: %@ / %@: Top-level object was not a dictionary", bundle, tableName); + CFRelease(stringsDictTable); + stringsDictTable = NULL; + } else if (stringsDictTable) { + // Post-process the strings table. CFMutableDictionaryRef mutableStringsDictTable; if (stringsTable) { - // Use the strings table as base content for the stringsdict + // Any strings that are in the stringsTable that are not in the stringsDict must be added to the stringsDict. + // However, any entry in the stringsDictTable must override the content from stringsTable. + + // Start by copying the stringsTable. mutableStringsDictTable = CFDictionaryCreateMutableCopy(NULL, 0, stringsTable); + + // Replace any stringsTable entries with entries from stringsDictTable. This will override any entries from the original stringsTable if they existed. + CFDictionaryApplyFunction(stringsDictTable, __CFStringsDictMergeApplyFunction, mutableStringsDictTable); } else { - // Start from scratch with the stringsdict - mutableStringsDictTable = CFDictionaryCreateMutable(NULL, 0, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks); + // Start with a copy of the stringsDictTable on its own. + mutableStringsDictTable = CFDictionaryCreateMutableCopy(NULL, 0, stringsDictTable); } - CFRelease(stringsDictTable); + if (stringsTable) CFRelease(stringsTable); + // The new strings table is the result of all the transforms above. stringsTable = mutableStringsDictTable; } } diff --git a/CoreFoundation/PlugIn.subproj/CFPlugIn.c b/CoreFoundation/PlugIn.subproj/CFPlugIn.c index 6f72b6f4f7..db278107a0 100644 --- a/CoreFoundation/PlugIn.subproj/CFPlugIn.c +++ b/CoreFoundation/PlugIn.subproj/CFPlugIn.c @@ -1,7 +1,7 @@ /* CFPlugIn.c - Copyright (c) 1999-2017, Apple Inc. and the Swift project authors + Copyright (c) 1999-2018, Apple Inc. and the Swift project authors - Portions Copyright (c) 2014-2017, Apple Inc. and the Swift project authors + Portions Copyright (c) 2014-2018, Apple Inc. and the Swift project authors Licensed under Apache License v2.0 with Runtime Library Exception See http://swift.org/LICENSE.txt for license information See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors @@ -17,55 +17,6 @@ CONST_STRING_DECL(kCFPlugInUnloadFunctionKey, "CFPlugInUnloadFunction") CONST_STRING_DECL(kCFPlugInFactoriesKey, "CFPlugInFactories") CONST_STRING_DECL(kCFPlugInTypesKey, "CFPlugInTypes") -CF_PRIVATE void __CFPlugInInitialize(void) { -} - -/* ===================== Finding factories and creating instances ===================== */ -/* For plugIn hosts. */ -/* Functions for finding factories to create specific types and actually creating instances of a type. */ - -CF_EXPORT CFArrayRef CFPlugInFindFactoriesForPlugInType(CFUUIDRef typeID) { - CFArrayRef array = _CFPFactoryFindCopyForType(typeID); - CFMutableArrayRef result = NULL; - - if (array) { - SInt32 i, c = CFArrayGetCount(array); - result = CFArrayCreateMutable(kCFAllocatorSystemDefault, 0, &kCFTypeArrayCallBacks); - for (i = 0; i < c; i++) { - CFUUIDRef factoryId = _CFPFactoryCopyFactoryID((_CFPFactoryRef)CFArrayGetValueAtIndex(array, i)); - if (factoryId) { - CFArrayAppendValue(result, factoryId); - CFRelease(factoryId); - } - } - CFRelease(array); - } - return result; -} - -CF_EXPORT CFArrayRef CFPlugInFindFactoriesForPlugInTypeInPlugIn(CFUUIDRef typeID, CFPlugInRef plugIn) { - CFArrayRef array = _CFPFactoryFindCopyForType(typeID); - CFMutableArrayRef result = NULL; - - if (array) { - SInt32 i, c = CFArrayGetCount(array); - _CFPFactoryRef factory; - result = CFArrayCreateMutable(kCFAllocatorSystemDefault, 0, &kCFTypeArrayCallBacks); - for (i = 0; i < c; i++) { - factory = (_CFPFactoryRef )CFArrayGetValueAtIndex(array, i); - CFPlugInRef factoryPlugIn = _CFPFactoryCopyPlugIn(factory); - if (factoryPlugIn == plugIn) { - CFUUIDRef factoryId = _CFPFactoryCopyFactoryID(factory); - CFArrayAppendValue(result, factoryId); - CFRelease(factoryId); - } - if (factoryPlugIn) CFRelease(factoryPlugIn); - } - CFRelease(array); - } - return result; -} - CF_EXPORT void *CFPlugInInstanceCreate(CFAllocatorRef allocator, CFUUIDRef factoryID, CFUUIDRef typeID) { _CFPFactoryRef factory = _CFPFactoryFind(factoryID, true); void *result = NULL; diff --git a/CoreFoundation/PlugIn.subproj/CFPlugIn.h b/CoreFoundation/PlugIn.subproj/CFPlugIn.h index 78528f2cc9..ce4e1f8bea 100644 --- a/CoreFoundation/PlugIn.subproj/CFPlugIn.h +++ b/CoreFoundation/PlugIn.subproj/CFPlugIn.h @@ -1,7 +1,7 @@ /* CFPlugIn.h - Copyright (c) 1999-2017, Apple Inc. and the Swift project authors + Copyright (c) 1999-2018, Apple Inc. and the Swift project authors - Portions Copyright (c) 2014-2017, Apple Inc. and the Swift project authors + Portions Copyright (c) 2014-2018, Apple Inc. and the Swift project authors Licensed under Apache License v2.0 with Runtime Library Exception See http://swift.org/LICENSE.txt for license information See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors diff --git a/CoreFoundation/PlugIn.subproj/CFPlugInCOM.h b/CoreFoundation/PlugIn.subproj/CFPlugInCOM.h index adb55e943d..b75c8cd1dd 100644 --- a/CoreFoundation/PlugIn.subproj/CFPlugInCOM.h +++ b/CoreFoundation/PlugIn.subproj/CFPlugInCOM.h @@ -1,7 +1,7 @@ /* CFPlugInCOM.h - Copyright (c) 1999-2017, Apple Inc. and the Swift project authors + Copyright (c) 1999-2018, Apple Inc. and the Swift project authors - Portions Copyright (c) 2014-2017, Apple Inc. and the Swift project authors + Portions Copyright (c) 2014-2018, Apple Inc. and the Swift project authors Licensed under Apache License v2.0 with Runtime Library Exception See http://swift.org/LICENSE.txt for license information See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors diff --git a/CoreFoundation/PlugIn.subproj/CFPlugIn_Factory.c b/CoreFoundation/PlugIn.subproj/CFPlugIn_Factory.c index db8e0083dd..2dfde6c72b 100644 --- a/CoreFoundation/PlugIn.subproj/CFPlugIn_Factory.c +++ b/CoreFoundation/PlugIn.subproj/CFPlugIn_Factory.c @@ -1,7 +1,7 @@ /* CFPlugIn_Factory.c - Copyright (c) 1999-2017, Apple Inc. and the Swift project authors + Copyright (c) 1999-2018, Apple Inc. and the Swift project authors - Portions Copyright (c) 2014-2017, Apple Inc. and the Swift project authors + Portions Copyright (c) 2014-2018, Apple Inc. and the Swift project authors Licensed under Apache License v2.0 with Runtime Library Exception See http://swift.org/LICENSE.txt for license information See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors @@ -10,8 +10,7 @@ #include "CFBundle_Internal.h" #include "CFInternal.h" - -static CFTypeID __kCFPFactoryTypeID = _kCFRuntimeNotATypeID; +#include "CFRuntime_Internal.h" struct __CFPFactory { CFRuntimeBase _base; @@ -31,7 +30,7 @@ struct __CFPFactory { static void _CFPFactoryDeallocate(CFTypeRef factory); -static const CFRuntimeClass __CFPFactoryClass = { +const CFRuntimeClass __CFPFactoryClass = { 0, "_CFPFactory", NULL, // init @@ -43,13 +42,8 @@ static const CFRuntimeClass __CFPFactoryClass = { NULL, // debug desc }; -CF_PRIVATE void __CFPFactoryInitialize(void) { - static dispatch_once_t initOnce; - dispatch_once(&initOnce, ^{ __kCFPFactoryTypeID = _CFRuntimeRegisterClass(&__CFPFactoryClass); }); -} - static CFTypeID _CFPFactoryGetTypeID(void) { - return __kCFPFactoryTypeID; + return _kCFRuntimeIDCFPFactory; } static CFLock_t CFPlugInGlobalDataLock = CFLockInit; @@ -272,18 +266,6 @@ CF_PRIVATE Boolean _CFPFactorySupportsType(_CFPFactoryRef factory, CFUUIDRef typ return (idx >= 0 ? true : false); } -CF_PRIVATE CFArrayRef _CFPFactoryFindCopyForType(CFUUIDRef typeID) { - CFArrayRef result = NULL; - __CFLock(&CFPlugInGlobalDataLock); - if (_factoriesByTypeID) { - result = (CFArrayRef)CFDictionaryGetValue(_factoriesByTypeID, typeID); - if (result) CFRetain(result); - } - __CFUnlock(&CFPlugInGlobalDataLock); - - return result; -} - /* These methods are called by CFPlugInInstance when an instance is created or destroyed. If a factory's instance count goes to 0 and the factory has been disabled, the factory is destroyed. */ CF_PRIVATE void _CFPFactoryAddInstance(_CFPFactoryRef factory) { /* MF:!!! Assert that factory is enabled. */ @@ -309,3 +291,63 @@ CF_PRIVATE void _CFPFactoryRemoveInstance(_CFPFactoryRef factory) { } CFRelease(factory); } + +#pragma mark - + +/* ===================== Finding factories and creating instances ===================== */ +/* For plugIn hosts. */ +/* Functions for finding factories to create specific types and actually creating instances of a type. */ + +CF_EXPORT CFArrayRef CFPlugInFindFactoriesForPlugInType(CFUUIDRef typeID) CF_RETURNS_RETAINED { + __CFLock(&CFPlugInGlobalDataLock); + CFArrayRef array = NULL; + if (_factoriesByTypeID) { + array = (CFArrayRef)CFDictionaryGetValue(_factoriesByTypeID, typeID); + } + + CFMutableArrayRef result = NULL; + if (array) { + result = CFArrayCreateMutable(kCFAllocatorSystemDefault, 0, &kCFTypeArrayCallBacks); + + CFIndex c = CFArrayGetCount(array); + for (CFIndex i = 0; i < c; i++) { + CFUUIDRef factoryId = _CFPFactoryCopyFactoryID((_CFPFactoryRef)CFArrayGetValueAtIndex(array, i)); + if (factoryId) { + CFArrayAppendValue(result, factoryId); + CFRelease(factoryId); + } + } + } + + __CFUnlock(&CFPlugInGlobalDataLock); + return result; +} + +CF_EXPORT CFArrayRef CFPlugInFindFactoriesForPlugInTypeInPlugIn(CFUUIDRef typeID, CFPlugInRef plugIn) CF_RETURNS_RETAINED { + __CFLock(&CFPlugInGlobalDataLock); + CFArrayRef array = NULL; + if (_factoriesByTypeID) { + array = (CFArrayRef)CFDictionaryGetValue(_factoriesByTypeID, typeID); + } + + + CFMutableArrayRef result = NULL; + if (array) { + CFIndex c = CFArrayGetCount(array); + result = CFArrayCreateMutable(kCFAllocatorSystemDefault, 0, &kCFTypeArrayCallBacks); + for (CFIndex i = 0; i < c; i++) { + _CFPFactoryRef factory = (_CFPFactoryRef)CFArrayGetValueAtIndex(array, i); + CFPlugInRef factoryPlugIn = _CFPFactoryCopyPlugIn(factory); + if (factoryPlugIn == plugIn) { + CFUUIDRef factoryId = _CFPFactoryCopyFactoryID(factory); + CFArrayAppendValue(result, factoryId); + CFRelease(factoryId); + } + if (factoryPlugIn) CFRelease(factoryPlugIn); + } + } + + __CFUnlock(&CFPlugInGlobalDataLock); + return result; +} + diff --git a/CoreFoundation/PlugIn.subproj/CFPlugIn_Factory.h b/CoreFoundation/PlugIn.subproj/CFPlugIn_Factory.h index e2bb97d7b3..314c3ac215 100644 --- a/CoreFoundation/PlugIn.subproj/CFPlugIn_Factory.h +++ b/CoreFoundation/PlugIn.subproj/CFPlugIn_Factory.h @@ -1,7 +1,7 @@ /* CFPlugIn_Factory.h - Copyright (c) 1999-2017, Apple Inc. and the Swift project authors + Copyright (c) 1999-2018, Apple Inc. and the Swift project authors - Portions Copyright (c) 2014-2017, Apple Inc. and the Swift project authors + Portions Copyright (c) 2014-2018, Apple Inc. and the Swift project authors Licensed under Apache License v2.0 with Runtime Library Exception See http://swift.org/LICENSE.txt for license information See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors @@ -33,7 +33,6 @@ extern void _CFPFactoryAddType(_CFPFactoryRef factory, CFUUIDRef typeID); extern void _CFPFactoryRemoveType(_CFPFactoryRef factory, CFUUIDRef typeID); extern Boolean _CFPFactorySupportsType(_CFPFactoryRef factory, CFUUIDRef typeID); -extern CFArrayRef _CFPFactoryFindCopyForType(CFUUIDRef typeID); /* These methods are called by CFPlugInInstance when an instance is created or destroyed. If a factory's instance count goes to 0 and the factory has been disabled, the factory is destroyed. */ extern void _CFPFactoryAddInstance(_CFPFactoryRef factory); diff --git a/CoreFoundation/PlugIn.subproj/CFPlugIn_Instance.c b/CoreFoundation/PlugIn.subproj/CFPlugIn_Instance.c index a54428d0c9..4cbdd52cc6 100644 --- a/CoreFoundation/PlugIn.subproj/CFPlugIn_Instance.c +++ b/CoreFoundation/PlugIn.subproj/CFPlugIn_Instance.c @@ -1,7 +1,7 @@ /* CFPlugIn_Instance.c - Copyright (c) 1999-2017, Apple Inc. and the Swift project authors + Copyright (c) 1999-2018, Apple Inc. and the Swift project authors - Portions Copyright (c) 2014-2017, Apple Inc. and the Swift project authors + Portions Copyright (c) 2014-2018, Apple Inc. and the Swift project authors Licensed under Apache License v2.0 with Runtime Library Exception See http://swift.org/LICENSE.txt for license information See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors @@ -10,8 +10,7 @@ #include "CFBundle_Internal.h" #include "CFInternal.h" - -static CFTypeID __kCFPlugInInstanceTypeID = _kCFRuntimeNotATypeID; +#include "CFRuntime_Internal.h" struct __CFPlugInInstance { CFRuntimeBase _base; @@ -49,7 +48,7 @@ static void __CFPlugInInstanceDeallocate(CFTypeRef cf) { if (instance->factory) _CFPFactoryRemoveInstance(instance->factory); } -static const CFRuntimeClass __CFPlugInInstanceClass = { +const CFRuntimeClass __CFPlugInInstanceClass = { 0, "CFPlugInInstance", NULL, // init @@ -62,9 +61,7 @@ static const CFRuntimeClass __CFPlugInInstanceClass = { }; CFTypeID CFPlugInInstanceGetTypeID(void) { - static dispatch_once_t initOnce; - dispatch_once(&initOnce, ^{ __kCFPlugInInstanceTypeID = _CFRuntimeRegisterClass(&__CFPlugInInstanceClass); }); - return __kCFPlugInInstanceTypeID; + return _kCFRuntimeIDCFPlugInInstance; } CF_EXPORT CFPlugInInstanceRef CFPlugInInstanceCreateWithInstanceDataSize(CFAllocatorRef allocator, CFIndex instanceDataSize, CFPlugInInstanceDeallocateInstanceDataFunction deallocateInstanceFunction, CFStringRef factoryName, CFPlugInInstanceGetInterfaceFunction getInterfaceFunction) { diff --git a/CoreFoundation/PlugIn.subproj/CFPlugIn_PlugIn.c b/CoreFoundation/PlugIn.subproj/CFPlugIn_PlugIn.c index fd2075e85f..477358ea6f 100644 --- a/CoreFoundation/PlugIn.subproj/CFPlugIn_PlugIn.c +++ b/CoreFoundation/PlugIn.subproj/CFPlugIn_PlugIn.c @@ -1,7 +1,7 @@ /* CFPlugIn_PlugIn.c - Copyright (c) 1999-2017, Apple Inc. and the Swift project authors + Copyright (c) 1999-2018, Apple Inc. and the Swift project authors - Portions Copyright (c) 2014-2017, Apple Inc. and the Swift project authors + Portions Copyright (c) 2014-2018, Apple Inc. and the Swift project authors Licensed under Apache License v2.0 with Runtime Library Exception See http://swift.org/LICENSE.txt for license information See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors diff --git a/CoreFoundation/Preferences.subproj/CFApplicationPreferences.c b/CoreFoundation/Preferences.subproj/CFApplicationPreferences.c index 046efe7cab..c587cbc205 100644 --- a/CoreFoundation/Preferences.subproj/CFApplicationPreferences.c +++ b/CoreFoundation/Preferences.subproj/CFApplicationPreferences.c @@ -1,7 +1,7 @@ /* CFApplicationPreferences.c - Copyright (c) 1998-2017, Apple Inc. and the Swift project authors + Copyright (c) 1998-2018, Apple Inc. and the Swift project authors - Portions Copyright (c) 2014-2017, Apple Inc. and the Swift project authors + Portions Copyright (c) 2014-2018, Apple Inc. and the Swift project authors Licensed under Apache License v2.0 with Runtime Library Exception See http://swift.org/LICENSE.txt for license information See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors @@ -17,7 +17,7 @@ #include #include #include -#if DEPLOYMENT_TARGET_MACOSX || DEPLOYMENT_TARGET_EMBEDDED || DEPLOYMENT_TARGET_LINUX +#if DEPLOYMENT_TARGET_MACOSX || DEPLOYMENT_TARGET_EMBEDDED #include #endif @@ -25,8 +25,24 @@ static Boolean _CFApplicationPreferencesSynchronizeNoLock(_CFApplicationPreferen void _CFPreferencesDomainSetMultiple(CFPreferencesDomainRef domain, CFDictionaryRef dict); static void updateDictRep(_CFApplicationPreferences *self); static void _CFApplicationPreferencesSetSearchList(_CFApplicationPreferences *self, CFArrayRef newSearchList); +void _CFApplicationPreferencesSet(_CFApplicationPreferences *self, CFStringRef defaultName, CFTypeRef value); +void _CFApplicationPreferencesRemove(_CFApplicationPreferences *self, CFStringRef defaultName); +void _CFDeallocateApplicationPreferences(_CFApplicationPreferences *self); +Boolean _CFApplicationPreferencesSynchronize(_CFApplicationPreferences *self); Boolean _CFApplicationPreferencesContainsDomainNoLock(_CFApplicationPreferences *self, CFPreferencesDomainRef domain); +void _CFApplicationPreferencesAddSuitePreferences(_CFApplicationPreferences *appPrefs, CFStringRef suiteName); +void _CFApplicationPreferencesRemoveSuitePreferences(_CFApplicationPreferences *appPrefs, CFStringRef suiteName); static CFTypeRef _CFApplicationPreferencesCreateValueForKey2(_CFApplicationPreferences *self, CFStringRef defaultName); +void _CFApplicationPreferencesRemoveDomain(_CFApplicationPreferences *self, CFPreferencesDomainRef domain); + +CF_PRIVATE void _CFPreferencesDomainSet(CFPreferencesDomainRef domain, CFStringRef key, CFTypeRef _Nullable value); +CF_PRIVATE CFDictionaryRef _CFPreferencesDomainDeepCopyDictionary(CFPreferencesDomainRef domain); +CF_PRIVATE void _CFPreferencesPurgeDomainCache(void); +CF_PRIVATE CFPreferencesDomainRef _CFPreferencesStandardDomain(CFStringRef domainName, CFStringRef userName, CFStringRef hostName); +CF_PRIVATE Boolean _CFSynchronizeDomainCache(void); +CF_PRIVATE CFAllocatorRef __CFPreferencesAllocator(void); +CF_PRIVATE _CFApplicationPreferences *_CFStandardApplicationPreferences(CFStringRef appName); + // Right now, nothing is getting destroyed pretty much ever. We probably don't want this to be the case, but it's very tricky - domains live in the cache as well as a given application's preferences, and since they're not CFTypes, there's no reference count. Also, it's not clear we ever want domains destroyed. When they're synchronized, they clear their internal state (to force reading from the disk again), so they're not very big.... REW, 12/17/98 diff --git a/CoreFoundation/Preferences.subproj/CFPreferences.c b/CoreFoundation/Preferences.subproj/CFPreferences.c index 19cd77be97..901ff4fec5 100644 --- a/CoreFoundation/Preferences.subproj/CFPreferences.c +++ b/CoreFoundation/Preferences.subproj/CFPreferences.c @@ -1,7 +1,7 @@ /* CFPreferences.c - Copyright (c) 1998-2017, Apple Inc. and the Swift project authors + Copyright (c) 1998-2018, Apple Inc. and the Swift project authors - Portions Copyright (c) 2014-2017, Apple Inc. and the Swift project authors + Portions Copyright (c) 2014-2018, Apple Inc. and the Swift project authors Licensed under Apache License v2.0 with Runtime Library Exception See http://swift.org/LICENSE.txt for license information See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors @@ -26,12 +26,24 @@ #include #endif -#include - #if DEBUG_PREFERENCES_MEMORY #include "../Tests/CFCountingAllocator.c" #endif +#include +#include "CFRuntime_Internal.h" +#include "CFKnownLocations.h" + +CF_PRIVATE Boolean _CFPreferencesDomainSynchronize(CFPreferencesDomainRef domain); +CF_PRIVATE void _CFPreferencesDomainSetIsWorldReadable(CFPreferencesDomainRef domain, Boolean isWorldReadable); +CF_PRIVATE CFArrayRef _CFPreferencesCreateDomainList(CFStringRef userName, CFStringRef hostName); +CF_PRIVATE const _CFPreferencesDomainCallBacks __kCFXMLPropertyListDomainCallBacks; + +void _CFPreferencesDomainSet(CFPreferencesDomainRef domain, CFStringRef key, CFTypeRef value); +CFTypeRef _CFPreferencesDomainCreateValueForKey(CFPreferencesDomainRef domain, CFStringRef key); +CFPreferencesDomainRef _CFPreferencesStandardDomain(CFStringRef domainName, CFStringRef userName, CFStringRef hostName); +CFPreferencesDomainRef _CFPreferencesDomainCreate(CFTypeRef context, const _CFPreferencesDomainCallBacks *callBacks); +CFDictionaryRef _CFPreferencesDomainDeepCopyDictionary(CFPreferencesDomainRef domain); static CFURLRef _CFPreferencesURLForStandardDomainWithSafetyLevel(CFStringRef domainName, CFStringRef userName, CFStringRef hostName, unsigned long safeLevel); struct __CFPreferencesDomain { @@ -63,7 +75,7 @@ CF_PRIVATE CFAllocatorRef __CFPreferencesAllocator(void) { return _preferencesAllocator; } -// declaration for telling the +// declaration for telling the void _CFApplicationPreferencesDomainHasChanged(CFPreferencesDomainRef); #if DEBUG_PREFERENCES_MEMORY @@ -386,9 +398,7 @@ static void __CFPreferencesDomainDeallocate(CFTypeRef cf) { if (domain->_context) CFRelease(domain->_context); } -static CFTypeID __kCFPreferencesDomainTypeID = _kCFRuntimeNotATypeID; - -static const CFRuntimeClass __CFPreferencesDomainClass = { +const CFRuntimeClass __CFPreferencesDomainClass = { 0, "CFPreferencesDomain", NULL, // init @@ -396,7 +406,7 @@ static const CFRuntimeClass __CFPreferencesDomainClass = { __CFPreferencesDomainDeallocate, NULL, NULL, - NULL, // + NULL, // __CFPreferencesDomainCopyDescription }; @@ -526,7 +536,7 @@ CFPreferencesDomainRef _CFPreferencesStandardDomain(CFStringRef domainName, CFS domain = checkDomain; // repoint it at the domain picked up out of the cache. } else { // We must not have found the domain in the cache, so it's ok for us to put this in. - CFDictionarySetValue(domainCache, domainKey, domain); + CFDictionarySetValue(domainCache, domainKey, domain); } if(shouldReleaseDomain) CFRelease(domain); } @@ -562,7 +572,7 @@ CF_PRIVATE void _CFPreferencesPurgeDomainCache(void) { __CFUnlock(&domainCacheLock); } -CF_PRIVATE CFArrayRef _CFPreferencesCreateDomainList(CFStringRef userName, CFStringRef hostName) { +CF_PRIVATE CFArrayRef _CFPreferencesCreateDomainList(CFStringRef userName, CFStringRef hostName) { CFAllocatorRef prefAlloc = __CFPreferencesAllocator(); CFArrayRef domains; CFMutableArrayRef marray; @@ -665,12 +675,10 @@ CF_PRIVATE CFArrayRef _CFPreferencesCreateDomainList(CFStringRef userName, CFS // CFPreferencesDomainRef _CFPreferencesDomainCreate(CFTypeRef context, const _CFPreferencesDomainCallBacks *callBacks) { - static dispatch_once_t initOnce; - dispatch_once(&initOnce, ^{ __kCFPreferencesDomainTypeID = _CFRuntimeRegisterClass(&__CFPreferencesDomainClass); }); CFAllocatorRef alloc = __CFPreferencesAllocator(); CFPreferencesDomainRef newDomain; CFAssert(callBacks != NULL && callBacks->createDomain != NULL && callBacks->freeDomain != NULL && callBacks->fetchValue != NULL && callBacks->writeValue != NULL, __kCFLogAssertion, "Cannot create a domain with NULL callbacks"); - newDomain = (CFPreferencesDomainRef)_CFRuntimeCreateInstance(alloc, __kCFPreferencesDomainTypeID, sizeof(struct __CFPreferencesDomain) - sizeof(CFRuntimeBase), NULL); + newDomain = (CFPreferencesDomainRef)_CFRuntimeCreateInstance(alloc, _kCFRuntimeIDCFPreferencesDomain, sizeof(struct __CFPreferencesDomain) - sizeof(CFRuntimeBase), NULL); if (newDomain) { newDomain->_callBacks = callBacks; if (context) CFRetain(context); diff --git a/CoreFoundation/Preferences.subproj/CFPreferences.h b/CoreFoundation/Preferences.subproj/CFPreferences.h index 6597e5303d..c37cf7c26b 100644 --- a/CoreFoundation/Preferences.subproj/CFPreferences.h +++ b/CoreFoundation/Preferences.subproj/CFPreferences.h @@ -1,7 +1,7 @@ /* CFPreferences.h - Copyright (c) 1998-2017, Apple Inc. and the Swift project authors + Copyright (c) 1998-2018, Apple Inc. and the Swift project authors - Portions Copyright (c) 2014-2017, Apple Inc. and the Swift project authors + Portions Copyright (c) 2014-2018, Apple Inc. and the Swift project authors Licensed under Apache License v2.0 with Runtime Library Exception See http://swift.org/LICENSE.txt for license information See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors @@ -93,7 +93,7 @@ keysToFetch that are not present in the returned dictionary are not present in the domain. If keysToFetch is NULL, all keys are fetched. */ CF_EXPORT -_Nullable CFDictionaryRef CFPreferencesCopyMultiple(_Nullable CFArrayRef keysToFetch, CFStringRef applicationID, CFStringRef userName, CFStringRef hostName); +CFDictionaryRef CFPreferencesCopyMultiple(_Nullable CFArrayRef keysToFetch, CFStringRef applicationID, CFStringRef userName, CFStringRef hostName); /* The primitive set function; all arguments except value must be non-NULL. If value is NULL, the given key is removed */ diff --git a/CoreFoundation/Preferences.subproj/CFXMLPreferencesDomain.c b/CoreFoundation/Preferences.subproj/CFXMLPreferencesDomain.c index f5f55476b8..1b767091f0 100644 --- a/CoreFoundation/Preferences.subproj/CFXMLPreferencesDomain.c +++ b/CoreFoundation/Preferences.subproj/CFXMLPreferencesDomain.c @@ -1,7 +1,7 @@ /* CFXMLPreferencesDomain.c - Copyright (c) 1998-2017, Apple Inc. and the Swift project authors + Copyright (c) 1998-2018, Apple Inc. and the Swift project authors - Portions Copyright (c) 2014-2017, Apple Inc. and the Swift project authors + Portions Copyright (c) 2014-2018, Apple Inc. and the Swift project authors Licensed under Apache License v2.0 with Runtime Library Exception See http://swift.org/LICENSE.txt for license information See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors @@ -16,12 +16,10 @@ #include #include "CFInternal.h" #include -#if DEPLOYMENT_TARGET_MACOSX || DEPLOYMENT_TARGET_LINUX +#if DEPLOYMENT_TARGET_MACOSX #include #include #include -#endif -#if DEPLOYMENT_TARGET_MACOSX #include #include #endif @@ -46,7 +44,10 @@ static void getXMLKeysAndValues(CFAllocatorRef alloc, CFTypeRef context, void *x static CFDictionaryRef copyXMLDomainDictionary(CFTypeRef context, void *domain); static void setXMLDomainIsWorldReadable(CFTypeRef context, void *domain, Boolean isWorldReadable); -CF_PRIVATE const _CFPreferencesDomainCallBacks __kCFXMLPropertyListDomainCallBacks = {createXMLDomain, freeXMLDomain, fetchXMLValue, writeXMLValue, synchronizeXMLDomain, getXMLKeysAndValues, copyXMLDomainDictionary, setXMLDomainIsWorldReadable}; +CF_PRIVATE const _CFPreferencesDomainCallBacks __kCFXMLPropertyListDomainCallBacks; +const _CFPreferencesDomainCallBacks __kCFXMLPropertyListDomainCallBacks = {createXMLDomain, freeXMLDomain, fetchXMLValue, writeXMLValue, synchronizeXMLDomain, getXMLKeysAndValues, copyXMLDomainDictionary, setXMLDomainIsWorldReadable}; + +CF_PRIVATE CFAllocatorRef __CFPreferencesAllocator(void); // Directly ripped from Foundation.... static void __CFMilliSleep(uint32_t msecs) { diff --git a/CoreFoundation/RunLoop.subproj/CFMachPort.c b/CoreFoundation/RunLoop.subproj/CFMachPort.c index 47731f40a5..33b8f74f18 100644 --- a/CoreFoundation/RunLoop.subproj/CFMachPort.c +++ b/CoreFoundation/RunLoop.subproj/CFMachPort.c @@ -1,7 +1,7 @@ /* CFMachPort.c - Copyright (c) 1998-2017, Apple Inc. and the Swift project authors + Copyright (c) 1998-2018, Apple Inc. and the Swift project authors - Portions Copyright (c) 2014-2017, Apple Inc. and the Swift project authors + Portions Copyright (c) 2014-2018, Apple Inc. and the Swift project authors Licensed under Apache License v2.0 with Runtime Library Exception See http://swift.org/LICENSE.txt for license information See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors @@ -19,7 +19,8 @@ #include #include #include "CFInternal.h" -#include +#include "CFRuntime_Internal.h" +#include "CFMachPort_Lifetime.h" // This queue is used for the cancel/event handler for dead name notification. @@ -28,170 +29,11 @@ static dispatch_queue_t _CFMachPortQueue() { static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ dispatch_queue_attr_t dqattr = dispatch_queue_attr_make_with_qos_class(DISPATCH_QUEUE_SERIAL, QOS_CLASS_BACKGROUND, 0); - __CFMachPortQueue = dispatch_queue_create("com.apple.CFMachPort", dispatch_queue_attr_make_with_overcommit(dqattr, true)); + __CFMachPortQueue = dispatch_queue_create("com.apple.CFMachPort", dqattr); }); return __CFMachPortQueue; } -// NOTE: all _cfmp_ prefixed state/functions exist to orchestrate the exact time/circumstances we want to call _cfmp_mod_refs. -CF_INLINE void _cfmp_mod_refs(const mach_port_t port, const Boolean doSend, const Boolean doReceive) { - // MUST deallocate the send right FIRST if necessary, - // then the receive right if necessary. Don't ask me why; - // if it's done in the other order the port will leak. - if (doSend) { - mach_port_mod_refs(mach_task_self(), port, MACH_PORT_RIGHT_SEND, -1); - } - if (doReceive) { - mach_port_mod_refs(mach_task_self(), port, MACH_PORT_RIGHT_RECEIVE, -1); - } -} - -// Records information relevant for cleaning up after a given mach port. It has states: -// port & invalidated -- dispatch_source invalidated, but _CFMachPortDeallocate has yet to be called -// port & doSend & doReceive -- _CFMachPortDeallocate has been called, but dispatch_source not yet invalidate -typedef struct { - mach_port_t port; - uint8_t doSend:1; - uint8_t doReceive:1; - uint8_t invalidated:1; // flag to indicate that the source has already been invalidated and the port can be cleaned up inline during deallocation - uint8_t unused:5; -} _cfmp_deallocation_record; -// Various CFSet callbacks for _cfmp_deallocation_record -Boolean _cfmp_equal(const void *value1, const void *value2) { - Boolean equal = false; - if (value1 && value2) { - if (value1 == value2) { - equal = true; - } else { - const _cfmp_deallocation_record R1 = *(_cfmp_deallocation_record *)value1; - const _cfmp_deallocation_record R2 = *(_cfmp_deallocation_record *)value2; - equal = R1.port == R2.port; - } - } - return equal; -} -CFHashCode _cfmp_hash(const void *value) { - CFHashCode hash = 0; - if (value) { - const _cfmp_deallocation_record R = *(_cfmp_deallocation_record *)value; - hash = _CFHashInt(R.port); - } - return hash; -} -void _cfmp_deallocation_record_release(CFAllocatorRef allocator, const void *value) { - free((_cfmp_deallocation_record *)value); -} -CFStringRef _cfmp_copy_description(const void *value) { - CFStringRef s = CFSTR("{null}"); - if (value) { - const _cfmp_deallocation_record R = *(_cfmp_deallocation_record *)value; - s = CFStringCreateWithFormat(NULL, NULL, CFSTR("{p:%d,s:%d,r:%d,i:%d}"), R.port, R.doSend, R.doReceive, R.invalidated); - } - return s; -} -CF_BREAKPOINT_FUNCTION(void _CFMachPortDeallocationFailure(void)); -void _cfmp_log_failure(const char *const msg, _cfmp_deallocation_record *pr) { - if (pr) { - const _cfmp_deallocation_record R = *pr; - os_log(OS_LOG_DEFAULT, "*** %{public}s break on '_CFMachPortDeallocationFailure' to debug: {p:%{private}d,s:%d,r:%d,i:%d}", msg, R.port, R.doSend, R.doReceive, R.invalidated); - } - else { - os_log(OS_LOG_DEFAULT, "*** %{public}s break on '_CFMachPortDeallocationFailure' to debug: {null}", msg); - } - _CFMachPortDeallocationFailure(); -} - -// all pending deallocates are recording in this global set, if there are every -static os_unfair_lock _cfmp_records_lock = OS_UNFAIR_LOCK_INIT; -CF_INLINE CFMutableSetRef _cfmp_records() { // mutations of result GuardedBy(_cfmp_records_lock) - static CFSetCallBacks oCallbacks; - static CFMutableSetRef oRecords; - static dispatch_once_t oGuard; - dispatch_once(&oGuard, ^{ - oCallbacks.hash = _cfmp_hash; - oCallbacks.equal = _cfmp_equal; - oCallbacks.release = _cfmp_deallocation_record_release; - oCallbacks.copyDescription = _cfmp_copy_description; - oRecords = CFSetCreateMutable(NULL, 16, &oCallbacks); - }); - return oRecords; -}; -CF_INLINE _cfmp_deallocation_record *_cfmp_find_record_for_port(CFSetRef records, const mach_port_t port) { - _cfmp_deallocation_record lookup = {.port = port}; - _cfmp_deallocation_record *pr = (_cfmp_deallocation_record *)CFSetGetValue(records, &lookup); - return pr; -} -CF_INLINE void _cfmp_record_deallocation(const mach_port_t port, const Boolean doSend, const Boolean doReceive) { - if (port == MACH_PORT_NULL) { return; } - if (doSend == false && doReceive == false) { return; } - - // now that we know we're not a no-op, look for an existing deallocation record - CFMutableSetRef records = _cfmp_records(); - Boolean cleanupNow = false; - _cfmp_deallocation_record R; - - os_unfair_lock_lock(&_cfmp_records_lock); - _cfmp_deallocation_record *pr = _cfmp_find_record_for_port(records, port); - if (pr) { - // if we have a pr it means we're expecting invalidation. which has either happened or not. if not, record doSend/Receive for later, otherwise get ready to handle it. - R = *(_cfmp_deallocation_record *)pr; - if (R.invalidated) { - cleanupNow = true; - R.port = port; - R.doSend = doSend; - R.doReceive = doReceive; - CFSetRemoveValue(records, pr); - } else { - pr->doSend = doSend; - pr->doReceive = doReceive; - } - } else { - cleanupNow = true; - R.port = port; - R.doSend = doSend; - R.doReceive = doReceive; - } - os_unfair_lock_unlock(&_cfmp_records_lock); - - if (cleanupNow) { - _cfmp_mod_refs(R.port, R.doSend, R.doReceive); - } -} -CF_INLINE void _cfmp_record_intent_to_invalidate(const mach_port_t port) { - CFMutableSetRef records = _cfmp_records(); - _cfmp_deallocation_record *pr = calloc(1, sizeof(_cfmp_deallocation_record)); - if (pr) { - pr->port = port; - os_unfair_lock_lock(&_cfmp_records_lock); - CFSetAddValue(records, pr); - os_unfair_lock_unlock(&_cfmp_records_lock); - } -} -CF_INLINE void _cfmp_source_invalidated(mach_port_t port) { - Boolean cleanupNow = false; - _cfmp_deallocation_record R; - - CFMutableSetRef records = _cfmp_records(); - os_unfair_lock_lock(&_cfmp_records_lock); - _cfmp_deallocation_record *pr = _cfmp_find_record_for_port(records, port); - if (pr) { - R = *(_cfmp_deallocation_record *)pr; - if (!R.invalidated) { - cleanupNow = true; - CFSetRemoveValue(records, pr); - } else { - _cfmp_log_failure("already invalidated", pr); - } - } else { - _cfmp_log_failure("not expecting invalidation", pr); - } - os_unfair_lock_unlock(&_cfmp_records_lock); - - if (cleanupNow) { - _cfmp_mod_refs(R.port, R.doSend, R.doReceive); - } -} - enum { kCFMachPortStateReady = 0, kCFMachPortStateInvalidating = 1, @@ -323,7 +165,7 @@ static void __CFMachPortDeallocate(CFTypeRef cf) { const Boolean doSend = __CFMachPortHasSend(mp), doReceive = __CFMachPortHasReceive(mp); __CFUnlock(&mp->_lock); - _cfmp_record_deallocation(port, doSend, doReceive); + _cfmp_record_deallocation(_CFMPLifetimeClientCFMachPort, port, doSend, doReceive); } @@ -339,6 +181,9 @@ static Boolean __CFMachPortCheck(mach_port_t port) { return (KERN_SUCCESS != ret || (0 == (type & MACH_PORT_TYPE_PORT_RIGHTS))) ? false : true; } +// This function exists regardless of platform, but is only declared in headers for legacy clients. +CF_EXPORT CFIndex CFGetRetainCount(CFTypeRef object); + static void __CFMachPortChecker(Boolean fromTimer) { __CFLock(&__CFAllMachPortsLock); // take this lock first before any instance-specific lock for (CFIndex idx = 0, cnt = __CFAllMachPorts ? CFArrayGetCount(__CFAllMachPorts) : 0; idx < cnt; idx++) { @@ -385,9 +230,7 @@ static void __CFMachPortChecker(Boolean fromTimer) { }; -static CFTypeID __kCFMachPortTypeID = _kCFRuntimeNotATypeID; - -static const CFRuntimeClass __CFMachPortClass = { +const CFRuntimeClass __CFMachPortClass = { 0, "CFMachPort", NULL, // init @@ -400,9 +243,7 @@ static const CFRuntimeClass __CFMachPortClass = { }; CFTypeID CFMachPortGetTypeID(void) { - static dispatch_once_t initOnce; - dispatch_once(&initOnce, ^{ __kCFMachPortTypeID = _CFRuntimeRegisterClass(&__CFMachPortClass); }); - return __kCFMachPortTypeID; + return _kCFRuntimeIDCFMachPort; } /* Note: any receive or send rights that the port contains coming in will @@ -422,18 +263,6 @@ CFMachPortRef _CFMachPortCreateWithPort2(CFAllocatorRef allocator, mach_port_t p return NULL; } -#if 0 - static dispatch_source_t timerSource = NULL; - static dispatch_once_t onceToken; - dispatch_once(&onceToken, ^{ - timerSource = dispatch_source_create(DISPATCH_SOURCE_TYPE_INTERVAL, 60 * 1000 /* milliseconds */, 0, _CFMachPortQueue()); - dispatch_source_set_event_handler(timerSource, ^{ - __CFMachPortChecker(true); - }); - dispatch_resume(timerSource); - }); -#endif - CFMachPortRef mp = NULL; __CFLock(&__CFAllMachPortsLock); for (CFIndex idx = 0, cnt = __CFAllMachPorts ? CFArrayGetCount(__CFAllMachPorts) : 0; idx < cnt; idx++) { @@ -481,11 +310,11 @@ CFMachPortRef _CFMachPortCreateWithPort2(CFAllocatorRef allocator, mach_port_t p if (shouldFreeInfo) *shouldFreeInfo = false; if (type & MACH_PORT_TYPE_SEND_RIGHTS) { - _cfmp_record_intent_to_invalidate(port); + _cfmp_record_intent_to_invalidate(_CFMPLifetimeClientCFMachPort, port); dispatch_source_t theSource = dispatch_source_create(DISPATCH_SOURCE_TYPE_MACH_SEND, port, DISPATCH_MACH_SEND_DEAD, _CFMachPortQueue()); if (theSource) { dispatch_source_set_cancel_handler(theSource, ^{ - _cfmp_source_invalidated(port); + _cfmp_source_invalidated(_CFMPLifetimeClientCFMachPort, port); dispatch_release(theSource); }); dispatch_source_set_event_handler(theSource, ^{ __CFMachPortChecker(false); }); @@ -515,12 +344,19 @@ CFMachPortRef CFMachPortCreate(CFAllocatorRef allocator, CFMachPortCallBack call ret = mach_port_insert_right(mach_task_self(), port, port, MACH_MSG_TYPE_MAKE_SEND); } if (KERN_SUCCESS != ret) { - if (MACH_PORT_NULL != port) mach_port_destroy(mach_task_self(), port); + if (MACH_PORT_NULL != port) { + // inserting the send right failed, so only decrement the receive + mach_port_mod_refs(mach_task_self(), port, MACH_PORT_RIGHT_RECEIVE, -1); + } return NULL; } CFMachPortRef result = _CFMachPortCreateWithPort2(allocator, port, callout, context, shouldFreeInfo, true); if (NULL == result) { - if (MACH_PORT_NULL != port) mach_port_destroy(mach_task_self(), port); + if (MACH_PORT_NULL != port) { + // both receive and send succeeded above so decrement both + mach_port_mod_refs(mach_task_self(), port, MACH_PORT_RIGHT_RECEIVE, -1); + mach_port_deallocate(mach_task_self(), port); + } return NULL; } __CFMachPortSetHasReceive(result); @@ -699,3 +535,27 @@ CFRunLoopSourceRef CFMachPortCreateRunLoopSource(CFAllocatorRef allocator, CFMac return result; } +void __CFMachMessageCheckForAndDestroyUnsentMessage(kern_return_t const kr, mach_msg_header_t *const msg) { + switch (kr) { + case MACH_SEND_TIMEOUT: + case MACH_SEND_INTERRUPTED: { + // pseudo-receive + mach_port_t const localPort = msg->msgh_local_port; + if (MACH_PORT_VALID(localPort)) { + // handle pseudo-receive of local_port + mach_msg_bits_t const mbits = MACH_MSGH_BITS_LOCAL(msg->msgh_bits); + if (mbits == MACH_MSG_TYPE_MOVE_SEND || mbits == MACH_MSG_TYPE_MOVE_SEND_ONCE) { + mach_port_deallocate(mach_task_self(), localPort); + } + msg->msgh_bits &= ~MACH_MSGH_BITS_LOCAL_MASK; + } + } // fallthrough + case MACH_SEND_INVALID_HEADER: + case MACH_SEND_INVALID_DEST: + case MACH_SEND_INVALID_REPLY: + case MACH_SEND_INVALID_VOUCHER: + // destroy unsent message + mach_msg_destroy(msg); + break; + } +} diff --git a/CoreFoundation/RunLoop.subproj/CFMachPort.h b/CoreFoundation/RunLoop.subproj/CFMachPort.h index e21c5af87b..f9371a7718 100644 --- a/CoreFoundation/RunLoop.subproj/CFMachPort.h +++ b/CoreFoundation/RunLoop.subproj/CFMachPort.h @@ -1,7 +1,7 @@ /* CFMachPort.h - Copyright (c) 1998-2017, Apple Inc. and the Swift project authors + Copyright (c) 1998-2018, Apple Inc. and the Swift project authors - Portions Copyright (c) 2014-2017, Apple Inc. and the Swift project authors + Portions Copyright (c) 2014-2018, Apple Inc. and the Swift project authors Licensed under Apache License v2.0 with Runtime Library Exception See http://swift.org/LICENSE.txt for license information See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors diff --git a/CoreFoundation/RunLoop.subproj/CFMachPort_Internal.h b/CoreFoundation/RunLoop.subproj/CFMachPort_Internal.h new file mode 100644 index 0000000000..2e33e76588 --- /dev/null +++ b/CoreFoundation/RunLoop.subproj/CFMachPort_Internal.h @@ -0,0 +1,19 @@ +/* CFMachPort_Internal.h + Copyright (c) 1998-2017, Apple Inc. and the Swift project authors + + Portions Copyright (c) 2014-2017, Apple Inc. and the Swift project authors + Licensed under Apache License v2.0 with Runtime Library Exception + See http://swift.org/LICENSE.txt for license information + See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors + */ + +#if TARGET_OS_MAC + +/// Encapsulates the complexities of cleaning up after unsent mach messages. +/// Call this after you mach_msg to clean up in case of errors. +/// +/// @param kr return value of mach_msg +/// @param msg that was attempted to be sent +CF_EXPORT void __CFMachMessageCheckForAndDestroyUnsentMessage(kern_return_t const kr, mach_msg_header_t *const msg); + +#endif diff --git a/CoreFoundation/RunLoop.subproj/CFMachPort_Lifetime.c b/CoreFoundation/RunLoop.subproj/CFMachPort_Lifetime.c new file mode 100644 index 0000000000..b305aec0c6 --- /dev/null +++ b/CoreFoundation/RunLoop.subproj/CFMachPort_Lifetime.c @@ -0,0 +1,293 @@ +/* + CFMachPort_Lifetime.h + Copyright (c) 1998-2018, Apple Inc. and the Swift project authors + + All of the functions in this file exist to orchestrate the exact time/circumstances we decrement the port references. + */ + +#import "CFMachPort_Lifetime.h" +#import +#import "CFInternal.h" + +// Records information relevant for cleaning up after a given mach port. Here's +// a summary of its life cycle: +// A) _cfmp_deallocation_record created and stored in _cfmp_records +// This means a dispatch source has been created to track dead name for +// the port. +// B) There is no record for a given port in _cfmp_records +// This means either: the dispatch source above has been cancelled, or that +// there was a never a dispatch source in the first place. +// +// For pure CFMachPorts with no Foundation NSPort references, the flags doSend +// and doReceive record the kind of rights a given port should clear up when +// the cancel handler is called. +// +// The reason for this is that the Deallocate of a CFMachPort can happen before +// the cancel handler has been called, and historically the deallocate was the +// where the rights would be decremented. +// +// When NSPort's are involved, we track a few other bits for exactly the same +// reasons. The reason these are tracked seperately is out of an abundance of +// caution - by all reads, the two mechanisms do not overlap, but tracking them +// seperate is more debugable. +// +typedef struct { + mach_port_t port; // which port (contributes to identity) + uint8_t client; // which subsystem is tracking (contributes to identity) + // should be kept in sync with MAX_CLIENTS constants below + + uint8_t inSet:1; // helps detect invariant violations + + uint8_t deallocated:1; + uint8_t invalidated:1; + + uint8_t doSend:1; + uint8_t doReceive:1; + + // indicates that there is additional invalidation requested by NSMachPort + uint8_t nsportIsInterested:1; + uint8_t nsportDoSend:1; + uint8_t nsportDoReceive:1; +} _cfmp_deallocation_record; + +#define MAX_CLIENTS 256 +#define MAX_CLIENTS_BITS 8 + +#pragma mark - Port Right Modification +CF_INLINE void _cfmp_mod_refs(mach_port_t const port, const Boolean doSend, const Boolean doReceive) { + // NOTE: do receive right first per: https://howto.apple.com/wiki/pages/r853A7H2j/Mach_Ports_and_You.html + if (doReceive) { + mach_port_mod_refs(mach_task_self(), port, MACH_PORT_RIGHT_RECEIVE, -1); + } + if (doSend) { + mach_port_deallocate(mach_task_self(), port); + } +} + +#pragma mark - Logging +CF_BREAKPOINT_FUNCTION(void _CFMachPortDeallocationFailure(void)); +static void _cfmp_log_failure(char const *const msg, _cfmp_deallocation_record *const pr, _CFMPLifetimeClient const client, mach_port_t const port) { + if (pr) { + _cfmp_deallocation_record const R = *pr; + os_log_error(OS_LOG_DEFAULT, "*** %{public}s break on '_CFMachPortDeallocationFailure' to debug: {p:%{private}d c:%d is:%d s:%d,r:%d nsi:%d,nss:%d,nsr:%d - ic:%d,ip:%d}", msg, R.port, R.client, R.inSet, R.invalidated, R.deallocated, R.doSend, R.doReceive, R.nsportIsInterested, R.nsportDoSend, R.nsportDoReceive, client, port); + } else { + os_log_error(OS_LOG_DEFAULT, "*** %{public}s break on '_CFMachPortDeallocationFailure' to debug: {null - ic:%d,ip:%d}", msg, client, port); + } + _CFMachPortDeallocationFailure(); +} + + + +#pragma mark - _cfmp_deallocation_record CFSet Callbacks +// Various CFSet callbacks for _cfmp_deallocation_record +static CFTypeRef _cfmp_deallocation_record_retain(CFAllocatorRef allocator, CFTypeRef const cf) { + _cfmp_deallocation_record *const pr = (_cfmp_deallocation_record *)cf; + if (pr->inSet) { + HALT_MSG("refcnt overflow"); + } + pr->inSet = 1; + return pr; +} +static Boolean _cfmp_equal(void const *const value1, void const *const value2) { + Boolean equal = false; + if (value1 == value2) { + equal = true; + } else if (value1 && value2){ + _cfmp_deallocation_record const R1 = *(_cfmp_deallocation_record *)value1; + _cfmp_deallocation_record const R2 = *(_cfmp_deallocation_record *)value2; + equal = R1.port == R2.port && R1.client == R2.client; + } + return equal; +} +static CFHashCode _cfmp_hash(void const *const value) { + CFHashCode hash = 0; + if (value) { + _cfmp_deallocation_record const R = *(_cfmp_deallocation_record *)value; + hash = _CFHashInt(R.port << MAX_CLIENTS_BITS | R.client); + } + return hash; +} +static void _cfmp_deallocation_record_release(CFAllocatorRef const allocator, void const *const value) { + _cfmp_deallocation_record *pr = (_cfmp_deallocation_record *)value; + if (!pr->inSet) { + _cfmp_log_failure("Freeing a record not in the set", pr, pr->client, pr->port); + } + free((_cfmp_deallocation_record *)value); +} +static CFStringRef _cfmp_copy_description(const void *value) { + CFStringRef s = CFSTR("{null}"); + if (value) { + _cfmp_deallocation_record const R = *(_cfmp_deallocation_record *)value; + s = CFStringCreateWithFormat(NULL, NULL, CFSTR("{p:%d c:%d is:%d s:%d,r:%d nsi:%d,nss:%d,nsr:%d}"), R.port, R.client, R.inSet, R.invalidated, R.deallocated, R.doSend, R.doReceive, R.nsportIsInterested, R.nsportDoSend, R.nsportDoReceive); + } + return s; +} + +#pragma mark - Deallocation Records + +// Pending deallocations/invalidations are recorded in the global set returned by _cfmp_records, whose access should be protected by _cfmp_records_lock +static os_unfair_lock _cfmp_records_lock = OS_UNFAIR_LOCK_INIT; +static CFMutableSetRef _cfmp_records(void) { + static CFMutableSetRef oRecords; + static dispatch_once_t oGuard; + dispatch_once(&oGuard, ^{ + CFSetCallBacks const cb = { + .version = 0, + .retain = _cfmp_deallocation_record_retain, + .release = _cfmp_deallocation_record_release, + .copyDescription = _cfmp_copy_description, + .equal = _cfmp_equal, + .hash = _cfmp_hash + }; + oRecords = CFSetCreateMutable(NULL, 16, &cb); + }); + return oRecords; +}; + +CF_INLINE _cfmp_deallocation_record *const _cfmp_find_record_for_port(CFSetRef const records, _CFMPLifetimeClient const client, mach_port_t const port) { + _cfmp_deallocation_record const lookup = {.port = port, .client = client}; + _cfmp_deallocation_record *const pr = (_cfmp_deallocation_record *)CFSetGetValue(records, &lookup); + return pr; +} + +#pragma mark - Lifetime Management +CF_PRIVATE void _cfmp_cleanup(_cfmp_deallocation_record const R) { + _cfmp_mod_refs(R.port, R.doSend, R.doReceive); + if (R.nsportIsInterested) { + _cfmp_mod_refs(R.port, R.nsportDoSend, R.nsportDoReceive); + } +} + +/// Records that a given mach_port has been deallocated. +void _cfmp_record_deallocation(_CFMPLifetimeClient const client, mach_port_t const port, Boolean const doSend, Boolean const doReceive) { + if (port == MACH_PORT_NULL) { return; } + if (doSend == false && doReceive == false) { return; } + + // now that we know we're not a no-op, look for an existing deallocation record + CFMutableSetRef records = _cfmp_records(); + + Boolean cleanupNow = false; + _cfmp_deallocation_record R = {0}; + + os_unfair_lock_lock(&_cfmp_records_lock); + _cfmp_deallocation_record *const pr = _cfmp_find_record_for_port(records, client, port); + if (pr) { + if (pr->invalidated) { + // it's already been invalidated, so can tidy up now + R = *(_cfmp_deallocation_record *)pr; + CFSetRemoveValue(records, pr); + cleanupNow = true; + } else { + // we're expecting invalidation, record that we want clean up doSend/Receive for later + pr->deallocated = true; + pr->doSend = doSend; + pr->doReceive = doReceive; + } + } else { + R.port = port; + R.doSend = doSend; + R.doReceive = doReceive; + cleanupNow = true; + } + os_unfair_lock_unlock(&_cfmp_records_lock); + + if (cleanupNow) { + _cfmp_cleanup(R); + } +} + +void _cfmp_record_intent_to_invalidate(_CFMPLifetimeClient const client, mach_port_t const port) { + if (port == MACH_PORT_NULL) { return; } + + _cfmp_deallocation_record *pr = calloc(1, sizeof(_cfmp_deallocation_record)); + if (pr == NULL) { + HALT_MSG("Unable to allocate mach_port deallocation record"); + } + pr->port = port; + pr->client = client; + + CFMutableSetRef const records = _cfmp_records(); + os_unfair_lock_lock(&_cfmp_records_lock); + CFSetAddValue(records, pr); + os_unfair_lock_unlock(&_cfmp_records_lock); +} + +void _cfmp_source_invalidated(_CFMPLifetimeClient const client, mach_port_t port) { + Boolean cleanupNow = false; + _cfmp_deallocation_record R = {0}; + + CFMutableSetRef const records = _cfmp_records(); + os_unfair_lock_lock(&_cfmp_records_lock); + _cfmp_deallocation_record *pr = _cfmp_find_record_for_port(records, client, port); + if (pr == NULL) { + _cfmp_log_failure("not expecting invalidation", pr, client, port); + } else { + if (pr->deallocated) { + cleanupNow = true; + R = *(_cfmp_deallocation_record *)pr; + CFSetRemoveValue(records, pr); + } else { + pr->invalidated = true; + } + } + os_unfair_lock_unlock(&_cfmp_records_lock); + + if (cleanupNow) { + _cfmp_cleanup(R); + } +} + +void _cfmp_record_nsmachport_is_interested(_CFMPLifetimeClient const client, mach_port_t const port) { + if (port == MACH_PORT_NULL) { return; } + + // now that we know we're not a no-op, look for an existing deallocation record + CFMutableSetRef records = _cfmp_records(); + + os_unfair_lock_lock(&_cfmp_records_lock); + _cfmp_deallocation_record *const pr = _cfmp_find_record_for_port(records, client, port); + if (pr) { + // we're expecting invalidation. record that nsport is interested. + pr->nsportIsInterested = true; + } + os_unfair_lock_unlock(&_cfmp_records_lock); +} + +void _cfmp_record_nsmachport_deallocation(_CFMPLifetimeClient const client, mach_port_t const port, Boolean const doSend, Boolean const doReceive) { + if (port == MACH_PORT_NULL) { return; } + if (doSend == false && doReceive == false) { return; } + + CFMutableSetRef records = _cfmp_records(); + + Boolean cleanupNow = false; + _cfmp_deallocation_record R = {0}; + + os_unfair_lock_lock(&_cfmp_records_lock); + _cfmp_deallocation_record *const pr = _cfmp_find_record_for_port(records, client, port); + if (pr == NULL) { + R.port = port; + R.nsportDoSend = doSend; + R.nsportDoReceive = doReceive; + cleanupNow = true; + } else { + // we're expecting invalidation. record that we want to doSend/Receive for nsport later + // but first make sure we were expecting an NSMachPort at all + if (!pr->nsportIsInterested) { + _cfmp_log_failure("setting nsport state - when its not interested", pr, client, port); + } else if (pr->invalidated) { + // it's already been invalidated, so can tidy up now + R = *(_cfmp_deallocation_record *)pr; + CFSetRemoveValue(records, pr); + cleanupNow = true; + } else { + // we're expecting invalidation, record that we want clean up doSend/Receive for later + pr->deallocated = true; + pr->nsportDoSend = doSend; + pr->nsportDoReceive = doReceive; + } + } + os_unfair_lock_unlock(&_cfmp_records_lock); + + if (cleanupNow) { + _cfmp_cleanup(R); + } +} diff --git a/CoreFoundation/RunLoop.subproj/CFMachPort_Lifetime.h b/CoreFoundation/RunLoop.subproj/CFMachPort_Lifetime.h new file mode 100644 index 0000000000..9f652fece7 --- /dev/null +++ b/CoreFoundation/RunLoop.subproj/CFMachPort_Lifetime.h @@ -0,0 +1,43 @@ +/* + CFMachPort_Lifetime.h + + Copyright (c) 1998-2018, Apple Inc. and the Swift project authors + + Utilities for orchestrating the exact time/circumstances we decrement + mach_port rights for CF types that make use of: deallocate, invalidate + and dispatch_sources. +*/ + +#if !defined(__COREFOUNDATION_CFMACHPORT_LIFETIME__) +#define __COREFOUNDATION_CFMACHPORT_LIFETIME__ 1 + +CF_EXTERN_C_BEGIN + +#include +#include + +typedef CF_ENUM(uint8_t, _CFMPLifetimeClient) { + _CFMPLifetimeClientCFMachPort = 0, + _CFMPLifetimeClientCFMessagePort = 1, + // NOTE: We current support MAX_CLIENTS more clients (currently 2) +}; + +/// Records that that a given mach_port has been deallocated. +CF_PRIVATE void _cfmp_record_deallocation(_CFMPLifetimeClient const client, mach_port_t const port, Boolean const doSend, Boolean const doReceive); + +/// Records that we have called dispatch_source_cancel. +CF_PRIVATE void _cfmp_record_intent_to_invalidate(_CFMPLifetimeClient const client, mach_port_t const port); + +/// Records when the cancel-handler for a given dispatch_port is called. +CF_PRIVATE void _cfmp_source_invalidated(_CFMPLifetimeClient const client, mach_port_t const port); + +/// For Foundation Only +/// Records when an nsmach port is going to be interested in a bridges CFMachPort +CF_EXPORT void _cfmp_record_nsmachport_is_interested(_CFMPLifetimeClient const client, mach_port_t const port); + +/// For Foundation Only +/// Records when an nsmachport deallocates its context +CF_EXPORT void _cfmp_record_nsmachport_deallocation(_CFMPLifetimeClient const client, mach_port_t const port, Boolean const doSend, Boolean const doReceive); + +CF_EXTERN_C_END +#endif // __COREFOUNDATION_CFMACHPORT_LIFETIME__ diff --git a/CoreFoundation/RunLoop.subproj/CFMessagePort.c b/CoreFoundation/RunLoop.subproj/CFMessagePort.c index b20d0854cb..8bb7b7826b 100644 --- a/CoreFoundation/RunLoop.subproj/CFMessagePort.c +++ b/CoreFoundation/RunLoop.subproj/CFMessagePort.c @@ -1,7 +1,7 @@ /* CFMessagePort.c - Copyright (c) 1998-2017, Apple Inc. and the Swift project authors + Copyright (c) 1998-2018, Apple Inc. and the Swift project authors - Portions Copyright (c) 2014-2017, Apple Inc. and the Swift project authors + Portions Copyright (c) 2014-2018, Apple Inc. and the Swift project authors Licensed under Apache License v2.0 with Runtime Library Exception See http://swift.org/LICENSE.txt for license information See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors @@ -13,11 +13,15 @@ #include #include #include +#include #include #include "CFInternal.h" +#include "CFRuntime_Internal.h" #include #include #include +#include "CFMachPort_Internal.h" +#include "CFMachPort_Lifetime.h" #include #include #include @@ -28,6 +32,10 @@ #endif #endif +#if (DEPLOYMENT_TARGET_MACOSX || DEPLOYMENT_TARGET_EMBEDDED) +#include +#endif + extern pid_t getpid(void); #define __kCFMessagePortMaxNameLengthMax 255 @@ -142,7 +150,17 @@ struct __CFMessagePortMachMessage { uint8_t bytes[0]; } innards; }; -#define __INNARD_OFFSET (((!(msgp->header.msgh_bits & MACH_MSGH_BITS_COMPLEX) && ((mach_msg_header_t *)msgp)->msgh_id == 0) || ( (msgp->header.msgh_bits & MACH_MSGH_BITS_COMPLEX) && !__LP64__)) ? 40 : 44) + +#define CFMP_MSGH_ID_64 0x63666d70 // 'cfmp' +#define CFMP_MSGH_ID_32 0x43464d50 // 'CFMP' +#if __LP64__ +#define CFMP_MSGH_ID CFMP_MSGH_ID_64 +#else +#define CFMP_MSGH_ID CFMP_MSGH_ID_32 +#endif + +// NOTE: mach_msg_ool_descriptor_t has different sizes based on 32/64-bit for send/receive +#define __INNARD_OFFSET (((!(msgp->header.msgh_bits & MACH_MSGH_BITS_COMPLEX) && ((mach_msg_header_t *)msgp)->msgh_id == CFMP_MSGH_ID_32) || ( (msgp->header.msgh_bits & MACH_MSGH_BITS_COMPLEX) && !__LP64__)) ? 40 : 44) #define MAGIC 0xF0F2F4F8 @@ -160,11 +178,7 @@ static mach_msg_base_t *__CFMessagePortCreateMessage(bool reply, mach_port_t por struct __CFMessagePortMachMessage *msg = CFAllocatorAllocate(kCFAllocatorSystemDefault, size, 0); if (!msg) return NULL; memset(msg, 0, size); -#if __LP64__ - msg->base.header.msgh_id = 1; -#else - msg->base.header.msgh_id = 0; -#endif + msg->base.header.msgh_id = CFMP_MSGH_ID; msg->base.header.msgh_size = size; msg->base.header.msgh_remote_port = port; msg->base.header.msgh_local_port = replyPort; @@ -229,10 +243,10 @@ static void __CFMessagePortDeallocate(CFTypeRef cf) { CFRelease(ms->_name); } if (NULL != ms->_port) { - if (__CFMessagePortExtraMachRef(ms)) { - mach_port_mod_refs(mach_task_self(), CFMachPortGetPort(ms->_port), MACH_PORT_RIGHT_SEND, -1); - mach_port_mod_refs(mach_task_self(), CFMachPortGetPort(ms->_port), MACH_PORT_RIGHT_RECEIVE, -1); - } + mach_port_t const mp = CFMachPortGetPort(ms->_port); + if (__CFMessagePortExtraMachRef(ms)) { + _cfmp_record_deallocation(_CFMPLifetimeClientCFMessagePort, mp, true /*doSend*/, true /*doReceive*/); + } CFMachPortInvalidate(ms->_port); CFRelease(ms->_port); } @@ -265,9 +279,7 @@ static void __CFMessagePortDeallocate(CFTypeRef cf) { } } -static CFTypeID __kCFMessagePortTypeID = _kCFRuntimeNotATypeID; - -static const CFRuntimeClass __CFMessagePortClass = { +const CFRuntimeClass __CFMessagePortClass = { 0, "CFMessagePort", NULL, // init @@ -280,12 +292,10 @@ static const CFRuntimeClass __CFMessagePortClass = { }; CFTypeID CFMessagePortGetTypeID(void) { - static dispatch_once_t initOnce; - dispatch_once(&initOnce, ^{ __kCFMessagePortTypeID = _CFRuntimeRegisterClass(&__CFMessagePortClass); }); - return __kCFMessagePortTypeID; + return _kCFRuntimeIDCFMessagePort; } -static CFStringRef __CFMessagePortSanitizeStringName(CFStringRef name, uint8_t **utfnamep, CFIndex *utfnamelenp) { +static CFStringRef __CFMessagePortSanitizeStringName(CFStringRef name, uint8_t **utfnamep, CFIndex *utfnamelenp) CF_RETURNS_RETAINED { uint8_t *utfname; CFIndex utflen; CFStringRef result = NULL; @@ -324,14 +334,17 @@ static void __CFMessagePortInvalidationCallBack(CFMachPortRef port, void *info) if (info) CFMessagePortInvalidate(info); } -static CFMessagePortRef __CFMessagePortCreateLocal(CFAllocatorRef allocator, CFStringRef name, CFMessagePortCallBack callout, CFMessagePortContext *context, Boolean *shouldFreeInfo, Boolean perPID, CFMessagePortCallBackEx calloutEx) { +static CFMessagePortRef __CFMessagePortCreateLocal(CFAllocatorRef allocator, CFStringRef inName, CFMessagePortCallBack callout, CFMessagePortContext *context, Boolean *shouldFreeInfo, Boolean perPID, CFMessagePortCallBackEx calloutEx) { CFMessagePortRef memory; uint8_t *utfname = NULL; if (shouldFreeInfo) *shouldFreeInfo = true; - if (NULL != name) { - name = __CFMessagePortSanitizeStringName(name, &utfname, NULL); + + CFStringRef name = NULL; + if (inName != NULL) { + name = __CFMessagePortSanitizeStringName(inName, &utfname, NULL); } + __CFLock(&__CFAllMessagePortsLock); if (!perPID && NULL != name) { CFMessagePortRef existing; @@ -361,7 +374,7 @@ static CFMessagePortRef __CFMessagePortCreateLocal(CFAllocatorRef allocator, CFS __CFMessagePortUnsetExtraMachRef(memory); __CFMessagePortUnsetRemote(memory); memory->_lock = CFLockInit; - memory->_name = name; + memory->_name = name; // memory takes ownership of name henceforth memory->_port = NULL; memory->_replies = NULL; memory->_convCounter = 0; @@ -378,6 +391,7 @@ static CFMessagePortRef __CFMessagePortCreateLocal(CFAllocatorRef allocator, CFS memory->_context.release = NULL; memory->_context.copyDescription = NULL; + // sadly this is mostly a repeat of SetName function below sans locks... if (NULL != name) { CFMachPortRef native = NULL; kern_return_t ret; @@ -437,7 +451,7 @@ CFMessagePortRef _CFMessagePortCreateLocalEx(CFAllocatorRef allocator, CFStringR return __CFMessagePortCreateLocal(allocator, name, NULL, context, shouldFreeInfo, perPID, calloutEx); } -static CFMessagePortRef __CFMessagePortCreateRemote(CFAllocatorRef allocator, CFStringRef name, Boolean perPID, CFIndex pid) { +static CFMessagePortRef __CFMessagePortCreateRemote(CFAllocatorRef allocator, CFStringRef inName, Boolean perPID, CFIndex pid) { CFMessagePortRef memory; CFMachPortRef native; CFMachPortContext ctx; @@ -446,7 +460,7 @@ static CFMessagePortRef __CFMessagePortCreateRemote(CFAllocatorRef allocator, CF mach_port_t bp, port; kern_return_t ret; - name = __CFMessagePortSanitizeStringName(name, &utfname, NULL); + CFStringRef const name = __CFMessagePortSanitizeStringName(inName, &utfname, NULL); if (NULL == name) { return NULL; } @@ -554,16 +568,17 @@ CFStringRef CFMessagePortGetName(CFMessagePortRef ms) { return ms->_name; } -Boolean CFMessagePortSetName(CFMessagePortRef ms, CFStringRef name) { +Boolean CFMessagePortSetName(CFMessagePortRef ms, CFStringRef inName) { CFAllocatorRef allocator = CFGetAllocator(ms); uint8_t *utfname = NULL; __CFGenericValidateType(ms, CFMessagePortGetTypeID()); if (ms->_perPID || __CFMessagePortIsRemote(ms)) return false; - name = __CFMessagePortSanitizeStringName(name, &utfname, NULL); + CFStringRef const name = __CFMessagePortSanitizeStringName(inName, &utfname, NULL); if (NULL == name) { return false; } + __CFLock(&__CFAllMessagePortsLock); if (NULL != name) { CFMessagePortRef existing; @@ -575,31 +590,53 @@ Boolean CFMessagePortSetName(CFMessagePortRef ms, CFStringRef name) { } } __CFUnlock(&__CFAllMessagePortsLock); - + + + __CFMessagePortLock(ms); + if (ms->_dispatchSource) { + CFLog(kCFLogLevelDebug, CFSTR("*** CFMessagePort: Unable to SetName on CFMessagePort %p as it already has a dispatch queue associated with itself."), ms); + __CFMessagePortUnlock(ms); + CFRelease(name); + CFAllocatorDeallocate(kCFAllocatorSystemDefault, utfname); + return false; + } + + if (NULL != name && (NULL == ms->_name || !CFEqual(ms->_name, name))) { - CFMachPortRef oldPort = ms->_port; + CFMachPortRef oldPort = ms->_port; + Boolean const previousNameHadExtraRef = ms->_name != NULL && __CFMessagePortExtraMachRef(ms); CFMachPortRef native = NULL; kern_return_t ret; mach_port_t bs, mp; task_get_bootstrap_port(mach_task_self(), &bs); + + // NOTE: bootstrap_check_in always yields +1 receive-right ret = bootstrap_check_in(bs, (char *)utfname, &mp); /* If we're started by launchd or the old mach_init */ + if (ret == KERN_SUCCESS) { ret = mach_port_insert_right(mach_task_self(), mp, mp, MACH_MSG_TYPE_MAKE_SEND); if (KERN_SUCCESS == ret) { CFMachPortContext ctx = {0, ms, NULL, NULL, NULL}; native = CFMachPortCreateWithPort(allocator, mp, __CFMessagePortDummyCallback, &ctx, NULL); - __CFMessagePortSetExtraMachRef(ms); + // at this point we have +1 SEND, +1 RECV, so we record that fact + __CFMessagePortSetExtraMachRef(ms); } else { - mach_port_destroy(mach_task_self(), mp); + __CFMessagePortUnlock(ms); + // balance the +1 receive-right we got from bootstrap_check_in + mach_port_mod_refs(mach_task_self(), mp, MACH_PORT_RIGHT_RECEIVE, -1); + + // the insert failed, so we don't need to decrement send right here CFAllocatorDeallocate(kCFAllocatorSystemDefault, utfname); - CFRelease(name); + CFRelease(name); return false; } } + if (!native) { CFMachPortContext ctx = {0, ms, NULL, NULL, NULL}; native = CFMachPortCreate(allocator, __CFMessagePortDummyCallback, &ctx, NULL); if (!native) { + __CFMessagePortUnlock(ms); CFAllocatorDeallocate(kCFAllocatorSystemDefault, utfname); CFRelease(name); return false; @@ -609,9 +646,14 @@ Boolean CFMessagePortSetName(CFMessagePortRef ms, CFStringRef name) { CFMachPortSetInvalidationCallBack(native, __CFMessagePortInvalidationCallBack); ms->_port = native; if (NULL != oldPort && oldPort != native) { - if (__CFMessagePortExtraMachRef(ms)) { - mach_port_mod_refs(mach_task_self(), CFMachPortGetPort(oldPort), MACH_PORT_RIGHT_SEND, -1); - mach_port_mod_refs(mach_task_self(), CFMachPortGetPort(oldPort), MACH_PORT_RIGHT_RECEIVE, -1); + if (previousNameHadExtraRef) { + // this code is known to be incorrect when ms->_dispatchSource is non-null, we prevent this above, but just to be sure we're not about to do something bad we assert + assert(ms->_dispatchSource == NULL); + + // this is one of the reasons we are deprecating this API + mach_port_t const oldmp = CFMachPortGetPort(oldPort); + mach_port_mod_refs(mach_task_self(), oldmp, MACH_PORT_RIGHT_RECEIVE, -1); + mach_port_deallocate(mach_task_self(), oldmp); } CFMachPortInvalidate(oldPort); CFRelease(oldPort); @@ -631,7 +673,7 @@ Boolean CFMessagePortSetName(CFMessagePortRef ms, CFStringRef name) { CFDictionaryRemoveValue(__CFAllLocalMessagePorts, ms->_name); CFRelease(ms->_name); } - ms->_name = name; + ms->_name = name; // consumes the +1 from sanitize above CFDictionaryAddValue(__CFAllLocalMessagePorts, name, ms); __CFUnlock(&__CFAllMessagePortsLock); } @@ -639,7 +681,7 @@ Boolean CFMessagePortSetName(CFMessagePortRef ms, CFStringRef name) { // if setting the same name on the message port, then avoid leak CFRelease(name); } - + __CFMessagePortUnlock(ms); CFAllocatorDeallocate(kCFAllocatorSystemDefault, utfname); return true; } @@ -700,11 +742,12 @@ void CFMessagePortInvalidate(CFMessagePortRef ms) { CFMachPortInvalidate(replyPort); CFRelease(replyPort); } - if (__CFMessagePortIsRemote(ms)) { - // Get rid of our extra ref on the Mach port gotten from bs server - mach_port_deallocate(mach_task_self(), CFMachPortGetPort(port)); - } + if (NULL != port) { + mach_port_t const mp = CFMachPortGetPort(port); + if (__CFMessagePortIsRemote(ms)) { + _cfmp_record_deallocation(_CFMPLifetimeClientCFMessagePort, mp, true /*doSend*/, false /*doReceive*/); + } // We already know we're going invalid, don't need this callback // anymore; plus, this solves a reentrancy deadlock; also, this // must be done before the deallocate of the Mach port, to @@ -712,8 +755,7 @@ void CFMessagePortInvalidate(CFMessagePortRef ms) { // handled in another thread, and this NULL'ing out. CFMachPortSetInvalidationCallBack(port, NULL); if (__CFMessagePortExtraMachRef(ms)) { - mach_port_mod_refs(mach_task_self(), CFMachPortGetPort(port), MACH_PORT_RIGHT_SEND, -1); - mach_port_mod_refs(mach_task_self(), CFMachPortGetPort(port), MACH_PORT_RIGHT_RECEIVE, -1); + _cfmp_record_deallocation(_CFMPLifetimeClientCFMessagePort, mp, true /*doSend*/, true /*doReceive*/); } CFMachPortInvalidate(port); CFRelease(port); @@ -776,7 +818,7 @@ static void __CFMessagePortReplyCallBack(CFMachPortRef port, void *msg, CFIndex Boolean wayTooBig = false; if (!wayTooSmall) { invalidMagic = ((MSGP_INFO(msgp, magic) != MAGIC) && (CFSwapInt32(MSGP_INFO(msgp, magic)) != MAGIC)); - invalidComplex = (msgp->header.msgh_bits & MACH_MSGH_BITS_COMPLEX) && (1 != msgp->body.msgh_descriptor_count); + invalidComplex = (msgp->header.msgh_bits & MACH_MSGH_BITS_COMPLEX) && ((1 != msgp->body.msgh_descriptor_count) || MSGP_GET(msgp, ool).type != MACH_MSG_OOL_DESCRIPTOR); wayTooBig = ((int32_t)MSGP_SIZE(msgp) + __CFMessagePortMaxInlineBytes) < msgp->header.msgh_size; // also less than a 32-bit signed int can hold } Boolean wrongSize = false; @@ -883,7 +925,9 @@ SInt32 CFMessagePortSendRequest(CFMessagePortRef remote, SInt32 msgid, CFDataRef __CFMessagePortLock(remote); if (KERN_SUCCESS != ret) { // need to deallocate the send-once right that might have been created - if (replyMode != NULL) mach_port_deallocate(mach_task_self(), ((mach_msg_header_t *)sendmsg)->msgh_local_port); + if (replyMode != NULL) { + mach_port_deallocate(mach_task_self(), ((mach_msg_header_t *)sendmsg)->msgh_local_port); + } if (didRegister) { CFRunLoopRemoveSource(currentRL, source, replyMode); } @@ -1123,10 +1167,13 @@ void CFMessagePortSetDispatchQueue(CFMessagePortRef ms, dispatch_queue_t queue) dispatch_queue_attr_t dqattr = dispatch_queue_attr_make_with_qos_class(DISPATCH_QUEUE_SERIAL, qos_class_main(), 0); mportQueue = dispatch_queue_create("com.apple.CFMessagePort", dqattr); }); + + _cfmp_record_intent_to_invalidate(_CFMPLifetimeClientCFMessagePort, port); dispatch_source_t theSource = dispatch_source_create(DISPATCH_SOURCE_TYPE_MACH_RECV, port, 0, mportQueue); dispatch_source_set_cancel_handler(theSource, ^{ dispatch_release(queue); dispatch_release(theSource); + _cfmp_source_invalidated(_CFMPLifetimeClientCFMessagePort, port); }); dispatch_source_set_event_handler(theSource, ^{ CFRetain(ms); @@ -1151,8 +1198,10 @@ void CFMessagePortSetDispatchQueue(CFMessagePortRef ms, dispatch_queue_t queue) dispatch_async(queue, ^{ mach_msg_header_t *reply = __CFMessagePortPerform(msg, msg->msgh_size, kCFAllocatorSystemDefault, ms); if (NULL != reply) { - kern_return_t ret = mach_msg(reply, MACH_SEND_MSG, reply->msgh_size, 0, MACH_PORT_NULL, 0, MACH_PORT_NULL); - if (KERN_SUCCESS != ret) mach_msg_destroy(reply); + kern_return_t const ret = mach_msg(reply, MACH_SEND_MSG, reply->msgh_size, 0, MACH_PORT_NULL, 0, MACH_PORT_NULL); + + __CFMachMessageCheckForAndDestroyUnsentMessage(ret, msg); + CFAllocatorDeallocate(kCFAllocatorSystemDefault, reply); } CFAllocatorDeallocate(kCFAllocatorSystemDefault, msg); @@ -1171,4 +1220,3 @@ void CFMessagePortSetDispatchQueue(CFMessagePortRef ms, dispatch_queue_t queue) } __CFMessagePortUnlock(ms); } - diff --git a/CoreFoundation/RunLoop.subproj/CFMessagePort.h b/CoreFoundation/RunLoop.subproj/CFMessagePort.h index 619fff42c5..9660362dcc 100644 --- a/CoreFoundation/RunLoop.subproj/CFMessagePort.h +++ b/CoreFoundation/RunLoop.subproj/CFMessagePort.h @@ -1,7 +1,7 @@ /* CFMessagePort.h - Copyright (c) 1998-2017, Apple Inc. and the Swift project authors + Copyright (c) 1998-2018, Apple Inc. and the Swift project authors - Portions Copyright (c) 2014-2017, Apple Inc. and the Swift project authors + Portions Copyright (c) 2014-2018, Apple Inc. and the Swift project authors Licensed under Apache License v2.0 with Runtime Library Exception See http://swift.org/LICENSE.txt for license information See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors diff --git a/CoreFoundation/RunLoop.subproj/CFRunLoop.c b/CoreFoundation/RunLoop.subproj/CFRunLoop.c index f179a829c6..152765b050 100644 --- a/CoreFoundation/RunLoop.subproj/CFRunLoop.c +++ b/CoreFoundation/RunLoop.subproj/CFRunLoop.c @@ -1,11 +1,11 @@ /* CFRunLoop.c - Copyright (c) 1998-2017, Apple Inc. and the Swift project authors + Copyright (c) 1998-2018, Apple Inc. and the Swift project authors - Portions Copyright (c) 2014-2017, Apple Inc. and the Swift project authors + Portions Copyright (c) 2014-2018, Apple Inc. and the Swift project authors Licensed under Apache License v2.0 with Runtime Library Exception See http://swift.org/LICENSE.txt for license information See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors - Responsibility: Tony Parker + Responsibility: Michael LeHew */ #include @@ -14,6 +14,8 @@ #include #include #include "CFInternal.h" +#include "CFRuntime_Internal.h" +#include "CFMachPort_Internal.h" #include #include #include @@ -21,8 +23,8 @@ #if __HAS_DISPATCH__ #include #endif -#define cf_trace(...) +extern void objc_terminate(void); #if DEPLOYMENT_TARGET_WINDOWS @@ -50,9 +52,10 @@ CF_INLINE uint64_t check_uint64_add(uint64_t x, uint64_t y, int32_t* err) { extern dispatch_queue_t _dispatch_runloop_root_queue_create_4CF(const char *_Nullable label, unsigned long flags); extern mach_port_t _dispatch_runloop_root_queue_get_port_4CF(dispatch_queue_t queue); extern void _dispatch_source_set_runloop_timer_4CF(dispatch_source_t source, dispatch_time_t start, uint64_t interval, uint64_t leeway); +extern bool _dispatch_runloop_root_queue_perform_4CF(dispatch_queue_t queue); #endif -#if DEPLOYMENT_TARGET_MACOSX || DEPLOYMENT_TARGET_EMBEDDED || DEPLOYMENT_TARGET_EMBEDDED_MINI +#if DEPLOYMENT_TARGET_MACOSX || DEPLOYMENT_TARGET_EMBEDDED || DEPLOYMENT_TARGET_EMBEDDED_MINI || DEPLOYMENT_TARGET_SIMULATOR #include #include #include @@ -61,6 +64,8 @@ extern void _dispatch_source_set_runloop_timer_4CF(dispatch_source_t source, dis #include #include +extern void _dispatch_main_queue_callback_4CF(void *); + extern pthread_t pthread_main_thread_np(void); typedef struct voucher_s *voucher_t; @@ -83,6 +88,7 @@ DISPATCH_EXPORT void _dispatch_main_queue_callback_4CF(void); #define AbsoluteTime LARGE_INTEGER #elif DEPLOYMENT_TARGET_LINUX + #include #include #include @@ -96,7 +102,7 @@ extern void _dispatch_main_queue_callback_4CF(void *_Null_unspecified msg); #define _dispatch_main_queue_callback_4CF(x) _dispatch_main_queue_callback_4CF(x) #endif -#if DEPLOYMENT_TARGET_WINDOWS || DEPLOYMENT_TARGET_IPHONESIMULATOR || DEPLOYMENT_TARGET_LINUX +#if DEPLOYMENT_TARGET_WINDOWS || DEPLOYMENT_TARGET_LINUX CF_EXPORT pthread_t _CF_pthread_main_thread_np(void); #define pthread_main_thread_np() _CF_pthread_main_thread_np() #endif @@ -116,6 +122,10 @@ CF_EXPORT pthread_t _CF_pthread_main_thread_np(void); #define USE_MK_TIMER_TOO 1 #endif +// Open source CF may not have this defined. +#ifndef cf_trace +#define cf_trace(...) do {} while (0) +#endif static int _LogCFRunLoop = 0; static void _runLoopTimerWithBlockContext(CFRunLoopTimerRef timer, void *opaqueBlock); @@ -130,21 +140,21 @@ static void _runLoopTimerWithBlockContext(CFRunLoopTimerRef timer, void *opaqueB #if DEPLOYMENT_TARGET_WINDOWS -static pthread_t kNilPthreadT = { nil, nil }; +static pthread_t const kNilPthreadT = { nil, nil }; #define pthreadPointer(a) a.p typedef int kern_return_t; #define KERN_SUCCESS 0 #elif DEPLOYMENT_TARGET_LINUX -static pthread_t kNilPthreadT = (pthread_t)0; +static pthread_t const kNilPthreadT = (pthread_t)0; #define pthreadPointer(a) ((void*)a) typedef int kern_return_t; #define KERN_SUCCESS 0 #else -static pthread_t kNilPthreadT = (pthread_t)0; +static pthread_t const kNilPthreadT = (pthread_t)0; #define pthreadPointer(a) a #define lockCount(a) a #endif @@ -249,7 +259,7 @@ CF_PRIVATE void __CFRestartAllThreads(CFArrayRef threads) { static uint32_t __CF_last_warned_port_count = 0; -static void foo() __attribute__((unused)); +static void foo(void) __attribute__((unused)); static void foo() { uint32_t pcnt = __CFGetProcessPortCount(); if (__CF_last_warned_port_count + 1000 < pcnt) { @@ -285,9 +295,16 @@ typedef mach_port_t __CFPortSet; static void __THE_SYSTEM_HAS_NO_PORTS_AVAILABLE__(kern_return_t ret) __attribute__((noinline)); static void __THE_SYSTEM_HAS_NO_PORTS_AVAILABLE__(kern_return_t ret) { HALT; }; -static __CFPort __CFPortAllocate(void) { +static __CFPort __CFPortAllocate(uintptr_t guard) { __CFPort result = CFPORT_NULL; - kern_return_t ret = mach_port_allocate(mach_task_self(), MACH_PORT_RIGHT_RECEIVE, &result); + + mach_port_options_t options = { + .flags = MPO_CONTEXT_AS_GUARD | MPO_QLIMIT | MPO_INSERT_SEND_RIGHT | MPO_STRICT, + .mpl.mpl_qlimit = 1, + }; + + kern_return_t const ret = mach_port_construct(mach_task_self(), &options, (mach_port_context_t)guard, &result); + if (KERN_SUCCESS != ret) { char msg[256]; snprintf(msg, 256, "*** The system has no mach ports available. You may be able to diagnose which application(s) are using ports by using 'top' or Activity Monitor. (%d) ***", ret); @@ -296,20 +313,18 @@ static __CFPort __CFPortAllocate(void) { return CFPORT_NULL; } - ret = mach_port_insert_right(mach_task_self(), result, result, MACH_MSG_TYPE_MAKE_SEND); - if (KERN_SUCCESS != ret) CRASH("*** Unable to set send right on mach port. (%d) ***", ret); - - - mach_port_limits_t limits; - limits.mpl_qlimit = 1; - ret = mach_port_set_attributes(mach_task_self(), result, MACH_PORT_LIMITS_INFO, (mach_port_info_t)&limits, MACH_PORT_LIMITS_INFO_COUNT); - if (KERN_SUCCESS != ret) CRASH("*** Unable to set attributes on mach port. (%d) ***", ret); - return result; } -CF_INLINE void __CFPortFree(__CFPort port) { - mach_port_destroy(mach_task_self(), port); +CF_INLINE void __CFPortFree(__CFPort port, uintptr_t guard) { + kern_return_t const ret = mach_port_destruct(mach_task_self(), port, -1, (mach_port_context_t)guard); + if (KERN_SUCCESS != ret) { + + char msg[256]; + snprintf(msg, 256, "*** Unable to destruct port. (0x%x, %d, %p) ***", port, ret, (void *)guard); + CRSetCrashLogMessage(msg); + HALT; + } } static void __NO_SPACE__(kern_return_t ret) __attribute__((noinline)); @@ -372,11 +387,11 @@ typedef struct ___CFPortSet { CFLock_t lock; // insert and remove must be thread safe, like the Mach calls } *__CFPortSet; -CF_INLINE __CFPort __CFPortAllocate(void) { +CF_INLINE __CFPort __CFPortAllocate(__unused uintptr_t guard) { return CreateEventA(NULL, true, false, NULL); } -CF_INLINE void __CFPortFree(__CFPort port) { +CF_INLINE void __CFPortFree(__CFPort port, __unused uintptr_t guard) { CloseHandle(port); } @@ -460,11 +475,19 @@ typedef int __CFPort; typedef int __CFPortSet; #define CFPORTSET_NULL -1 -static __CFPort __CFPortAllocate(void) { +#ifndef __unused + #if __has_attribute(unused) + #define __unused __attribute__((unused)) + #else + #define __unused + #endif +#endif // !defined(__unused) + +static __CFPort __CFPortAllocate(__unused uintptr_t guard) { return eventfd(0, EFD_CLOEXEC|EFD_NONBLOCK); } -CF_INLINE void __CFPortFree(__CFPort port) { +CF_INLINE void __CFPortFree(__CFPort port, __unused uintptr_t guard) { close(port); } @@ -523,18 +546,17 @@ extern kern_return_t mk_timer_arm(mach_port_name_t name, uint64_t expire_time); #endif static uint32_t __CFSendTrivialMachMessage(mach_port_t port, uint32_t msg_id, CFOptionFlags options, uint32_t timeout) { - kern_return_t result; mach_msg_header_t header; header.msgh_bits = MACH_MSGH_BITS(MACH_MSG_TYPE_COPY_SEND, 0); header.msgh_size = sizeof(mach_msg_header_t); header.msgh_remote_port = port; header.msgh_local_port = MACH_PORT_NULL; header.msgh_id = msg_id; - result = mach_msg(&header, MACH_SEND_MSG|options, header.msgh_size, 0, MACH_PORT_NULL, timeout, MACH_PORT_NULL); - if (result == MACH_SEND_TIMED_OUT) mach_msg_destroy(&header); + kern_return_t const result = mach_msg(&header, MACH_SEND_MSG|options, header.msgh_size, 0, MACH_PORT_NULL, timeout, MACH_PORT_NULL); + __CFMachMessageCheckForAndDestroyUnsentMessage(result, &header); return result; } -#elif DEPLOYMENT_TARGET_LINUX && !TARGET_OS_CYGWIN +#elif DEPLOYMENT_TARGET_LINUX static int mk_timer_create(void) { return timerfd_create(CLOCK_MONOTONIC, TFD_NONBLOCK|TFD_CLOEXEC); @@ -564,7 +586,7 @@ CF_INLINE int64_t __CFUInt64ToAbsoluteTime(int64_t x) { return x; } -#elif DEPLOYMENT_TARGET_WINDOWS || TARGET_OS_CYGWIN +#elif DEPLOYMENT_TARGET_WINDOWS static HANDLE mk_timer_create(void) { return CreateWaitableTimer(NULL, FALSE, NULL); @@ -612,7 +634,6 @@ static kern_return_t mk_timer_cancel(HANDLE name, LARGE_INTEGER *result_time) { #endif -CF_EXPORT Boolean __CFMainThreadHasExited; CF_BREAKPOINT_FUNCTION(void _CFRunLoopError_MainThreadHasExited(void)); #pragma mark - @@ -623,12 +644,6 @@ CF_BREAKPOINT_FUNCTION(void _CFRunLoopError_MainThreadHasExited(void)); /* be very careful of common subexpression elimination and compacting code, particular across locks and unlocks! */ /* run loop mode structures should never be deallocated, even if they become empty */ -static CFTypeID __kCFRunLoopModeTypeID = _kCFRuntimeNotATypeID; -static CFTypeID __kCFRunLoopTypeID = _kCFRuntimeNotATypeID; -static CFTypeID __kCFRunLoopSourceTypeID = _kCFRuntimeNotATypeID; -static CFTypeID __kCFRunLoopObserverTypeID = _kCFRuntimeNotATypeID; -static CFTypeID __kCFRunLoopTimerTypeID = _kCFRuntimeNotATypeID; - typedef struct __CFRunLoopMode *CFRunLoopModeRef; struct __CFRunLoopMode { @@ -873,7 +888,7 @@ static CFRunLoopModeRef __CFRunLoopFindMode(CFRunLoopRef rl, CFStringRef modeNam CFRunLoopModeRef rlm; struct __CFRunLoopMode srlm; memset(&srlm, 0, sizeof(srlm)); - _CFRuntimeSetInstanceTypeIDAndIsa(&srlm, __kCFRunLoopModeTypeID); + _CFRuntimeSetInstanceTypeIDAndIsa(&srlm, _kCFRuntimeIDCFRunLoopMode); srlm._name = modeName; rlm = (CFRunLoopModeRef)CFSetGetValue(rl->_modes, &srlm); if (NULL != rlm) { @@ -883,7 +898,7 @@ static CFRunLoopModeRef __CFRunLoopFindMode(CFRunLoopRef rl, CFStringRef modeNam if (!create) { return NULL; } - rlm = (CFRunLoopModeRef)_CFRuntimeCreateInstance(kCFAllocatorSystemDefault, __kCFRunLoopModeTypeID, sizeof(struct __CFRunLoopMode) - sizeof(CFRuntimeBase), NULL); + rlm = (CFRunLoopModeRef)_CFRuntimeCreateInstance(kCFAllocatorSystemDefault, _kCFRuntimeIDCFRunLoopMode, sizeof(struct __CFRunLoopMode) - sizeof(CFRuntimeBase), NULL); if (NULL == rlm) { return NULL; } @@ -1386,7 +1401,7 @@ static void __CFRunLoopDeallocate(CFTypeRef cf) { if (NULL != rl->_modes) { CFRelease(rl->_modes); } - __CFPortFree(rl->_wakeUpPort); + __CFPortFree(rl->_wakeUpPort, (uintptr_t)rl); rl->_wakeUpPort = CFPORT_NULL; __CFRunLoopPopPerRunData(rl, NULL); __CFRunLoopUnlock(rl); @@ -1394,7 +1409,7 @@ static void __CFRunLoopDeallocate(CFTypeRef cf) { memset((char *)cf + sizeof(CFRuntimeBase), 0x8C, sizeof(struct __CFRunLoop) - sizeof(CFRuntimeBase)); } -static const CFRuntimeClass __CFRunLoopModeClass = { +const CFRuntimeClass __CFRunLoopModeClass = { 0, "CFRunLoopMode", NULL, // init @@ -1406,7 +1421,7 @@ static const CFRuntimeClass __CFRunLoopModeClass = { __CFRunLoopModeCopyDescription }; -static const CFRuntimeClass __CFRunLoopClass = { +const CFRuntimeClass __CFRunLoopClass = { 0, "CFRunLoop", NULL, // init @@ -1421,9 +1436,7 @@ static const CFRuntimeClass __CFRunLoopClass = { CF_PRIVATE void __CFFinalizeRunLoop(uintptr_t data); CFTypeID CFRunLoopGetTypeID(void) { - static dispatch_once_t initOnce; - dispatch_once(&initOnce, ^{ __kCFRunLoopTypeID = _CFRuntimeRegisterClass(&__CFRunLoopClass); __kCFRunLoopModeTypeID = _CFRuntimeRegisterClass(&__CFRunLoopModeClass); }); - return __kCFRunLoopTypeID; + return _kCFRuntimeIDCFRunLoop; } static CFRunLoopRef __CFRunLoopCreate(pthread_t t) { @@ -1436,7 +1449,7 @@ static CFRunLoopRef __CFRunLoopCreate(pthread_t t) { } (void)__CFRunLoopPushPerRunData(loop); __CFRunLoopLockInit(&loop->_lock); - loop->_wakeUpPort = __CFPortAllocate(); + loop->_wakeUpPort = __CFPortAllocate((uintptr_t)loop); if (CFPORT_NULL == loop->_wakeUpPort) HALT; __CFRunLoopSetIgnoreWakeUps(loop); loop->_commonModes = CFSetCreateMutable(kCFAllocatorSystemDefault, 0, &kCFTypeSetCallBacks); @@ -1751,7 +1764,7 @@ void CFRunLoopAddCommonMode(CFRunLoopRef rl, CFStringRef modeName) { #if __HAS_DISPATCH__ -static void __CFRUNLOOP_IS_SERVICING_THE_MAIN_DISPATCH_QUEUE__() __attribute__((noinline)); +static void __CFRUNLOOP_IS_SERVICING_THE_MAIN_DISPATCH_QUEUE__(void *msg) __attribute__((noinline)); static void __CFRUNLOOP_IS_SERVICING_THE_MAIN_DISPATCH_QUEUE__(void *msg) { _dispatch_main_queue_callback_4CF(msg); __asm __volatile__(""); // thwart tail-call optimization @@ -1759,7 +1772,7 @@ static void __CFRUNLOOP_IS_SERVICING_THE_MAIN_DISPATCH_QUEUE__(void *msg) { #endif -static void __CFRUNLOOP_IS_CALLING_OUT_TO_AN_OBSERVER_CALLBACK_FUNCTION__() __attribute__((noinline)); +static void __CFRUNLOOP_IS_CALLING_OUT_TO_AN_OBSERVER_CALLBACK_FUNCTION__(CFRunLoopObserverCallBack func, CFRunLoopObserverRef observer, CFRunLoopActivity activity, void *info) __attribute__((noinline)); static void __CFRUNLOOP_IS_CALLING_OUT_TO_AN_OBSERVER_CALLBACK_FUNCTION__(CFRunLoopObserverCallBack func, CFRunLoopObserverRef observer, CFRunLoopActivity activity, void *info) { if (func) { func(observer, activity, info); @@ -1767,7 +1780,7 @@ static void __CFRUNLOOP_IS_CALLING_OUT_TO_AN_OBSERVER_CALLBACK_FUNCTION__(CFRunL __asm __volatile__(""); // thwart tail-call optimization } -static void __CFRUNLOOP_IS_CALLING_OUT_TO_A_TIMER_CALLBACK_FUNCTION__() __attribute__((noinline)); +static void __CFRUNLOOP_IS_CALLING_OUT_TO_A_TIMER_CALLBACK_FUNCTION__(CFRunLoopTimerCallBack func, CFRunLoopTimerRef timer, void *info) __attribute__((noinline)); static void __CFRUNLOOP_IS_CALLING_OUT_TO_A_TIMER_CALLBACK_FUNCTION__(CFRunLoopTimerCallBack func, CFRunLoopTimerRef timer, void *info) { if (func) { func(timer, info); @@ -1775,7 +1788,7 @@ static void __CFRUNLOOP_IS_CALLING_OUT_TO_A_TIMER_CALLBACK_FUNCTION__(CFRunLoopT __asm __volatile__(""); // thwart tail-call optimization } -static void __CFRUNLOOP_IS_CALLING_OUT_TO_A_BLOCK__() __attribute__((noinline)); +static void __CFRUNLOOP_IS_CALLING_OUT_TO_A_BLOCK__(void (^block)(void)) __attribute__((noinline)); static void __CFRUNLOOP_IS_CALLING_OUT_TO_A_BLOCK__(void (^block)(void)) { if (block) { block(); @@ -1840,7 +1853,7 @@ static Boolean __CFRunLoopDoBlocks(CFRunLoopRef rl, CFRunLoopModeRef rlm) { // C } /* rl is locked, rlm is locked on entrance and exit */ -static void __CFRunLoopDoObservers() __attribute__((noinline)); +static void __CFRunLoopDoObservers(CFRunLoopRef rl, CFRunLoopModeRef rlm, CFRunLoopActivity activity) __attribute__((noinline)); static void __CFRunLoopDoObservers(CFRunLoopRef rl, CFRunLoopModeRef rlm, CFRunLoopActivity activity) { /* DOES CALLOUT */ cf_trace(KDEBUG_EVENT_CFRL_IS_DOING_OBSERVERS | DBG_FUNC_START, rl, rlm, activity, 0); @@ -1917,7 +1930,7 @@ static void __CFRunLoopCollectSources0(const void *value, void *context) { } } -static void __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE0_PERFORM_FUNCTION__() __attribute__((noinline)); +static void __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE0_PERFORM_FUNCTION__(void (*perform)(void *), void *info) __attribute__((noinline)); static void __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE0_PERFORM_FUNCTION__(void (*perform)(void *), void *info) { if (perform) { perform(info); @@ -1925,7 +1938,15 @@ static void __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE0_PERFORM_FUNCTION__(void (*pe __asm __volatile__(""); // thwart tail-call optimization } -static void __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE1_PERFORM_FUNCTION__() __attribute__((noinline)); +static void __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE1_PERFORM_FUNCTION__( +#if DEPLOYMENT_TARGET_MACOSX || DEPLOYMENT_TARGET_EMBEDDED || DEPLOYMENT_TARGET_EMBEDDED_MINI + void *(*perform)(void *msg, CFIndex size, CFAllocatorRef allocator, void *info), + mach_msg_header_t *msg, CFIndex size, mach_msg_header_t **reply, +#else + void (*perform)(void *), +#endif + void *info) __attribute__((noinline)); + static void __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE1_PERFORM_FUNCTION__( #if DEPLOYMENT_TARGET_MACOSX || DEPLOYMENT_TARGET_EMBEDDED || DEPLOYMENT_TARGET_EMBEDDED_MINI void *(*perform)(void *msg, CFIndex size, CFAllocatorRef allocator, void *info), @@ -2020,9 +2041,9 @@ CF_INLINE void __CFRunLoopDebugInfoForRunLoopSource(CFRunLoopSourceRef rls) { } // msg, size and reply are unused on Windows -static Boolean __CFRunLoopDoSource1() __attribute__((noinline)); - #if DEPLOYMENT_TARGET_MACOSX || DEPLOYMENT_TARGET_EMBEDDED || DEPLOYMENT_TARGET_EMBEDDED_MINI +static Boolean __CFRunLoopDoSource1(CFRunLoopRef rl, CFRunLoopModeRef rlm, CFRunLoopSourceRef rls, mach_msg_header_t *msg, CFIndex size, mach_msg_header_t **reply) __attribute__((noinline)); + static Boolean __CFRunLoopDoSource1(CFRunLoopRef rl, CFRunLoopModeRef rlm, CFRunLoopSourceRef rls, mach_msg_header_t *msg, CFIndex size, mach_msg_header_t **reply) #else static Boolean __CFRunLoopDoSource1(CFRunLoopRef rl, CFRunLoopModeRef rlm, CFRunLoopSourceRef rls) @@ -2812,7 +2833,7 @@ static int32_t __CFRunLoopRun(CFRunLoopRef rl, CFRunLoopModeRef rlm, CFTimeInter #elif DEPLOYMENT_TARGET_WINDOWS // Here, use the app-supplied message queue mask. They will set this if they are interested in having this run loop receive windows messages. __CFRunLoopWaitForMultipleObjects(waitSet, NULL, poll ? 0 : TIMEOUT_INFINITY, rlm->_msgQMask, &livePort, &windowsMessageReceived); -#elif DEPLOYMENT_TARGET_LINUX && !TARGET_OS_CYGWIN +#elif DEPLOYMENT_TARGET_LINUX __CFRunLoopServiceFileDescriptors(waitSet, CFPORT_NULL, TIMEOUT_INFINITY, &livePort); #endif @@ -3069,7 +3090,7 @@ void CFRunLoopWakeUp(CFRunLoopRef rl) { if (__CFMainThreadHasExited && rl == CFRunLoopGetMain()) { static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ - os_log_error(_CFOSLog(), "Attempting to wake up main runloop, but the main thread has exited. This message will only log once. Break on _CFRunLoopError_MainThreadHasExited to debug."); + os_log_error(_CFOSLog(), "Attempting to wake up main runloop, but the main thread as exited. This message will only log once. Break on _CFRunLoopError_MainThreadHasExited to debug."); }); _CFRunLoopError_MainThreadHasExited(); return; @@ -3219,6 +3240,8 @@ Boolean CFRunLoopContainsSource(CFRunLoopRef rl, CFRunLoopSourceRef rls, CFStrin return hasValue; } +CF_BREAKPOINT_FUNCTION(void __CFRunLoopError_AddingSourceLackingReceiveRight(void)); + void CFRunLoopAddSource(CFRunLoopRef rl, CFRunLoopSourceRef rls, CFStringRef modeName) { /* DOES CALLOUT */ CHECK_FOR_FORK(); if (__CFRunLoopIsDeallocating(rl)) return; @@ -3231,6 +3254,22 @@ void CFRunLoopAddSource(CFRunLoopRef rl, CFRunLoopSourceRef rls, CFStringRef mod return; } +#if TARGET_OS_MAC + // Preflight Version-1 ports to make sure their mach port has a RECV right. + if (rls->_context.version0.version == 1) { + mach_port_t const mp = rls->_context.version1.getPort(rls->_context.version1.info); + mach_port_type_t type = MACH_PORT_TYPE_NONE; + kern_return_t const ret = mach_port_type(mach_task_self(), mp, &type); + if (ret == KERN_SUCCESS && (type & MACH_PORT_TYPE_RECEIVE) == 0) { + static dispatch_once_t onceToken; + dispatch_once(&onceToken, ^{ + CFLog(kCFLogLevelError, CFSTR("Attempting to add a runloop source %p to runloop %p in mode '%@', but the port associated with this source does not have a receive right. This means your source will never be signalled and is likely an error. Break on __CFRunLoopError_AddingSourceLackingReceiveRight to debug. This message will only appear once per execution."), rls, rl, modeName); + }); + __CFRunLoopError_AddingSourceLackingReceiveRight(); + } + } +#endif + if (!__CFIsValid(rls)) return; Boolean doVer0Callout = false; __CFRunLoopLock(rl); @@ -3532,7 +3571,7 @@ void CFRunLoopAddTimer(CFRunLoopRef rl, CFRunLoopTimerRef rlt, CFStringRef modeN if (__CFMainThreadHasExited && rl == CFRunLoopGetMain()) { static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ - CFLog(kCFLogLevelError, CFSTR("Attempting to add timer to main runloop, but the main thread has exited. This message will only log once. Break on _CFRunLoopError_MainThreadHasExited to debug.")); + CFLog(kCFLogLevelError, CFSTR("Attempting to add timer to main runloop, but the main thread as exited. This message will only log once. Break on _CFRunLoopError_MainThreadHasExited to debug.")); }); _CFRunLoopError_MainThreadHasExited(); return; @@ -3691,7 +3730,7 @@ static void __CFRunLoopSourceDeallocate(CFTypeRef cf) { /* DOES CALLOUT */ memset((char *)cf + sizeof(CFRuntimeBase), 0, sizeof(struct __CFRunLoopSource) - sizeof(CFRuntimeBase)); } -static const CFRuntimeClass __CFRunLoopSourceClass = { +const CFRuntimeClass __CFRunLoopSourceClass = { _kCFRuntimeScannedObject, "CFRunLoopSource", NULL, // init @@ -3704,9 +3743,7 @@ static const CFRuntimeClass __CFRunLoopSourceClass = { }; CFTypeID CFRunLoopSourceGetTypeID(void) { - static dispatch_once_t initOnce; - dispatch_once(&initOnce, ^{ __kCFRunLoopSourceTypeID = _CFRuntimeRegisterClass(&__CFRunLoopSourceClass); }); - return __kCFRunLoopSourceTypeID; + return _kCFRuntimeIDCFRunLoopSource; } CFRunLoopSourceRef CFRunLoopSourceCreate(CFAllocatorRef allocator, CFIndex order, CFRunLoopSourceContext *context) { @@ -3883,7 +3920,7 @@ static void __CFRunLoopObserverDeallocate(CFTypeRef cf) { /* DOES CALLOUT */ pthread_mutex_destroy(&rlo->_lock); } -static const CFRuntimeClass __CFRunLoopObserverClass = { +const CFRuntimeClass __CFRunLoopObserverClass = { 0, "CFRunLoopObserver", NULL, // init @@ -3896,9 +3933,7 @@ static const CFRuntimeClass __CFRunLoopObserverClass = { }; CFTypeID CFRunLoopObserverGetTypeID(void) { - static dispatch_once_t initOnce; - dispatch_once(&initOnce, ^{ __kCFRunLoopObserverTypeID = _CFRuntimeRegisterClass(&__CFRunLoopObserverClass); }); - return __kCFRunLoopObserverTypeID; + return _kCFRuntimeIDCFRunLoopObserver; } CFRunLoopObserverRef CFRunLoopObserverCreate(CFAllocatorRef allocator, CFOptionFlags activities, Boolean repeats, CFIndex order, CFRunLoopObserverCallBack callout, CFRunLoopObserverContext *context) { @@ -4076,7 +4111,7 @@ static void __CFRunLoopTimerDeallocate(CFTypeRef cf) { /* DOES CALLOUT */ pthread_mutex_destroy(&rlt->_lock); } -static const CFRuntimeClass __CFRunLoopTimerClass = { +const CFRuntimeClass __CFRunLoopTimerClass = { 0, "CFRunLoopTimer", NULL, // init @@ -4089,9 +4124,7 @@ static const CFRuntimeClass __CFRunLoopTimerClass = { }; CFTypeID CFRunLoopTimerGetTypeID(void) { - static dispatch_once_t initOnce; - dispatch_once(&initOnce, ^{ __kCFRunLoopTimerTypeID = _CFRuntimeRegisterClass(&__CFRunLoopTimerClass); }); - return __kCFRunLoopTimerTypeID; + return _kCFRuntimeIDCFRunLoopTimer; } CFRunLoopTimerRef CFRunLoopTimerCreate(CFAllocatorRef allocator, CFAbsoluteTime fireDate, CFTimeInterval interval, CFOptionFlags flags, CFIndex order, CFRunLoopTimerCallBack callout, CFRunLoopTimerContext *context) { diff --git a/CoreFoundation/RunLoop.subproj/CFRunLoop.h b/CoreFoundation/RunLoop.subproj/CFRunLoop.h index 9fef4fa178..1f11fa681b 100644 --- a/CoreFoundation/RunLoop.subproj/CFRunLoop.h +++ b/CoreFoundation/RunLoop.subproj/CFRunLoop.h @@ -1,7 +1,7 @@ /* CFRunLoop.h - Copyright (c) 1998-2017, Apple Inc. and the Swift project authors + Copyright (c) 1998-2018, Apple Inc. and the Swift project authors - Portions Copyright (c) 2014-2017, Apple Inc. and the Swift project authors + Portions Copyright (c) 2014-2018, Apple Inc. and the Swift project authors Licensed under Apache License v2.0 with Runtime Library Exception See http://swift.org/LICENSE.txt for license information See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors diff --git a/CoreFoundation/RunLoop.subproj/CFSocket.c b/CoreFoundation/RunLoop.subproj/CFSocket.c index 33a57cf69a..0b37772e9f 100644 --- a/CoreFoundation/RunLoop.subproj/CFSocket.c +++ b/CoreFoundation/RunLoop.subproj/CFSocket.c @@ -1,7 +1,7 @@ /* CFSocket.c - Copyright (c) 1999-2017, Apple Inc. and the Swift project authors + Copyright (c) 1999-2018, Apple Inc. and the Swift project authors - Portions Copyright (c) 2014-2017, Apple Inc. and the Swift project authors + Portions Copyright (c) 2014-2018, Apple Inc. and the Swift project authors Licensed under Apache License v2.0 with Runtime Library Exception See http://swift.org/LICENSE.txt for license information See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors @@ -177,7 +177,7 @@ static void __CFSocketDeallocate(CFTypeRef cf) { static CFTypeID __kCFSocketTypeID = _kCFRuntimeNotATypeID; -static const CFRuntimeClass __CFSocketClass = { +const CFRuntimeClass __CFSocketClass = { 0, "CFSocket", NULL, // init @@ -942,10 +942,10 @@ Boolean __CFSocketGetBytesAvailable(CFSocketRef s, CFIndex* ctBytesAvailable) { #include #include #include -#endif #if TARGET_OS_CYGWIN #include #endif +#endif #include #include #include @@ -957,6 +957,7 @@ Boolean __CFSocketGetBytesAvailable(CFSocketRef s, CFIndex* ctBytesAvailable) { #include #include #include "CFInternal.h" +#include "CFRuntime_Internal.h" #ifndef NBBY #define NBBY 8 @@ -2470,9 +2471,7 @@ static void __CFSocketDeallocate(CFTypeRef cf) { s->_bufferedReadError = 0; } -static CFTypeID __kCFSocketTypeID = _kCFRuntimeNotATypeID; - -static const CFRuntimeClass __CFSocketClass = { +const CFRuntimeClass __CFSocketClass = { 0, "CFSocket", NULL, // init @@ -2487,7 +2486,6 @@ static const CFRuntimeClass __CFSocketClass = { CFTypeID CFSocketGetTypeID(void) { static dispatch_once_t initOnce; dispatch_once(&initOnce, ^{ - __kCFSocketTypeID = _CFRuntimeRegisterClass(&__CFSocketClass); // initOnce covered #if DEPLOYMENT_TARGET_MACOSX || DEPLOYMENT_TARGET_EMBEDDED || DEPLOYMENT_TARGET_EMBEDDED_MINI struct rlimit lim1; int ret1 = getrlimit(RLIMIT_NOFILE, &lim1); @@ -2505,7 +2503,7 @@ CFTypeID CFSocketGetTypeID(void) { } #endif }); - return __kCFSocketTypeID; + return _kCFRuntimeIDCFSocket; } #if DEPLOYMENT_TARGET_WINDOWS diff --git a/CoreFoundation/RunLoop.subproj/CFSocket.h b/CoreFoundation/RunLoop.subproj/CFSocket.h index 462d6b1089..ee6897dcf2 100644 --- a/CoreFoundation/RunLoop.subproj/CFSocket.h +++ b/CoreFoundation/RunLoop.subproj/CFSocket.h @@ -1,7 +1,7 @@ /* CFSocket.h - Copyright (c) 1999-2017, Apple Inc. and the Swift project authors + Copyright (c) 1999-2018, Apple Inc. and the Swift project authors - Portions Copyright (c) 2014-2017, Apple Inc. and the Swift project authors + Portions Copyright (c) 2014-2018, Apple Inc. and the Swift project authors Licensed under Apache License v2.0 with Runtime Library Exception See http://swift.org/LICENSE.txt for license information See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors diff --git a/CoreFoundation/Stream.subproj/CFConcreteStreams.c b/CoreFoundation/Stream.subproj/CFConcreteStreams.c index b86ec5dff4..4a722cb82e 100644 --- a/CoreFoundation/Stream.subproj/CFConcreteStreams.c +++ b/CoreFoundation/Stream.subproj/CFConcreteStreams.c @@ -1,7 +1,7 @@ /* CFConcreteStreams.c - Copyright (c) 2000-2017, Apple Inc. and the Swift project authors + Copyright (c) 2000-2018, Apple Inc. and the Swift project authors - Portions Copyright (c) 2014-2017, Apple Inc. and the Swift project authors + Portions Copyright (c) 2014-2018, Apple Inc. and the Swift project authors Licensed under Apache License v2.0 with Runtime Library Exception See http://swift.org/LICENSE.txt for license information See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors @@ -101,10 +101,10 @@ static Boolean constructFD(_CFFileStreamContext *fileStream, CFStreamError *erro flags |= (_O_BINARY|_O_NOINHERIT); if (_CFURLGetWideFileSystemRepresentation(fileStream->url, TRUE, path, CFMaxPathSize) == FALSE) #else - char path[CFMaxPathSize]; + char path[CFMaxPathSize]; if (CFURLGetFileSystemRepresentation(fileStream->url, TRUE, (UInt8 *)path, CFMaxPathSize) == FALSE) #endif - { + { error->error = ENOENT; error->domain = kCFStreamErrorDomainPOSIX; return FALSE; @@ -116,29 +116,29 @@ static Boolean constructFD(_CFFileStreamContext *fileStream, CFStreamError *erro do { #if DEPLOYMENT_TARGET_WINDOWS - fileStream->fd = _wopen(path, flags, 0666); + fileStream->fd = _wopen(path, flags, 0666); #else - fileStream->fd = open((const char *)path, flags, 0666); + fileStream->fd = open((const char *)path, flags, 0666); #endif if (fileStream->fd < 0) break; if ((fileStream->offset != -1) && (lseek(fileStream->fd, fileStream->offset, SEEK_SET) == -1)) break; - + #ifdef REAL_FILE_SCHEDULING if (fileStream->rlInfo.rlArray != NULL) { constructCFFD(fileStream, forRead, stream); } #endif - + return TRUE; } while (1); - + __CFBitSet(fileStream->flags, USE_RUNLOOP_ARRAY); error->error = errno; error->domain = kCFStreamErrorDomainPOSIX; - + return FALSE; } diff --git a/CoreFoundation/Stream.subproj/CFSocketStream.c b/CoreFoundation/Stream.subproj/CFSocketStream.c index 60c9191195..e1406a5e16 100644 --- a/CoreFoundation/Stream.subproj/CFSocketStream.c +++ b/CoreFoundation/Stream.subproj/CFSocketStream.c @@ -1,7 +1,7 @@ /* CFSocketStream.c - Copyright (c) 2000-2017, Apple Inc. and the Swift project authors + Copyright (c) 2000-2018, Apple Inc. and the Swift project authors - Portions Copyright (c) 2014-2017, Apple Inc. and the Swift project authors + Portions Copyright (c) 2014-2018, Apple Inc. and the Swift project authors Licensed under Apache License v2.0 with Runtime Library Exception See http://swift.org/LICENSE.txt for license information See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors diff --git a/CoreFoundation/Stream.subproj/CFStream.c b/CoreFoundation/Stream.subproj/CFStream.c index 5fffb592fa..9f130c79df 100644 --- a/CoreFoundation/Stream.subproj/CFStream.c +++ b/CoreFoundation/Stream.subproj/CFStream.c @@ -1,7 +1,7 @@ /* CFStream.c - Copyright (c) 2000-2017, Apple Inc. and the Swift project authors + Copyright (c) 2000-2018, Apple Inc. and the Swift project authors - Portions Copyright (c) 2014-2017, Apple Inc. and the Swift project authors + Portions Copyright (c) 2014-2018, Apple Inc. and the Swift project authors Licensed under Apache License v2.0 with Runtime Library Exception See http://swift.org/LICENSE.txt for license information See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors @@ -13,6 +13,7 @@ #include #include "CFStreamInternal.h" #include "CFInternal.h" +#include "CFRuntime_Internal.h" #include #if defined(DEBUG) @@ -66,9 +67,6 @@ enum { static CFLock_t sSourceLock = CFLockInit; static CFMutableDictionaryRef sSharedSources = NULL; -static CFTypeID __kCFReadStreamTypeID = _kCFRuntimeNotATypeID; -static CFTypeID __kCFWriteStreamTypeID = _kCFRuntimeNotATypeID; - // Just reads the bits, for those cases where we don't want to go through any callback checking #define __CFStreamGetStatus(x) __CFBitfieldGetValue((x)->flags, MAX_STATUS_CODE_BIT, MIN_STATUS_CODE_BIT) @@ -185,7 +183,7 @@ static CFStringRef __CFStreamCopyDescription(CFTypeRef cf) { } else { contextDescription = CFStringCreateWithFormat(CFGetAllocator(stream), NULL, CFSTR("info = %p"), _CFStreamGetInfoPointer(stream)); } - if (CFGetTypeID(cf) == __kCFReadStreamTypeID) { + if (CFGetTypeID(cf) == _kCFRuntimeIDCFReadStream) { desc = CFStringCreateWithFormat(CFGetAllocator(stream), NULL, CFSTR("{%@}"), stream, contextDescription); } else { desc = CFStringCreateWithFormat(CFGetAllocator(stream), NULL, CFSTR("{%@}"), stream, contextDescription); @@ -315,7 +313,7 @@ static void __CFStreamDeallocate(CFTypeRef cf) { #endif } -static const CFRuntimeClass __CFReadStreamClass = { +const CFRuntimeClass __CFReadStreamClass = { 0, "CFReadStream", NULL, // init @@ -327,7 +325,7 @@ static const CFRuntimeClass __CFReadStreamClass = { __CFStreamCopyDescription }; -static const CFRuntimeClass __CFWriteStreamClass = { +const CFRuntimeClass __CFWriteStreamClass = { 0, "CFWriteStream", NULL, // init @@ -345,22 +343,16 @@ CONST_STRING_DECL(kCFStreamPropertySocketRemotePortNumber, "kCFStreamPropertySoc CONST_STRING_DECL(kCFStreamPropertyDataWritten, "kCFStreamPropertyDataWritten") CONST_STRING_DECL(kCFStreamPropertyAppendToFile, "kCFStreamPropertyAppendToFile") -CF_PRIVATE void __CFStreamInitialize(void) { - static dispatch_once_t initOnce; - dispatch_once(&initOnce, ^{ __kCFReadStreamTypeID = _CFRuntimeRegisterClass(&__CFReadStreamClass); __kCFWriteStreamTypeID = _CFRuntimeRegisterClass(&__CFWriteStreamClass); }); -} - - CF_EXPORT CFTypeID CFReadStreamGetTypeID(void) { - return __kCFReadStreamTypeID; + return _kCFRuntimeIDCFReadStream; } CF_EXPORT CFTypeID CFWriteStreamGetTypeID(void) { - return __kCFWriteStreamTypeID; + return _kCFRuntimeIDCFWriteStream; } static struct _CFStream *_CFStreamCreate(CFAllocatorRef allocator, Boolean isReadStream) { - struct _CFStream *newStream = (struct _CFStream *)_CFRuntimeCreateInstance(allocator, isReadStream ? __kCFReadStreamTypeID : __kCFWriteStreamTypeID, sizeof(struct _CFStream) - sizeof(CFRuntimeBase), NULL); + struct _CFStream *newStream = (struct _CFStream *)_CFRuntimeCreateInstance(allocator, isReadStream ? _kCFRuntimeIDCFReadStream : _kCFRuntimeIDCFWriteStream, sizeof(struct _CFStream) - sizeof(CFRuntimeBase), NULL); if (newStream) { // numStreamInstances ++; newStream->flags = 0; @@ -895,12 +887,12 @@ CF_PRIVATE CFStreamStatus _CFStreamGetStatus(struct _CFStream *stream) { } CF_EXPORT CFStreamStatus CFReadStreamGetStatus(CFReadStreamRef stream) { - CF_OBJC_FUNCDISPATCHV(__kCFReadStreamTypeID, CFStreamStatus, (NSInputStream *)stream, streamStatus); + CF_OBJC_FUNCDISPATCHV(_kCFRuntimeIDCFReadStream, CFStreamStatus, (NSInputStream *)stream, streamStatus); return _CFStreamGetStatus((struct _CFStream *)stream); } CF_EXPORT CFStreamStatus CFWriteStreamGetStatus(CFWriteStreamRef stream) { - CF_OBJC_FUNCDISPATCHV(__kCFWriteStreamTypeID, CFStreamStatus, (NSOutputStream *)stream, streamStatus); + CF_OBJC_FUNCDISPATCHV(_kCFRuntimeIDCFWriteStream, CFStreamStatus, (NSOutputStream *)stream, streamStatus); return _CFStreamGetStatus((struct _CFStream *)stream); } @@ -920,12 +912,12 @@ static CFStreamError _CFStreamGetStreamError(struct _CFStream *stream) { } CF_EXPORT CFStreamError CFReadStreamGetError(CFReadStreamRef stream) { - CF_OBJC_FUNCDISPATCHV(__kCFReadStreamTypeID, CFStreamError, (NSInputStream *)stream, _cfStreamError); + CF_OBJC_FUNCDISPATCHV(_kCFRuntimeIDCFReadStream, CFStreamError, (NSInputStream *)stream, _cfStreamError); return _CFStreamGetStreamError((struct _CFStream *)stream); } CF_EXPORT CFStreamError CFWriteStreamGetError(CFWriteStreamRef stream) { - CF_OBJC_FUNCDISPATCHV(__kCFWriteStreamTypeID, CFStreamError, (NSOutputStream *)stream, _cfStreamError); + CF_OBJC_FUNCDISPATCHV(_kCFRuntimeIDCFWriteStream, CFStreamError, (NSOutputStream *)stream, _cfStreamError); return _CFStreamGetStreamError((struct _CFStream *)stream); } @@ -941,13 +933,13 @@ static CFErrorRef _CFStreamCopyError(struct _CFStream *stream) { } CF_EXPORT CFErrorRef CFReadStreamCopyError(CFReadStreamRef stream) { - CF_OBJC_FUNCDISPATCHV(__kCFReadStreamTypeID, CFErrorRef, (NSInputStream *)stream, streamError); + CF_OBJC_FUNCDISPATCHV(_kCFRuntimeIDCFReadStream, CFErrorRef, (NSInputStream *)stream, streamError); return _CFStreamCopyError((struct _CFStream *)stream); } CF_EXPORT CFErrorRef CFWriteStreamCopyError(CFWriteStreamRef stream) { return _CFStreamCopyError((struct _CFStream *)stream); - CF_OBJC_FUNCDISPATCHV(__kCFWriteStreamTypeID, CFErrorRef, (NSOutputStream *)stream, streamError); + CF_OBJC_FUNCDISPATCHV(_kCFRuntimeIDCFWriteStream, CFErrorRef, (NSOutputStream *)stream, streamError); } CF_PRIVATE Boolean _CFStreamOpen(struct _CFStream *stream) { @@ -990,7 +982,7 @@ CF_PRIVATE Boolean _CFStreamOpen(struct _CFStream *stream) { } CF_EXPORT Boolean CFReadStreamOpen(CFReadStreamRef stream) { - if(CF_IS_OBJC(__kCFReadStreamTypeID, stream)) { + if(CF_IS_OBJC(_kCFRuntimeIDCFReadStream, stream)) { (void)CF_OBJC_CALLV((NSInputStream *)stream, open); return TRUE; } @@ -998,7 +990,7 @@ CF_EXPORT Boolean CFReadStreamOpen(CFReadStreamRef stream) { } CF_EXPORT Boolean CFWriteStreamOpen(CFWriteStreamRef stream) { - if(CF_IS_OBJC(__kCFWriteStreamTypeID, stream)) { + if(CF_IS_OBJC(_kCFRuntimeIDCFWriteStream, stream)) { (void)CF_OBJC_CALLV((NSOutputStream *)stream, open); return TRUE; } @@ -1006,17 +998,17 @@ CF_EXPORT Boolean CFWriteStreamOpen(CFWriteStreamRef stream) { } CF_EXPORT void CFReadStreamClose(CFReadStreamRef stream) { - CF_OBJC_FUNCDISPATCHV(__kCFReadStreamTypeID, void, (NSInputStream *)stream, close); + CF_OBJC_FUNCDISPATCHV(_kCFRuntimeIDCFReadStream, void, (NSInputStream *)stream, close); _CFStreamClose((struct _CFStream *)stream); } CF_EXPORT void CFWriteStreamClose(CFWriteStreamRef stream) { - CF_OBJC_FUNCDISPATCHV(__kCFWriteStreamTypeID, void, (NSOutputStream *)stream, close); + CF_OBJC_FUNCDISPATCHV(_kCFRuntimeIDCFWriteStream, void, (NSOutputStream *)stream, close); _CFStreamClose((struct _CFStream *)stream); } CF_EXPORT Boolean CFReadStreamHasBytesAvailable(CFReadStreamRef readStream) { - CF_OBJC_FUNCDISPATCHV(__kCFReadStreamTypeID, Boolean, (NSInputStream *)readStream, hasBytesAvailable); + CF_OBJC_FUNCDISPATCHV(_kCFRuntimeIDCFReadStream, Boolean, (NSInputStream *)readStream, hasBytesAvailable); struct _CFStream *stream = (struct _CFStream *)readStream; CFStreamStatus status = _CFStreamGetStatus(stream); const struct _CFStreamCallBacks *cb; @@ -1046,7 +1038,7 @@ CF_EXPORT Boolean CFReadStreamHasBytesAvailable(CFReadStreamRef readStream) { static void waitForOpen(struct _CFStream *stream); CFIndex CFReadStreamRead(CFReadStreamRef readStream, UInt8 *buffer, CFIndex bufferLength) { - CF_OBJC_FUNCDISPATCHV(__kCFReadStreamTypeID, CFIndex, (NSInputStream *)readStream, read:(uint8_t *)buffer maxLength:(NSUInteger)bufferLength); + CF_OBJC_FUNCDISPATCHV(_kCFRuntimeIDCFReadStream, CFIndex, (NSInputStream *)readStream, read:(uint8_t *)buffer maxLength:(NSUInteger)bufferLength); struct _CFStream *stream = (struct _CFStream *)readStream; CFStreamStatus status = _CFStreamGetStatus(stream); const struct _CFStreamCallBacks *cb = _CFStreamGetCallBackPtr(stream); @@ -1092,7 +1084,7 @@ CFIndex CFReadStreamRead(CFReadStreamRef readStream, UInt8 *buffer, CFIndex buff } CF_EXPORT const UInt8 *CFReadStreamGetBuffer(CFReadStreamRef readStream, CFIndex maxBytesToRead, CFIndex *numBytesRead) { - if (CF_IS_OBJC(__kCFReadStreamTypeID, readStream)) { + if (CF_IS_OBJC(_kCFRuntimeIDCFReadStream, readStream)) { uint8_t *bufPtr = NULL; Boolean gotBytes = (Boolean) CF_OBJC_CALLV((NSInputStream *)readStream, getBuffer:&bufPtr length:(NSUInteger *)numBytesRead); if(gotBytes) { @@ -1152,7 +1144,7 @@ CF_EXPORT const UInt8 *CFReadStreamGetBuffer(CFReadStreamRef readStream, CFIndex } CF_EXPORT Boolean CFWriteStreamCanAcceptBytes(CFWriteStreamRef writeStream) { - CF_OBJC_FUNCDISPATCHV(__kCFWriteStreamTypeID, Boolean, (NSOutputStream *)writeStream, hasSpaceAvailable); + CF_OBJC_FUNCDISPATCHV(_kCFRuntimeIDCFWriteStream, Boolean, (NSOutputStream *)writeStream, hasSpaceAvailable); struct _CFStream *stream = (struct _CFStream *)writeStream; CFStreamStatus status = _CFStreamGetStatus(stream); const struct _CFStreamCallBacks *cb; @@ -1180,7 +1172,7 @@ CF_EXPORT Boolean CFWriteStreamCanAcceptBytes(CFWriteStreamRef writeStream) { } CF_EXPORT CFIndex CFWriteStreamWrite(CFWriteStreamRef writeStream, const UInt8 *buffer, CFIndex bufferLength) { - CF_OBJC_FUNCDISPATCHV(__kCFWriteStreamTypeID, CFIndex, (NSOutputStream *)writeStream, write:(const uint8_t *)buffer maxLength:(NSUInteger)bufferLength); + CF_OBJC_FUNCDISPATCHV(_kCFRuntimeIDCFWriteStream, CFIndex, (NSOutputStream *)writeStream, write:(const uint8_t *)buffer maxLength:(NSUInteger)bufferLength); struct _CFStream *stream = (struct _CFStream *)writeStream; CFStreamStatus status = _CFStreamGetStatus(stream); const struct _CFStreamCallBacks *cb = _CFStreamGetCallBackPtr(stream); @@ -1234,12 +1226,12 @@ CF_PRIVATE CFTypeRef _CFStreamCopyProperty(struct _CFStream *stream, CFStringRef } CF_EXPORT CFTypeRef CFReadStreamCopyProperty(CFReadStreamRef stream, CFStringRef propertyName) { - CF_OBJC_FUNCDISPATCHV(__kCFReadStreamTypeID, CFTypeRef, (NSInputStream *)stream, propertyForKey:(NSString *)propertyName); + CF_OBJC_FUNCDISPATCHV(_kCFRuntimeIDCFReadStream, CFTypeRef, (NSInputStream *)stream, propertyForKey:(NSString *)propertyName); return _CFStreamCopyProperty((struct _CFStream *)stream, propertyName); } CF_EXPORT CFTypeRef CFWriteStreamCopyProperty(CFWriteStreamRef stream, CFStringRef propertyName) { - CF_OBJC_FUNCDISPATCHV(__kCFWriteStreamTypeID, CFTypeRef, (NSOutputStream *)stream, propertyForKey:(NSString *)propertyName); + CF_OBJC_FUNCDISPATCHV(_kCFRuntimeIDCFWriteStream, CFTypeRef, (NSOutputStream *)stream, propertyForKey:(NSString *)propertyName); return _CFStreamCopyProperty((struct _CFStream *)stream, propertyName); } @@ -1258,13 +1250,13 @@ CF_PRIVATE Boolean _CFStreamSetProperty(struct _CFStream *stream, CFStringRef pr CF_EXPORT Boolean CFReadStreamSetProperty(CFReadStreamRef stream, CFStringRef propertyName, CFTypeRef propertyValue) { - CF_OBJC_FUNCDISPATCHV(__kCFReadStreamTypeID, Boolean, (NSInputStream *)stream, setProperty:(id)propertyValue forKey:(NSString *)propertyName); + CF_OBJC_FUNCDISPATCHV(_kCFRuntimeIDCFReadStream, Boolean, (NSInputStream *)stream, setProperty:(id)propertyValue forKey:(NSString *)propertyName); return _CFStreamSetProperty((struct _CFStream *)stream, propertyName, propertyValue); } CF_EXPORT Boolean CFWriteStreamSetProperty(CFWriteStreamRef stream, CFStringRef propertyName, CFTypeRef propertyValue) { - CF_OBJC_FUNCDISPATCHV(__kCFWriteStreamTypeID, Boolean, (NSOutputStream *)stream, setProperty:(id)propertyValue forKey:(NSString *)propertyName); + CF_OBJC_FUNCDISPATCHV(_kCFRuntimeIDCFWriteStream, Boolean, (NSOutputStream *)stream, setProperty:(id)propertyValue forKey:(NSString *)propertyName); return _CFStreamSetProperty((struct _CFStream *)stream, propertyName, propertyValue); } @@ -1324,7 +1316,7 @@ CF_PRIVATE Boolean _CFStreamSetClient(struct _CFStream *stream, CFOptionFlags st CF_EXPORT Boolean CFReadStreamSetClient(CFReadStreamRef readStream, CFOptionFlags streamEvents, CFReadStreamClientCallBack clientCB, CFStreamClientContext *clientContext) { #if defined(CFSTREAM_SUPPORTS_BRIDGING) - if (CF_IS_OBJC(__kCFReadStreamTypeID, (const void *)(NSInputStream *)readStream)) { + if (CF_IS_OBJC(_kCFRuntimeIDCFReadStream, (const void *)(NSInputStream *)readStream)) { NSInputStream* is = (NSInputStream*) readStream; if ([is respondsToSelector:@selector(_setCFClientFlags:callback:context:)]) @@ -1347,7 +1339,7 @@ CF_EXPORT Boolean CFReadStreamSetClient(CFReadStreamRef readStream, CFOptionFlag CF_EXPORT Boolean CFWriteStreamSetClient(CFWriteStreamRef writeStream, CFOptionFlags streamEvents, CFWriteStreamClientCallBack clientCB, CFStreamClientContext *clientContext) { #if defined(CFSTREAM_SUPPORTS_BRIDGING) - if (CF_IS_OBJC(__kCFWriteStreamTypeID, (const void *)(NSOutputStream *)writeStream)) { + if (CF_IS_OBJC(_kCFRuntimeIDCFWriteStream, (const void *)(NSOutputStream *)writeStream)) { NSOutputStream* os = (NSOutputStream*) writeStream; if ([os respondsToSelector:@selector(_setCFClientFlags:callback:context:)]) @@ -1543,7 +1535,7 @@ CF_PRIVATE void _CFStreamScheduleWithRunLoop(struct _CFStream *stream, CFRunLoop CF_EXPORT void CFReadStreamScheduleWithRunLoop(CFReadStreamRef stream, CFRunLoopRef runLoop, CFStringRef runLoopMode) { #if defined(CFSTREAM_SUPPORTS_BRIDGING) - if (CF_IS_OBJC(__kCFReadStreamTypeID, (const void *)(NSInputStream *)stream)) { + if (CF_IS_OBJC(_kCFRuntimeIDCFReadStream, (const void *)(NSInputStream *)stream)) { NSInputStream* is = (NSInputStream*) stream; if ([is respondsToSelector:@selector(_scheduleInCFRunLoop:forMode:)]) [is _scheduleInCFRunLoop:runLoop forMode:runLoopMode]; @@ -1558,7 +1550,7 @@ CF_EXPORT void CFReadStreamScheduleWithRunLoop(CFReadStreamRef stream, CFRunLoop CF_EXPORT void CFWriteStreamScheduleWithRunLoop(CFWriteStreamRef stream, CFRunLoopRef runLoop, CFStringRef runLoopMode) { #if defined(CFSTREAM_SUPPORTS_BRIDGING) - if (CF_IS_OBJC(__kCFWriteStreamTypeID, (const void *)(NSOutputStream *)stream)) { + if (CF_IS_OBJC(_kCFRuntimeIDCFWriteStream, (const void *)(NSOutputStream *)stream)) { NSOutputStream* os = (NSOutputStream*) stream; if ([os respondsToSelector:@selector(_scheduleInCFRunLoop:forMode:)]) [os _scheduleInCFRunLoop:runLoop forMode:runLoopMode]; @@ -1630,7 +1622,7 @@ CF_PRIVATE void _CFStreamUnscheduleFromRunLoop(struct _CFStream *stream, CFRunLo CF_EXPORT void CFReadStreamUnscheduleFromRunLoop(CFReadStreamRef stream, CFRunLoopRef runLoop, CFStringRef runLoopMode) { #if defined(CFSTREAM_SUPPORTS_BRIDGING) - if (CF_IS_OBJC(__kCFReadStreamTypeID, (const void *)(NSInputStream *)stream)) { + if (CF_IS_OBJC(_kCFRuntimeIDCFReadStream, (const void *)(NSInputStream *)stream)) { NSInputStream* is = (NSInputStream*) stream; if ([is respondsToSelector:@selector(_unscheduleFromCFRunLoop:forMode:)]) [is _unscheduleFromCFRunLoop:runLoop forMode:runLoopMode]; @@ -1645,7 +1637,7 @@ CF_EXPORT void CFReadStreamUnscheduleFromRunLoop(CFReadStreamRef stream, CFRunLo void CFWriteStreamUnscheduleFromRunLoop(CFWriteStreamRef stream, CFRunLoopRef runLoop, CFStringRef runLoopMode) { #if defined(CFSTREAM_SUPPORTS_BRIDGING) - if (CF_IS_OBJC(__kCFWriteStreamTypeID, (const void *)(NSOutputStream *)stream)) { + if (CF_IS_OBJC(_kCFRuntimeIDCFWriteStream, (const void *)(NSOutputStream *)stream)) { NSOutputStream* os = (NSOutputStream*) stream; if ([os respondsToSelector:@selector(_unscheduleFromCFRunLoop:forMode:)]) [os _unscheduleFromCFRunLoop:runLoop forMode:runLoopMode]; @@ -1925,7 +1917,7 @@ void __CFStreamCleanup(void) { fprintf(stderr, "*** CFNetwork is shutting down, but %ld streams are still scheduled.\n", count); #if defined(DEBUG) for (i = 0; i < count;i ++) { - if ((CFGetTypeID(keys[i]) == __kCFReadStreamTypeID) || (CFGetTypeID(keys[i]) == __kCFWriteStreamTypeID)) { + if ((CFGetTypeID(keys[i]) == _kCFRuntimeIDCFReadStream) || (CFGetTypeID(keys[i]) == _kCFRuntimeIDCFWriteStream)) { CFShow(keys[i]); } } diff --git a/CoreFoundation/Stream.subproj/CFStream.h b/CoreFoundation/Stream.subproj/CFStream.h index 274ad9095d..1f59e232e6 100644 --- a/CoreFoundation/Stream.subproj/CFStream.h +++ b/CoreFoundation/Stream.subproj/CFStream.h @@ -1,7 +1,7 @@ /* CFStream.h - Copyright (c) 2000-2017, Apple Inc. and the Swift project authors + Copyright (c) 2000-2018, Apple Inc. and the Swift project authors - Portions Copyright (c) 2014-2017, Apple Inc. and the Swift project authors + Portions Copyright (c) 2014-2018, Apple Inc. and the Swift project authors Licensed under Apache License v2.0 with Runtime Library Exception See http://swift.org/LICENSE.txt for license information See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors @@ -22,6 +22,11 @@ CF_IMPLICIT_BRIDGING_ENABLED CF_EXTERN_C_BEGIN +typedef struct { + CFIndex domain; + SInt32 error; +} CFStreamError; + typedef CFStringRef CFStreamPropertyKey CF_EXTENSIBLE_STRING_ENUM; typedef CF_ENUM(CFIndex, CFStreamStatus) { @@ -46,17 +51,17 @@ typedef CF_OPTIONS(CFOptionFlags, CFStreamEventType) { typedef struct { CFIndex version; - void *info; - void *(*retain)(void *info); - void (*release)(void *info); - CFStringRef (*copyDescription)(void *info); + void * _Null_unspecified info; + void *_Null_unspecified(* _Null_unspecified retain)(void * _Null_unspecified info); + void (* _Null_unspecified release)(void * _Null_unspecified info); + CFStringRef _Null_unspecified (* _Null_unspecified copyDescription)(void * _Null_unspecified info); } CFStreamClientContext; typedef struct CF_BRIDGED_MUTABLE_TYPE(NSInputStream) __CFReadStream * CFReadStreamRef; typedef struct CF_BRIDGED_MUTABLE_TYPE(NSOutputStream) __CFWriteStream * CFWriteStreamRef; -typedef void (*CFReadStreamClientCallBack)(CFReadStreamRef stream, CFStreamEventType type, void *clientCallBackInfo); -typedef void (*CFWriteStreamClientCallBack)(CFWriteStreamRef stream, CFStreamEventType type, void *clientCallBackInfo); +typedef void (*CFReadStreamClientCallBack)(CFReadStreamRef _Null_unspecified stream, CFStreamEventType type, void * _Null_unspecified clientCallBackInfo); +typedef void (*CFWriteStreamClientCallBack)(CFWriteStreamRef _Null_unspecified stream, CFStreamEventType type, void * _Null_unspecified clientCallBackInfo); CF_EXPORT CFTypeID CFReadStreamGetTypeID(void); @@ -67,74 +72,280 @@ CFTypeID CFWriteStreamGetTypeID(void); /* Value will be a CFData containing all bytes thusfar written; used to recover the data written to a memory write stream. */ CF_EXPORT -const CFStreamPropertyKey kCFStreamPropertyDataWritten; +const CFStreamPropertyKey _Null_unspecified kCFStreamPropertyDataWritten; /* Pass kCFAllocatorNull for bytesDeallocator to prevent CFReadStream from deallocating bytes; otherwise, CFReadStream will deallocate bytes when the stream is destroyed */ CF_EXPORT -CFReadStreamRef CFReadStreamCreateWithBytesNoCopy(CFAllocatorRef alloc, const UInt8 *bytes, CFIndex length, CFAllocatorRef bytesDeallocator); +CFReadStreamRef _Null_unspecified CFReadStreamCreateWithBytesNoCopy(CFAllocatorRef _Null_unspecified alloc, const UInt8 * _Null_unspecified bytes, CFIndex length, CFAllocatorRef _Null_unspecified bytesDeallocator); /* The stream writes into the buffer given; when bufferCapacity is exhausted, the stream is exhausted (status becomes kCFStreamStatusAtEnd) */ CF_EXPORT -CFWriteStreamRef CFWriteStreamCreateWithBuffer(CFAllocatorRef alloc, UInt8 *buffer, CFIndex bufferCapacity); +CFWriteStreamRef _Null_unspecified CFWriteStreamCreateWithBuffer(CFAllocatorRef _Null_unspecified alloc, UInt8 * _Null_unspecified buffer, CFIndex bufferCapacity); /* New buffers are allocated from bufferAllocator as bytes are written to the stream. At any point, you can recover the bytes thusfar written by asking for the property kCFStreamPropertyDataWritten, above */ CF_EXPORT -CFWriteStreamRef CFWriteStreamCreateWithAllocatedBuffers(CFAllocatorRef alloc, CFAllocatorRef bufferAllocator); +CFWriteStreamRef _Null_unspecified CFWriteStreamCreateWithAllocatedBuffers(CFAllocatorRef _Null_unspecified alloc, CFAllocatorRef _Null_unspecified bufferAllocator); /* File streams */ CF_EXPORT -CFReadStreamRef CFReadStreamCreateWithFile(CFAllocatorRef alloc, CFURLRef fileURL); +CFReadStreamRef _Null_unspecified CFReadStreamCreateWithFile(CFAllocatorRef _Null_unspecified alloc, CFURLRef _Null_unspecified fileURL); CF_EXPORT -CFWriteStreamRef CFWriteStreamCreateWithFile(CFAllocatorRef alloc, CFURLRef fileURL); +CFWriteStreamRef _Null_unspecified CFWriteStreamCreateWithFile(CFAllocatorRef _Null_unspecified alloc, CFURLRef _Null_unspecified fileURL); CF_IMPLICIT_BRIDGING_DISABLED CF_EXPORT -void CFStreamCreateBoundPair(CFAllocatorRef alloc, CFReadStreamRef *readStream, CFWriteStreamRef *writeStream, CFIndex transferBufferSize); +void CFStreamCreateBoundPair(CFAllocatorRef _Null_unspecified alloc, CFReadStreamRef _Null_unspecified * _Null_unspecified readStream, CFWriteStreamRef _Null_unspecified * _Null_unspecified writeStream, CFIndex transferBufferSize); CF_IMPLICIT_BRIDGING_ENABLED /* Property for file write streams; value should be a CFBoolean. Set to TRUE to append to a file, rather than to replace its contents */ CF_EXPORT -const CFStreamPropertyKey kCFStreamPropertyAppendToFile; +const CFStreamPropertyKey _Null_unspecified kCFStreamPropertyAppendToFile; CF_EXPORT -const CFStreamPropertyKey kCFStreamPropertyFileCurrentOffset; // Value is a CFNumber +const CFStreamPropertyKey _Null_unspecified kCFStreamPropertyFileCurrentOffset; // Value is a CFNumber /* Socket stream properties */ /* Value will be a CFData containing the native handle */ CF_EXPORT -const CFStreamPropertyKey kCFStreamPropertySocketNativeHandle; +const CFStreamPropertyKey _Null_unspecified kCFStreamPropertySocketNativeHandle; /* Value will be a CFString, or NULL if unknown */ CF_EXPORT -const CFStreamPropertyKey kCFStreamPropertySocketRemoteHostName; +const CFStreamPropertyKey _Null_unspecified kCFStreamPropertySocketRemoteHostName; /* Value will be a CFNumber, or NULL if unknown */ CF_EXPORT -const CFStreamPropertyKey kCFStreamPropertySocketRemotePortNumber; +const CFStreamPropertyKey _Null_unspecified kCFStreamPropertySocketRemotePortNumber; +/* + * kCFStreamErrorDomainSOCKS + * + * Discussion: + * SOCKS proxy error domain. Errors formulated using inlines below. + * + */ +CF_EXPORT const int kCFStreamErrorDomainSOCKS CF_AVAILABLE(10_0, 2_0); + +/* + * kCFStreamPropertySOCKSProxy + * + * Discussion: + * Stream property key, for both set and copy operations. To set a + * stream to use a SOCKS proxy, call CFReadStreamSetProperty or + * CFWriteStreamSetProperty with the property name set to + * kCFStreamPropertySOCKSProxy and the value being a dictionary with + * at least the following two keys: kCFStreamPropertySOCKSProxyHost + * and kCFStreamPropertySOCKSProxyPort. The dictionary returned by + * SystemConfiguration for SOCKS proxies will work without + * alteration. + * + */ +CF_EXPORT const CFStringRef _Nonnull kCFStreamPropertySOCKSProxy CF_AVAILABLE(10_2, 2_0); + +/* + * kCFStreamPropertySOCKSProxyHost + * + * Discussion: + * CFDictionary key for SOCKS proxy information. The key + * kCFStreamPropertySOCKSProxyHost should contain a CFStringRef + * value representing the SOCKS proxy host. Defined to match + * kSCPropNetProxiesSOCKSProxy + * + */ +CF_EXPORT const CFStringRef _Nonnull kCFStreamPropertySOCKSProxyHost CF_AVAILABLE(10_2, 2_0); + +/* + * kCFStreamPropertySOCKSProxyPort + * + * Discussion: + * CFDictionary key for SOCKS proxy information. The key + * kCFStreamPropertySOCKSProxyPort should contain a CFNumberRef + * which itself is of type kCFNumberSInt32Type. This value should + * represent the port on which the proxy is listening. Defined to + * match kSCPropNetProxiesSOCKSPort + * + */ +CF_EXPORT const CFStringRef _Nonnull kCFStreamPropertySOCKSProxyPort CF_AVAILABLE(10_2, 2_0); + +/* + * kCFStreamPropertySOCKSVersion + * + * Discussion: + * CFDictionary key for SOCKS proxy information. By default, SOCKS5 + * will be used unless there is a kCFStreamPropertySOCKSVersion key + * in the dictionary. Its value must be + * kCFStreamSocketSOCKSVersion4 or kCFStreamSocketSOCKSVersion5 to + * set SOCKS4 or SOCKS5, respectively. + * + */ +CF_EXPORT const CFStringRef _Nonnull kCFStreamPropertySOCKSVersion CF_AVAILABLE(10_2, 2_0); + +/* + * kCFStreamSocketSOCKSVersion4 + * + * Discussion: + * CFDictionary value for SOCKS proxy information. Indcates that + * SOCKS will or is using version 4 of the SOCKS protocol. + * + */ +CF_EXPORT const CFStringRef _Nonnull kCFStreamSocketSOCKSVersion4 CF_AVAILABLE(10_2, 2_0); + +/* + * kCFStreamSocketSOCKSVersion5 + * + * Discussion: + * CFDictionary value for SOCKS proxy information. Indcates that + * SOCKS will or is using version 5 of the SOCKS protocol. + * + */ +CF_EXPORT const CFStringRef _Nonnull kCFStreamSocketSOCKSVersion5 CF_AVAILABLE(10_2, 2_0); + +/* + * kCFStreamPropertySOCKSUser + * + * Discussion: + * CFDictionary key for SOCKS proxy information. To set a user name + * and/or password, if required, the dictionary must contain the + * key(s) kCFStreamPropertySOCKSUser and/or + * kCFStreamPropertySOCKSPassword with the value being the user's + * name as a CFStringRef and/or the user's password as a + * CFStringRef, respectively. + * + */ +CF_EXPORT const CFStringRef _Nonnull kCFStreamPropertySOCKSUser CF_AVAILABLE(10_2, 2_0); + +/* + * kCFStreamPropertySOCKSPassword + * + * Discussion: + * CFDictionary key for SOCKS proxy information. To set a user name + * and/or password, if required, the dictionary must contain the + * key(s) kCFStreamPropertySOCKSUser and/or + * kCFStreamPropertySOCKSPassword with the value being the user's + * name as a CFStringRef and/or the user's password as a + * CFStringRef, respectively. + * + */ +CF_EXPORT const CFStringRef _Nonnull kCFStreamPropertySOCKSPassword CF_AVAILABLE(10_2, 2_0); + +/* + * kCFStreamErrorDomainSSL + * + * Discussion: + * Errors located in Security/SecureTransport.h + * + */ +CF_EXPORT const int kCFStreamErrorDomainSSL CF_AVAILABLE(10_2, 2_0); + +/* + * kCFStreamPropertySocketSecurityLevel + * + * Discussion: + * Stream property key, for both set and copy operations. To set a + * stream to be secure, call CFReadStreamSetProperty or + * CFWriteStreamSetPropertywith the property name set to + * kCFStreamPropertySocketSecurityLevel and the value being one of + * the following values. Streams may set a security level after + * open in order to allow on-the-fly securing of a stream. + * + */ +CF_EXPORT const CFStringRef _Nonnull kCFStreamPropertySocketSecurityLevel CF_AVAILABLE(10_2, 2_0); + +/* + * kCFStreamSocketSecurityLevelNone + * + * Discussion: + * Stream property value, for both set and copy operations. + * Indicates to use no security (default setting). + * + */ +CF_EXPORT const CFStringRef _Nonnull kCFStreamSocketSecurityLevelNone CF_AVAILABLE(10_2, 2_0); + +/* + * kCFStreamSocketSecurityLevelSSLv2 + * + * Note: SSLv2 is DEPRECATED starting in OS X 10.12 and iOS 10.0. + * + * Discussion: + * Stream property value, for both set and copy operations. + * Indicates to use SSLv2 security. + * + */ +CF_EXPORT const CFStringRef _Nonnull kCFStreamSocketSecurityLevelSSLv2 CF_DEPRECATED(10_2, 10_12, 2_0, 10_0); + +/* + * kCFStreamSocketSecurityLevelSSLv3 + * + * Note: SSLv3 is DEPRECATED starting in OS X 10.12 and iOS 10.0. + * + * Discussion: + * Stream property value, for both set and copy operations. + * Indicates to use SSLv3 security. + * + */ +CF_EXPORT const CFStringRef _Nonnull kCFStreamSocketSecurityLevelSSLv3 CF_DEPRECATED(10_2, 10_12, 2_0, 10_0); + +/* + * kCFStreamSocketSecurityLevelTLSv1 + * + * Discussion: + * Stream property value, for both set and copy operations. + * Indicates to use TLSv1 security. + * + */ +CF_EXPORT const CFStringRef _Nonnull kCFStreamSocketSecurityLevelTLSv1 CF_AVAILABLE(10_2, 2_0); + +/* + * kCFStreamSocketSecurityLevelNegotiatedSSL + * + * Discussion: + * Stream property value, for both set and copy operations. + * Indicates to use TLS or SSL with fallback to lower versions. This + * is what HTTPS does, for instance. + * + */ +CF_EXPORT const CFStringRef _Nonnull kCFStreamSocketSecurityLevelNegotiatedSSL CF_AVAILABLE(10_2, 2_0); + +/* + * kCFStreamPropertyShouldCloseNativeSocket + * + * Discussion: + * Set the value to kCFBooleanTrue if the stream should close and + * release the underlying native socket when the stream is released. + * Set the value to kCFBooleanFalse to keep the native socket from + * closing and releasing when the stream is released. If the stream + * was created with a native socket, the default property setting on + * the stream is kCFBooleanFalse. The + * kCFStreamPropertyShouldCloseNativeSocket can be set through + * CFReadStreamSetProperty or CFWriteStreamSetProperty. The + * property can be copied through CFReadStreamCopyProperty or + * CFWriteStreamCopyProperty. + * + */ +CF_EXPORT const CFStringRef _Nonnull kCFStreamPropertyShouldCloseNativeSocket CF_AVAILABLE(10_2, 2_0); CF_IMPLICIT_BRIDGING_DISABLED /* Socket streams; the returned streams are paired such that they use the same socket; pass NULL if you want only the read stream or the write stream */ CF_EXPORT -void CFStreamCreatePairWithSocket(CFAllocatorRef alloc, CFSocketNativeHandle sock, CFReadStreamRef *readStream, CFWriteStreamRef *writeStream); +void CFStreamCreatePairWithSocket(CFAllocatorRef _Null_unspecified alloc, CFSocketNativeHandle sock, CFReadStreamRef _Null_unspecified * _Null_unspecified readStream, CFWriteStreamRef _Null_unspecified * _Null_unspecified writeStream); CF_EXPORT -void CFStreamCreatePairWithSocketToHost(CFAllocatorRef alloc, CFStringRef host, UInt32 port, CFReadStreamRef *readStream, CFWriteStreamRef *writeStream); +void CFStreamCreatePairWithSocketToHost(CFAllocatorRef _Null_unspecified alloc, CFStringRef _Null_unspecified host, UInt32 port, CFReadStreamRef _Null_unspecified * _Null_unspecified readStream, CFWriteStreamRef _Null_unspecified * _Null_unspecified writeStream); CF_EXPORT -void CFStreamCreatePairWithPeerSocketSignature(CFAllocatorRef alloc, const CFSocketSignature *signature, CFReadStreamRef *readStream, CFWriteStreamRef *writeStream); +void CFStreamCreatePairWithPeerSocketSignature(CFAllocatorRef _Null_unspecified alloc, const CFSocketSignature * _Null_unspecified signature, CFReadStreamRef _Null_unspecified * _Null_unspecified readStream, CFWriteStreamRef _Null_unspecified * _Null_unspecified writeStream); CF_IMPLICIT_BRIDGING_ENABLED /* Returns the current state of the stream */ CF_EXPORT -CFStreamStatus CFReadStreamGetStatus(CFReadStreamRef stream); +CFStreamStatus CFReadStreamGetStatus(CFReadStreamRef _Null_unspecified stream); CF_EXPORT -CFStreamStatus CFWriteStreamGetStatus(CFWriteStreamRef stream); +CFStreamStatus CFWriteStreamGetStatus(CFWriteStreamRef _Null_unspecified stream); /* Returns NULL if no error has occurred; otherwise returns the error. */ CF_EXPORT -CFErrorRef CFReadStreamCopyError(CFReadStreamRef stream) API_AVAILABLE(macos(10.5), ios(2.0), watchos(2.0), tvos(9.0)); +CFErrorRef _Null_unspecified CFReadStreamCopyError(CFReadStreamRef _Null_unspecified stream) API_AVAILABLE(macos(10.5), ios(2.0), watchos(2.0), tvos(9.0)); CF_EXPORT -CFErrorRef CFWriteStreamCopyError(CFWriteStreamRef stream) API_AVAILABLE(macos(10.5), ios(2.0), watchos(2.0), tvos(9.0)); +CFErrorRef _Null_unspecified CFWriteStreamCopyError(CFWriteStreamRef _Null_unspecified stream) API_AVAILABLE(macos(10.5), ios(2.0), watchos(2.0), tvos(9.0)); /* Returns success/failure. Opening a stream causes it to reserve all the system resources it requires. If the stream can open non-blocking, this will always @@ -142,22 +353,22 @@ CFErrorRef CFWriteStreamCopyError(CFWriteStreamRef stream) API_AVAILABLE(macos(1 and whether it was successful, or poll using CFRead/WriteStreamGetStatus(), waiting for a status of kCFStreamStatusOpen or kCFStreamStatusError. */ CF_EXPORT -Boolean CFReadStreamOpen(CFReadStreamRef stream); +Boolean CFReadStreamOpen(CFReadStreamRef _Null_unspecified stream); CF_EXPORT -Boolean CFWriteStreamOpen(CFWriteStreamRef stream); +Boolean CFWriteStreamOpen(CFWriteStreamRef _Null_unspecified stream); /* Terminates the flow of bytes; releases any system resources required by the stream. The stream may not fail to close. You may call CFStreamClose() to effectively abort a stream. */ CF_EXPORT -void CFReadStreamClose(CFReadStreamRef stream); +void CFReadStreamClose(CFReadStreamRef _Null_unspecified stream); CF_EXPORT -void CFWriteStreamClose(CFWriteStreamRef stream); +void CFWriteStreamClose(CFWriteStreamRef _Null_unspecified stream); /* Whether there is data currently available for reading; returns TRUE if it's impossible to tell without trying */ CF_EXPORT -Boolean CFReadStreamHasBytesAvailable(CFReadStreamRef stream); +Boolean CFReadStreamHasBytesAvailable(CFReadStreamRef _Null_unspecified stream); /* Returns the number of bytes read, or -1 if an error occurs preventing any bytes from being read, or 0 if the stream's end was encountered. @@ -167,7 +378,7 @@ Boolean CFReadStreamHasBytesAvailable(CFReadStreamRef stream); CFReadStreamHasBytesAvailable() or use the run loop and listen for the kCFStreamEventHasBytesAvailable event for notification of data available. */ CF_EXPORT -CFIndex CFReadStreamRead(CFReadStreamRef stream, UInt8 *buffer, CFIndex bufferLength); +CFIndex CFReadStreamRead(CFReadStreamRef _Null_unspecified stream, UInt8 * _Null_unspecified buffer, CFIndex bufferLength); /* Returns a pointer to an internal buffer if possible (setting *numBytesRead to the length of the returned buffer), otherwise returns NULL; guaranteed @@ -179,12 +390,12 @@ CFIndex CFReadStreamRead(CFReadStreamRef stream, UInt8 *buffer, CFIndex bufferLe change the contents of the returned buffer nor attempt to deallocate the buffer; it is still owned by the stream. */ CF_EXPORT -const UInt8 *CFReadStreamGetBuffer(CFReadStreamRef stream, CFIndex maxBytesToRead, CFIndex *numBytesRead); +const UInt8 * _Null_unspecified CFReadStreamGetBuffer(CFReadStreamRef _Null_unspecified stream, CFIndex maxBytesToRead, CFIndex * _Null_unspecified numBytesRead); /* Whether the stream can currently be written to without blocking; returns TRUE if it's impossible to tell without trying */ CF_EXPORT -Boolean CFWriteStreamCanAcceptBytes(CFWriteStreamRef stream); +Boolean CFWriteStreamCanAcceptBytes(CFWriteStreamRef _Null_unspecified stream); /* Returns the number of bytes successfully written, -1 if an error has occurred, or 0 if the stream has been filled to capacity (for fixed-length @@ -192,7 +403,7 @@ Boolean CFWriteStreamCanAcceptBytes(CFWriteStreamRef stream); one byte is written. To avoid blocking, either poll via CFWriteStreamCanAcceptBytes or use the run loop and listen for the kCFStreamEventCanAcceptBytes event. */ CF_EXPORT -CFIndex CFWriteStreamWrite(CFWriteStreamRef stream, const UInt8 *buffer, CFIndex bufferLength); +CFIndex CFWriteStreamWrite(CFWriteStreamRef _Null_unspecified stream, const UInt8 * _Null_unspecified buffer, CFIndex bufferLength); /* Particular streams can name properties and assign meanings to them; you access these properties through the following calls. A property is any interesting @@ -203,16 +414,16 @@ CFIndex CFWriteStreamWrite(CFWriteStreamRef stream, const UInt8 *buffer, CFIndex (like before the stream has been opened). See the documentation for particular properties to determine their get- and set-ability. */ CF_EXPORT -CFTypeRef CFReadStreamCopyProperty(CFReadStreamRef stream, CFStreamPropertyKey propertyName); +CFTypeRef _Null_unspecified CFReadStreamCopyProperty(CFReadStreamRef _Null_unspecified stream, CFStreamPropertyKey _Null_unspecified propertyName); CF_EXPORT -CFTypeRef CFWriteStreamCopyProperty(CFWriteStreamRef stream, CFStreamPropertyKey propertyName); +CFTypeRef _Null_unspecified CFWriteStreamCopyProperty(CFWriteStreamRef _Null_unspecified stream, CFStreamPropertyKey _Null_unspecified propertyName); /* Returns TRUE if the stream recognizes and accepts the given property-value pair; FALSE otherwise. */ CF_EXPORT -Boolean CFReadStreamSetProperty(CFReadStreamRef stream, CFStreamPropertyKey propertyName, CFTypeRef propertyValue); +Boolean CFReadStreamSetProperty(CFReadStreamRef _Null_unspecified stream, CFStreamPropertyKey _Null_unspecified propertyName, CFTypeRef _Null_unspecified propertyValue); CF_EXPORT -Boolean CFWriteStreamSetProperty(CFWriteStreamRef stream, CFStreamPropertyKey propertyName, CFTypeRef propertyValue); +Boolean CFWriteStreamSetProperty(CFWriteStreamRef _Null_unspecified stream, CFStreamPropertyKey _Null_unspecified propertyName, CFTypeRef _Null_unspecified propertyValue); /* Asynchronous processing - If you wish to neither poll nor block, you may register a client to hear about interesting events that occur on a stream. Only one client @@ -231,19 +442,19 @@ Boolean CFWriteStreamSetProperty(CFWriteStreamRef stream, CFStreamPropertyKey pr */ CF_EXPORT -Boolean CFReadStreamSetClient(CFReadStreamRef stream, CFOptionFlags streamEvents, CFReadStreamClientCallBack clientCB, CFStreamClientContext *clientContext); +Boolean CFReadStreamSetClient(CFReadStreamRef _Null_unspecified stream, CFOptionFlags streamEvents, CFReadStreamClientCallBack _Null_unspecified clientCB, CFStreamClientContext * _Null_unspecified clientContext); CF_EXPORT -Boolean CFWriteStreamSetClient(CFWriteStreamRef stream, CFOptionFlags streamEvents, CFWriteStreamClientCallBack clientCB, CFStreamClientContext *clientContext); +Boolean CFWriteStreamSetClient(CFWriteStreamRef _Null_unspecified stream, CFOptionFlags streamEvents, CFWriteStreamClientCallBack _Null_unspecified clientCB, CFStreamClientContext * _Null_unspecified clientContext); CF_EXPORT -void CFReadStreamScheduleWithRunLoop(CFReadStreamRef stream, CFRunLoopRef runLoop, CFRunLoopMode runLoopMode); +void CFReadStreamScheduleWithRunLoop(CFReadStreamRef _Null_unspecified stream, CFRunLoopRef _Null_unspecified runLoop, CFRunLoopMode _Null_unspecified runLoopMode); CF_EXPORT -void CFWriteStreamScheduleWithRunLoop(CFWriteStreamRef stream, CFRunLoopRef runLoop, CFRunLoopMode runLoopMode); +void CFWriteStreamScheduleWithRunLoop(CFWriteStreamRef _Null_unspecified stream, CFRunLoopRef _Null_unspecified runLoop, _Null_unspecified CFRunLoopMode runLoopMode); CF_EXPORT -void CFReadStreamUnscheduleFromRunLoop(CFReadStreamRef stream, CFRunLoopRef runLoop, CFRunLoopMode runLoopMode); +void CFReadStreamUnscheduleFromRunLoop(CFReadStreamRef _Null_unspecified stream, CFRunLoopRef _Null_unspecified runLoop, CFRunLoopMode _Null_unspecified runLoopMode); CF_EXPORT -void CFWriteStreamUnscheduleFromRunLoop(CFWriteStreamRef stream, CFRunLoopRef runLoop, CFRunLoopMode runLoopMode); +void CFWriteStreamUnscheduleFromRunLoop(CFWriteStreamRef _Null_unspecified stream, CFRunLoopRef _Null_unspecified runLoop, CFRunLoopMode _Null_unspecified runLoopMode); /* @@ -254,10 +465,10 @@ void CFWriteStreamUnscheduleFromRunLoop(CFWriteStreamRef stream, CFRunLoopRef ru * with a runloop will disassociate the stream from any existing dispatch queue. */ CF_EXPORT -void CFReadStreamSetDispatchQueue(CFReadStreamRef stream, dispatch_queue_t q) API_AVAILABLE(macos(10.9), ios(7.0), watchos(2.0), tvos(9.0)); +void CFReadStreamSetDispatchQueue(CFReadStreamRef _Null_unspecified stream, dispatch_queue_t _Null_unspecified q) API_AVAILABLE(macos(10.9), ios(7.0), watchos(2.0), tvos(9.0)); CF_EXPORT -void CFWriteStreamSetDispatchQueue(CFWriteStreamRef stream, dispatch_queue_t q) API_AVAILABLE(macos(10.9), ios(7.0), watchos(2.0), tvos(9.0)); +void CFWriteStreamSetDispatchQueue(CFWriteStreamRef _Null_unspecified stream, dispatch_queue_t _Null_unspecified q) API_AVAILABLE(macos(10.9), ios(7.0), watchos(2.0), tvos(9.0)); /* * Returns the previously set dispatch queue with an incremented retain count. @@ -265,10 +476,10 @@ void CFWriteStreamSetDispatchQueue(CFWriteStreamRef stream, dispatch_queue_t q) * scheduled on a runloop subsequent to it having had a dispatch queue set. */ CF_EXPORT -dispatch_queue_t CFReadStreamCopyDispatchQueue(CFReadStreamRef stream) API_AVAILABLE(macos(10.9), ios(7.0), watchos(2.0), tvos(9.0)); +dispatch_queue_t _Null_unspecified CFReadStreamCopyDispatchQueue(CFReadStreamRef _Null_unspecified stream) API_AVAILABLE(macos(10.9), ios(7.0), watchos(2.0), tvos(9.0)); CF_EXPORT -dispatch_queue_t CFWriteStreamCopyDispatchQueue(CFWriteStreamRef stream) API_AVAILABLE(macos(10.9), ios(7.0), watchos(2.0), tvos(9.0)); +dispatch_queue_t _Null_unspecified CFWriteStreamCopyDispatchQueue(CFWriteStreamRef _Null_unspecified stream) API_AVAILABLE(macos(10.9), ios(7.0), watchos(2.0), tvos(9.0)); /* The following API is deprecated starting in 10.5; please use CFRead/WriteStreamCopyError(), above, instead */ @@ -278,14 +489,10 @@ typedef CF_ENUM(CFIndex, CFStreamErrorDomain) { kCFStreamErrorDomainMacOSStatus /* OSStatus type from Carbon APIs; interpret using */ }; -typedef struct { - CFIndex domain; - SInt32 error; -} CFStreamError; CF_EXPORT -CFStreamError CFReadStreamGetError(CFReadStreamRef stream); +CFStreamError CFReadStreamGetError(CFReadStreamRef _Null_unspecified stream); CF_EXPORT -CFStreamError CFWriteStreamGetError(CFWriteStreamRef stream); +CFStreamError CFWriteStreamGetError(CFWriteStreamRef _Null_unspecified stream); CF_EXTERN_C_END diff --git a/CoreFoundation/Stream.subproj/CFStreamAbstract.h b/CoreFoundation/Stream.subproj/CFStreamAbstract.h index f19de2ef33..cda9622a3f 100644 --- a/CoreFoundation/Stream.subproj/CFStreamAbstract.h +++ b/CoreFoundation/Stream.subproj/CFStreamAbstract.h @@ -1,7 +1,7 @@ /* CFStreamAbstract.h - Copyright (c) 2000-2017, Apple Inc.and the Swift project authors + Copyright (c) 2000-2018, Apple Inc.and the Swift project authors - Portions Copyright (c) 2014-2017, Apple Inc. and the Swift project authors + Portions Copyright (c) 2014-2018, Apple Inc. and the Swift project authors Licensed under Apache License v2.0 with Runtime Library Exception See http://swift.org/LICENSE.txt for license information See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors diff --git a/CoreFoundation/Stream.subproj/CFStreamInternal.h b/CoreFoundation/Stream.subproj/CFStreamInternal.h index ec1f521f0d..4706088289 100644 --- a/CoreFoundation/Stream.subproj/CFStreamInternal.h +++ b/CoreFoundation/Stream.subproj/CFStreamInternal.h @@ -1,7 +1,7 @@ /* CFStreamInternal.h - Copyright (c) 2000-2017, Apple Inc. and the Swift project authors + Copyright (c) 2000-2018, Apple Inc. and the Swift project authors - Portions Copyright (c) 2014-2017, Apple Inc. and the Swift project authors + Portions Copyright (c) 2014-2018, Apple Inc. and the Swift project authors Licensed under Apache License v2.0 with Runtime Library Exception See http://swift.org/LICENSE.txt for license information See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors diff --git a/CoreFoundation/Stream.subproj/CFStreamPriv.h b/CoreFoundation/Stream.subproj/CFStreamPriv.h index 6633cc59d4..cd14666d3b 100644 --- a/CoreFoundation/Stream.subproj/CFStreamPriv.h +++ b/CoreFoundation/Stream.subproj/CFStreamPriv.h @@ -1,7 +1,7 @@ /* CFStreamPriv.h - Copyright (c) 2000-2017, Apple Inc. and the Swift project authors + Copyright (c) 2000-2018, Apple Inc. and the Swift project authors - Portions Copyright (c) 2014-2017, Apple Inc. and the Swift project authors + Portions Copyright (c) 2014-2018, Apple Inc. and the Swift project authors Licensed under Apache License v2.0 with Runtime Library Exception See http://swift.org/LICENSE.txt for license information See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors @@ -105,6 +105,17 @@ CFIndex __CFSocketRead(CFSocketRef s, UInt8* buffer, CFIndex length, int* error) CF_EXPORT void __CFSocketSetSocketReadBufferAttrs(CFSocketRef s, CFTimeInterval timeout, CFIndex length); +/* + * kCFStreamPropertySocketSSLContext + * + * Discussion: + * Stream property key, for both set and copy operations. CFDataRef + * containing a reference to the SecureTransport SecureContext + * structure. + * + */ +CF_EXPORT const CFStringRef kCFStreamPropertySocketSSLContext; + CF_EXTERN_C_END /* @@ -124,6 +135,5 @@ CF_EXPORT const CFStringRef _kCFStreamPropertyFileNativeHandle API_AVAILABLE(mac */ CF_EXPORT const CFStringRef _kCFStreamPropertyHTTPTrailer API_AVAILABLE(macosx(10.12), ios(10.0), watchos(3.0), tvos(10.0)); - #endif /* ! __COREFOUNDATION_CFSTREAMPRIV__ */ diff --git a/CoreFoundation/String.subproj/CFAttributedString.c b/CoreFoundation/String.subproj/CFAttributedString.c index 3241600faf..5859aceebc 100644 --- a/CoreFoundation/String.subproj/CFAttributedString.c +++ b/CoreFoundation/String.subproj/CFAttributedString.c @@ -1,15 +1,12 @@ -// This source file is part of the Swift.org open source project -// -// Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors -// Licensed under Apache License v2.0 with Runtime Library Exception -// -// See http://swift.org/LICENSE.txt for license information -// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors -// -/* CFAttributedString.c - Copyright (c) 2004-2017, Apple Inc. All rights reserved. +/* CFAttributedString.c + Copyright (c) 2004-2018, Apple Inc. All rights reserved. + + Portions Copyright (c) 2014-2018, Apple Inc. and the Swift project authors + Licensed under Apache License v2.0 with Runtime Library Exception + See http://swift.org/LICENSE.txt for license information + See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors Original Author: Ali Ozer - Responsibility: Ali Ozer + Responsibility: Ali Ozer */ #include @@ -17,7 +14,14 @@ #include "CFRunArray.h" #include #include "CFInternal.h" +#include "CFRuntime_Internal.h" +#if (DEPLOYMENT_TARGET_MACOSX || DEPLOYMENT_TARGET_EMBEDDED || DEPLOYMENT_TARGET_WINDOWS) && DEPLOYMENT_RUNTIME_OBJC +#import +@interface NSAttributedString (NSPrivate) +- (NSAttributedString *)_createAttributedSubstringWithRange:(NSRange)range; +@end +#endif struct __CFAttributedString { CFRuntimeBase base; @@ -118,9 +122,7 @@ static void __CFAttributedStringDeallocate(CFTypeRef cf) { CFRelease(attrStr->attributeArray); } -static CFTypeID __kCFAttributedStringTypeID = _kCFRuntimeNotATypeID; - -static const CFRuntimeClass __CFAttributedStringClass = { +const CFRuntimeClass __CFAttributedStringClass = { 0, "CFAttributedString", NULL, // init @@ -133,9 +135,7 @@ static const CFRuntimeClass __CFAttributedStringClass = { }; CFTypeID CFAttributedStringGetTypeID(void) { - static dispatch_once_t initOnce; - dispatch_once(&initOnce, ^{ __kCFAttributedStringTypeID = _CFRuntimeRegisterClass(&__CFAttributedStringClass); }); - return __kCFAttributedStringTypeID; + return _kCFRuntimeIDCFAttributedString; } @@ -475,14 +475,14 @@ void CFAttributedStringReplaceString(CFMutableAttributedStringRef attrStr, CFRan void CFAttributedStringSetAttributes(CFMutableAttributedStringRef attrStr, CFRange range, CFDictionaryRef replacementAttrs, Boolean clearOtherAttributes) { if (clearOtherAttributes) { - CF_OBJC_FUNCDISPATCHV(CFAttributedStringGetTypeID(), void, (NSMutableAttributedString *)attrStr, setAttributes:(NSDictionary *)replacementAttrs range: NSMakeRange(range.location, range.length)); + CF_OBJC_FUNCDISPATCHV(CFAttributedStringGetTypeID(), void, (NSMutableAttributedString *)attrStr, setAttributes:(NSDictionary *)replacementAttrs range: NSMakeRange(range.location, range.length)); } else { - CF_OBJC_FUNCDISPATCHV(CFAttributedStringGetTypeID(), void, (NSMutableAttributedString *)attrStr, addAttributes:(NSDictionary *)replacementAttrs range: NSMakeRange(range.location, range.length)); + CF_OBJC_FUNCDISPATCHV(CFAttributedStringGetTypeID(), void, (NSMutableAttributedString *)attrStr, addAttributes:(NSDictionary *)replacementAttrs range: NSMakeRange(range.location, range.length)); } - + __CFAssertIsAttributedStringAndMutable(attrStr); __CFAssertRangeIsInBounds(attrStr, range.location, range.length); - + if (clearOtherAttributes) { // Just blast all attribute dictionaries in the specified range if (range.length) { CFMutableDictionaryRef attrs = __CFAttributedStringCreateAttributesDictionary(CFGetAllocator(attrStr), replacementAttrs); @@ -494,29 +494,39 @@ void CFAttributedStringSetAttributes(CFMutableAttributedStringRef attrStr, CFRan CFIndex numAdditionalItems = CFDictionaryGetCount(replacementAttrs); if (numAdditionalItems) { // Extract the new keys and values so we don't do it over and over for each range - createLocalArray(additionalKeys, numAdditionalItems); - createLocalArray(additionalValues, numAdditionalItems); + createLocalArray(additionalKeys, numAdditionalItems); + createLocalArray(additionalValues, numAdditionalItems); CFDictionaryGetKeysAndValues(replacementAttrs, additionalKeys, additionalValues); - - // CFAttributedStringBeginEditing(attrStr); + + // CFAttributedStringBeginEditing(attrStr); while (range.length) { CFRange effectiveRange; CFMutableDictionaryRef attrs = (CFMutableDictionaryRef)CFRunArrayGetValueAtIndex(attrStr->attributeArray, range.location, &effectiveRange, NULL); - // Intersect effectiveRange and range - if (effectiveRange.location < range.location) { - effectiveRange.length -= (range.location - effectiveRange.location); - effectiveRange.location = range.location; - } - if (effectiveRange.length > range.length) effectiveRange.length = range.length; +#if !DEPLOYMENT_RUNTIME_SWIFT // We can't make assumptions of the retain count in Swift. + if (effectiveRange.location == range.location && effectiveRange.length <= range.length && CFGetRetainCount(attrs) == 1) { + // !!! Retain count check cheesy; need to keep our own reference count + // The attributes dictionary can just be modified in place + // Here we are assuming that CFRunArray is not under-reporting the effectiveRange for a given item! + __CFDictionaryAddMultiple(attrs, additionalKeys, additionalValues, numAdditionalItems); + } else +#endif // !DEPLOYMENT_RUNTIME_SWIFT + { + // Intersect effectiveRange and range + if (effectiveRange.location < range.location) { + effectiveRange.length -= (range.location - effectiveRange.location); + effectiveRange.location = range.location; + } + if (effectiveRange.length > range.length) effectiveRange.length = range.length; // We need to make a new copy attrs = __CFAttributedStringCreateAttributesDictionary(CFGetAllocator(attrStr), attrs); __CFDictionaryAddMultiple(attrs, additionalKeys, additionalValues, numAdditionalItems); CFRunArrayReplace(attrStr->attributeArray, effectiveRange, attrs, effectiveRange.length); CFRelease(attrs); + } range.length -= effectiveRange.length; range.location += effectiveRange.length; } - // CFAttributedStringEndEditing(attrStr); + // CFAttributedStringEndEditing(attrStr); freeLocalArray(additionalKeys); freeLocalArray(additionalValues); @@ -534,6 +544,15 @@ void CFAttributedStringSetAttribute(CFMutableAttributedStringRef attrStr, CFRang CFRange effectiveRange; // effectiveRange.location returned here may be equal to or smaller than range.location CFMutableDictionaryRef attrs = (CFMutableDictionaryRef)CFRunArrayGetValueAtIndex(attrStr->attributeArray, range.location, &effectiveRange, NULL); +#if !DEPLOYMENT_RUNTIME_SWIFT // We can't make assumptions of the retain count in Swift. + if (effectiveRange.location == range.location && effectiveRange.length <= range.length && CFGetRetainCount(attrs) == 1) { + // !!! Retain count check cheesy; need to keep our own reference count) + // The attributes dictionary can just be modified in place + // Here we are assuming that CFRunArray is not under-reporting the effectiveRange for a given item! + CFDictionarySetValue(attrs, attrName, value); + } else +#endif // !DEPLOYMENT_RUNTIME_SWIFT + { // Intersect effectiveRange and range if (effectiveRange.location < range.location) { effectiveRange.length -= (range.location - effectiveRange.location); @@ -549,6 +568,7 @@ void CFAttributedStringSetAttribute(CFMutableAttributedStringRef attrStr, CFRang CFRunArrayReplace(attrStr->attributeArray, effectiveRange, attrs, effectiveRange.length); CFRelease(attrs); } + } range.length -= effectiveRange.length; range.location += effectiveRange.length; } @@ -564,6 +584,15 @@ void CFAttributedStringRemoveAttribute(CFMutableAttributedStringRef attrStr, CFR while (range.length) { CFRange effectiveRange; CFMutableDictionaryRef attrs = (CFMutableDictionaryRef)CFRunArrayGetValueAtIndex(attrStr->attributeArray, range.location, &effectiveRange, NULL); +#if !DEPLOYMENT_RUNTIME_SWIFT // We can't make assumptions of the retain count in Swift. + if (effectiveRange.location == range.location && effectiveRange.length <= range.length && CFGetRetainCount(attrs) == 1) { + // !!! Retain count check cheesy; need to keep our own reference count + // The attributes dictionary can just be modified in place + // Here we are assuming that CFRunArray is not under-reporting the effectiveRange for a given item! + CFDictionaryRemoveValue(attrs, attrName); + } else +#endif // !DEPLOYMENT_RUNTIME_SWIFT + { // Intersect effectiveRange and range if (effectiveRange.location < range.location) { effectiveRange.length -= (range.location - effectiveRange.location); @@ -578,6 +607,7 @@ void CFAttributedStringRemoveAttribute(CFMutableAttributedStringRef attrStr, CFR CFRunArrayReplace(attrStr->attributeArray, effectiveRange, attrs, effectiveRange.length); CFRelease(attrs); } + } range.length -= effectiveRange.length; range.location += effectiveRange.length; } diff --git a/CoreFoundation/String.subproj/CFAttributedString.h b/CoreFoundation/String.subproj/CFAttributedString.h index aa137e114c..25d3493abf 100644 --- a/CoreFoundation/String.subproj/CFAttributedString.h +++ b/CoreFoundation/String.subproj/CFAttributedString.h @@ -8,7 +8,7 @@ // /* CFAttributedString.h - Copyright (c) 2004-2015, Apple Inc. All rights reserved. + Copyright (c) 2004-2018, Apple Inc. All rights reserved. */ /*! @header CFAttributedString diff --git a/CoreFoundation/String.subproj/CFAttributedStringPriv.h b/CoreFoundation/String.subproj/CFAttributedStringPriv.h new file mode 100644 index 0000000000..dd9c66823e --- /dev/null +++ b/CoreFoundation/String.subproj/CFAttributedStringPriv.h @@ -0,0 +1,25 @@ +/* CFAttributedStringPriv.h + Copyright (c) 2004-2018, Apple Inc. All rights reserved. +*/ + +#if !defined(__COREFOUNDATION_CFATTRIBUTEDSTRINGPRIV__) +#define __COREFOUNDATION_CFATTRIBUTEDSTRINGPRIV__ 1 + +#include + +CF_EXTERN_C_BEGIN + +/* CFAttributedStringCreateWithRuns() creates an attributed string from the specified string and a list of sparse attribute dictionaries. The ranges for the dictionaries do not have to cover the string, but they should be ordered from low to high indexes, and they shouldn't overlap. CFAttributedStringGetRuns() will return conformant arrays. +*/ +CF_EXPORT CFAttributedStringRef _CFAttributedStringCreateWithRuns(CFAllocatorRef alloc, CFStringRef str, const CFDictionaryRef *attrDictionaries, const CFRange *runRanges, CFIndex numRuns); + +/* The next two functions are SPI which allow return bulk information about attributes. The includeEmpty argument enables choosing to ignore or include runs where the attribute dictionaries are empty. The size of the CFRange and CFDictionaryRef arguments passed to CFAttributedStringGetRuns() should be obtained from CFAttributedStringGetNumberOfRuns(), called with the same value for includeEmpty. +*/ +CF_EXPORT void _CFAttributedStringGetRuns(CFAttributedStringRef attrStr, Boolean includeEmpty, CFDictionaryRef *attrDictionaries, CFRange *runRanges); +CF_EXPORT CFIndex _CFAttributedStringGetNumberOfRuns(CFAttributedStringRef attrStr, Boolean includeEmpty); + + +CF_EXTERN_C_END + +#endif /* ! __COREFOUNDATION_CFATTRIBUTEDSTRINGPRIV__ */ + diff --git a/CoreFoundation/String.subproj/CFBurstTrie.c b/CoreFoundation/String.subproj/CFBurstTrie.c index 70da3c8601..72cc1ea04f 100644 --- a/CoreFoundation/String.subproj/CFBurstTrie.c +++ b/CoreFoundation/String.subproj/CFBurstTrie.c @@ -1,7 +1,7 @@ /* CFBurstTrie.c - Copyright (c) 2008-2017, Apple Inc. and the Swift project authors + Copyright (c) 2008-2018, Apple Inc. and the Swift project authors - Portions Copyright (c) 2014-2017, Apple Inc. and the Swift project authors + Portions Copyright (c) 2014-2018, Apple Inc. and the Swift project authors Licensed under Apache License v2.0 with Runtime Library Exception See http://swift.org/LICENSE.txt for license information See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors @@ -11,7 +11,7 @@ #include "CFInternal.h" #include "CFBurstTrie.h" #include -#include +#include "CFNumber.h" #include #include #include diff --git a/CoreFoundation/String.subproj/CFBurstTrie.h b/CoreFoundation/String.subproj/CFBurstTrie.h index fd7bcdfedc..fd86e0cc90 100644 --- a/CoreFoundation/String.subproj/CFBurstTrie.h +++ b/CoreFoundation/String.subproj/CFBurstTrie.h @@ -1,7 +1,7 @@ /* CFBurstTrie.h - Copyright (c) 2008-2017, Apple Inc. and the Swift project authors + Copyright (c) 2008-2018, Apple Inc. and the Swift project authors - Portions Copyright (c) 2014-2017, Apple Inc. and the Swift project authors + Portions Copyright (c) 2014-2018, Apple Inc. and the Swift project authors Licensed under Apache License v2.0 with Runtime Library Exception See http://swift.org/LICENSE.txt for license information See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors @@ -60,7 +60,7 @@ typedef CF_OPTIONS(CFOptionFlags, CFBurstTrieOpts) { typedef void (*CFBurstTrieTraversalCallback)(void* context, const UInt8* key, uint32_t keyLength, uint32_t payload, Boolean *stop); CF_EXPORT -CFBurstTrieRef CFBurstTrieCreate() API_AVAILABLE(macos(10.7), ios(4.2), watchos(2.0), tvos(9.0)); +CFBurstTrieRef CFBurstTrieCreate(void) API_AVAILABLE(macos(10.7), ios(4.2), watchos(2.0), tvos(9.0)); CF_EXPORT CFBurstTrieRef CFBurstTrieCreateWithOptions(CFDictionaryRef options) API_AVAILABLE(macos(10.8), ios(6.0), watchos(2.0), tvos(9.0)); diff --git a/CoreFoundation/String.subproj/CFCharacterSet.c b/CoreFoundation/String.subproj/CFCharacterSet.c index 59791f2e92..a3dbdcd256 100644 --- a/CoreFoundation/String.subproj/CFCharacterSet.c +++ b/CoreFoundation/String.subproj/CFCharacterSet.c @@ -1,7 +1,7 @@ /* CFCharacterSet.c - Copyright (c) 1999-2017, Apple Inc. and the Swift project authors + Copyright (c) 1999-2018, Apple Inc. and the Swift project authors - Portions Copyright (c) 2014-2017, Apple Inc. and the Swift project authors + Portions Copyright (c) 2014-2018, Apple Inc. and the Swift project authors Licensed under Apache License v2.0 with Runtime Library Exception See http://swift.org/LICENSE.txt for license information See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors @@ -14,6 +14,7 @@ #include #include #include "CFInternal.h" +#include "CFRuntime_Internal.h" #include #include "CFUniCharPriv.h" #include @@ -184,7 +185,7 @@ CF_INLINE void __CFCSetValidateRange(CFRange theRange, const char *func) { CFAssert3(theRange.location >= 0 && theRange.location + theRange.length <= 0x1FFFFF, __kCFLogAssertion, "%s: Range out of Unicode range (location -> %d length -> %d)", func, theRange.location, theRange.length); } CF_INLINE void __CFCSetValidateTypeAndMutability(CFCharacterSetRef cset, const char *func) { - __CFGenericValidateType(cset, __kCFCharacterSetTypeID); + __CFGenericValidateType(cset, _kCFRuntimeIDCFCharacterSet); CFAssert1(__CFCSetIsMutable(cset), __kCFLogAssertion, "%s: Immutable character set passed to mutable function", func); } #else @@ -895,11 +896,16 @@ CF_INLINE Boolean __CFCSetBsearchUniChar(const UniChar *theTable, CFIndex length /* Array of instantiated builtin set. Note builtin set ID starts with 1 so the array index is ID - 1 */ -static CFCharacterSetRef *__CFBuiltinSets = NULL; +static CFCharacterSetRef __CFBuiltinSets[sizeof(CFCharacterSetRef) * __kCFLastBuiltinSetID] = {0}; /* Global lock for character set */ + +#ifndef CHARACTER_SET_LOCK_DEFINED static OSSpinLock __CFCharacterSetLock = OS_SPINLOCK_INIT; +CF_INLINE void _CFCharacterSetLockGlobal() { OSSpinLockLock(&__CFCharacterSetLock); } +CF_INLINE void _CFCharacterSetUnlockGlobal() { OSSpinLockUnlock(&__CFCharacterSetLock); } +#endif /* CFBase API functions */ @@ -1281,9 +1287,7 @@ static void __CFCharacterSetDeallocate(CFTypeRef cf) { __CFCSetDeallocateAnnexPlane((CFCharacterSetRef)cf); } -static CFTypeID __kCFCharacterSetTypeID = _kCFRuntimeNotATypeID; - -static const CFRuntimeClass __CFCharacterSetClass = { +const CFRuntimeClass __CFCharacterSetClass = { 0, "CFCharacterSet", NULL, // init @@ -1300,11 +1304,8 @@ static bool __CFCheckForExapendedSet = false; CF_PRIVATE void __CFCharacterSetInitialize(void) { static dispatch_once_t initOnce; dispatch_once(&initOnce, ^{ - __kCFCharacterSetTypeID = _CFRuntimeRegisterClass(&__CFCharacterSetClass); // initOnce covered const char *checkForExpandedSet = __CFgetenv("__CF_DEBUG_EXPANDED_SET"); if (checkForExpandedSet && (*checkForExpandedSet == 'Y')) __CFCheckForExapendedSet = true; - __CFBuiltinSets = (CFCharacterSetRef *)CFAllocatorAllocate(__CFGetDefaultAllocator(), sizeof(CFCharacterSetRef) * __kCFLastBuiltinSetID, 0); - memset(__CFBuiltinSets, 0, sizeof(CFCharacterSetRef) * __kCFLastBuiltinSetID); }); } @@ -1312,7 +1313,7 @@ CF_PRIVATE void __CFCharacterSetInitialize(void) { */ CFTypeID CFCharacterSetGetTypeID(void) { - return __kCFCharacterSetTypeID; + return _kCFRuntimeIDCFCharacterSet; } /*** CharacterSet creation ***/ @@ -1325,18 +1326,25 @@ CFCharacterSetRef CFCharacterSetGetPredefined(CFCharacterSetPredefinedSet theSet if ((theSetIdentifier < kCFCharacterSetControl) || (theSetIdentifier > __kCFLastBuiltinSetID)) { return NULL; } - OSSpinLockLock(&__CFCharacterSetLock); - cset = ((NULL != __CFBuiltinSets) ? __CFBuiltinSets[theSetIdentifier - 1] : NULL); - OSSpinLockUnlock(&__CFCharacterSetLock); + _CFCharacterSetLockGlobal(); + cset = __CFBuiltinSets[theSetIdentifier - 1]; + _CFCharacterSetUnlockGlobal(); if (NULL != cset) return cset; if (!(cset = __CFCSetGenericCreate(kCFAllocatorSystemDefault, __kCFCharSetClassBuiltin, false))) return NULL; - __CFCSetPutBuiltinType((CFMutableCharacterSetRef)cset, theSetIdentifier); - OSSpinLockLock(&__CFCharacterSetLock); - __CFBuiltinSets[theSetIdentifier - 1] = cset; - OSSpinLockUnlock(&__CFCharacterSetLock); + _CFCharacterSetLockGlobal(); + if (__CFBuiltinSets[theSetIdentifier - 1] == NULL) { + __CFBuiltinSets[theSetIdentifier - 1] = cset; + __CFCSetPutBuiltinType((CFMutableCharacterSetRef)cset, theSetIdentifier); //make builtin + _CFCharacterSetUnlockGlobal(); + } else { + CFCharacterSetRef tmp = cset; + cset = __CFBuiltinSets[theSetIdentifier - 1]; + _CFCharacterSetUnlockGlobal(); + CFRelease(tmp); //another thread got here before we took the lock, so release the now-unneeded character set we made. Do this outside the lock both for performance and because deallocate can call back into this + } return cset; } @@ -1580,7 +1588,7 @@ CFCharacterSetRef CFCharacterSetCreateWithBitmapRepresentation(CFAllocatorRef al CFCharacterSetRef CFCharacterSetCreateInvertedSet(CFAllocatorRef alloc, CFCharacterSetRef theSet) { CFMutableCharacterSetRef cset; - CF_OBJC_FUNCDISPATCHV(__kCFCharacterSetTypeID, CFCharacterSetRef , (NSCharacterSet *)theSet, invertedSet); + CF_OBJC_FUNCDISPATCHV(_kCFRuntimeIDCFCharacterSet, CFCharacterSetRef , (NSCharacterSet *)theSet, invertedSet); cset = CFCharacterSetCreateMutableCopy(alloc, theSet); CFCharacterSetInvert(cset); @@ -1614,10 +1622,10 @@ static CFMutableCharacterSetRef __CFCharacterSetCreateCopy(CFAllocatorRef alloc, CFMutableCharacterSetRef cset; if (validateSubclasses) { - CF_OBJC_FUNCDISPATCHV(__kCFCharacterSetTypeID, CFMutableCharacterSetRef , (NSCharacterSet *)theSet, mutableCopy); - CF_SWIFT_FUNCDISPATCHV(__kCFCharacterSetTypeID, CFMutableCharacterSetRef, (CFSwiftRef)theSet, NSCharacterSet.mutableCopy); + CF_OBJC_FUNCDISPATCHV(_kCFRuntimeIDCFCharacterSet, CFMutableCharacterSetRef , (NSCharacterSet *)theSet, mutableCopy); + CF_SWIFT_FUNCDISPATCHV(_kCFRuntimeIDCFCharacterSet, CFMutableCharacterSetRef, (CFSwiftRef)theSet, NSCharacterSet.mutableCopy); - __CFGenericValidateType(theSet, __kCFCharacterSetTypeID); + __CFGenericValidateType(theSet, _kCFRuntimeIDCFCharacterSet); } if (!isMutable && !__CFCSetIsMutable(theSet)) { @@ -1722,9 +1730,9 @@ Boolean CFCharacterSetIsCharacterMember(CFCharacterSetRef theSet, UniChar theCha Boolean isInverted; Boolean result = false; - CF_OBJC_FUNCDISPATCHV(__kCFCharacterSetTypeID, Boolean, (NSCharacterSet *)theSet, longCharacterIsMember:(UTF32Char)theChar); + CF_OBJC_FUNCDISPATCHV(_kCFRuntimeIDCFCharacterSet, Boolean, (NSCharacterSet *)theSet, longCharacterIsMember:(UTF32Char)theChar); - __CFGenericValidateType(theSet, __kCFCharacterSetTypeID); + __CFGenericValidateType(theSet, _kCFRuntimeIDCFCharacterSet); isInverted = __CFCSetIsInverted(theSet); @@ -1822,9 +1830,9 @@ CF_CROSS_PLATFORM_EXPORT Boolean _CFCharacterSetIsLongCharacterMember(CFCharacte } Boolean CFCharacterSetIsLongCharacterMember(CFCharacterSetRef theSet, UTF32Char theChar) { - CF_OBJC_FUNCDISPATCHV(__kCFCharacterSetTypeID, Boolean, (NSCharacterSet *)theSet, longCharacterIsMember:(UTF32Char)theChar); - CF_SWIFT_FUNCDISPATCHV(__kCFCharacterSetTypeID, Boolean, (CFSwiftRef)theSet, NSCharacterSet.longCharacterIsMember, theChar); - __CFGenericValidateType(theSet, __kCFCharacterSetTypeID); + CF_OBJC_FUNCDISPATCHV(_kCFRuntimeIDCFCharacterSet, Boolean, (NSCharacterSet *)theSet, longCharacterIsMember:(UTF32Char)theChar); + CF_SWIFT_FUNCDISPATCHV(_kCFRuntimeIDCFCharacterSet, Boolean, (CFSwiftRef)theSet, NSCharacterSet.longCharacterIsMember, theChar); + __CFGenericValidateType(theSet, _kCFRuntimeIDCFCharacterSet); return _CFCharacterSetIsLongCharacterMember(theSet, theChar); } @@ -1834,7 +1842,7 @@ Boolean CFCharacterSetIsSurrogatePairMember(CFCharacterSetRef theSet, UniChar su static inline CFCharacterSetRef __CFCharacterSetGetExpandedSetForNSCharacterSet(const void *characterSet) { - CF_OBJC_FUNCDISPATCHV(__kCFCharacterSetTypeID, CFCharacterSetRef , (NSCharacterSet *)characterSet, _expandedCFCharacterSet); + CF_OBJC_FUNCDISPATCHV(_kCFRuntimeIDCFCharacterSet, CFCharacterSetRef , (NSCharacterSet *)characterSet, _expandedCFCharacterSet); return NULL; } @@ -1844,12 +1852,12 @@ Boolean CFCharacterSetIsSupersetOfSet(CFCharacterSetRef theSet, CFCharacterSetRe CFCharacterSetRef expandedOtherSet = NULL; Boolean result; - if ((!CF_IS_OBJC(__kCFCharacterSetTypeID, theSet) || (expandedSet = __CFCharacterSetGetExpandedSetForNSCharacterSet(theSet))) && (!CF_IS_OBJC(__kCFCharacterSetTypeID, theOtherSet) || (expandedOtherSet = __CFCharacterSetGetExpandedSetForNSCharacterSet(theOtherSet)))) { // Really CF, we can do some trick here + if ((!CF_IS_OBJC(_kCFRuntimeIDCFCharacterSet, theSet) || (expandedSet = __CFCharacterSetGetExpandedSetForNSCharacterSet(theSet))) && (!CF_IS_OBJC(_kCFRuntimeIDCFCharacterSet, theOtherSet) || (expandedOtherSet = __CFCharacterSetGetExpandedSetForNSCharacterSet(theOtherSet)))) { // Really CF, we can do some trick here if (expandedSet) theSet = expandedSet; if (expandedOtherSet) theOtherSet = expandedOtherSet; - __CFGenericValidateType(theSet, __kCFCharacterSetTypeID); - __CFGenericValidateType(theOtherSet, __kCFCharacterSetTypeID); + __CFGenericValidateType(theSet, _kCFRuntimeIDCFCharacterSet); + __CFGenericValidateType(theOtherSet, _kCFRuntimeIDCFCharacterSet); if (__CFCSetIsEmpty(theSet)) { if (__CFCSetIsInverted(theSet)) { @@ -1937,7 +1945,7 @@ Boolean CFCharacterSetIsSupersetOfSet(CFCharacterSetRef theSet, CFCharacterSetRe Boolean CFCharacterSetHasMemberInPlane(CFCharacterSetRef theSet, CFIndex thePlane) { Boolean isInverted = __CFCSetIsInverted(theSet); - CF_OBJC_FUNCDISPATCHV(__kCFCharacterSetTypeID, Boolean, (NSCharacterSet *)theSet, hasMemberInPlane:(uint8_t)thePlane); + CF_OBJC_FUNCDISPATCHV(_kCFRuntimeIDCFCharacterSet, Boolean, (NSCharacterSet *)theSet, hasMemberInPlane:(uint8_t)thePlane); if (__CFCSetIsEmpty(theSet)) { return (isInverted ? TRUE : FALSE); @@ -2022,9 +2030,9 @@ CFDataRef CFCharacterSetCreateBitmapRepresentation(CFAllocatorRef alloc, CFChara int length; bool isAnnexInverted; - CF_OBJC_FUNCDISPATCHV(__kCFCharacterSetTypeID, CFDataRef , (NSCharacterSet *)theSet, _retainedBitmapRepresentation); + CF_OBJC_FUNCDISPATCHV(_kCFRuntimeIDCFCharacterSet, CFDataRef , (NSCharacterSet *)theSet, _retainedBitmapRepresentation); - __CFGenericValidateType(theSet, __kCFCharacterSetTypeID); + __CFGenericValidateType(theSet, _kCFRuntimeIDCFCharacterSet); isAnnexInverted = (__CFCSetAnnexIsInverted(theSet) != 0); @@ -2178,7 +2186,7 @@ CFDataRef CFCharacterSetCreateBitmapRepresentation(CFAllocatorRef alloc, CFChara /*** MutableCharacterSet functions ***/ void CFCharacterSetAddCharactersInRange(CFMutableCharacterSetRef theSet, CFRange theRange) { - CF_OBJC_FUNCDISPATCHV(__kCFCharacterSetTypeID, void, (NSMutableCharacterSet *)theSet, addCharactersInRange:NSMakeRange(theRange.location, theRange.length)); + CF_OBJC_FUNCDISPATCHV(_kCFRuntimeIDCFCharacterSet, void, (NSMutableCharacterSet *)theSet, addCharactersInRange:NSMakeRange(theRange.location, theRange.length)); __CFCSetValidateTypeAndMutability(theSet, __PRETTY_FUNCTION__); __CFCSetValidateRange(theRange, __PRETTY_FUNCTION__); @@ -2245,7 +2253,7 @@ void CFCharacterSetAddCharactersInRange(CFMutableCharacterSetRef theSet, CFRange } void CFCharacterSetRemoveCharactersInRange(CFMutableCharacterSetRef theSet, CFRange theRange) { - CF_OBJC_FUNCDISPATCHV(__kCFCharacterSetTypeID, void, (NSMutableCharacterSet *)theSet, removeCharactersInRange:NSMakeRange(theRange.location, theRange.length)); + CF_OBJC_FUNCDISPATCHV(_kCFRuntimeIDCFCharacterSet, void, (NSMutableCharacterSet *)theSet, removeCharactersInRange:NSMakeRange(theRange.location, theRange.length)); __CFCSetValidateTypeAndMutability(theSet, __PRETTY_FUNCTION__); __CFCSetValidateRange(theRange, __PRETTY_FUNCTION__); @@ -2321,7 +2329,7 @@ void CFCharacterSetAddCharactersInString(CFMutableCharacterSetRef theSet, CFStr CFIndex length; BOOL hasSurrogate = NO; - CF_OBJC_FUNCDISPATCHV(__kCFCharacterSetTypeID, void, (NSMutableCharacterSet *)theSet, addCharactersInString:(NSString *)theString); + CF_OBJC_FUNCDISPATCHV(_kCFRuntimeIDCFCharacterSet, void, (NSMutableCharacterSet *)theSet, addCharactersInString:(NSString *)theString); __CFCSetValidateTypeAndMutability(theSet, __PRETTY_FUNCTION__); @@ -2414,7 +2422,7 @@ void CFCharacterSetRemoveCharactersInString(CFMutableCharacterSetRef theSet, CFS CFIndex length; BOOL hasSurrogate = NO; - CF_OBJC_FUNCDISPATCHV(__kCFCharacterSetTypeID, void, (NSMutableCharacterSet *)theSet, removeCharactersInString:(NSString *)theString); + CF_OBJC_FUNCDISPATCHV(_kCFRuntimeIDCFCharacterSet, void, (NSMutableCharacterSet *)theSet, removeCharactersInString:(NSString *)theString); __CFCSetValidateTypeAndMutability(theSet, __PRETTY_FUNCTION__); @@ -2499,7 +2507,7 @@ void CFCharacterSetRemoveCharactersInString(CFMutableCharacterSetRef theSet, CFS void CFCharacterSetUnion(CFMutableCharacterSetRef theSet, CFCharacterSetRef theOtherSet) { CFCharacterSetRef expandedSet = NULL; - CF_OBJC_FUNCDISPATCHV(__kCFCharacterSetTypeID, void, (NSMutableCharacterSet *)theSet, formUnionWithCharacterSet:(NSCharacterSet *)theOtherSet); + CF_OBJC_FUNCDISPATCHV(_kCFRuntimeIDCFCharacterSet, void, (NSMutableCharacterSet *)theSet, formUnionWithCharacterSet:(NSCharacterSet *)theOtherSet); __CFCSetValidateTypeAndMutability(theSet, __PRETTY_FUNCTION__); @@ -2513,7 +2521,7 @@ void CFCharacterSetUnion(CFMutableCharacterSetRef theSet, CFCharacterSetRef theO if (__CFCSetIsEmpty(theSet) && __CFCSetIsInverted(theSet)) return; // Inverted empty set contains all char - if (!CF_IS_OBJC(__kCFCharacterSetTypeID, theOtherSet) || (expandedSet = __CFCharacterSetGetExpandedSetForNSCharacterSet(theOtherSet))) { // Really CF, we can do some trick here + if (!CF_IS_OBJC(_kCFRuntimeIDCFCharacterSet, theOtherSet) || (expandedSet = __CFCharacterSetGetExpandedSetForNSCharacterSet(theOtherSet))) { // Really CF, we can do some trick here if (expandedSet) theOtherSet = expandedSet; if (__CFCSetIsEmpty(theOtherSet)) { @@ -2630,7 +2638,7 @@ void CFCharacterSetUnion(CFMutableCharacterSetRef theSet, CFCharacterSetRef theO void CFCharacterSetIntersect(CFMutableCharacterSetRef theSet, CFCharacterSetRef theOtherSet) { CFCharacterSetRef expandedSet = NULL; - CF_OBJC_FUNCDISPATCHV(__kCFCharacterSetTypeID, void, (NSMutableCharacterSet *)theSet, formIntersectionWithCharacterSet:(NSCharacterSet *)theOtherSet); + CF_OBJC_FUNCDISPATCHV(_kCFRuntimeIDCFCharacterSet, void, (NSMutableCharacterSet *)theSet, formIntersectionWithCharacterSet:(NSCharacterSet *)theOtherSet); __CFCSetValidateTypeAndMutability(theSet, __PRETTY_FUNCTION__); @@ -2644,7 +2652,7 @@ void CFCharacterSetIntersect(CFMutableCharacterSetRef theSet, CFCharacterSetRef if (__CFCSetIsEmpty(theSet) && !__CFCSetIsInverted(theSet)) return; // empty set - if (!CF_IS_OBJC(__kCFCharacterSetTypeID, theOtherSet) || (expandedSet = __CFCharacterSetGetExpandedSetForNSCharacterSet(theOtherSet))) { // Really CF, we can do some trick here + if (!CF_IS_OBJC(_kCFRuntimeIDCFCharacterSet, theOtherSet) || (expandedSet = __CFCharacterSetGetExpandedSetForNSCharacterSet(theOtherSet))) { // Really CF, we can do some trick here if (expandedSet) theOtherSet = expandedSet; if (__CFCSetIsEmpty(theOtherSet)) { @@ -2854,7 +2862,7 @@ void CFCharacterSetIntersect(CFMutableCharacterSetRef theSet, CFCharacterSetRef void CFCharacterSetInvert(CFMutableCharacterSetRef theSet) { - CF_OBJC_FUNCDISPATCHV(__kCFCharacterSetTypeID, void, (NSMutableCharacterSet *)theSet, invert); + CF_OBJC_FUNCDISPATCHV(_kCFRuntimeIDCFCharacterSet, void, (NSMutableCharacterSet *)theSet, invert); __CFCSetValidateTypeAndMutability(theSet, __PRETTY_FUNCTION__); @@ -2938,7 +2946,7 @@ void CFCharacterSetFast(CFMutableCharacterSetRef theSet) { /* Keyed-coding support */ CFCharacterSetKeyedCodingType _CFCharacterSetGetKeyedCodingType(CFCharacterSetRef cset) { - if (CF_IS_OBJC(__kCFCharacterSetTypeID, cset)) return kCFCharacterSetKeyedCodingTypeBitmap; + if (CF_IS_OBJC(_kCFRuntimeIDCFCharacterSet, cset)) return kCFCharacterSetKeyedCodingTypeBitmap; switch (__CFCSetClassType(cset)) { case __kCFCharSetClassBuiltin: return ((__CFCSetBuiltinType(cset) < kCFCharacterSetSymbol) ? kCFCharacterSetKeyedCodingTypeBuiltin : kCFCharacterSetKeyedCodingTypeBuiltinAndBitmap); @@ -2967,7 +2975,7 @@ void CFCharacterSetInitInlineBuffer(CFCharacterSetRef cset, CFCharacterSetInline buffer->cset = cset; buffer->rangeLimit = 0x10000; - if (CF_IS_OBJC(__kCFCharacterSetTypeID, cset) || CF_IS_SWIFT(__kCFCharacterSetTypeID, cset)) { + if (CF_IS_OBJC(_kCFRuntimeIDCFCharacterSet, cset) || CF_IS_SWIFT(_kCFRuntimeIDCFCharacterSet, cset)) { CFCharacterSetRef expandedSet = __CFCharacterSetGetExpandedSetForNSCharacterSet(cset); if (NULL == expandedSet) { diff --git a/CoreFoundation/String.subproj/CFCharacterSet.h b/CoreFoundation/String.subproj/CFCharacterSet.h index 9a7c9ab77f..2b26369a1b 100644 --- a/CoreFoundation/String.subproj/CFCharacterSet.h +++ b/CoreFoundation/String.subproj/CFCharacterSet.h @@ -1,7 +1,7 @@ /* CFCharacterSet.h - Copyright (c) 1999-2017, Apple Inc. and the Swift project authors + Copyright (c) 1999-2018, Apple Inc. and the Swift project authors - Portions Copyright (c) 2014-2017, Apple Inc. and the Swift project authors + Portions Copyright (c) 2014-2018, Apple Inc. and the Swift project authors Licensed under Apache License v2.0 with Runtime Library Exception See http://swift.org/LICENSE.txt for license information See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors diff --git a/CoreFoundation/String.subproj/CFCharacterSetPriv.h b/CoreFoundation/String.subproj/CFCharacterSetPriv.h index ef47e79720..1803f47796 100644 --- a/CoreFoundation/String.subproj/CFCharacterSetPriv.h +++ b/CoreFoundation/String.subproj/CFCharacterSetPriv.h @@ -1,7 +1,7 @@ /* CFCharacterSetPriv.h - Copyright (c) 1998-2017, Apple Inc. and the Swift project authors + Copyright (c) 1998-2018, Apple Inc. and the Swift project authors - Portions Copyright (c) 2014-2017, Apple Inc. and the Swift project authors + Portions Copyright (c) 2014-2018, Apple Inc. and the Swift project authors Licensed under Apache License v2.0 with Runtime Library Exception See http://swift.org/LICENSE.txt for license information See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors diff --git a/CoreFoundation/String.subproj/CFRunArray.c b/CoreFoundation/String.subproj/CFRunArray.c index 3fab904eb2..981083c57b 100644 --- a/CoreFoundation/String.subproj/CFRunArray.c +++ b/CoreFoundation/String.subproj/CFRunArray.c @@ -1,6 +1,6 @@ // This source file is part of the Swift.org open source project // -// Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors +// Copyright (c) 2014 - 2018 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information @@ -9,12 +9,13 @@ /* CFRunArray.c - Copyright (c) 2004-2015, Apple Inc. All rights reserved. + Copyright (c) 2004-2018, Apple Inc. All rights reserved. */ #include "CFRunArray.h" #include #include "CFInternal.h" +#include "CFRuntime_Internal.h" /* CFRunArrayGuts (which holds an array of CFRunArrayItems) is the actual data keeper; the objects just point at these... CFRunArrayGuts has copy-on-write behavior. */ @@ -111,7 +112,7 @@ static void __CFRunArraySetBlockCapacity(CFRunArrayRef array, CFIndex desiredCou /* We realloc either when there isn't enough room, or when the needed size is less than half of what's there. In both cases we allocate 33% extra. */ if ((array->guts->maxBlocks < desiredCount) || (array->guts->maxBlocks / 2) > desiredCount) { CFIndex newCapacity = ((desiredCount + 3) / 3) * 4; - ((struct __CFRunArray *)array)->guts = (CFRunArrayGuts *)CFAllocatorReallocate(CFGetAllocator(array), array->guts, sizeof(CFRunArrayGuts) + newCapacity * sizeof(CFRunArrayItem), 0); + ((struct __CFRunArray *)array)->guts = __CFSafelyReallocateWithAllocator(CFGetAllocator(array), array->guts, sizeof(CFRunArrayGuts) + newCapacity * sizeof(CFRunArrayItem), 0, NULL); array->guts->maxBlocks = newCapacity; } } @@ -157,9 +158,7 @@ static void __CFRunArrayDeallocate(CFTypeRef cf) { } } -static CFTypeID __kCFRunArrayTypeID = _kCFRuntimeNotATypeID; - -static const CFRuntimeClass __CFRunArrayClass = { +const CFRuntimeClass __CFRunArrayClass = { 0, "CFRunArray", NULL, // init @@ -172,9 +171,7 @@ static const CFRuntimeClass __CFRunArrayClass = { }; CFTypeID CFRunArrayGetTypeID(void) { - static dispatch_once_t initOnce; - dispatch_once(&initOnce, ^{ __kCFRunArrayTypeID = _CFRuntimeRegisterClass(&__CFRunArrayClass); }); - return __kCFRunArrayTypeID; + return _kCFRuntimeIDCFRunArray; } diff --git a/CoreFoundation/String.subproj/CFRunArray.h b/CoreFoundation/String.subproj/CFRunArray.h index 4c075b7533..ee987b685a 100644 --- a/CoreFoundation/String.subproj/CFRunArray.h +++ b/CoreFoundation/String.subproj/CFRunArray.h @@ -1,6 +1,6 @@ // This source file is part of the Swift.org open source project // -// Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors +// Copyright (c) 2014 - 2018 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information @@ -9,8 +9,8 @@ /* CFRunArray.h - Copyright (c) 2004-2015, Apple Inc. All rights reserved. - + Copyright (c) 2004-2018, Apple Inc. All rights reserved. + Contains CFRunArray */ diff --git a/CoreFoundation/String.subproj/CFString.c b/CoreFoundation/String.subproj/CFString.c index a71d96ca3a..8c943636dd 100644 --- a/CoreFoundation/String.subproj/CFString.c +++ b/CoreFoundation/String.subproj/CFString.c @@ -1,7 +1,7 @@ /* CFString.c - Copyright (c) 1998-2017, Apple Inc. and the Swift project authors + Copyright (c) 1998-2018, Apple Inc. and the Swift project authors - Portions Copyright (c) 2014-2017, Apple Inc. and the Swift project authors + Portions Copyright (c) 2014-2018, Apple Inc. and the Swift project authors Licensed under Apache License v2.0 with Runtime Library Exception See http://swift.org/LICENSE.txt for license information See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors @@ -14,6 +14,7 @@ #include #include #include +#include "CFStringEncodingConverterPriv.h" #include #include #include @@ -22,6 +23,10 @@ #include #include #include "CFInternal.h" +#include "CFUniCharPriv.h" +#include "CFString_Internal.h" +#include "CFRuntime_Internal.h" +#include #if DEPLOYMENT_TARGET_MACOSX || DEPLOYMENT_TARGET_EMBEDDED || DEPLOYMENT_TARGET_EMBEDDED_MINI || DEPLOYMENT_TARGET_WINDOWS || DEPLOYMENT_TARGET_LINUX #include "CFLocaleInternal.h" #include "CFStringLocalizedFormattingInternal.h" @@ -49,32 +54,42 @@ #define INSTRUMENT_SHARED_STRINGS 0 #endif -extern CF_PRIVATE const CFStringRef __kCFLocaleCollatorID; - #if INSTRUMENT_SHARED_STRINGS #include /* for umask() */ +#include /* for confstr */ +#include static void __CFRecordStringAllocationEvent(const char *encoding, const char *bytes, CFIndex byteCount) { static CFLock_t lock = CFLockInit; - + if (memchr(bytes, '\n', byteCount)) return; //never record string allocation events for strings with newlines, because those confuse our parser and because they'll never go into the ROM - + __CFLock(&lock); - static int fd; - if (! fd) { - extern char **_NSGetProgname(void); - const char *name = *_NSGetProgname(); - if (! name) name = "UNKNOWN"; - umask(0); - char path[1024]; - snprintf(path, sizeof(path), "/tmp/CFSharedStringInstrumentation_%s_%d.txt", name, getpid()); - fd = open(path, O_WRONLY | O_APPEND | O_CREAT, 0666); - if (fd <= 0) { - int error = errno; - const char *errString = strerror(error); - fprintf(stderr, "open() failed with error %d (%s)\n", error, errString); - } - } + static int fd = -1; + dispatch_once_t pred; + + dispatch_once(&pred, ^{ + const char *name = *_NSGetProgname(); + if (! name) name = "UNKNOWN"; + umask(0); + + char temp_dir[PATH_MAX]; + char path[PATH_MAX]; + + size_t temp_dir_len = confstr(_CS_DARWIN_USER_TEMP_DIR, temp_dir, PATH_MAX); + if (temp_dir_len == 0){ + fprintf(stderr, "confstr failed due to %s", strerror(errno)); + } else { + snprintf(path, sizeof(path), "%s/CFSharedStringInstrumentation_%s_%d.txt", temp_dir, name, getpid()); + fd = open(path, O_WRONLY | O_APPEND | O_CREAT, 0666); + if (fd <= 0) { + int error = errno; + const char *errString = strerror(error); + fprintf(stderr, "open() failed with error %d (%s)\n", error, errString); + } + } + }); + if (fd > 0) { char *buffer = NULL; char formatString[256]; @@ -88,14 +103,14 @@ static void __CFRecordStringAllocationEvent(const char *encoding, const char *by } #endif //INSTRUMENT_SHARED_STRINGS -typedef Boolean (*UNI_CHAR_FUNC)(UInt32 flags, UInt8 ch, UniChar *unicodeChar); - #if DEPLOYMENT_TARGET_MACOSX || DEPLOYMENT_TARGET_EMBEDDED || DEPLOYMENT_TARGET_EMBEDDED_MINI extern size_t malloc_good_size(size_t size); #endif extern void __CFStrConvertBytesToUnicode(const uint8_t *bytes, UniChar *buffer, CFIndex numChars); -static void __CFStringAppendFormatCore(CFMutableStringRef outputString, CFStringRef (*copyDescFunc)(void *, const void *), CFStringRef (*contextDescFunc)(void *, const void *, const void *, bool, bool *), CFDictionaryRef formatOptions, CFDictionaryRef stringsDictConfig, CFStringRef validFormatSpecifiers, CFStringRef formatString, CFIndex initialArgPosition, const void *origValues, CFIndex originalValuesSize, va_list args, CFErrorRef *errorPtr); +CF_PRIVATE uint32_t CFUniCharGetConditionalCaseMappingFlags(UTF32Char theChar, UTF16Char *buffer, CFIndex currentIndex, CFIndex length, uint32_t type, const uint8_t *langCode, uint32_t lastFlags); + +static Boolean __CFStringAppendFormatCore(CFMutableStringRef outputString, CFStringRef (*copyDescFunc)(void *, const void *), CFStringRef (*contextDescFunc)(void *, const void *, const void *, bool, bool *), CFDictionaryRef formatOptions, CFDictionaryRef stringsDictConfig, CFStringRef validFormatSpecifiers, CFStringRef formatString, CFIndex initialArgPosition, const void *origValues, CFIndex originalValuesSize, va_list args, CFErrorRef *errorPtr); #if defined(DEBUG) @@ -412,7 +427,7 @@ CFStringEncoding CFStringGetSystemEncoding(void) { if (__CFDefaultSystemEncoding == kCFStringEncodingInvalidId) { __CFDefaultSystemEncoding = __defaultEncoding; const CFStringEncodingConverter *converter = CFStringEncodingGetConverter(__CFDefaultSystemEncoding); - __CFSetCharToUniCharFunc(converter->encodingClass == kCFStringEncodingConverterCheapEightBit ? (UNI_CHAR_FUNC)converter->toUnicode : NULL); + __CFSetCharToUniCharFunc(converter->encodingClass == kCFStringEncodingConverterCheapEightBit ? converter->toUnicode.cheapEightBit : NULL); } return __CFDefaultSystemEncoding; } @@ -588,11 +603,11 @@ CF_INLINE Boolean __CFCanUseLengthByte(CFIndex len) { /* Various string assertions */ -#define __CFAssertIsString(cf) __CFGenericValidateType(cf, __kCFStringTypeID) +#define __CFAssertIsString(cf) __CFGenericValidateType(cf, _kCFRuntimeIDCFString) #define __CFAssertIndexIsInStringBounds(cf, idx) CFAssert3((idx) >= 0 && (idx) < __CFStrLength(cf), __kCFLogAssertion, "%s(): string index %ld out of bounds (length %ld)", __PRETTY_FUNCTION__, idx, __CFStrLength(cf)) #define __CFAssertRangeIsInStringBounds(cf, idx, count) CFAssert4((idx) >= 0 && (idx + count) <= __CFStrLength(cf), __kCFLogAssertion, "%s(): string range %ld,%ld out of bounds (length %ld)", __PRETTY_FUNCTION__, idx, count, __CFStrLength(cf)) -#define __CFAssertIsStringAndMutable(cf) {__CFGenericValidateType(cf, __kCFStringTypeID); CFAssert1(__CFStrIsMutable(cf), __kCFLogAssertion, "%s(): string not mutable", __PRETTY_FUNCTION__);} -#define __CFAssertIsStringAndExternalMutable(cf) {__CFGenericValidateType(cf, __kCFStringTypeID); CFAssert1(__CFStrIsMutable(cf) && __CFStrIsExternalMutable(cf), __kCFLogAssertion, "%s(): string not external mutable", __PRETTY_FUNCTION__);} +#define __CFAssertIsStringAndMutable(cf) {__CFGenericValidateType(cf, _kCFRuntimeIDCFString); CFAssert1(__CFStrIsMutable(cf), __kCFLogAssertion, "%s(): string not mutable", __PRETTY_FUNCTION__);} +#define __CFAssertIsStringAndExternalMutable(cf) {__CFGenericValidateType(cf, _kCFRuntimeIDCFString); CFAssert1(__CFStrIsMutable(cf) && __CFStrIsExternalMutable(cf), __kCFLogAssertion, "%s(): string not external mutable", __PRETTY_FUNCTION__);} #define __CFAssertIsNotNegative(idx) CFAssert2(idx >= 0, __kCFLogAssertion, "%s(): index %ld is negative", __PRETTY_FUNCTION__, idx) #define __CFAssertIfFixedLengthIsOK(cf, reqLen) CFAssert2(!__CFStrIsFixed(cf) || (reqLen <= __CFStrDesiredCapacity(cf)), __kCFLogAssertion, "%s(): length %ld too large", __PRETTY_FUNCTION__, reqLen) @@ -1014,7 +1029,7 @@ If the length is greater than 96, then the above algorithm applies to characters 0..31, (length/2)-16..(length/2)+15, and length-32..length-1, inclusive; thus the first, middle, and last 32 characters. -Note that the loops below are unrolled; and: 257^2 = 66049; 257^3 = 16974593; 257^4 = 4362470401; 67503105 is 257^4 - 256^4 +Note that the loops below are unrolled; and: 67503105 is 257^4 - 256^4 If hashcode is changed from UInt32 to something else, this last piece needs to be readjusted. !!! We haven't updated for LP64 yet @@ -1025,7 +1040,7 @@ Hash function was changed between Panther and Tiger, and Tiger and Leopard. #define HashEverythingLimit 96 #define HashNextFourUniChars(accessStart, accessEnd, pointer) \ - {result = result * 67503105 + (accessStart 0 accessEnd) * 16974593 + (accessStart 1 accessEnd) * 66049 + (accessStart 2 accessEnd) * 257 + (accessStart 3 accessEnd); pointer += 4;} + {result = result * 67503105 + (((accessStart 0 accessEnd) * 257 + (accessStart 1 accessEnd)) * 257 + (accessStart 2 accessEnd)) * 257 + (accessStart 3 accessEnd); pointer += 4;} #define HashNextUniChar(accessStart, accessEnd, pointer) \ {result = result * 257 + (accessStart 0 accessEnd); pointer++;} @@ -1186,11 +1201,9 @@ static CFStringRef __CFStringCopyFormattingDescription(CFTypeRef cf, CFDictionar return (CFStringRef)CFStringCreateCopy(__CFGetAllocator(cf), (CFStringRef)cf); } -static CFTypeID __kCFStringTypeID = _kCFRuntimeNotATypeID; - typedef CFTypeRef (*CF_STRING_CREATE_COPY)(CFAllocatorRef alloc, CFTypeRef theString); -static const CFRuntimeClass __CFStringClass = { +const CFRuntimeClass __CFStringClass = { _kCFRuntimeScannedObject, "CFString", NULL, // init @@ -1202,20 +1215,15 @@ static const CFRuntimeClass __CFStringClass = { __CFStringCopyDescription }; -CF_PRIVATE void __CFStringInitialize(void) { - static dispatch_once_t initOnce; - dispatch_once(&initOnce, ^{ __kCFStringTypeID = _CFRuntimeRegisterClass(&__CFStringClass); }); -} - CFTypeID CFStringGetTypeID(void) { - return __kCFStringTypeID; + return _kCFRuntimeIDCFString; } static Boolean CFStrIsUnicode(CFStringRef str) { - CF_SWIFT_FUNCDISPATCHV(__kCFStringTypeID, Boolean, str, NSString._encodingCantBeStoredInEightBitCFString); - CF_OBJC_FUNCDISPATCHV(__kCFStringTypeID, Boolean, (NSString *)str, _encodingCantBeStoredInEightBitCFString); + CF_SWIFT_FUNCDISPATCHV(_kCFRuntimeIDCFString, Boolean, str, NSString._encodingCantBeStoredInEightBitCFString); + CF_OBJC_FUNCDISPATCHV(_kCFRuntimeIDCFString, Boolean, (NSString *)str, _encodingCantBeStoredInEightBitCFString); return __CFStrIsUnicode(str); } @@ -1409,7 +1417,7 @@ CF_PRIVATE CFStringRef __CFStringCreateImmutableFunnel3( #endif #if INSTRUMENT_SHARED_STRINGS - if (stringSupportsROM) __CFRecordStringAllocationEvent(recordedEncoding, realBytes, realNumBytes); + if (stringSupportsROM) __CFRecordStringAllocationEvent(recordedEncoding, (const char *)realBytes, realNumBytes); #endif #if USE_STRING_ROM @@ -1447,7 +1455,7 @@ CF_PRIVATE CFStringRef __CFStringCreateImmutableFunnel3( #endif #if INSTRUMENT_SHARED_STRINGS - if (stringSupportsROM) __CFRecordStringAllocationEvent(recordedEncoding, realBytes, realNumBytes); + if (stringSupportsROM) __CFRecordStringAllocationEvent(recordedEncoding, (const char *)realBytes, realNumBytes); #endif #if INSTRUMENT_TAGGED_POINTER_STRINGS _CFTaggedPointerStringStats.otherStringCount++; @@ -1500,7 +1508,7 @@ CF_PRIVATE CFStringRef __CFStringCreateImmutableFunnel3( CFIndex swiftStringSize = sizeof(CFRuntimeBase) + (sizeof(void *) * 3); if (swiftStringSize > size) size = swiftStringSize; #endif - str = (CFMutableStringRef)_CFRuntimeCreateInstance(alloc, __kCFStringTypeID, size, NULL); + str = (CFMutableStringRef)_CFRuntimeCreateInstance(alloc, _kCFRuntimeIDCFString, size, NULL); if (str) { if (__CFOASafe) __CFSetLastAllocationEventName(str, "CFString (immutable)"); @@ -1608,15 +1616,19 @@ CFStringRef CFStringCreateWithBytesNoCopy(CFAllocatorRef alloc, const uint8_t * } CFStringRef CFStringCreateStringWithValidatedFormat(CFAllocatorRef alloc, CFDictionaryRef formatOptions, CFStringRef validFormatSpecifiers, CFStringRef format, va_list arguments, CFErrorRef *errorPtr) { - CFStringRef str; CFMutableStringRef outputString = CFStringCreateMutable(kCFAllocatorSystemDefault, 0); //should use alloc if no copy/release __CFStrSetDesiredCapacity(outputString, 120); // Given this will be tightened later, choosing a larger working string is fine - __CFStringAppendFormatCore(outputString, NULL, NULL, formatOptions, NULL, validFormatSpecifiers, format, 0, NULL, 0, arguments, errorPtr); - // ??? copy/release should not be necessary here -- just make immutable, compress if possible - // (However, this does make the string inline, and cause the supplied allocator to be used...) - str = (CFStringRef)CFStringCreateCopy(alloc, outputString); - CFRelease(outputString); - return str; + if (__CFStringAppendFormatCore(outputString, NULL, NULL, formatOptions, NULL, validFormatSpecifiers, format, 0, NULL, 0, arguments, errorPtr)) { + // ??? copy/release should not be necessary here -- just make immutable, compress if possible + // (However, this does make the string inline, and cause the supplied allocator to be used...) + CFStringRef str = (CFStringRef)CFStringCreateCopy(alloc, outputString); + CFRelease(outputString); + return str; + } else { + CFRelease(outputString); + // errorPtr set by __CFStringAppendFormatCore + return NULL; + } } CFStringRef CFStringCreateWithFormatAndArguments(CFAllocatorRef alloc, CFDictionaryRef formatOptions, CFStringRef format, va_list arguments) { @@ -1624,13 +1636,18 @@ CFStringRef CFStringCreateWithFormatAndArguments(CFAllocatorRef alloc, CFDictio } CFStringRef _CFStringCreateWithFormatAndArgumentsAux2(CFAllocatorRef alloc, CFStringRef (*copyDescFunc)(void *, const void *), CFStringRef (*contextDescFunc)(void *, const void *, const void *, bool , bool *), CFDictionaryRef formatOptions, CFStringRef format, va_list arguments) { - CFStringRef str; + CFStringRef str = NULL; CFMutableStringRef outputString = CFStringCreateMutable(kCFAllocatorSystemDefault, 0); //should use alloc if no copy/release __CFStrSetDesiredCapacity(outputString, 120); // Given this will be tightened later, choosing a larger working string is fine - __CFStringAppendFormatCore(outputString, copyDescFunc, contextDescFunc, formatOptions, NULL, NULL, format, 0, NULL, 0, arguments, NULL); - // ??? copy/release should not be necessary here -- just make immutable, compress if possible - // (However, this does make the string inline, and cause the supplied allocator to be used...) - str = (CFStringRef)CFStringCreateCopy(alloc, outputString); + CFErrorRef error; + if (__CFStringAppendFormatCore(outputString, copyDescFunc, contextDescFunc, formatOptions, NULL, NULL, format, 0, NULL, 0, arguments, &error)) { + // ??? copy/release should not be necessary here -- just make immutable, compress if possible + // (However, this does make the string inline, and cause the supplied allocator to be used...) + str = (CFStringRef)CFStringCreateCopy(alloc, outputString); + } else { + CFLog(kCFLogLevelError, CFSTR("ERROR: Failed to format string: %@"), error); + if (error) CFRelease(error); + } CFRelease(outputString); return str; } @@ -1651,8 +1668,8 @@ CFStringRef CFStringCreateWithFormat(CFAllocatorRef alloc, CFDictionaryRef form } CFStringRef CFStringCreateWithSubstring(CFAllocatorRef alloc, CFStringRef str, CFRange range) { - CF_SWIFT_FUNCDISPATCHV(__kCFStringTypeID, CFStringRef, (CFSwiftRef)str, NSString._createSubstringWithRange, range); -// CF_OBJC_FUNCDISPATCHV(__kCFStringTypeID, CFStringRef , (NSString *)str, _createSubstringWithRange:NSMakeRange(range.location, range.length)); + CF_SWIFT_FUNCDISPATCHV(_kCFRuntimeIDCFString, CFStringRef, (CFSwiftRef)str, NSString._createSubstringWithRange, range); +// CF_OBJC_FUNCDISPATCHV(_kCFRuntimeIDCFString, CFStringRef , (NSString *)str, _createSubstringWithRange:NSMakeRange(range.location, range.length)); __CFAssertIsString(str); __CFAssertRangeIsInStringBounds(str, range.location, range.length); @@ -1694,8 +1711,8 @@ CF_PRIVATE CFStringRef _CFStringCopyBundleUnloadingProtectedString(CFStringRef s CFStringRef CFStringCreateCopy(CFAllocatorRef alloc, CFStringRef str) { - CF_SWIFT_FUNCDISPATCHV(__kCFStringTypeID, CFStringRef, (CFSwiftRef)str, NSString.copy); -// CF_OBJC_FUNCDISPATCHV(__kCFStringTypeID, CFStringRef, (NSString *)str, copy); + CF_SWIFT_FUNCDISPATCHV(_kCFRuntimeIDCFString, CFStringRef, (CFSwiftRef)str, NSString.copy); +// CF_OBJC_FUNCDISPATCHV(_kCFRuntimeIDCFString, CFStringRef, (NSString *)str, copy); __CFAssertIsString(str); if (!__CFStrIsMutable((CFStringRef)str) && // If the string is not mutable @@ -1801,7 +1818,7 @@ CFStringRef __CFStringMakeConstantString(const char *cStr) { CFLog(__kCFLogAssertion, CFSTR("Can't interpret CFSTR() as MacOS Roman, crashing")); HALT; } - Boolean isTaggedPointerString = CF_IS_OBJC(__kCFStringTypeID, result); + Boolean isTaggedPointerString = CF_IS_OBJC(_kCFRuntimeIDCFString, result); if (!isTaggedPointerString) { if (__CFOASafe) __CFSetLastAllocationEventName((void *)result, "CFString (CFSTR)"); @@ -1932,7 +1949,7 @@ CF_INLINE CFMutableStringRef __CFStringCreateMutableFunnel(CFAllocatorRef alloc, if (alloc == NULL) alloc = __CFGetDefaultAllocator(); // Note that if there is an externalContentsAllocator, then we also have the storage for the string allocator... - str = (CFMutableStringRef)_CFRuntimeCreateInstance(alloc, __kCFStringTypeID, sizeof(struct __notInlineMutable) - (hasExternalContentsAllocator ? 0 : sizeof(CFAllocatorRef)), NULL); + str = (CFMutableStringRef)_CFRuntimeCreateInstance(alloc, _kCFRuntimeIDCFString, sizeof(struct __notInlineMutable) - (hasExternalContentsAllocator ? 0 : sizeof(CFAllocatorRef)), NULL); if (str) { if (__CFOASafe) __CFSetLastAllocationEventName(str, "CFString (mutable)"); @@ -1975,7 +1992,7 @@ CFMutableStringRef CFStringCreateMutable(CFAllocatorRef alloc, CFIndex maxLength CFMutableStringRef CFStringCreateMutableCopy(CFAllocatorRef alloc, CFIndex maxLength, CFStringRef string) { CFMutableStringRef newString; - // CF_OBJC_FUNCDISPATCHV(__kCFStringTypeID, CFMutableStringRef, (NSString *)string, mutableCopy); + // CF_OBJC_FUNCDISPATCHV(_kCFRuntimeIDCFString, CFMutableStringRef, (NSString *)string, mutableCopy); __CFAssertIsString(string); @@ -1995,8 +2012,8 @@ CF_PRIVATE void _CFStrSetDesiredCapacity(CFMutableStringRef str, CFIndex len) { /* This one is for CF */ CFIndex CFStringGetLength(CFStringRef str) { - CF_SWIFT_FUNCDISPATCHV(__kCFStringTypeID, CFIndex, (CFSwiftRef)str, NSString.length); - CF_OBJC_FUNCDISPATCHV(__kCFStringTypeID, CFIndex, (NSString *)str, length); + CF_SWIFT_FUNCDISPATCHV(_kCFRuntimeIDCFString, CFIndex, (CFSwiftRef)str, NSString.length); + CF_OBJC_FUNCDISPATCHV(_kCFRuntimeIDCFString, CFIndex, (NSString *)str, length); __CFAssertIsString(str); return __CFStrLength(str); @@ -2029,8 +2046,8 @@ CF_INLINE UniChar __CFStringGetCharacterAtIndexGuts(CFStringRef str, CFIndex idx /* This one is for the CF API */ UniChar CFStringGetCharacterAtIndex(CFStringRef str, CFIndex idx) { - CF_SWIFT_FUNCDISPATCHV(__kCFStringTypeID, UniChar, (CFSwiftRef)str, NSString.characterAtIndex, idx); - CF_OBJC_FUNCDISPATCHV(__kCFStringTypeID, UniChar, (NSString *)str, characterAtIndex:(NSUInteger)idx); + CF_SWIFT_FUNCDISPATCHV(_kCFRuntimeIDCFString, UniChar, (CFSwiftRef)str, NSString.characterAtIndex, idx); + CF_OBJC_FUNCDISPATCHV(_kCFRuntimeIDCFString, UniChar, (NSString *)str, characterAtIndex:(NSUInteger)idx); __CFAssertIsString(str); __CFAssertIndexIsInStringBounds(str, idx); @@ -2061,8 +2078,8 @@ CF_INLINE void __CFStringGetCharactersGuts(CFStringRef str, CFRange range, UniCh /* This one is for the CF API */ void CFStringGetCharacters(CFStringRef str, CFRange range, UniChar *buffer) { - CF_SWIFT_FUNCDISPATCHV(__kCFStringTypeID, void, (CFSwiftRef)str, NSString.getCharacters, range, buffer); - CF_OBJC_FUNCDISPATCHV(__kCFStringTypeID, void, (NSString *)str, getCharacters:(unichar *)buffer range:NSMakeRange(range.location, range.length)); + CF_SWIFT_FUNCDISPATCHV(_kCFRuntimeIDCFString, void, (CFSwiftRef)str, NSString.getCharacters, range, buffer); + CF_OBJC_FUNCDISPATCHV(_kCFRuntimeIDCFString, void, (NSString *)str, getCharacters:(unichar *)buffer range:NSMakeRange(range.location, range.length)); __CFAssertIsString(str); __CFAssertRangeIsInStringBounds(str, range.location, range.length); @@ -2111,7 +2128,7 @@ CFIndex CFStringGetBytes(CFStringRef str, CFRange range, CFStringEncoding encodi ConstStringPtr CFStringGetPascalStringPtr (CFStringRef str, CFStringEncoding encoding) { - if (!CF_IS_OBJC(__kCFStringTypeID, str) && !CF_IS_SWIFT(__kCFStringTypeID, str)) { /* ??? Hope the compiler optimizes this away if OBJC_MAPPINGS is not on */ + if (!CF_IS_OBJC(_kCFRuntimeIDCFString, str) && !CF_IS_SWIFT(_kCFRuntimeIDCFString, str)) { /* ??? Hope the compiler optimizes this away if OBJC_MAPPINGS is not on */ __CFAssertIsString(str); if (__CFStrHasLengthByte(str) && __CFStrIsEightBit(str) && ((__CFStringGetEightBitStringEncoding() == encoding) || (__CFStringGetEightBitStringEncoding() == kCFStringEncodingASCII && __CFStringEncodingIsSupersetOfASCII(encoding)))) { // Requested encoding is equal to the encoding in string || the contents is in ASCII const uint8_t *contents = (const uint8_t *)__CFStrContents(str); @@ -2131,8 +2148,8 @@ const char * CFStringGetCStringPtr(CFStringRef str, CFStringEncoding encoding) { if (str == NULL) return NULL; // Should really just crash, but for compatibility... see - CF_SWIFT_FUNCDISPATCHV(__kCFStringTypeID, const char *, (CFSwiftRef)str, NSString._fastCStringContents, true); - CF_OBJC_FUNCDISPATCHV(__kCFStringTypeID, const char *, (NSString *)str, _fastCStringContents:true); + CF_SWIFT_FUNCDISPATCHV(_kCFRuntimeIDCFString, const char *, (CFSwiftRef)str, NSString._fastCStringContents, true); + CF_OBJC_FUNCDISPATCHV(_kCFRuntimeIDCFString, const char *, (NSString *)str, _fastCStringContents:true); __CFAssertIsString(str); @@ -2147,8 +2164,8 @@ const char * CFStringGetCStringPtr(CFStringRef str, CFStringEncoding encoding) { const UniChar *CFStringGetCharactersPtr(CFStringRef str) { - CF_SWIFT_FUNCDISPATCHV(__kCFStringTypeID, const UniChar *, (CFSwiftRef)str, NSString._fastCharacterContents); - CF_OBJC_FUNCDISPATCHV(__kCFStringTypeID, const UniChar *, (NSString *)str, _fastCharacterContents); + CF_SWIFT_FUNCDISPATCHV(_kCFRuntimeIDCFString, const UniChar *, (CFSwiftRef)str, NSString._fastCharacterContents); + CF_OBJC_FUNCDISPATCHV(_kCFRuntimeIDCFString, const UniChar *, (NSString *)str, _fastCharacterContents); __CFAssertIsString(str); if (__CFStrIsUnicode(str)) return (const UniChar *)__CFStrContents(str); @@ -2163,7 +2180,7 @@ Boolean CFStringGetPascalString(CFStringRef str, Str255 buffer, CFIndex bufferSi __CFAssertIsNotNegative(bufferSize); if (bufferSize < 1) return false; - if (CF_IS_OBJC(__kCFStringTypeID, str) || CF_IS_SWIFT(__kCFStringTypeID, str)) { /* ??? Hope the compiler optimizes this away if OBJC_MAPPINGS is not on */ + if (CF_IS_OBJC(_kCFRuntimeIDCFString, str) || CF_IS_SWIFT(_kCFRuntimeIDCFString, str)) { /* ??? Hope the compiler optimizes this away if OBJC_MAPPINGS is not on */ length = CFStringGetLength(str); if (!__CFCanUseLengthByte(length)) return false; // Can't fit into pstring } else { @@ -2206,8 +2223,8 @@ Boolean CFStringGetCString(CFStringRef str, char *buffer, CFIndex bufferSize, CF __CFAssertIsNotNegative(bufferSize); if (bufferSize < 1) return false; - CF_SWIFT_FUNCDISPATCHV(__kCFStringTypeID, Boolean, (CFSwiftRef)str, NSString._getCString, buffer, bufferSize - 1, encoding); - CF_OBJC_FUNCDISPATCHV(__kCFStringTypeID, Boolean, (NSString *)str, _getCString:buffer maxLength:(NSUInteger)bufferSize - 1 encoding:encoding); + CF_SWIFT_FUNCDISPATCHV(_kCFRuntimeIDCFString, Boolean, (CFSwiftRef)str, NSString._getCString, buffer, bufferSize - 1, encoding); + CF_OBJC_FUNCDISPATCHV(_kCFRuntimeIDCFString, Boolean, (NSString *)str, _getCString:buffer maxLength:(NSUInteger)bufferSize - 1 encoding:encoding); __CFAssertIsString(str); @@ -3420,7 +3437,7 @@ CF_INLINE bool _CFStringIsHangulLVT(UTF32Char character) { return (((character - HANGUL_SYLLABLE_START) % HANGUL_JONGSEONG_COUNT) ? true : false); } -static uint8_t __CFTranscodingHintLength[] = { +static uint8_t const __CFTranscodingHintLength[] = { 2, 3, 4, 4, 4, 4, 4, 2, 2, 2, 2, 4, 0, 0, 0, 0 }; @@ -3983,7 +4000,7 @@ CFRange CFStringGetRangeOfCharacterClusterAtIndex(CFStringRef string, CFIndex ch /* Fast case. If we're eight-bit, it's either the default encoding is cheap or the content is all ASCII. Watch out when (or if) adding more 8bit Mac-scripts in CFStringEncodingConverters */ - if (!CF_IS_OBJC(__kCFStringTypeID, string) && !CF_IS_SWIFT(__kCFStringTypeID, string) && __CFStrIsEightBit(string)) return CFRangeMake(charIndex, 1); + if (!CF_IS_OBJC(_kCFRuntimeIDCFString, string) && !CF_IS_SWIFT(_kCFRuntimeIDCFString, string) && __CFStrIsEightBit(string)) return CFRangeMake(charIndex, 1); bmpBitmap = CFUniCharGetBitmapPtrForPlane(csetType, 0); letterBMP = CFUniCharGetBitmapPtrForPlane(kCFUniCharLetterCharacterSet, 0); @@ -4493,12 +4510,12 @@ static void __CFStringGetLineOrParagraphBounds(CFStringRef string, CFRange range } void CFStringGetLineBounds(CFStringRef string, CFRange range, CFIndex *lineBeginIndex, CFIndex *lineEndIndex, CFIndex *contentsEndIndex) { - CF_OBJC_FUNCDISPATCHV(__kCFStringTypeID, void, (NSString *)string, getLineStart:(NSUInteger *)lineBeginIndex end:(NSUInteger *)lineEndIndex contentsEnd:(NSUInteger *)contentsEndIndex forRange:NSMakeRange(range.location, range.length)); + CF_OBJC_FUNCDISPATCHV(_kCFRuntimeIDCFString, void, (NSString *)string, getLineStart:(NSUInteger *)lineBeginIndex end:(NSUInteger *)lineEndIndex contentsEnd:(NSUInteger *)contentsEndIndex forRange:NSMakeRange(range.location, range.length)); __CFStringGetLineOrParagraphBounds(string, range, lineBeginIndex, lineEndIndex, contentsEndIndex, true); } void CFStringGetParagraphBounds(CFStringRef string, CFRange range, CFIndex *parBeginIndex, CFIndex *parEndIndex, CFIndex *contentsEndIndex) { - CF_OBJC_FUNCDISPATCHV(__kCFStringTypeID, void, (NSString *)string, getParagraphStart:(NSUInteger *)parBeginIndex end:(NSUInteger *)parEndIndex contentsEnd:(NSUInteger *)contentsEndIndex forRange:NSMakeRange(range.location, range.length)); + CF_OBJC_FUNCDISPATCHV(_kCFRuntimeIDCFString, void, (NSString *)string, getParagraphStart:(NSUInteger *)parBeginIndex end:(NSUInteger *)parEndIndex contentsEnd:(NSUInteger *)contentsEndIndex forRange:NSMakeRange(range.location, range.length)); __CFStringGetLineOrParagraphBounds(string, range, parBeginIndex, parEndIndex, contentsEndIndex, false); } @@ -4507,7 +4524,7 @@ CFStringRef CFStringCreateByCombiningStrings(CFAllocatorRef alloc, CFArrayRef ar CFIndex numChars; CFIndex separatorNumByte; CFIndex stringCount = CFArrayGetCount(array); - Boolean isSepCFString = !CF_IS_OBJC(__kCFStringTypeID, separatorString) && !CF_IS_SWIFT(__kCFStringTypeID, separatorString); + Boolean isSepCFString = !CF_IS_OBJC(_kCFRuntimeIDCFString, separatorString) && !CF_IS_SWIFT(_kCFRuntimeIDCFString, separatorString); Boolean canBeEightbit = isSepCFString && __CFStrIsEightBit(separatorString); CFIndex idx; CFStringRef otherString; @@ -4528,7 +4545,7 @@ CFStringRef CFStringCreateByCombiningStrings(CFAllocatorRef alloc, CFArrayRef ar otherString = (CFStringRef)CFArrayGetValueAtIndex(array, idx); numChars += CFStringGetLength(otherString); // canBeEightbit is already false if the separator is an NSString... - if (CF_IS_OBJC(__kCFStringTypeID, otherString) || CF_IS_SWIFT(__kCFStringTypeID, otherString) || ! __CFStrIsEightBit(otherString)) canBeEightbit = false; + if (CF_IS_OBJC(_kCFRuntimeIDCFString, otherString) || CF_IS_SWIFT(_kCFRuntimeIDCFString, otherString) || ! __CFStrIsEightBit(otherString)) canBeEightbit = false; } buffer = (uint8_t *)CFAllocatorAllocate(alloc, canBeEightbit ? ((numChars + 1) * sizeof(uint8_t)) : (numChars * sizeof(UniChar)), 0); @@ -4554,7 +4571,7 @@ CFStringRef CFStringCreateByCombiningStrings(CFAllocatorRef alloc, CFArrayRef ar } otherString = (CFStringRef )CFArrayGetValueAtIndex(array, idx); - if (CF_IS_OBJC(__kCFStringTypeID, otherString) || CF_IS_SWIFT(__kCFStringTypeID, otherString)) { + if (CF_IS_OBJC(_kCFRuntimeIDCFString, otherString) || CF_IS_SWIFT(_kCFRuntimeIDCFString, otherString)) { CFIndex otherLength = CFStringGetLength(otherString); CFStringGetCharacters(otherString, CFRangeMake(0, otherLength), (UniChar *)bufPtr); bufPtr += otherLength * sizeof(UniChar); @@ -4623,7 +4640,7 @@ CFDataRef CFStringCreateExternalRepresentation(CFAllocatorRef alloc, CFStringRef CFIndex usedLength; SInt32 result; - if (CF_IS_OBJC(__kCFStringTypeID, string) || CF_IS_SWIFT(__kCFStringTypeID, string)) { /* ??? Hope the compiler optimizes this away if OBJC_MAPPINGS is not on */ + if (CF_IS_OBJC(_kCFRuntimeIDCFString, string) || CF_IS_SWIFT(_kCFRuntimeIDCFString, string)) { /* ??? Hope the compiler optimizes this away if OBJC_MAPPINGS is not on */ length = CFStringGetLength(string); } else { __CFAssertIsString(string); @@ -4637,7 +4654,7 @@ CFDataRef CFStringCreateExternalRepresentation(CFAllocatorRef alloc, CFStringRef if (((encoding & 0x0FFF) == kCFStringEncodingUnicode) && ((encoding == kCFStringEncodingUnicode) || ((encoding > kCFStringEncodingUTF8) && (encoding <= kCFStringEncodingUTF32LE)))) { guessedByteLength = (length + 1) * ((((encoding >> 26) & 2) == 0) ? sizeof(UTF16Char) : sizeof(UTF32Char)); // UTF32 format has the bit set - } else if (((guessedByteLength = CFStringGetMaximumSizeForEncoding(length, encoding)) > length) && !CF_IS_OBJC(__kCFStringTypeID, string) && !CF_IS_SWIFT(__kCFStringTypeID, string)) { // Multi byte encoding + } else if (((guessedByteLength = CFStringGetMaximumSizeForEncoding(length, encoding)) > length) && !CF_IS_OBJC(_kCFRuntimeIDCFString, string) && !CF_IS_SWIFT(_kCFRuntimeIDCFString, string)) { // Multi byte encoding #if DEPLOYMENT_TARGET_MACOSX || DEPLOYMENT_TARGET_EMBEDDED || DEPLOYMENT_TARGET_EMBEDDED_MINI || DEPLOYMENT_TARGET_LINUX || DEPLOYMENT_TARGET_FREEBSD if (__CFStrIsUnicode(string)) { CFIndex aLength = CFStringEncodingByteLengthForCharacters(encoding, kCFStringEncodingPrependBOM, __CFStrContents(string), __CFStrLength(string)); @@ -4672,10 +4689,10 @@ CFDataRef CFStringCreateExternalRepresentation(CFAllocatorRef alloc, CFStringRef CFStringEncoding CFStringGetSmallestEncoding(CFStringRef str) { CFIndex len; - if (CF_IS_SWIFT(__kCFStringTypeID, str)) { + if (CF_IS_SWIFT(_kCFRuntimeIDCFString, str)) { return kCFStringEncodingUnicode; } - CF_OBJC_FUNCDISPATCHV(__kCFStringTypeID, CFStringEncoding, (NSString *)str, _smallestEncodingInCFStringEncoding); + CF_OBJC_FUNCDISPATCHV(_kCFRuntimeIDCFString, CFStringEncoding, (NSString *)str, _smallestEncodingInCFStringEncoding); __CFAssertIsString(str); if (__CFStrIsEightBit(str)) return __CFStringGetEightBitStringEncoding(); @@ -4687,10 +4704,10 @@ CFStringEncoding CFStringGetSmallestEncoding(CFStringRef str) { CFStringEncoding CFStringGetFastestEncoding(CFStringRef str) { - if (CF_IS_SWIFT(__kCFStringTypeID, str)) { + if (CF_IS_SWIFT(_kCFRuntimeIDCFString, str)) { return kCFStringEncodingUnicode; } - CF_OBJC_FUNCDISPATCHV(__kCFStringTypeID, CFStringEncoding, (NSString *)str, _fastestEncodingInCFStringEncoding); + CF_OBJC_FUNCDISPATCHV(_kCFRuntimeIDCFString, CFStringEncoding, (NSString *)str, _fastestEncodingInCFStringEncoding); __CFAssertIsString(str); return __CFStrIsEightBit(str) ? __CFStringGetEightBitStringEncoding() : kCFStringEncodingUnicode; /* ??? */ } @@ -4733,8 +4750,8 @@ void CFStringSetExternalCharactersNoCopy(CFMutableStringRef string, UniChar *cha void CFStringInsert(CFMutableStringRef str, CFIndex idx, CFStringRef insertedStr) { - CF_SWIFT_FUNCDISPATCHV(__kCFStringTypeID, void, (CFSwiftRef)str, NSMutableString.insertString, idx, (CFSwiftRef)insertedStr); - CF_OBJC_FUNCDISPATCHV(__kCFStringTypeID, void, (NSMutableString *)str, insertString:(NSString *)insertedStr atIndex:(NSUInteger)idx); + CF_SWIFT_FUNCDISPATCHV(_kCFRuntimeIDCFString, void, (CFSwiftRef)str, NSMutableString.insertString, idx, (CFSwiftRef)insertedStr); + CF_OBJC_FUNCDISPATCHV(_kCFRuntimeIDCFString, void, (NSMutableString *)str, insertString:(NSString *)insertedStr atIndex:(NSUInteger)idx); __CFAssertIsStringAndMutable(str); CFAssert3(idx >= 0 && idx <= __CFStrLength(str), __kCFLogAssertion, "%s(): string index %ld out of bounds (length %ld)", __PRETTY_FUNCTION__, idx, __CFStrLength(str)); __CFStringReplace(str, CFRangeMake(idx, 0), insertedStr); @@ -4742,8 +4759,8 @@ void CFStringInsert(CFMutableStringRef str, CFIndex idx, CFStringRef insertedStr void CFStringDelete(CFMutableStringRef str, CFRange range) { - CF_SWIFT_FUNCDISPATCHV(__kCFStringTypeID, void, (CFSwiftRef)str, NSMutableString.deleteCharactersInRange, range); - CF_OBJC_FUNCDISPATCHV(__kCFStringTypeID, void, (NSMutableString *)str, deleteCharactersInRange:NSMakeRange(range.location, range.length)); + CF_SWIFT_FUNCDISPATCHV(_kCFRuntimeIDCFString, void, (CFSwiftRef)str, NSMutableString.deleteCharactersInRange, range); + CF_OBJC_FUNCDISPATCHV(_kCFRuntimeIDCFString, void, (NSMutableString *)str, deleteCharactersInRange:NSMakeRange(range.location, range.length)); __CFAssertIsStringAndMutable(str); __CFAssertRangeIsInStringBounds(str, range.location, range.length); __CFStringChangeSize(str, range, 0, false); @@ -4751,8 +4768,8 @@ void CFStringDelete(CFMutableStringRef str, CFRange range) { void CFStringReplace(CFMutableStringRef str, CFRange range, CFStringRef replacement) { - CF_SWIFT_FUNCDISPATCHV(__kCFStringTypeID, void, (CFSwiftRef)str, NSMutableString.replaceCharactersInRange, range, (CFSwiftRef)replacement); - CF_OBJC_FUNCDISPATCHV(__kCFStringTypeID, void, (NSMutableString *)str, replaceCharactersInRange:NSMakeRange(range.location, range.length) withString:(NSString *)replacement); + CF_SWIFT_FUNCDISPATCHV(_kCFRuntimeIDCFString, void, (CFSwiftRef)str, NSMutableString.replaceCharactersInRange, range, (CFSwiftRef)replacement); + CF_OBJC_FUNCDISPATCHV(_kCFRuntimeIDCFString, void, (NSMutableString *)str, replaceCharactersInRange:NSMakeRange(range.location, range.length) withString:(NSString *)replacement); __CFAssertIsStringAndMutable(str); __CFAssertRangeIsInStringBounds(str, range.location, range.length); __CFStringReplace(str, range, replacement); @@ -4760,16 +4777,16 @@ void CFStringReplace(CFMutableStringRef str, CFRange range, CFStringRef replacem void CFStringReplaceAll(CFMutableStringRef str, CFStringRef replacement) { - CF_SWIFT_FUNCDISPATCHV(__kCFStringTypeID, void, (CFSwiftRef)str, NSMutableString.setString, (CFSwiftRef)replacement); - CF_OBJC_FUNCDISPATCHV(__kCFStringTypeID, void, (NSMutableString *)str, setString:(NSString *)replacement); + CF_SWIFT_FUNCDISPATCHV(_kCFRuntimeIDCFString, void, (CFSwiftRef)str, NSMutableString.setString, (CFSwiftRef)replacement); + CF_OBJC_FUNCDISPATCHV(_kCFRuntimeIDCFString, void, (NSMutableString *)str, setString:(NSString *)replacement); __CFAssertIsStringAndMutable(str); __CFStringReplace(str, CFRangeMake(0, __CFStrLength(str)), replacement); } void CFStringAppend(CFMutableStringRef str, CFStringRef appended) { - CF_SWIFT_FUNCDISPATCHV(__kCFStringTypeID, void, (CFSwiftRef)str, NSMutableString.appendString, (CFSwiftRef)appended); - CF_OBJC_FUNCDISPATCHV(__kCFStringTypeID, void, (NSMutableString *)str, appendString:(NSString *)appended); + CF_SWIFT_FUNCDISPATCHV(_kCFRuntimeIDCFString, void, (CFSwiftRef)str, NSMutableString.appendString, (CFSwiftRef)appended); + CF_OBJC_FUNCDISPATCHV(_kCFRuntimeIDCFString, void, (NSMutableString *)str, appendString:(NSString *)appended); __CFAssertIsStringAndMutable(str); __CFStringReplace(str, CFRangeMake(__CFStrLength(str), 0), appended); } @@ -4779,8 +4796,8 @@ void CFStringAppendCharacters(CFMutableStringRef str, const UniChar *chars, CFIn CFIndex strLength, idx; __CFAssertIsNotNegative(appendedLength); - CF_SWIFT_FUNCDISPATCHV(__kCFStringTypeID, void, (CFSwiftRef)str, NSMutableString.appendCharacters, chars, appendedLength); - CF_OBJC_FUNCDISPATCHV(__kCFStringTypeID, void, (NSMutableString *)str, appendCharacters:chars length:(NSUInteger)appendedLength); + CF_SWIFT_FUNCDISPATCHV(_kCFRuntimeIDCFString, void, (CFSwiftRef)str, NSMutableString.appendCharacters, chars, appendedLength); + CF_OBJC_FUNCDISPATCHV(_kCFRuntimeIDCFString, void, (NSMutableString *)str, appendCharacters:chars length:(NSUInteger)appendedLength); __CFAssertIsStringAndMutable(str); @@ -4842,17 +4859,17 @@ void __CFStringAppendBytes(CFMutableStringRef str, const char *cStr, CFIndex app freeCStrWhenDone = !usingPassedInMemory && vBuf.shouldFreeChars; } - if (CF_IS_OBJC(__kCFStringTypeID, str)) { + if (CF_IS_OBJC(_kCFRuntimeIDCFString, str)) { if (!appendedIsUnicode && !demoteAppendedUnicode) { - CF_OBJC_FUNCDISPATCHV(__kCFStringTypeID, void, (NSMutableString *)str, _cfAppendCString:(const unsigned char *)cStr length:(NSInteger)appendedLength); + CF_OBJC_FUNCDISPATCHV(_kCFRuntimeIDCFString, void, (NSMutableString *)str, _cfAppendCString:(const unsigned char *)cStr length:(NSInteger)appendedLength); } else { - CF_OBJC_FUNCDISPATCHV(__kCFStringTypeID, void, (NSMutableString *)str, appendCharacters:(const unichar *)cStr length:(NSUInteger)appendedLength); + CF_OBJC_FUNCDISPATCHV(_kCFRuntimeIDCFString, void, (NSMutableString *)str, appendCharacters:(const unichar *)cStr length:(NSUInteger)appendedLength); } - } else if (CF_IS_SWIFT(__kCFStringTypeID, str)) { + } else if (CF_IS_SWIFT(_kCFRuntimeIDCFString, str)) { if (!appendedIsUnicode && !demoteAppendedUnicode) { - CF_SWIFT_FUNCDISPATCHV(__kCFStringTypeID, void, (CFSwiftRef)str, NSMutableString._cfAppendCString,(const char *)cStr, appendedLength); + CF_SWIFT_FUNCDISPATCHV(_kCFRuntimeIDCFString, void, (CFSwiftRef)str, NSMutableString._cfAppendCString,(const char *)cStr, appendedLength); } else { - CF_SWIFT_FUNCDISPATCHV(__kCFStringTypeID, void, (CFSwiftRef)str, NSMutableString.appendCharacters, (const UniChar *)cStr, appendedLength); + CF_SWIFT_FUNCDISPATCHV(_kCFRuntimeIDCFString, void, (CFSwiftRef)str, NSMutableString.appendCharacters, (const UniChar *)cStr, appendedLength); } } else { CFIndex strLength; @@ -4903,7 +4920,7 @@ void CFStringAppendFormat(CFMutableStringRef str, CFDictionaryRef formatOptions, CFIndex CFStringFindAndReplace(CFMutableStringRef string, CFStringRef stringToFind, CFStringRef replacementString, CFRange rangeToSearch, CFStringCompareFlags compareOptions) { - CF_OBJC_FUNCDISPATCHV(__kCFStringTypeID, CFIndex, (NSMutableString *)string, replaceOccurrencesOfString:(NSString *)stringToFind withString:(NSString *)replacementString options:(NSStringCompareOptions)compareOptions range:NSMakeRange(rangeToSearch.location, rangeToSearch.length)); + CF_OBJC_FUNCDISPATCHV(_kCFRuntimeIDCFString, CFIndex, (NSMutableString *)string, replaceOccurrencesOfString:(NSString *)stringToFind withString:(NSString *)replacementString options:(NSStringCompareOptions)compareOptions range:NSMakeRange(rangeToSearch.location, rangeToSearch.length)); CFRange foundRange; Boolean backwards = ((compareOptions & kCFCompareBackwards) != 0); UInt32 endIndex = rangeToSearch.location + rangeToSearch.length; @@ -4989,7 +5006,7 @@ void CFStringPad(CFMutableStringRef string, CFStringRef padString, CFIndex lengt __CFAssertIsNotNegative(length); __CFAssertIsNotNegative(indexIntoPad); - CF_OBJC_FUNCDISPATCHV(__kCFStringTypeID, void, (NSMutableString *)string, _cfPad:padString length:(uint32_t)length padIndex:(uint32_t)indexIntoPad); + CF_OBJC_FUNCDISPATCHV(_kCFRuntimeIDCFString, void, (NSMutableString *)string, _cfPad:padString length:(uint32_t)length padIndex:(uint32_t)indexIntoPad); __CFAssertIsStringAndMutable(string); @@ -5004,7 +5021,7 @@ void CFStringPad(CFMutableStringRef string, CFStringRef padString, CFIndex lengt CFIndex padLength; CFIndex padRemaining = length - originalLength; - if (CF_IS_OBJC(__kCFStringTypeID, padString) || CF_IS_SWIFT(__kCFStringTypeID, padString)) { /* ??? Hope the compiler optimizes this away if OBJC_MAPPINGS is not on */ + if (CF_IS_OBJC(_kCFRuntimeIDCFString, padString) || CF_IS_SWIFT(_kCFRuntimeIDCFString, padString)) { /* ??? Hope the compiler optimizes this away if OBJC_MAPPINGS is not on */ padStringLength = CFStringGetLength(padString); isUnicode = true; /* !!! Bad for now */ } else { @@ -5040,7 +5057,7 @@ void CFStringTrim(CFMutableStringRef string, CFStringRef trimString) { CFIndex newStartIndex; CFIndex length; - CF_OBJC_FUNCDISPATCHV(__kCFStringTypeID, void, (NSMutableString *)string, _cfTrim:trimString); + CF_OBJC_FUNCDISPATCHV(_kCFRuntimeIDCFString, void, (NSMutableString *)string, _cfTrim:trimString); __CFAssertIsStringAndMutable(string); __CFAssertIsString(trimString); @@ -5074,7 +5091,7 @@ void CFStringTrimWhitespace(CFMutableStringRef string) { CFIndex length; CFStringInlineBuffer buffer; - CF_OBJC_FUNCDISPATCHV(__kCFStringTypeID, void, (NSMutableString *)string, _cfTrimWS); + CF_OBJC_FUNCDISPATCHV(_kCFRuntimeIDCFString, void, (NSMutableString *)string, _cfTrimWS); __CFAssertIsStringAndMutable(string); @@ -5110,7 +5127,7 @@ void CFStringLowercase(CFMutableStringRef string, CFLocaleRef locale) { const uint8_t *langCode; Boolean isEightBit = __CFStrIsEightBit(string); - CF_OBJC_FUNCDISPATCHV(__kCFStringTypeID, void, (NSMutableString *)string, _cfLowercase:(const void *)locale); + CF_OBJC_FUNCDISPATCHV(_kCFRuntimeIDCFString, void, (NSMutableString *)string, _cfLowercase:(const void *)locale); __CFAssertIsStringAndMutable(string); @@ -5201,7 +5218,7 @@ void CFStringUppercase(CFMutableStringRef string, CFLocaleRef locale) { const uint8_t *langCode; Boolean isEightBit = __CFStrIsEightBit(string); - CF_OBJC_FUNCDISPATCHV(__kCFStringTypeID, void, (NSMutableString *)string, _cfUppercase:(const void *)locale); + CF_OBJC_FUNCDISPATCHV(_kCFRuntimeIDCFString, void, (NSMutableString *)string, _cfUppercase:(const void *)locale); __CFAssertIsStringAndMutable(string); @@ -5295,7 +5312,7 @@ void CFStringCapitalize(CFMutableStringRef string, CFLocaleRef locale) { Boolean isLastCased = false; const uint8_t *caseIgnorableForBMP; - CF_OBJC_FUNCDISPATCHV(__kCFStringTypeID, void, (NSMutableString *)string, _cfCapitalize:(const void *)locale); + CF_OBJC_FUNCDISPATCHV(_kCFRuntimeIDCFString, void, (NSMutableString *)string, _cfCapitalize:(const void *)locale); __CFAssertIsStringAndMutable(string); @@ -5434,7 +5451,7 @@ void CFStringNormalize(CFMutableStringRef string, CFStringNormalizationForm theF CFIndex length; bool needToReorder = true; - CF_OBJC_FUNCDISPATCHV(__kCFStringTypeID, void, (NSMutableString *)string, _cfNormalize:theForm); + CF_OBJC_FUNCDISPATCHV(_kCFRuntimeIDCFString, void, (NSMutableString *)string, _cfNormalize:theForm); __CFAssertIsStringAndMutable(string); @@ -5743,7 +5760,7 @@ void CFStringFold(CFMutableStringRef theString, CFStringCompareFlags theFlags, C const uint8_t *langCode; CFStringEncoding eightBitEncoding; bool caseInsensitive = ((theFlags & kCFCompareCaseInsensitive) ? true : false); - bool isObjcOrSwift = CF_IS_OBJC(__kCFStringTypeID, theString) || CF_IS_SWIFT(__kCFStringTypeID, theString); + bool isObjcOrSwift = CF_IS_OBJC(_kCFRuntimeIDCFString, theString) || CF_IS_SWIFT(_kCFRuntimeIDCFString, theString); CFLocaleRef theLocale = locale; if ((theFlags & kCFCompareLocalized) && (NULL == locale)) { @@ -6233,8 +6250,23 @@ static Boolean __CFStringFormatLocalizedNumber(CFMutableStringRef output, CFLoca return false; } #endif + +#if !DEPLOYMENT_RUNTIME_OBJC +// Open-source Core Foundation cannot rely on Foundation headers being present, so we redefine this here. +// This must match the code that is vended by FoundationErrors.h and swift-corelibs-foundation. +static const CFIndex NSFormattingError = 2048; +#endif // !DEPLOYMENT_RUNTIME_OBJC + +CF_INLINE CFErrorRef __CFCreateOverflowError(void) { + CFAllocatorRef tmpAlloc = __CFGetDefaultAllocator(); + CFMutableDictionaryRef userInfo = CFDictionaryCreateMutable(tmpAlloc, 0, &kCFCopyStringDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks); + CFDictionarySetValue(userInfo, kCFErrorDebugDescriptionKey, CFSTR("Overflow occurred")); + CFErrorRef result = CFErrorCreate(tmpAlloc, kCFErrorDomainCocoa, NSFormattingError, userInfo); + CFRelease(userInfo); + return result; +} -CF_INLINE void __CFParseFormatSpec(const UniChar *uformat, const uint8_t *cformat, SInt32 *fmtIdx, SInt32 fmtLen, CFFormatSpec *spec, CFStringRef *configKeyPointer) { +CF_INLINE Boolean __CFParseFormatSpec(const UniChar *uformat, const uint8_t *cformat, SInt32 *fmtIdx, SInt32 fmtLen, CFFormatSpec *spec, CFStringRef *configKeyPointer, CFErrorRef *errorPtr) { Boolean seenDot = false; Boolean seenSharp = false; Boolean seenOpenBracket = false; @@ -6244,7 +6276,7 @@ CF_INLINE void __CFParseFormatSpec(const UniChar *uformat, const uint8_t *cforma for (;;) { UniChar ch; - if (fmtLen <= *fmtIdx) return; /* no type */ + if (fmtLen <= *fmtIdx) return true; /* no type */ if (cformat) ch = (UniChar)cformat[(*fmtIdx)++]; else ch = uformat[(*fmtIdx)++]; if (keyIndex >= 0) { @@ -6272,7 +6304,7 @@ CF_INLINE void __CFParseFormatSpec(const UniChar *uformat, const uint8_t *cforma *configKeyPointer = CFStringCreateWithCharactersNoCopy(NULL, uformat + keyIndex, keyLength, kCFAllocatorNull); } } - return; + return true; } else { keyIndex = kCFNotFound; } @@ -6348,7 +6380,7 @@ reswtch:switch (ch) { case 'c': spec->type = CFFormatLongType; spec->size = CFFormatSize1; - return; + return true; case 'D': case 'd': case 'i': case 'U': case 'u': // we can localize all but octal or hex if (_CFExecutableLinkedOnOrAfter(CFSystemVersionMountainLion)) spec->flags |= kCFStringFormatLocalizable; @@ -6358,7 +6390,7 @@ reswtch:switch (ch) { case 'O': case 'o': case 'x': case 'X': spec->type = CFFormatLongType; // Seems like if spec->size == 0, we should spec->size = CFFormatSize4. However, 0 is handled correctly. - return; + return true; case 'f': case 'F': case 'g': case 'G': case 'e': case 'E': { // we can localize all but hex float output if (_CFExecutableLinkedOnOrAfter(CFSystemVersionMountainLion)) spec->flags |= kCFStringFormatLocalizable; @@ -6372,31 +6404,31 @@ reswtch:switch (ch) { case 'a': case 'A': spec->type = CFFormatDoubleType; if (spec->size != CFFormatSize16) spec->size = CFFormatSize8; - return; + return true; case 'n': /* %n is not handled correctly; for Leopard or newer apps, we disable it further */ spec->type = 1 ? CFFormatDummyPointerType : CFFormatPointerType; spec->size = CFFormatSizePointer; // 4 or 8 depending on LP64 - return; + return true; case 'p': spec->type = CFFormatPointerType; spec->size = CFFormatSizePointer; // 4 or 8 depending on LP64 - return; + return true; case 's': spec->type = CFFormatCharsType; spec->size = CFFormatSizePointer; // 4 or 8 depending on LP64 - return; + return true; case 'S': spec->type = CFFormatUnicharsType; spec->size = CFFormatSizePointer; // 4 or 8 depending on LP64 - return; + return true; case 'C': spec->type = CFFormatSingleUnicharType; spec->size = CFFormatSize2; - return; + return true; case 'P': spec->type = CFFormatPascalCharsType; spec->size = CFFormatSizePointer; // 4 or 8 depending on LP64 - return; + return true; case '@': if (seenSharp) { seenSharp = false; @@ -6405,15 +6437,22 @@ reswtch:switch (ch) { } else { spec->type = CFFormatCFType; spec->size = CFFormatSizePointer; // 4 or 8 depending on LP64 - return; + return true; } case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': { int64_t number = 0; do { - number = 10 * number + (ch - '0'); + if (__builtin_smulll_overflow(number, 10, &number) || __builtin_saddll_overflow(number, ch - '0', &number)) { + if (errorPtr) *errorPtr = __CFCreateOverflowError(); + return false; + } if (cformat) ch = (UniChar)cformat[(*fmtIdx)++]; else ch = uformat[(*fmtIdx)++]; } while ((UInt32)(ch - '0') <= 9); if ('$' == ch) { + if (number > INT8_MAX) { + if (errorPtr) *errorPtr = __CFCreateOverflowError(); + return false; + } if (-2 == spec->precArgNum) { spec->precArgNum = (int8_t)number - 1; // Arg numbers start from 1 } else if (-2 == spec->widthArgNum) { @@ -6423,8 +6462,16 @@ reswtch:switch (ch) { } break; } else if (seenDot) { /* else it's either precision or width */ - spec->precArg = (SInt32)number; + if (number > INT32_MAX) { + if (errorPtr) *errorPtr = __CFCreateOverflowError(); + return false; + } + spec->precArg = (SInt32)number; } else { + if (number > INT32_MAX) { + if (errorPtr) *errorPtr = __CFCreateOverflowError(); + return false; + } spec->widthArg = (SInt32)number; } goto reswtch; @@ -6442,9 +6489,10 @@ reswtch:switch (ch) { goto reswtch; default: spec->type = CFFormatLiteralType; - return; + return true; } } + return true; } // Length of the buffer to call sprintf() with @@ -6487,11 +6535,19 @@ reswtch:switch (ch) { /* These three functions are the external entry points for string formatting. */ void CFStringAppendFormatAndArguments(CFMutableStringRef outputString, CFDictionaryRef formatOptions, CFStringRef formatString, va_list args) { - __CFStringAppendFormatCore(outputString, NULL, NULL, formatOptions, NULL, NULL, formatString, 0, NULL, 0, args, NULL); + CFErrorRef error; + if (!__CFStringAppendFormatCore(outputString, NULL, NULL, formatOptions, NULL, NULL, formatString, 0, NULL, 0, args, &error)) { + CFLog(kCFLogLevelError, CFSTR("ERROR: Failed to format string: %@"), error); + if (error) CFRelease(error); + } } void _CFStringAppendFormatAndArgumentsAux2(CFMutableStringRef outputString, CFStringRef (*copyDescFunc)(void *, const void *), CFStringRef (*contextDescFunc)(void *, const void *, const void *, bool, bool *), CFDictionaryRef formatOptions, CFStringRef formatString, va_list args) { - __CFStringAppendFormatCore(outputString, copyDescFunc, contextDescFunc, formatOptions, NULL, NULL, formatString, 0, NULL, 0, args, NULL); + CFErrorRef error; + if (!__CFStringAppendFormatCore(outputString, copyDescFunc, contextDescFunc, formatOptions, NULL, NULL, formatString, 0, NULL, 0, args, &error)) { + CFLog(kCFLogLevelError, CFSTR("ERROR: Failed to format string: %@"), error); + if (error) CFRelease(error); + } } void _CFStringAppendFormatAndArgumentsAux(CFMutableStringRef outputString, CFStringRef (*copyDescFunc)(void *, const void *), CFDictionaryRef formatOptions, CFStringRef formatString, va_list args) { @@ -6524,9 +6580,8 @@ SInt32 __CFStringFindFormatSpecifiersInString(const uint8_t *cformat, const UniC curSpec--; /* Skip by writing the next spec over this one */ } } else { - CFStringRef configKey = NULL; newFmtIdx++; /* Skip % */ - __CFParseFormatSpec(uformat, cformat, &newFmtIdx, formatLen, &(specs[curSpec]), &configKey); + __CFParseFormatSpec(uformat, cformat, &newFmtIdx, formatLen, &(specs[curSpec]), NULL, NULL); if (CFFormatLiteralType == specs[curSpec].type) { if (curSpec > -1) { curSpec--; /* Skip literal chunks by writing the next spec over this one*/ @@ -6587,7 +6642,7 @@ static void __CFStringSetUpFormatAndSpecBuffers(CFStringRef formatString, CFInde SInt32 formatIdx, sizeSpecs = 0; CFAllocatorRef tmpAlloc = __CFGetDefaultAllocator(); - if (!CF_IS_OBJC(__kCFStringTypeID, formatString) && !CF_IS_SWIFT(CFStringGetTypeID(), formatString)) { + if (!CF_IS_OBJC(_kCFRuntimeIDCFString, formatString) && !CF_IS_SWIFT(CFStringGetTypeID(), formatString)) { __CFAssertIsString(formatString); if (!__CFStrIsUnicode(formatString)) { *cformat = (const uint8_t *)__CFStrContents(formatString); @@ -6613,7 +6668,7 @@ static void __CFStringSetUpFormatAndSpecBuffers(CFStringRef formatString, CFInde if (*formatSpecs != localFormatSpecsBuffer && __CFOASafe) __CFSetLastAllocationEventName(*formatSpecs, "CFString (temp)"); } -static bool __CFStringValidateFormat(CFStringRef expected, CFStringRef untrustedFormat, CFErrorRef *errorPtr) { +static CFIndex __CFStringValidateFormat(CFStringRef expected, CFStringRef untrustedFormat, CFIndex alreadyValidated, CFErrorRef *errorPtr) { bool verified = true; SInt32 numSpecsUntrusted = 0, numSpecsExpected = 0; CFIndex formatLenUntrusted = 0, formatLenExpected = 0, numFormatSpecsUntrusted = 0, numFormatSpecsExpected = 0; @@ -6653,19 +6708,21 @@ static bool __CFStringValidateFormat(CFStringRef expected, CFStringRef untrusted numSpecsUntrusted = __CFStringFindFormatSpecifiersInString(cformatUntrusted, uformatUntrusted, formatLenUntrusted, specsUntrusted, formatSpecsUntrusted, &numFormatSpecsUntrusted); numSpecsExpected = __CFStringFindFormatSpecifiersInString(cformatExpected, uformatExpected, formatLenExpected, specsExpected, formatSpecsExpected, &numFormatSpecsExpected); - if ((numSpecsUntrusted == numSpecsExpected) && (numFormatSpecsUntrusted == numFormatSpecsExpected)) { + // if we accept zero untrusted specs we should accept fewer than expected as well + if ((numSpecsUntrusted <= (numSpecsExpected - alreadyValidated)) && (numFormatSpecsUntrusted <= numFormatSpecsExpected)) { CFIndex idx; - for (idx = 0; idx < numSpecsExpected; idx++) { - if ((specsUntrusted[idx].type != specsExpected[idx].type) || (specsUntrusted[idx].size != specsExpected[idx].size)) { + for (idx = 0; idx < numSpecsUntrusted; idx++) { + int8_t argNum = specsUntrusted[idx].mainArgNum != -1 ? specsUntrusted[idx].mainArgNum : idx; + if (((argNum + alreadyValidated) >= numSpecsExpected) || (specsUntrusted[idx].type != specsExpected[argNum + alreadyValidated].type) || (specsUntrusted[idx].size != specsExpected[argNum].size)) { verified = false; break; } } if (verified) { - for (idx = 0; idx < numFormatSpecsExpected; idx++) { + for (idx = 0; idx < numFormatSpecsUntrusted; idx++) { CFComparisonResult comp = CFStringCompare(formatSpecsUntrusted[idx], formatSpecsExpected[idx], 0); if (comp != kCFCompareEqualTo) { - if (specsUntrusted[idx].numericFormatStyle != specsExpected[idx].numericFormatStyle) { + if (specsUntrusted[idx].numericFormatStyle != specsExpected[idx + alreadyValidated].numericFormatStyle) { verified = false; break; } @@ -6685,7 +6742,7 @@ static bool __CFStringValidateFormat(CFStringRef expected, CFStringRef untrusted CFStringRef debugMsg = CFStringCreateWithFormat(tmpAlloc, NULL, CFSTR("Format '%@' does not match expected '%@'"), untrustedFormat, expected); CFMutableDictionaryRef userInfo = CFDictionaryCreateMutable(tmpAlloc, 0, &kCFCopyStringDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks); CFDictionarySetValue(userInfo, kCFErrorDebugDescriptionKey, debugMsg); - *errorPtr = CFErrorCreate(tmpAlloc, kCFErrorDomainCocoa, /*NSFormattingError*/ 2048, userInfo); + *errorPtr = CFErrorCreate(tmpAlloc, kCFErrorDomainCocoa, NSFormattingError, userInfo); CFRelease(userInfo); CFRelease(debugMsg); #endif @@ -6709,7 +6766,7 @@ static bool __CFStringValidateFormat(CFStringRef expected, CFStringRef untrusted if (formatSpecsUntrusted != localFormatSpecsBufferUntrusted) CFAllocatorDeallocate(tmpAlloc, formatSpecsUntrusted); if (formatSpecsExpected != localFormatSpecsBufferExpected) CFAllocatorDeallocate(tmpAlloc, formatSpecsExpected); - return verified; + return (verified ? numSpecsUntrusted + alreadyValidated : -1); } /* @@ -6726,12 +6783,12 @@ static bool __CFStringValidateFormat(CFStringRef expected, CFStringRef untrusted origValues: Only used for recursive calls when doing stringsDict formatting. Otherwise NULL. <> originalValuesSize: Only used for recursive calls when doing stringsDict formatting. Otherwise 0. <> args: The arguments to be formatted. - errorPtr: Only used when validating the formatString against valid format specfiers. Nil unless the validation fails. + errorPtr: Only used when validating the formatString against valid format specfiers. Nil unless the validation fails. If error is set, return value is false. ??? %s depends on handling of encodings by __CFStringAppendBytes */ -static void __CFStringAppendFormatCore(CFMutableStringRef outputString, CFStringRef (*copyDescFunc)(void *, const void *), CFStringRef (*contextDescFunc)(void *, const void *, const void *, bool, bool *), CFDictionaryRef formatOptions, CFDictionaryRef stringsDictConfig, CFStringRef validFormatSpecifiers, CFStringRef formatString, CFIndex initialArgPosition, const void *origValues, CFIndex originalValuesSize, va_list args, CFErrorRef *errorPtr) { - SInt32 numSpecs, sizeSpecs, sizeArgNum, formatIdx, curSpec, argNum; +static Boolean __CFStringAppendFormatCore(CFMutableStringRef outputString, CFStringRef (*copyDescFunc)(void *, const void *), CFStringRef (*contextDescFunc)(void *, const void *, const void *, bool, bool *), CFDictionaryRef formatOptions, CFDictionaryRef stringsDictConfig, CFStringRef validFormatSpecifiers, CFStringRef formatString, CFIndex initialArgPosition, const void *origValues, CFIndex originalValuesSize, va_list args, CFErrorRef *errorPtr) { + int32_t numSpecs, sizeSpecs, sizeArgNum, formatIdx, curSpec, argNum; CFIndex formatLen; const uint8_t *cformat = NULL; const UniChar *uformat = NULL; @@ -6749,7 +6806,6 @@ static void __CFStringAppendFormatCore(CFMutableStringRef outputString, CFString CFAllocatorRef tmpAlloc = NULL; bool localizedFormatting = formatOptions && (CFGetTypeID(formatOptions) == CFLocaleGetTypeID()); - CFDictionaryRef configDict = NULL; intmax_t dummyLocation; // A place for %n to do its thing in; should be the widest possible int value numSpecs = 0; @@ -6761,15 +6817,55 @@ static void __CFStringAppendFormatCore(CFMutableStringRef outputString, CFString configs = NULL; - /* Validate expected format specifiers against untrusted format string */ - if (validFormatSpecifiers && !configDict) { - if(!__CFStringValidateFormat(validFormatSpecifiers, formatString, errorPtr)) { - return; + if (validFormatSpecifiers) { + const uint8_t *cExpectedFormat = NULL; + const UniChar *uExpectedFormat = NULL; + UniChar *expectedFormatChars = NULL; + UniChar expectedLocalFormatBuffer[FORMAT_BUFFER_LEN]; + CFFormatSpec *expectedSpecs = NULL; + CFFormatSpec localExpectedSpecsBuffer[VPRINTF_BUFFER_LEN]; + CFStringRef *expectedFormatSpecs = NULL; + CFStringRef expectedFormatSpecsBuffer[VPRINTF_BUFFER_LEN]; + + CFIndex expectedFormatLen = CFStringGetLength(validFormatSpecifiers); + __CFStringSetUpFormatAndSpecBuffers(validFormatSpecifiers, expectedFormatLen, &cExpectedFormat, &uExpectedFormat, &expectedFormatChars, expectedLocalFormatBuffer, &expectedSpecs, localExpectedSpecsBuffer, &expectedFormatSpecs, expectedFormatSpecsBuffer); + + SInt32 numExpectedSpecs = __CFStringFindFormatSpecifiersInString(cExpectedFormat, uExpectedFormat, expectedFormatLen, expectedSpecs, NULL, NULL); + + if (expectedFormatChars != expectedLocalFormatBuffer) CFAllocatorDeallocate(tmpAlloc, expectedFormatChars); + if (expectedSpecs != localExpectedSpecsBuffer) CFAllocatorDeallocate(tmpAlloc, expectedSpecs); + if (expectedFormatSpecs != expectedFormatSpecsBuffer) CFAllocatorDeallocate(tmpAlloc, expectedFormatSpecs); + + if (expectedFormatLen == 0 || numExpectedSpecs == 0) { + if (errorPtr) { + CFStringRef debugMsg = CFStringCreateWithFormat(tmpAlloc, NULL, CFSTR("Expected format '%@' is invalid"), validFormatSpecifiers); + CFMutableDictionaryRef userInfo = CFDictionaryCreateMutable(tmpAlloc, 0, &kCFCopyStringDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks); + CFDictionarySetValue(userInfo, kCFErrorDebugDescriptionKey, debugMsg); + *errorPtr = CFErrorCreate(tmpAlloc, kCFErrorDomainCocoa, NSFormattingError, userInfo); + CFRelease(debugMsg); + CFRelease(userInfo); + } + return false; } + + /* Validate expected format specifiers against untrusted format string */ + if (__CFStringValidateFormat(validFormatSpecifiers, formatString, 0, errorPtr) < 0) { + return false; + } } + Boolean success = true; + formatLen = CFStringGetLength(formatString); - if (!CF_IS_OBJC(__kCFStringTypeID, formatString) && !CF_IS_SWIFT(CFStringGetTypeID(), formatString)) { + + /* Avoid overflow of formatIdx in loops below that compare to formatIdx */ + if (formatLen > INT32_MAX) { + if (errorPtr) *errorPtr = __CFCreateOverflowError(); + success = false; + goto cleanup; + } + + if (!CF_IS_OBJC(_kCFRuntimeIDCFString, formatString) && !CF_IS_SWIFT(CFStringGetTypeID(), formatString)) { __CFAssertIsString(formatString); if (!__CFStrIsUnicode(formatString)) { cformat = (const uint8_t *)__CFStrContents(formatString); @@ -6787,10 +6883,35 @@ static void __CFStringAppendFormatCore(CFMutableStringRef outputString, CFString /* Compute an upper bound for the number of format specifications */ if (cformat) { - for (formatIdx = 0; formatIdx < formatLen; formatIdx++) if ('%' == cformat[formatIdx]) sizeSpecs++; + for (formatIdx = 0; formatIdx < formatLen; formatIdx++) { + if ('%' == cformat[formatIdx]) { + if (__builtin_sadd_overflow(sizeSpecs, 1, &sizeSpecs)) { + if (errorPtr) *errorPtr = __CFCreateOverflowError(); + success = false; + goto cleanup; + } + } + } } else { - for (formatIdx = 0; formatIdx < formatLen; formatIdx++) if ('%' == uformat[formatIdx]) sizeSpecs++; + for (formatIdx = 0; formatIdx < formatLen; formatIdx++) { + if ('%' == uformat[formatIdx]) { + if (__builtin_sadd_overflow(sizeSpecs, 1, &sizeSpecs)) { + if (errorPtr) *errorPtr = __CFCreateOverflowError(); + success = false; + goto cleanup; + } + } + } } + + /* The code following this point makes multiple integer calcuations based off sizeSpecs, which is an upper-bound of the number of tokens in the string based on the number of '%' characters found. In order to avoid integer overflow at multiple points throughout this function, we will cap sizeSpec to an amount that won't overflow, but is still plenty large enough to support any reasonable format strings */ +#define MAX_SIZE_SPECS (0xfffff) /* Won't overflow a 32-bit integer up to and including a multiplicative factor of 256 */ + if (sizeSpecs > MAX_SIZE_SPECS) { + if (errorPtr) *errorPtr = __CFCreateOverflowError(); + success = false; + goto cleanup; + } + tmpAlloc = __CFGetDefaultAllocator(); specs = ((2 * sizeSpecs + 1) > VPRINTF_BUFFER_LEN) ? (CFFormatSpec *)CFAllocatorAllocate(tmpAlloc, (2 * sizeSpecs + 1) * sizeof(CFFormatSpec), 0) : localSpecsBuffer; if (specs != localSpecsBuffer && __CFOASafe) __CFSetLastAllocationEventName(specs, "CFString (temp)"); @@ -6822,13 +6943,17 @@ static void __CFStringAppendFormatCore(CFMutableStringRef outputString, CFString } else { CFStringRef configKey = NULL; newFmtIdx++; /* Skip % */ - __CFParseFormatSpec(uformat, cformat, &newFmtIdx, formatLen, &(specs[curSpec]), &configKey); + if (!__CFParseFormatSpec(uformat, cformat, &newFmtIdx, formatLen, &(specs[curSpec]), &configKey, errorPtr)) { + success = false; + goto cleanup; + } if (CFFormatLiteralType == specs[curSpec].type) { specs[curSpec].loc = formatIdx + 1; specs[curSpec].len = 1; } else { specs[curSpec].len = newFmtIdx - formatIdx; } + if (NULL != configKey) CFRelease(configKey); } formatIdx = newFmtIdx; @@ -6852,6 +6977,7 @@ static void __CFStringAppendFormatCore(CFMutableStringRef outputString, CFString /* Compute values array */ argNum = initialArgPosition; + CFIndex validatedDictSpecs = 0; for (curSpec = 0; curSpec < numSpecs; curSpec++) { SInt32 newMaxArgNum; if (0 == specs[curSpec].type) continue; @@ -6870,7 +6996,9 @@ static void __CFStringAppendFormatCore(CFMutableStringRef outputString, CFString if (specs != localSpecsBuffer) CFAllocatorDeallocate(tmpAlloc, specs); if (values != localValuesBuffer) CFAllocatorDeallocate(tmpAlloc, values); if (formatChars && (formatChars != localFormatBuffer)) CFAllocatorDeallocate(tmpAlloc, formatChars); - return; // more args than we expected! + + // More arguments than expected - not an error case though. + return true; } /* It is actually incorrect to reorder some specs and not all; we just do some random garbage here */ if (-2 == specs[curSpec].widthArgNum) { @@ -6896,7 +7024,8 @@ static void __CFStringAppendFormatCore(CFMutableStringRef outputString, CFString values[specs[curSpec].precArgNum].type = CFFormatLongType; } } - + + CFIndex validatedInnerSpecs = 0; /* Collect the arguments in correct type from vararg list */ for (argNum = 0; argNum < sizeArgNum; argNum++) { if ((NULL != originalValues) && (0 == values[argNum].type)) values[argNum] = originalValues[argNum]; @@ -6987,18 +7116,24 @@ static void __CFStringAppendFormatCore(CFMutableStringRef outputString, CFString /* Otherwise fall-thru to the next case! */ #endif case CFFormatPointerType: { - char formatBuffer[128]; -#if defined(__GNUC__) - char buffer[BUFFER_LEN + width + precision]; -#else - char stackBuffer[BUFFER_LEN]; + char stackFormatBuffer[128]; + char *dynamicFormatBuffer = NULL; + char *formatBuffer = stackFormatBuffer; + if (specs[curSpec].len + 1 > sizeof(stackFormatBuffer)) { + // Leave space for the null terminator (+1) + dynamicFormatBuffer = (char *)CFAllocatorAllocate(kCFAllocatorSystemDefault, specs[curSpec].len + 1, 0); + formatBuffer = dynamicFormatBuffer; + } +#define EXTRA_BUFFER_LEN_FOR_WIDTH_PRECISION (16) + char stackBuffer[BUFFER_LEN + EXTRA_BUFFER_LEN_FOR_WIDTH_PRECISION]; char *dynamicBuffer = NULL; char *buffer = stackBuffer; - if (256+width+precision > BUFFER_LEN) { - dynamicBuffer = (char *)CFAllocatorAllocate(kCFAllocatorSystemDefault, 256+width+precision, 0); + size_t bufferSize = sizeof(stackBuffer); + if (width + precision > EXTRA_BUFFER_LEN_FOR_WIDTH_PRECISION) { + bufferSize = BUFFER_LEN + width + precision; + dynamicBuffer = (char *)CFAllocatorAllocate(kCFAllocatorSystemDefault, bufferSize, 0); buffer = dynamicBuffer; } -#endif SInt32 cidx, idx, loc; Boolean appended = false; loc = specs[curSpec].loc; @@ -7027,7 +7162,7 @@ static void __CFStringAppendFormatCore(CFMutableStringRef outputString, CFString formatBuffer[idx] = '\0'; // Should modify format buffer here if necessary; for example, to translate %qd to // the equivalent, on architectures which do not have %q. - buffer[sizeof(buffer) - 1] = '\0'; + buffer[bufferSize - 1] = '\0'; switch (specs[curSpec].type) { case CFFormatLongType: if (CFFormatSize8 == specs[curSpec].size) { @@ -7071,12 +7206,13 @@ static void __CFStringAppendFormatCore(CFMutableStringRef outputString, CFString } break; } - if (!appended) CFStringAppendCString(outputString, (const char *)buffer, __CFStringGetEightBitStringEncoding()); -#if !defined(__GNUC__) + if (!appended) CFStringAppendCString(outputString, (const char *)buffer, __CFStringGetEightBitStringEncoding()); if (dynamicBuffer) { CFAllocatorDeallocate(kCFAllocatorSystemDefault, dynamicBuffer); } -#endif + if (dynamicFormatBuffer) { + CFAllocatorDeallocate(kCFAllocatorSystemDefault, dynamicFormatBuffer); + } } break; case CFFormatLiteralType: @@ -7302,6 +7438,11 @@ static void __CFStringAppendFormatCore(CFMutableStringRef outputString, CFString } break; } + if (validFormatSpecifiers && specs[curSpec].type != CFFormatLiteralType && specs[curSpec].configDictIndex == -1) { + // We already took care of confirming special strings with config dictionaries; + // this makes other types of specs as validated as well + validatedInnerSpecs += 1; + } } for (SInt32 i = 0; i < numSpecsContext; i++) { @@ -7315,6 +7456,7 @@ static void __CFStringAppendFormatCore(CFMutableStringRef outputString, CFString free(specsContext); +cleanup: #if DEPLOYMENT_TARGET_MACOSX || DEPLOYMENT_TARGET_EMBEDDED || DEPLOYMENT_TARGET_EMBEDDED_MINI || DEPLOYMENT_TARGET_LINUX || DEPLOYMENT_TARGET_FREEBSD // va_copy is a C99 extension. No support on Windows @@ -7325,6 +7467,8 @@ static void __CFStringAppendFormatCore(CFMutableStringRef outputString, CFString if (formatChars && (formatChars != localFormatBuffer)) CFAllocatorDeallocate(tmpAlloc, formatChars); if (configs != localConfigs) CFAllocatorDeallocate(tmpAlloc, configs); if (formattingConfig != NULL) CFRelease(formattingConfig); + + return success; } #undef SNPRINTF @@ -7338,7 +7482,7 @@ void CFShowStr(CFStringRef str) { return; } - if (CF_IS_OBJC(__kCFStringTypeID, str) || CF_IS_SWIFT(__kCFStringTypeID, str)) { + if (CF_IS_OBJC(_kCFRuntimeIDCFString, str) || CF_IS_SWIFT(_kCFRuntimeIDCFString, str)) { fprintf(stdout, "This is an NSString, not CFString\n"); return; } diff --git a/CoreFoundation/String.subproj/CFString.h b/CoreFoundation/String.subproj/CFString.h index 3eab99a18a..1978646b9f 100644 --- a/CoreFoundation/String.subproj/CFString.h +++ b/CoreFoundation/String.subproj/CFString.h @@ -1,7 +1,7 @@ /* CFString.h - Copyright (c) 1998-2017, Apple Inc. and the Swift project authors + Copyright (c) 1998-2018, Apple Inc. and the Swift project authors - Portions Copyright (c) 2014-2017, Apple Inc. and the Swift project authors + Portions Copyright (c) 2014-2018, Apple Inc. and the Swift project authors Licensed under Apache License v2.0 with Runtime Library Exception See http://swift.org/LICENSE.txt for license information See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors @@ -152,41 +152,50 @@ since it is the default choice with Mac OS X developer tools. #endif #if DEPLOYMENT_RUNTIME_SWIFT + +#if TARGET_OS_MAC +#define _CF_CONSTANT_STRING_SWIFT_CLASS $s15SwiftFoundation19_NSCFConstantStringCN +#else +#define _CF_CONSTANT_STRING_SWIFT_CLASS $s10Foundation19_NSCFConstantStringCN +#endif + +CF_EXPORT void *_CF_CONSTANT_STRING_SWIFT_CLASS[]; + struct __CFConstStr { struct { uintptr_t _cfisa; uintptr_t _swift_rc; #if defined(__LP64__) || defined(__LLP64__) uint64_t _cfinfoa; -#else +#else // 32-bit: uint32_t _cfinfoa; -#endif +#endif // defined(__LP64__) || defined(__LLP64__) } _base; uint8_t *_ptr; #if defined(__LP64__) && defined(__BIG_ENDIAN__) uint64_t _length; -#else +#else // 32-bit: uint32_t _length; -#endif +#endif // defined(__LP64__) || defined(__LLP64__) }; #if DEPLOYMENT_TARGET_LINUX #define CONST_STRING_LITERAL_SECTION __attribute__((section(".cfstrlit.data"))) #else #define CONST_STRING_LITERAL_SECTION -#endif +#endif // DEPLOYMENT_TARGET_LINUX #if __BIG_ENDIAN__ #define CFSTR(cStr) ({ \ - static struct __CFConstStr str CONST_STRING_LITERAL_SECTION = {{(uintptr_t)&__CFConstantStringClassReference, _CF_CONSTANT_OBJECT_STRONG_RC, 0x00000000C8070000}, (uint8_t *)(cStr), sizeof(cStr) - 1}; \ + static struct __CFConstStr str CONST_STRING_LITERAL_SECTION = {{(uintptr_t)&_CF_CONSTANT_STRING_SWIFT_CLASS, _CF_CONSTANT_OBJECT_STRONG_RC, 0x00000000C8070000}, (uint8_t *)(cStr), sizeof(cStr) - 1}; \ (CFStringRef)&str; \ }) -#else +#else // Little endian: #define CFSTR(cStr) ({ \ - static struct __CFConstStr str CONST_STRING_LITERAL_SECTION = {{(uintptr_t)&__CFConstantStringClassReference, _CF_CONSTANT_OBJECT_STRONG_RC, 0x07C8}, (uint8_t *)(cStr), sizeof(cStr) - 1}; \ + static struct __CFConstStr str CONST_STRING_LITERAL_SECTION = {{(uintptr_t)&_CF_CONSTANT_STRING_SWIFT_CLASS, _CF_CONSTANT_OBJECT_STRONG_RC, 0x07C8}, (uint8_t *)(cStr), sizeof(cStr) - 1}; \ (CFStringRef)&str; \ }) -#endif +#endif // __BIG_ENDIAN__ #else diff --git a/CoreFoundation/String.subproj/CFStringDefaultEncoding.h b/CoreFoundation/String.subproj/CFStringDefaultEncoding.h index 87c920efca..7caf12e744 100644 --- a/CoreFoundation/String.subproj/CFStringDefaultEncoding.h +++ b/CoreFoundation/String.subproj/CFStringDefaultEncoding.h @@ -1,7 +1,7 @@ /* CFStringDefaultEncoding.h - Copyright (c) 1998-2017, Apple Inc. and the Swift project authors + Copyright (c) 1998-2018, Apple Inc. and the Swift project authors - Portions Copyright (c) 2014-2017, Apple Inc. and the Swift project authors + Portions Copyright (c) 2014-2018, Apple Inc. and the Swift project authors Licensed under Apache License v2.0 with Runtime Library Exception See http://swift.org/LICENSE.txt for license information See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors diff --git a/CoreFoundation/String.subproj/CFStringEncodingExt.h b/CoreFoundation/String.subproj/CFStringEncodingExt.h index a32e4bc9c0..d368b8678a 100644 --- a/CoreFoundation/String.subproj/CFStringEncodingExt.h +++ b/CoreFoundation/String.subproj/CFStringEncodingExt.h @@ -1,7 +1,7 @@ /* CFStringEncodingExt.h - Copyright (c) 1998-2017, Apple Inc. and the Swift project authors + Copyright (c) 1998-2018, Apple Inc. and the Swift project authors - Portions Copyright (c) 2014-2017, Apple Inc. and the Swift project authors + Portions Copyright (c) 2014-2018, Apple Inc. and the Swift project authors Licensed under Apache License v2.0 with Runtime Library Exception See http://swift.org/LICENSE.txt for license information See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors diff --git a/CoreFoundation/String.subproj/CFStringEncodings.c b/CoreFoundation/String.subproj/CFStringEncodings.c index 90e5141bd3..366ef8c29e 100644 --- a/CoreFoundation/String.subproj/CFStringEncodings.c +++ b/CoreFoundation/String.subproj/CFStringEncodings.c @@ -1,7 +1,7 @@ /* CFStringEncodings.c - Copyright (c) 1999-2017, Apple Inc. and the Swift project authors + Copyright (c) 1999-2018, Apple Inc. and the Swift project authors - Portions Copyright (c) 2014-2017, Apple Inc. and the Swift project authors + Portions Copyright (c) 2014-2018, Apple Inc. and the Swift project authors Licensed under Apache License v2.0 with Runtime Library Exception See http://swift.org/LICENSE.txt for license information See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors @@ -9,11 +9,13 @@ */ #include "CFInternal.h" +#include "CFString_Internal.h" #include #include #include #include #include +#include "CFStringEncodingConverterPriv.h" #include #include #if (TARGET_OS_MAC && !(TARGET_OS_EMBEDDED || TARGET_OS_IPHONE)) || (TARGET_OS_EMBEDDED || TARGET_OS_IPHONE) @@ -35,11 +37,11 @@ void _CFStringEncodingSetForceASCIICompatibility(Boolean flag) { __CFWantsToUseASCIICompatibleConversion = (flag ? (UInt32)true : (UInt32)false); } -Boolean (*__CFCharToUniCharFunc)(UInt32 flags, uint8_t ch, UniChar *unicodeChar) = NULL; +CFStringEncodingCheapEightBitToUnicodeProc __CFCharToUniCharFunc = NULL; // To avoid early initialization issues, we just initialize this here // This should not be const as it is changed -CF_PRIVATE UniChar __CFCharToUniCharTable[256] = { +UniChar __CFCharToUniCharTable[256] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, @@ -58,7 +60,7 @@ CF_PRIVATE UniChar __CFCharToUniCharTable[256] = { 240, 241, 242, 243, 244, 245, 246, 247, 248, 249, 250, 251, 252, 253, 254, 255 }; -CF_PRIVATE void __CFSetCharToUniCharFunc(Boolean (*func)(UInt32 flags, UInt8 ch, UniChar *unicodeChar)) { +CF_PRIVATE void __CFSetCharToUniCharFunc(CFStringEncodingCheapEightBitToUnicodeProc _Nullable func) { if (__CFCharToUniCharFunc != func) { int ch; __CFCharToUniCharFunc = func; @@ -303,7 +305,7 @@ Boolean __CFStringDecodeByteStream3(const uint8_t *bytes, CFIndex len, CFStringE if (!__CFFromUTF8) { const CFStringEncodingConverter *converter = CFStringEncodingGetConverter(kCFStringEncodingUTF8); - __CFFromUTF8 = (CFStringEncodingToUnicodeProc)converter->toUnicode; + __CFFromUTF8 = converter->toUnicode.standard; } buffer->shouldFreeChars = !buffer->chars.unicode && (len <= MAX_LOCAL_UNICHARS) ? false : true; @@ -429,7 +431,7 @@ Boolean __CFStringDecodeByteStream3(const uint8_t *bytes, CFIndex len, CFStringE for (idx = 0; idx < len; idx++) { if (chars[idx] < 0x80 && isASCIISuperset) { buffer->chars.unicode[idx] = (UniChar)chars[idx]; - } else if (!((CFStringEncodingCheapEightBitToUnicodeProc)converter->toUnicode)(0, chars[idx], buffer->chars.unicode + idx)) { + } else if (!converter->toUnicode.cheapEightBit(0, chars[idx], buffer->chars.unicode + idx)) { result = FALSE; break; } @@ -493,7 +495,7 @@ CFIndex __CFStringEncodeByteStream(CFStringRef string, CFIndex rangeLoc, CFIndex if (!__CFToUTF8) { const CFStringEncodingConverter *utf8Converter = CFStringEncodingGetConverter(kCFStringEncodingUTF8); - __CFToUTF8 = (CFStringEncodingToBytesProc)utf8Converter->toBytes; + __CFToUTF8 = utf8Converter->toBytes.standard; } numCharsProcessed = __CFToUTF8((generatingExternalFile ? kCFStringEncodingPrependBOM : 0), unichars + rangeLoc, rangeLen, buffer, (buffer ? max : 0), &totalBytesWritten); diff --git a/CoreFoundation/String.subproj/CFStringScanner.c b/CoreFoundation/String.subproj/CFStringScanner.c index 1137ab09c7..897b4095db 100644 --- a/CoreFoundation/String.subproj/CFStringScanner.c +++ b/CoreFoundation/String.subproj/CFStringScanner.c @@ -1,7 +1,7 @@ /* CFStringScanner.c - Copyright (c) 1999-2017, Apple Inc. and the Swift project authors + Copyright (c) 1999-2018, Apple Inc. and the Swift project authors - Portions Copyright (c) 2014-2017, Apple Inc. and the Swift project authors + Portions Copyright (c) 2014-2018, Apple Inc. and the Swift project authors Licensed under Apache License v2.0 with Runtime Library Exception See http://swift.org/LICENSE.txt for license information See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors diff --git a/CoreFoundation/String.subproj/CFStringUtilities.c b/CoreFoundation/String.subproj/CFStringUtilities.c index bfc21456f4..9f0cb989ea 100644 --- a/CoreFoundation/String.subproj/CFStringUtilities.c +++ b/CoreFoundation/String.subproj/CFStringUtilities.c @@ -1,7 +1,7 @@ /* CFStringUtilities.c - Copyright (c) 1999-2017, Apple Inc. and the Swift project authors + Copyright (c) 1999-2018, Apple Inc. and the Swift project authors - Portions Copyright (c) 2014-2017, Apple Inc. and the Swift project authors + Portions Copyright (c) 2014-2018, Apple Inc. and the Swift project authors Licensed under Apache License v2.0 with Runtime Library Exception See http://swift.org/LICENSE.txt for license information See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors @@ -12,6 +12,7 @@ #include #include #include +#include "CFStringEncodingConverterPriv.h" #include "CFStringEncodingDatabase.h" #include "CFICUConverters.h" #include @@ -369,8 +370,6 @@ static SInt32 __CompareCodePoints(const UniChar *text1Ptr, UniCharCount text1Len } -extern const CFStringRef __kCFLocaleCollatorID; - static UCollator *__CFStringCreateCollator(CFLocaleRef compareLocale) { CFStringRef canonLocaleCFStr = (CFStringRef)CFLocaleGetValue(compareLocale, __kCFLocaleCollatorID); char icuLocaleStr[128] = {0}; diff --git a/CoreFoundation/String.subproj/CFString_Internal.h b/CoreFoundation/String.subproj/CFString_Internal.h new file mode 100644 index 0000000000..9496b8ac4d --- /dev/null +++ b/CoreFoundation/String.subproj/CFString_Internal.h @@ -0,0 +1,22 @@ +/* CFString_Internal.h + Copyright (c) 1998-2018, Apple Inc. and the Swift project authors + + Portions Copyright (c) 2014-2018, Apple Inc. and the Swift project authors + Licensed under Apache License v2.0 with Runtime Library Exception + See http://swift.org/LICENSE.txt for license information + See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors +*/ + +#include +#include +#include + +CF_ASSUME_NONNULL_BEGIN + +CF_PRIVATE void __CFSetCharToUniCharFunc(CFStringEncodingCheapEightBitToUnicodeProc _Nullable func); +CF_PRIVATE UniChar __CFCharToUniCharTable[256]; +CF_PRIVATE CFIndex CFUniCharCompatibilityDecompose(UTF32Char *convertedChars, CFIndex length, CFIndex maxBufferLength); + + +CF_ASSUME_NONNULL_END + diff --git a/CoreFoundation/StringEncodings.subproj/CFBuiltinConverters.c b/CoreFoundation/StringEncodings.subproj/CFBuiltinConverters.c index 22af14b61c..e0a9f52908 100644 --- a/CoreFoundation/StringEncodings.subproj/CFBuiltinConverters.c +++ b/CoreFoundation/StringEncodings.subproj/CFBuiltinConverters.c @@ -1,7 +1,7 @@ /* CFBuiltinConverters.c - Copyright (c) 1999-2017, Apple Inc. and the Swift project authors + Copyright (c) 1999-2018, Apple Inc. and the Swift project authors - Portions Copyright (c) 2014-2017, Apple Inc. and the Swift project authors + Portions Copyright (c) 2014-2018, Apple Inc. and the Swift project authors Licensed under Apache License v2.0 with Runtime Library Exception See http://swift.org/LICENSE.txt for license information See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors @@ -10,20 +10,13 @@ #include "CFStringEncodingConverterExt.h" #include "CFUniChar.h" +#include "CFUniCharPriv.h" #include "CFUnicodeDecomposition.h" #include "CFUnicodePrecomposition.h" #include "CFStringEncodingConverterPriv.h" #include "CFInternal.h" -#define ParagraphSeparator 0x2029 #define ASCIINewLine 0x0a -static int8_t __CFMapsParagraphSeparator = -1; - -CF_INLINE bool __CFIsParagraphSeparator(UTF16Char character) { - if (-1 == __CFMapsParagraphSeparator) __CFMapsParagraphSeparator = (1 ? false : true); - - return ((__CFMapsParagraphSeparator && (ParagraphSeparator == character)) ? true : false); -} /* Precomposition */ static const uint32_t __CFLatin1CombiningCharBitmap[] = { // 0x300 ~ 0x35FF @@ -70,8 +63,6 @@ UniChar CFStringEncodingPrecomposeLatinCharacter(const UniChar *character, CFInd static bool __CFToASCII(uint32_t flags, UniChar character, uint8_t *byte) { if (character < 0x80) { *byte = (uint8_t)character; - } else if (__CFIsParagraphSeparator(character)) { - *byte = ASCIINewLine; } else { return false; } @@ -88,17 +79,24 @@ static bool __CFFromASCII(uint32_t flags, uint8_t byte, UniChar *character) { } -CF_PRIVATE const CFStringEncodingConverter __CFConverterASCII = { - __CFToASCII, __CFFromASCII, 1, 1, kCFStringEncodingConverterCheapEightBit, - NULL, NULL, NULL, NULL, NULL, NULL, +const CFStringEncodingConverter __CFConverterASCII = { + .encodingClass = kCFStringEncodingConverterCheapEightBit, + .toBytes.cheapEightBit = __CFToASCII, + .toUnicode.cheapEightBit = __CFFromASCII, + .maxBytesPerChar = 1, + .maxDecomposedCharLen = 1, + .toBytesLen = NULL, + .toUnicodeLen = NULL, + .toBytesFallback = NULL, + .toUnicodeFallback = NULL, + .toBytesPrecompose = NULL, + .isValidCombiningChar = NULL, }; /* ISO Latin 1 (8859-1) */ static bool __CFToISOLatin1(uint32_t flags, UniChar character, uint8_t *byte) { if (character <= 0xFF) { *byte = (uint8_t)character; - } else if (__CFIsParagraphSeparator(character)) { - *byte = ASCIINewLine; } else { return false; } @@ -124,9 +122,18 @@ static CFIndex __CFToISOLatin1Precompose(uint32_t flags, const UniChar *characte } } -CF_PRIVATE const CFStringEncodingConverter __CFConverterISOLatin1 = { - __CFToISOLatin1, __CFFromISOLatin1, 1, 1, kCFStringEncodingConverterCheapEightBit, - NULL, NULL, NULL, NULL, __CFToISOLatin1Precompose, CFStringEncodingIsValidCombiningCharacterForLatin1, +const CFStringEncodingConverter __CFConverterISOLatin1 = { + .encodingClass = kCFStringEncodingConverterCheapEightBit, + .toBytes.cheapEightBit = __CFToISOLatin1, + .toUnicode.cheapEightBit = __CFFromISOLatin1, + .maxBytesPerChar = 1, + .maxDecomposedCharLen = 1, + .toBytesLen = NULL, + .toUnicodeLen = NULL, + .toBytesFallback = NULL, + .toUnicodeFallback = NULL, + .toBytesPrecompose = __CFToISOLatin1Precompose, + .isValidCombiningChar = CFStringEncodingIsValidCombiningCharacterForLatin1, }; /* Mac Roman */ @@ -421,9 +428,18 @@ static CFIndex __CFToMacRomanPrecompose(uint32_t flags, const UniChar *character } } -CF_PRIVATE const CFStringEncodingConverter __CFConverterMacRoman = { - __CFToMacRoman, __CFFromMacRoman, 1, 1, kCFStringEncodingConverterCheapEightBit, - NULL, NULL, NULL, NULL, __CFToMacRomanPrecompose, CFStringEncodingIsValidCombiningCharacterForLatin1, +const CFStringEncodingConverter __CFConverterMacRoman = { + .encodingClass = kCFStringEncodingConverterCheapEightBit, + .toBytes.cheapEightBit = __CFToMacRoman, + .toUnicode.cheapEightBit = __CFFromMacRoman, + .maxBytesPerChar = 1, + .maxDecomposedCharLen = 1, + .toBytesLen = NULL, + .toUnicodeLen = NULL, + .toBytesFallback = NULL, + .toUnicodeFallback = NULL, + .toBytesPrecompose = __CFToMacRomanPrecompose, + .isValidCombiningChar = CFStringEncodingIsValidCombiningCharacterForLatin1, }; /* Win Latin1 (ANSI CodePage 1252) */ @@ -519,9 +535,18 @@ static CFIndex __CFToWinLatin1Precompose(uint32_t flags, const UniChar *characte } } -CF_PRIVATE const CFStringEncodingConverter __CFConverterWinLatin1 = { - __CFToWinLatin1, __CFFromWinLatin1, 1, 1, kCFStringEncodingConverterCheapEightBit, - NULL, NULL, NULL, NULL, __CFToWinLatin1Precompose, CFStringEncodingIsValidCombiningCharacterForLatin1, +const CFStringEncodingConverter __CFConverterWinLatin1 = { + .encodingClass = kCFStringEncodingConverterCheapEightBit, + .toBytes.cheapEightBit = __CFToWinLatin1, + .toUnicode.cheapEightBit = __CFFromWinLatin1, + .maxBytesPerChar = 1, + .maxDecomposedCharLen = 1, + .toBytesLen = NULL, + .toUnicodeLen = NULL, + .toBytesFallback = NULL, + .toUnicodeFallback = NULL, + .toBytesPrecompose = __CFToWinLatin1Precompose, + .isValidCombiningChar = CFStringEncodingIsValidCombiningCharacterForLatin1, }; /* NEXTSTEP Encoding */ @@ -662,9 +687,6 @@ static bool __CFToNextStepLatin(uint32_t flags, UniChar character, uint8_t *byte if (character < 0x80) { *byte = (uint8_t)character; return true; - } else if (__CFIsParagraphSeparator(character)) { - *byte = ASCIINewLine; - return true; } else { return CFStringEncodingUnicodeTo8BitEncoding(nextstep_from_tab, NUM_NEXTSTEP_FROM_UNI, character, byte); } @@ -819,9 +841,18 @@ static CFIndex __CFToNextStepLatinPrecompose(uint32_t flags, const UniChar *char } } -CF_PRIVATE const CFStringEncodingConverter __CFConverterNextStepLatin = { - __CFToNextStepLatin, __CFFromNextStepLatin, 1, 1, kCFStringEncodingConverterCheapEightBit, - NULL, NULL, NULL, NULL, __CFToNextStepLatinPrecompose, CFStringEncodingIsValidCombiningCharacterForLatin1, +const CFStringEncodingConverter __CFConverterNextStepLatin = { + .encodingClass = kCFStringEncodingConverterCheapEightBit, + .toBytes.cheapEightBit = __CFToNextStepLatin, + .toUnicode.cheapEightBit = __CFFromNextStepLatin, + .maxBytesPerChar = 1, + .maxDecomposedCharLen = 1, + .toBytesLen = NULL, + .toUnicodeLen = NULL, + .toBytesFallback = NULL, + .toUnicodeFallback = NULL, + .toBytesPrecompose = __CFToNextStepLatinPrecompose, + .isValidCombiningChar = CFStringEncodingIsValidCombiningCharacterForLatin1, }; /* UTF8 */ @@ -1173,7 +1204,16 @@ static CFIndex __CFFromUTF8Len(uint32_t flags, const uint8_t *source, CFIndex nu return theUsedCharLen; } -CF_PRIVATE const CFStringEncodingConverter __CFConverterUTF8 = { - __CFToUTF8, __CFFromUTF8, 3, 2, kCFStringEncodingConverterStandard, - __CFToUTF8Len, __CFFromUTF8Len, NULL, NULL, NULL, NULL, +const CFStringEncodingConverter __CFConverterUTF8 = { + .encodingClass = kCFStringEncodingConverterStandard, + .toBytes.standard = __CFToUTF8, + .toUnicode.standard = __CFFromUTF8, + .maxBytesPerChar = 3, + .maxDecomposedCharLen = 2, + .toBytesLen = __CFToUTF8Len, + .toUnicodeLen = __CFFromUTF8Len, + .toBytesFallback = NULL, + .toUnicodeFallback = NULL, + .toBytesPrecompose = NULL, + .isValidCombiningChar = NULL, }; diff --git a/CoreFoundation/StringEncodings.subproj/CFICUConverters.c b/CoreFoundation/StringEncodings.subproj/CFICUConverters.c index a6445149f2..dbb88528b4 100644 --- a/CoreFoundation/StringEncodings.subproj/CFICUConverters.c +++ b/CoreFoundation/StringEncodings.subproj/CFICUConverters.c @@ -1,7 +1,7 @@ /* CFICUConverters.c - Copyright (c) 2004-2017, Apple Inc. and the Swift project authors + Copyright (c) 2004-2018, Apple Inc. and the Swift project authors - Portions Copyright (c) 2014-2017, Apple Inc. and the Swift project authors + Portions Copyright (c) 2014-2018, Apple Inc. and the Swift project authors Licensed under Apache License v2.0 with Runtime Library Exception See http://swift.org/LICENSE.txt for license information See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors diff --git a/CoreFoundation/StringEncodings.subproj/CFICUConverters.h b/CoreFoundation/StringEncodings.subproj/CFICUConverters.h index c2f7883a94..4827b29b5f 100644 --- a/CoreFoundation/StringEncodings.subproj/CFICUConverters.h +++ b/CoreFoundation/StringEncodings.subproj/CFICUConverters.h @@ -2,9 +2,9 @@ CFICUConverters.h CoreFoundation - Copyright (c) 2007-2017, Apple Inc. and the Swift project authors + Copyright (c) 2007-2018, Apple Inc. and the Swift project authors - Portions Copyright (c) 2014-2017, Apple Inc. and the Swift project authors + Portions Copyright (c) 2014-2018, Apple Inc. and the Swift project authors Licensed under Apache License v2.0 with Runtime Library Exception See http://swift.org/LICENSE.txt for license information See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors diff --git a/CoreFoundation/StringEncodings.subproj/CFPlatformConverters.c b/CoreFoundation/StringEncodings.subproj/CFPlatformConverters.c index b3b8688b61..b8eeeea0fe 100644 --- a/CoreFoundation/StringEncodings.subproj/CFPlatformConverters.c +++ b/CoreFoundation/StringEncodings.subproj/CFPlatformConverters.c @@ -1,7 +1,7 @@ /* CFPlatformConverters.c - Copyright (c) 1998-2017, Apple Inc. and the Swift project authors + Copyright (c) 1998-2018, Apple Inc. and the Swift project authors - Portions Copyright (c) 2014-2017, Apple Inc. and the Swift project authors + Portions Copyright (c) 2014-2018, Apple Inc. and the Swift project authors Licensed under Apache License v2.0 with Runtime Library Exception See http://swift.org/LICENSE.txt for license information See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors @@ -30,19 +30,33 @@ CF_INLINE bool __CFIsPlatformConverterAvailable(int encoding) { #if DEPLOYMENT_TARGET_MACOSX || DEPLOYMENT_TARGET_EMBEDDED || DEPLOYMENT_TARGET_WINDOWS || DEPLOYMENT_TARGET_LINUX static const CFStringEncodingConverter __CFICUBootstrap = { - NULL /* toBytes */, NULL /* toUnicode */, 6 /* maxBytesPerChar */, 4 /* maxDecomposedCharLen */, - kCFStringEncodingConverterICU /* encodingClass */, - NULL /* toBytesLen */, NULL /* toUnicodeLen */, NULL /* toBytesFallback */, - NULL /* toUnicodeFallback */, NULL /* toBytesPrecompose */, NULL, /* isValidCombiningChar */ + .toBytes.standard = NULL, + .toUnicode.standard = NULL, + .maxBytesPerChar = 6, + .maxDecomposedCharLen = 4, + .encodingClass = kCFStringEncodingConverterICU, + .toBytesLen = NULL, + .toUnicodeLen = NULL, + .toBytesFallback = NULL, + .toUnicodeFallback = NULL, + .toBytesPrecompose = NULL, + .isValidCombiningChar = NULL, }; #endif static const CFStringEncodingConverter __CFPlatformBootstrap = { - NULL /* toBytes */, NULL /* toUnicode */, 6 /* maxBytesPerChar */, 4 /* maxDecomposedCharLen */, - kCFStringEncodingConverterPlatformSpecific /* encodingClass */, - NULL /* toBytesLen */, NULL /* toUnicodeLen */, NULL /* toBytesFallback */, - NULL /* toUnicodeFallback */, NULL /* toBytesPrecompose */, NULL, /* isValidCombiningChar */ + .toBytes.standard = NULL, + .toUnicode.standard = NULL, + .maxBytesPerChar = 6, + .maxDecomposedCharLen = 4, + .encodingClass = kCFStringEncodingConverterPlatformSpecific, + .toBytesLen = NULL, + .toUnicodeLen = NULL, + .toBytesFallback = NULL, + .toUnicodeFallback = NULL, + .toBytesPrecompose = NULL, + .isValidCombiningChar = NULL, }; CF_PRIVATE const CFStringEncodingConverter *__CFStringEncodingGetExternalConverter(uint32_t encoding) { diff --git a/CoreFoundation/StringEncodings.subproj/CFStringEncodingConverter.c b/CoreFoundation/StringEncodings.subproj/CFStringEncodingConverter.c index 924d257eaa..c40ef7b4c0 100644 --- a/CoreFoundation/StringEncodings.subproj/CFStringEncodingConverter.c +++ b/CoreFoundation/StringEncodings.subproj/CFStringEncodingConverter.c @@ -1,7 +1,7 @@ /* CFStringEncodingConverter.c - Copyright (c) 1998-2017, Apple Inc. and the Swift project authors + Copyright (c) 1998-2018, Apple Inc. and the Swift project authors - Portions Copyright (c) 2014-2017, Apple Inc. and the Swift project authors + Portions Copyright (c) 2014-2018, Apple Inc. and the Swift project authors Licensed under Apache License v2.0 with Runtime Library Exception See http://swift.org/LICENSE.txt for license information See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors @@ -19,6 +19,10 @@ #include "CFStringEncodingConverterPriv.h" #include +#if __has_include() +#include +#endif + typedef CFIndex (*_CFToBytesProc)(const void *converter, uint32_t flags, const UniChar *characters, CFIndex numChars, uint8_t *bytes, CFIndex maxByteLen, CFIndex *usedByteLen); typedef CFIndex (*_CFToUnicodeProc)(const void *converter, uint32_t flags, const uint8_t *bytes, CFIndex numBytes, UniChar *characters, CFIndex maxCharLen, CFIndex *usedCharLen); @@ -33,8 +37,8 @@ typedef struct { /* Macros */ -#define TO_BYTE(conv,flags,chars,numChars,bytes,max,used) (conv->toBytes ? conv->toBytes(conv,flags,chars,numChars,bytes,max,used) : ((CFStringEncodingToBytesProc)conv->definition->toBytes)(flags,chars,numChars,bytes,max,used)) -#define TO_UNICODE(conv,flags,bytes,numBytes,chars,max,used) (conv->toUnicode ? (flags & (kCFStringEncodingUseCanonical|kCFStringEncodingUseHFSPlusCanonical) ? conv->toCanonicalUnicode(conv,flags,bytes,numBytes,chars,max,used) : conv->toUnicode(conv,flags,bytes,numBytes,chars,max,used)) : ((CFStringEncodingToUnicodeProc)conv->definition->toUnicode)(flags,bytes,numBytes,chars,max,used)) +#define TO_BYTE(conv,flags,chars,numChars,bytes,max,used) (conv->toBytes ? conv->toBytes(conv,flags,chars,numChars,bytes,max,used) : conv->definition->toBytes.standard(flags,chars,numChars,bytes,max,used)) +#define TO_UNICODE(conv,flags,bytes,numBytes,chars,max,used) (conv->toUnicode ? (flags & (kCFStringEncodingUseCanonical|kCFStringEncodingUseHFSPlusCanonical) ? conv->toCanonicalUnicode(conv,flags,bytes,numBytes,chars,max,used) : conv->toUnicode(conv,flags,bytes,numBytes,chars,max,used)) : conv->definition->toUnicode.standard(flags,bytes,numBytes,chars,max,used)) #define ASCIINewLine 0x0a #define kSurrogateHighStart 0xD800 @@ -224,7 +228,7 @@ static CFIndex __CFToBytesCheapEightBitWrapper(const void *converter, uint32_t f uint8_t byte; while (processedCharLen < length) { - if (!((CFStringEncodingCheapEightBitToBytesProc)((const _CFEncodingConverter*)converter)->definition->toBytes)(flags, characters[processedCharLen], &byte)) break; + if (!((const _CFEncodingConverter*)converter)->definition->toBytes.cheapEightBit(flags, characters[processedCharLen], &byte)) break; if (maxByteLen) bytes[processedCharLen] = byte; processedCharLen++; @@ -240,7 +244,7 @@ static CFIndex __CFToUnicodeCheapEightBitWrapper(const void *converter, uint32_t UniChar character; while (processedByteLen < length) { - if (!((CFStringEncodingCheapEightBitToUnicodeProc)((const _CFEncodingConverter*)converter)->definition->toUnicode)(flags, bytes[processedByteLen], &character)) break; + if (!((const _CFEncodingConverter*)converter)->definition->toUnicode.cheapEightBit(flags, bytes[processedByteLen], &character)) break; if (maxCharLen) characters[processedByteLen] = character; processedByteLen++; @@ -259,7 +263,7 @@ static CFIndex __CFToCanonicalUnicodeCheapEightBitWrapper(const void *converter, bool isHFSPlus = (flags & kCFStringEncodingUseHFSPlusCanonical ? true : false); while ((processedByteLen < numBytes) && (!maxCharLen || (theUsedCharLen < maxCharLen))) { - if (!((CFStringEncodingCheapEightBitToUnicodeProc)((const _CFEncodingConverter*)converter)->definition->toUnicode)(flags, bytes[processedByteLen], &character)) break; + if (!((const _CFEncodingConverter*)converter)->definition->toUnicode.cheapEightBit(flags, bytes[processedByteLen], &character)) break; if (CFUniCharIsDecomposableCharacter(character, isHFSPlus)) { CFIndex idx; @@ -301,7 +305,7 @@ static CFIndex __CFToBytesStandardEightBitWrapper(const void *converter, uint32_ *usedByteLen = 0; while (numChars && (!maxByteLen || (*usedByteLen < maxByteLen))) { - if (!(usedLen = ((CFStringEncodingStandardEightBitToBytesProc)((const _CFEncodingConverter*)converter)->definition->toBytes)(flags, characters, numChars, &byte))) break; + if (!(usedLen = ((const _CFEncodingConverter*)converter)->definition->toBytes.standardEightBit(flags, characters, numChars, &byte))) break; if (maxByteLen) bytes[*usedByteLen] = byte; (*usedByteLen)++; @@ -321,7 +325,7 @@ static CFIndex __CFToUnicodeStandardEightBitWrapper(const void *converter, uint3 *usedCharLen = 0; while ((processedByteLen < numBytes) && (!maxCharLen || (*usedCharLen < maxCharLen))) { - if (!(usedLen = ((CFStringEncodingCheapEightBitToUnicodeProc)((const _CFEncodingConverter*)converter)->definition->toUnicode)(flags, bytes[processedByteLen], charBuffer))) break; + if (!(usedLen = ((const _CFEncodingConverter*)converter)->definition->toUnicode.cheapEightBit(flags, bytes[processedByteLen], charBuffer))) break; if (maxCharLen) { CFIndex idx; @@ -350,7 +354,7 @@ static CFIndex __CFToCanonicalUnicodeStandardEightBitWrapper(const void *convert CFIndex theUsedCharLen = 0; while ((processedByteLen < numBytes) && (!maxCharLen || (theUsedCharLen < maxCharLen))) { - if (!(usedLen = ((CFStringEncodingCheapEightBitToUnicodeProc)((const _CFEncodingConverter*)converter)->definition->toUnicode)(flags, bytes[processedByteLen], charBuffer))) break; + if (!(usedLen = ((const _CFEncodingConverter*)converter)->definition->toUnicode.cheapEightBit(flags, bytes[processedByteLen], charBuffer))) break; for (idx = 0;idx < usedLen;idx++) { if (CFUniCharIsDecomposableCharacter(charBuffer[idx], isHFSPlus)) { @@ -392,7 +396,7 @@ static CFIndex __CFToBytesCheapMultiByteWrapper(const void *converter, uint32_t *usedByteLen = 0; while ((processedCharLen < numChars) && (!maxByteLen || (*usedByteLen < maxByteLen))) { - if (!(usedLen = ((CFStringEncodingCheapMultiByteToBytesProc)((const _CFEncodingConverter*)converter)->definition->toBytes)(flags, characters[processedCharLen], byteBuffer))) break; + if (!(usedLen = ((const _CFEncodingConverter*)converter)->definition->toBytes.cheapMultibyte(flags, characters[processedCharLen], byteBuffer))) break; if (maxByteLen) { CFIndex idx; @@ -419,7 +423,7 @@ static CFIndex __CFToUnicodeCheapMultiByteWrapper(const void *converter, uint32_ *usedCharLen = 0; while (numBytes && (!maxCharLen || (*usedCharLen < maxCharLen))) { - if (!(usedLen = ((CFStringEncodingCheapMultiByteToUnicodeProc)((const _CFEncodingConverter*)converter)->definition->toUnicode)(flags, bytes, numBytes, &character))) break; + if (!(usedLen = ((const _CFEncodingConverter*)converter)->definition->toUnicode.cheapMultibyte(flags, bytes, numBytes, &character))) break; if (maxCharLen) *(characters++) = character; (*usedCharLen)++; @@ -441,7 +445,7 @@ static CFIndex __CFToCanonicalUnicodeCheapMultiByteWrapper(const void *converter bool isHFSPlus = (flags & kCFStringEncodingUseHFSPlusCanonical ? true : false); while (numBytes && (!maxCharLen || (theUsedCharLen < maxCharLen))) { - if (!(usedLen = ((CFStringEncodingCheapMultiByteToUnicodeProc)((const _CFEncodingConverter*)converter)->definition->toUnicode)(flags, bytes, numBytes, &character))) break; + if (!(usedLen = ((const _CFEncodingConverter*)converter)->definition->toUnicode.cheapMultibyte(flags, bytes, numBytes, &character))) break; if (CFUniCharIsDecomposableCharacter(character, isHFSPlus)) { CFIndex idx; @@ -580,7 +584,16 @@ static const _CFEncodingConverter *__CFGetConverter(uint32_t encoding) { const _CFEncodingConverter **commonConverterSlot = NULL; static _CFEncodingConverter *commonConverters[3] = {NULL, NULL, NULL}; // UTF8, MacRoman/WinLatin1, and the default encoding* static CFMutableDictionaryRef mappingTable = NULL; + +#if __has_include() static os_unfair_lock lock = OS_UNFAIR_LOCK_INIT; + #define _CFGetConverter_Lock() os_unfair_lock_lock(&lock) + #define _CFGetConverter_Unlock() os_unfair_lock_unlock(&lock) +#else + static CFLock_t cflock = CFLockInit; + #define _CFGetConverter_Lock() __CFLock(&cflock) + #define _CFGetConverter_Unlock() __CFUnlock(&cflock) +#endif switch (encoding) { case kCFStringEncodingUTF8: commonConverterSlot = (const _CFEncodingConverter **)&(commonConverters[0]); break; @@ -598,15 +611,15 @@ static const _CFEncodingConverter *__CFGetConverter(uint32_t encoding) { default: if (CFStringGetSystemEncoding() == encoding) commonConverterSlot = (const _CFEncodingConverter **)&(commonConverters[2]); break; } - os_unfair_lock_lock(&lock); + _CFGetConverter_Lock(); converter = ((NULL == commonConverterSlot) ? ((NULL == mappingTable) ? NULL : (const _CFEncodingConverter *)CFDictionaryGetValue(mappingTable, (const void *)(uintptr_t)encoding)) : *commonConverterSlot); - os_unfair_lock_unlock(&lock); + _CFGetConverter_Unlock(); if (NULL == converter) { const CFStringEncodingConverter *definition = __CFStringEncodingConverterGetDefinition(encoding); if (NULL != definition) { - os_unfair_lock_lock(&lock); + _CFGetConverter_Lock(); converter = ((NULL == commonConverterSlot) ? ((NULL == mappingTable) ? NULL : (const _CFEncodingConverter *)CFDictionaryGetValue(mappingTable, (const void *)(uintptr_t)encoding)) : *commonConverterSlot); if (NULL == converter) { @@ -620,11 +633,14 @@ static const _CFEncodingConverter *__CFGetConverter(uint32_t encoding) { *commonConverterSlot = converter; } } - os_unfair_lock_unlock(&lock); + _CFGetConverter_Unlock(); } } return converter; + +#undef _CFGetConverter_Lock +#undef _CFGetConverter_Unlock } /* Public API @@ -641,7 +657,7 @@ uint32_t CFStringEncodingUnicodeToBytes(uint32_t encoding, uint32_t flags, const } else { if (!__CFToUTF8) { const CFStringEncodingConverter *utf8Converter = CFStringEncodingGetConverter(kCFStringEncodingUTF8); - __CFToUTF8 = (CFStringEncodingToBytesProc)utf8Converter->toBytes; + __CFToUTF8 = utf8Converter->toBytes.standard; } convertedCharLen = __CFToUTF8(0, characters, numChars, bytes, maxByteLen, &usedLen); } diff --git a/CoreFoundation/StringEncodings.subproj/CFStringEncodingConverter.h b/CoreFoundation/StringEncodings.subproj/CFStringEncodingConverter.h index 17640282d5..3cdea7d2ba 100644 --- a/CoreFoundation/StringEncodings.subproj/CFStringEncodingConverter.h +++ b/CoreFoundation/StringEncodings.subproj/CFStringEncodingConverter.h @@ -1,7 +1,7 @@ /* CFStringEncodingConverter.h - Copyright (c) 1998-2017, Apple Inc. and the Swift project authors + Copyright (c) 1998-2018, Apple Inc. and the Swift project authors - Portions Copyright (c) 2014-2017, Apple Inc. and the Swift project authors + Portions Copyright (c) 2014-2018, Apple Inc. and the Swift project authors Licensed under Apache License v2.0 with Runtime Library Exception See http://swift.org/LICENSE.txt for license information See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors @@ -72,17 +72,6 @@ CF_EXPORT uint32_t CFStringEncodingBytesToUnicode(uint32_t encoding, uint32_t fl typedef CFIndex (*CFStringEncodingToBytesFallbackProc)(const UniChar *characters, CFIndex numChars, uint8_t *bytes, CFIndex maxByteLen, CFIndex *usedByteLen); typedef CFIndex (*CFStringEncodingToUnicodeFallbackProc)(const uint8_t *bytes, CFIndex numBytes, UniChar *characters, CFIndex maxCharLen, CFIndex *usedCharLen); -CF_EXPORT bool CFStringEncodingIsValidEncoding(uint32_t encoding); - -/* Returns kCFStringEncodingInvalidId terminated encoding list -*/ -CF_EXPORT const CFStringEncoding *CFStringEncodingListOfAvailableEncodings(void); - -/* Returns required length of destination buffer for conversion. These functions are faster than specifying 0 to maxByteLen (maxCharLen), but unnecessarily optimal length -*/ -CF_EXPORT CFIndex CFStringEncodingCharLengthForBytes(uint32_t encoding, uint32_t flags, const uint8_t *bytes, CFIndex numBytes); -CF_EXPORT CFIndex CFStringEncodingByteLengthForCharacters(uint32_t encoding, uint32_t flags, const UniChar *characters, CFIndex numChars); - /* Can register functions used for lossy conversion. Reregisters default procs if NULL */ CF_EXPORT void CFStringEncodingRegisterFallbackProcedures(uint32_t encoding, CFStringEncodingToBytesFallbackProc toBytes, CFStringEncodingToUnicodeFallbackProc toUnicode); diff --git a/CoreFoundation/StringEncodings.subproj/CFStringEncodingConverterExt.h b/CoreFoundation/StringEncodings.subproj/CFStringEncodingConverterExt.h index 58dfb1897d..41aefd3412 100644 --- a/CoreFoundation/StringEncodings.subproj/CFStringEncodingConverterExt.h +++ b/CoreFoundation/StringEncodings.subproj/CFStringEncodingConverterExt.h @@ -1,7 +1,7 @@ /* CFStringEncodingConverterExt.h - Copyright (c) 1998-2017, Apple Inc. and the Swift project authors + Copyright (c) 1998-2018, Apple Inc. and the Swift project authors - Portions Copyright (c) 2014-2017, Apple Inc. and the Swift project authors + Portions Copyright (c) 2014-2018, Apple Inc. and the Swift project authors Licensed under Apache License v2.0 with Runtime Library Exception See http://swift.org/LICENSE.txt for license information See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors @@ -45,8 +45,21 @@ typedef CFIndex (*CFStringEncodingToBytesPrecomposeProc)(uint32_t flags, const U typedef bool (*CFStringEncodingIsValidCombiningCharacterProc)(UniChar character); typedef struct { - void *toBytes; - void *toUnicode; + // These conversion functions should be accessed and called as dictated by .encodingClass. + // An encoding class of kCFStringEncodingConverterStandard corresponds to .standard; kCFStringEncodingConverterCheapEightBit corresponds to .cheapEightBit; etc. + union { + CFStringEncodingToBytesProc standard; + CFStringEncodingCheapEightBitToBytesProc cheapEightBit; + CFStringEncodingStandardEightBitToBytesProc standardEightBit; + CFStringEncodingCheapMultiByteToBytesProc cheapMultibyte; + } toBytes; + union { + CFStringEncodingToUnicodeProc standard; + CFStringEncodingCheapEightBitToUnicodeProc cheapEightBit; + CFStringEncodingStandardEightBitToUnicodeProc standardEightBit; + CFStringEncodingCheapMultiByteToUnicodeProc cheapMultibyte; + } toUnicode; + uint16_t maxBytesPerChar; uint16_t maxDecomposedCharLen; uint8_t encodingClass; @@ -59,8 +72,6 @@ typedef struct { CFStringEncodingIsValidCombiningCharacterProc isValidCombiningChar; } CFStringEncodingConverter; -extern const CFStringEncodingConverter *CFStringEncodingGetConverter(uint32_t encoding); - enum { kCFStringEncodingGetConverterSelector = 0, kCFStringEncodingIsDecomposableCharacterSelector = 1, @@ -69,8 +80,6 @@ enum { kCFStringEncodingPrecomposeLatin1CharacterSelector = 4 }; -extern const void *CFStringEncodingGetAddressForSelector(uint32_t selector); - #define BOOTSTRAPFUNC_NAME CFStringEncodingBootstrap typedef const CFStringEncodingConverter* (*CFStringEncodingBootstrapProc)(uint32_t encoding, const void *getSelector); diff --git a/CoreFoundation/StringEncodings.subproj/CFStringEncodingConverterPriv.h b/CoreFoundation/StringEncodings.subproj/CFStringEncodingConverterPriv.h index 4cb64f4d5e..6e03a01e29 100644 --- a/CoreFoundation/StringEncodings.subproj/CFStringEncodingConverterPriv.h +++ b/CoreFoundation/StringEncodings.subproj/CFStringEncodingConverterPriv.h @@ -1,7 +1,7 @@ /* CFStringEncodingConverterPriv.h - Copyright (c) 1998-2017, Apple Inc. and the Swift project authors + Copyright (c) 1998-2018, Apple Inc. and the Swift project authors - Portions Copyright (c) 2014-2017, Apple Inc. and the Swift project authors + Portions Copyright (c) 2014-2018, Apple Inc. and the Swift project authors Licensed under Apache License v2.0 with Runtime Library Exception See http://swift.org/LICENSE.txt for license information See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors @@ -13,19 +13,32 @@ #include #include "CFStringEncodingConverterExt.h" -extern const CFStringEncodingConverter __CFConverterASCII; -extern const CFStringEncodingConverter __CFConverterISOLatin1; -extern const CFStringEncodingConverter __CFConverterMacRoman; -extern const CFStringEncodingConverter __CFConverterWinLatin1; -extern const CFStringEncodingConverter __CFConverterNextStepLatin; -extern const CFStringEncodingConverter __CFConverterUTF8; - -extern CFStringEncoding *__CFStringEncodingCreateListOfAvailablePlatformConverters(CFAllocatorRef allocator, CFIndex *numberOfConverters); -extern const CFStringEncodingConverter *__CFStringEncodingGetExternalConverter(uint32_t encoding); -extern CFIndex __CFStringEncodingPlatformUnicodeToBytes(uint32_t encoding, uint32_t flags, const UniChar *characters, CFIndex numChars, CFIndex *usedCharLen, uint8_t *bytes, CFIndex maxByteLen, CFIndex *usedByteLen); -extern CFIndex __CFStringEncodingPlatformBytesToUnicode(uint32_t encoding, uint32_t flags, const uint8_t *bytes, CFIndex numBytes, CFIndex *usedByteLen, UniChar *characters, CFIndex maxCharLen, CFIndex *usedCharLen); -extern CFIndex __CFStringEncodingPlatformCharLengthForBytes(uint32_t encoding, uint32_t flags, const uint8_t *bytes, CFIndex numBytes); -extern CFIndex __CFStringEncodingPlatformByteLengthForCharacters(uint32_t encoding, uint32_t flags, const UniChar *characters, CFIndex numChars); +CF_PRIVATE const CFStringEncodingConverter __CFConverterASCII; +CF_PRIVATE const CFStringEncodingConverter __CFConverterISOLatin1; +CF_PRIVATE const CFStringEncodingConverter __CFConverterMacRoman; +CF_PRIVATE const CFStringEncodingConverter __CFConverterWinLatin1; +CF_PRIVATE const CFStringEncodingConverter __CFConverterNextStepLatin; +CF_PRIVATE const CFStringEncodingConverter __CFConverterUTF8; + +CF_PRIVATE CFStringEncoding *__CFStringEncodingCreateListOfAvailablePlatformConverters(CFAllocatorRef allocator, CFIndex *numberOfConverters); +CF_PRIVATE const CFStringEncodingConverter *__CFStringEncodingGetExternalConverter(uint32_t encoding); +CF_PRIVATE CFIndex __CFStringEncodingPlatformUnicodeToBytes(uint32_t encoding, uint32_t flags, const UniChar *characters, CFIndex numChars, CFIndex *usedCharLen, uint8_t *bytes, CFIndex maxByteLen, CFIndex *usedByteLen); +CF_PRIVATE CFIndex __CFStringEncodingPlatformBytesToUnicode(uint32_t encoding, uint32_t flags, const uint8_t *bytes, CFIndex numBytes, CFIndex *usedByteLen, UniChar *characters, CFIndex maxCharLen, CFIndex *usedCharLen); +CF_PRIVATE CFIndex __CFStringEncodingPlatformCharLengthForBytes(uint32_t encoding, uint32_t flags, const uint8_t *bytes, CFIndex numBytes); +CF_PRIVATE CFIndex __CFStringEncodingPlatformByteLengthForCharacters(uint32_t encoding, uint32_t flags, const UniChar *characters, CFIndex numChars); + +/* Returns required length of destination buffer for conversion. These functions are faster than specifying 0 to maxByteLen (maxCharLen), but unnecessarily optimal length + */ +CF_PRIVATE CFIndex CFStringEncodingCharLengthForBytes(uint32_t encoding, uint32_t flags, const uint8_t *bytes, CFIndex numBytes); +CF_PRIVATE CFIndex CFStringEncodingByteLengthForCharacters(uint32_t encoding, uint32_t flags, const UniChar *characters, CFIndex numChars); + +CF_PRIVATE bool CFStringEncodingIsValidEncoding(uint32_t encoding); + +/* Returns kCFStringEncodingInvalidId terminated encoding list + */ +CF_PRIVATE const CFStringEncoding *CFStringEncodingListOfAvailableEncodings(void); + +CF_PRIVATE const CFStringEncodingConverter *CFStringEncodingGetConverter(uint32_t encoding); #endif /* ! __COREFOUNDATION_CFSTRINGENCODINGCONVERTERPRIV__ */ diff --git a/CoreFoundation/StringEncodings.subproj/CFStringEncodingDatabase.c b/CoreFoundation/StringEncodings.subproj/CFStringEncodingDatabase.c index aabc3f128d..a8bfcd9970 100644 --- a/CoreFoundation/StringEncodings.subproj/CFStringEncodingDatabase.c +++ b/CoreFoundation/StringEncodings.subproj/CFStringEncodingDatabase.c @@ -1,7 +1,7 @@ /* CFStringEncodingDatabase.c - Copyright (c) 2005-2017, Apple Inc. and the Swift project authors + Copyright (c) 2005-2018, Apple Inc. and the Swift project authors - Portions Copyright (c) 2014-2017, Apple Inc. and the Swift project authors + Portions Copyright (c) 2014-2018, Apple Inc. and the Swift project authors Licensed under Apache License v2.0 with Runtime Library Exception See http://swift.org/LICENSE.txt for license information See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors @@ -242,7 +242,7 @@ static const uint16_t __CFWindowsCPList[] = { }; // Canonical name -static const char *__CFCanonicalNameList[] = { +static const char * const __CFCanonicalNameList[] = { "macintosh", "japanese", "trad-chinese", @@ -570,7 +570,7 @@ CF_PRIVATE CFStringEncoding __CFStringEncodingGetFromCanonicalName(const char *c #if DEPLOYMENT_TARGET_MACOSX || DEPLOYMENT_TARGET_LINUX // This list indexes from DOS range -static uint16_t __CFISO8859SimilarScriptList[] = { +static uint16_t const __CFISO8859SimilarScriptList[] = { kCFStringEncodingMacRoman, kCFStringEncodingMacCentralEurRoman, kCFStringEncodingMacRoman, @@ -588,7 +588,7 @@ static uint16_t __CFISO8859SimilarScriptList[] = { kCFStringEncodingMacRoman, kCFStringEncodingMacRomanian}; -static uint16_t __CFOtherSimilarScriptList[] = { +static uint16_t const __CFOtherSimilarScriptList[] = { kCFStringEncodingMacRoman, kCFStringEncodingMacGreek, kCFStringEncodingMacCentralEurRoman, @@ -658,7 +658,7 @@ static uint16_t __CFOtherSimilarScriptList[] = { kCFStringEncodingMacRoman }; -static const char *__CFISONameList[] = { +static const char * const __CFISONameList[] = { "Western (ISO Latin 1)", "Central European (ISO Latin 2)", "Western (ISO Latin 3)", @@ -677,7 +677,7 @@ static const char *__CFISONameList[] = { "Romanian (ISO Latin 10)", }; -static const char *__CFOtherNameList[] = { +static const char * const __CFOtherNameList[] = { "Western (Mac OS Roman)", "Japanese (Mac OS)", "Traditional Chinese (Mac OS)", diff --git a/CoreFoundation/StringEncodings.subproj/CFStringEncodingDatabase.h b/CoreFoundation/StringEncodings.subproj/CFStringEncodingDatabase.h index bab845af04..e4ae4f486d 100644 --- a/CoreFoundation/StringEncodings.subproj/CFStringEncodingDatabase.h +++ b/CoreFoundation/StringEncodings.subproj/CFStringEncodingDatabase.h @@ -2,9 +2,9 @@ CFStringEncodingDatabase.h CoreFoundation - Copyright (c) 2007-2017, Apple Inc. and the Swift project authors + Copyright (c) 2007-2018, Apple Inc. and the Swift project authors - Portions Copyright (c) 2014-2017, Apple Inc. and the Swift project authors + Portions Copyright (c) 2014-2018, Apple Inc. and the Swift project authors Licensed under Apache License v2.0 with Runtime Library Exception See http://swift.org/LICENSE.txt for license information See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors diff --git a/CoreFoundation/StringEncodings.subproj/CFUniChar.c b/CoreFoundation/StringEncodings.subproj/CFUniChar.c index 127e49a49f..17c92961e1 100644 --- a/CoreFoundation/StringEncodings.subproj/CFUniChar.c +++ b/CoreFoundation/StringEncodings.subproj/CFUniChar.c @@ -1,7 +1,7 @@ /* CFUniChar.c - Copyright (c) 2001-2017, Apple Inc. and the Swift project authors + Copyright (c) 2001-2018, Apple Inc. and the Swift project authors - Portions Copyright (c) 2014-2017, Apple Inc. and the Swift project authors + Portions Copyright (c) 2014-2018, Apple Inc. and the Swift project authors Licensed under Apache License v2.0 with Runtime Library Exception See http://swift.org/LICENSE.txt for license information See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors diff --git a/CoreFoundation/StringEncodings.subproj/CFUniChar.h b/CoreFoundation/StringEncodings.subproj/CFUniChar.h index ad702d810b..e01ec6f53c 100644 --- a/CoreFoundation/StringEncodings.subproj/CFUniChar.h +++ b/CoreFoundation/StringEncodings.subproj/CFUniChar.h @@ -1,7 +1,7 @@ /* CFUniChar.h - Copyright (c) 1998-2017, Apple Inc. and the Swift project authors + Copyright (c) 1998-2018, Apple Inc. and the Swift project authors - Portions Copyright (c) 2014-2017, Apple Inc. and the Swift project authors + Portions Copyright (c) 2014-2018, Apple Inc. and the Swift project authors Licensed under Apache License v2.0 with Runtime Library Exception See http://swift.org/LICENSE.txt for license information See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors @@ -28,7 +28,7 @@ CF_INLINE bool CFUniCharIsSurrogateLowCharacter(UniChar character) { } CF_INLINE UTF32Char CFUniCharGetLongCharacterForSurrogatePair(UniChar surrogateHigh, UniChar surrogateLow) { - return ((surrogateHigh - 0xD800UL) << 10) + (surrogateLow - 0xDC00UL) + 0x0010000UL; + return (UTF32Char)((((UTF32Char)surrogateHigh - 0xD800UL) << 10) + ((UTF32Char)surrogateLow - 0xDC00UL) + 0x0010000UL); } // The following values coinside TextEncodingFormat format defines in TextCommon.h @@ -92,10 +92,6 @@ enum { kCFUniCharBitmapAll = (uint8_t)1 }; -CF_EXPORT uint8_t CFUniCharGetBitmapForPlane(uint32_t charset, uint32_t plane, void *bitmap, bool isInverted); - -CF_EXPORT uint32_t CFUniCharGetNumberOfPlanes(uint32_t charset); - enum { kCFUniCharToLowercase = 0, kCFUniCharToUppercase, @@ -113,8 +109,6 @@ enum { CF_EXPORT CFIndex CFUniCharMapCaseTo(UTF32Char theChar, UTF16Char *convertedChar, CFIndex maxLength, uint32_t ctype, uint32_t flags, const uint8_t *langCode); -CF_EXPORT uint32_t CFUniCharGetConditionalCaseMappingFlags(UTF32Char theChar, UTF16Char *buffer, CFIndex currentIndex, CFIndex length, uint32_t type, const uint8_t *langCode, uint32_t lastFlags); - enum { kCFUniCharBiDiPropertyON = 0, kCFUniCharBiDiPropertyL, @@ -170,8 +164,6 @@ CF_INLINE uint8_t CFUniCharGetCombiningPropertyForCharacter(UTF16Char character, } CF_EXPORT const void *CFUniCharGetUnicodePropertyDataForPlane(uint32_t propertyType, uint32_t plane); -CF_EXPORT uint32_t CFUniCharGetNumberOfPlanesForUnicodePropertyData(uint32_t propertyType); -CF_EXPORT uint32_t CFUniCharGetUnicodeProperty(UTF32Char character, uint32_t propertyType); CF_EXPORT bool CFUniCharFillDestinationBuffer(const UTF32Char *src, CFIndex srcLength, void **dst, CFIndex dstLength, CFIndex *filledLength, uint32_t dstFormat); diff --git a/CoreFoundation/StringEncodings.subproj/CFUniCharPriv.h b/CoreFoundation/StringEncodings.subproj/CFUniCharPriv.h index d2ded5cfe9..66abedf924 100644 --- a/CoreFoundation/StringEncodings.subproj/CFUniCharPriv.h +++ b/CoreFoundation/StringEncodings.subproj/CFUniCharPriv.h @@ -1,7 +1,7 @@ /* CFUniCharPriv.h - Copyright (c) 1998-2017, Apple Inc. and the Swift project authors + Copyright (c) 1998-2018, Apple Inc. and the Swift project authors - Portions Copyright (c) 2014-2017, Apple Inc. and the Swift project authors + Portions Copyright (c) 2014-2018, Apple Inc. and the Swift project authors Licensed under Apache License v2.0 with Runtime Library Exception See http://swift.org/LICENSE.txt for license information See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors @@ -24,7 +24,19 @@ enum { kCFUniCharCompatibilityDecompMapping }; -CF_EXPORT const void *CFUniCharGetMappingData(uint32_t type); +CF_PRIVATE const void *CFUniCharGetMappingData(uint32_t type); + +CF_PRIVATE uint8_t CFUniCharGetBitmapForPlane(uint32_t charset, uint32_t plane, void *bitmap, bool isInverted); + +CF_PRIVATE uint32_t CFUniCharGetNumberOfPlanes(uint32_t charset); + +CF_PRIVATE uint32_t CFUniCharGetConditionalCaseMappingFlags(UTF32Char theChar, UTF16Char *buffer, CFIndex currentIndex, CFIndex length, uint32_t type, const uint8_t *langCode, uint32_t lastFlags); + +CF_PRIVATE uint32_t CFUniCharGetNumberOfPlanesForUnicodePropertyData(uint32_t propertyType); +CF_PRIVATE uint32_t CFUniCharGetUnicodeProperty(UTF32Char character, uint32_t propertyType); + +// As you can see, this function cannot precompose Hangul Jamo +CF_PRIVATE UTF32Char CFUniCharPrecomposeCharacter(UTF32Char base, UTF32Char combining); #endif /* ! __COREFOUNDATION_CFUNICHARPRIV__ */ diff --git a/CoreFoundation/StringEncodings.subproj/CFUnicodeDecomposition.c b/CoreFoundation/StringEncodings.subproj/CFUnicodeDecomposition.c index 68f5242aec..ba0ee1a230 100644 --- a/CoreFoundation/StringEncodings.subproj/CFUnicodeDecomposition.c +++ b/CoreFoundation/StringEncodings.subproj/CFUnicodeDecomposition.c @@ -1,7 +1,7 @@ /* CFUnicodeDecomposition.c - Copyright (c) 1999-2017, Apple Inc. and the Swift project authors + Copyright (c) 1999-2018, Apple Inc. and the Swift project authors - Portions Copyright (c) 2014-2017, Apple Inc. and the Swift project authors + Portions Copyright (c) 2014-2018, Apple Inc. and the Swift project authors Licensed under Apache License v2.0 with Runtime Library Exception See http://swift.org/LICENSE.txt for license information See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors diff --git a/CoreFoundation/StringEncodings.subproj/CFUnicodeDecomposition.h b/CoreFoundation/StringEncodings.subproj/CFUnicodeDecomposition.h index 5414930e30..10396d2dc8 100644 --- a/CoreFoundation/StringEncodings.subproj/CFUnicodeDecomposition.h +++ b/CoreFoundation/StringEncodings.subproj/CFUnicodeDecomposition.h @@ -3,9 +3,9 @@ CoreFoundation Created by aki on Wed Oct 03 2001. - Copyright (c) 2001-2017, Apple Inc. and the Swift project authors + Copyright (c) 2001-2018, Apple Inc. and the Swift project authors - Portions Copyright (c) 2014-2017, Apple Inc. and the Swift project authors + Portions Copyright (c) 2014-2018, Apple Inc. and the Swift project authors Licensed under Apache License v2.0 with Runtime Library Exception See http://swift.org/LICENSE.txt for license information See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors @@ -25,7 +25,6 @@ CF_INLINE bool CFUniCharIsDecomposableCharacter(UTF32Char character, bool isHFSP } CF_EXPORT CFIndex CFUniCharDecomposeCharacter(UTF32Char character, UTF32Char *convertedChars, CFIndex maxBufferLength); -CF_EXPORT CFIndex CFUniCharCompatibilityDecompose(UTF32Char *convertedChars, CFIndex length, CFIndex maxBufferLength); CF_EXPORT bool CFUniCharDecompose(const UTF16Char *src, CFIndex length, CFIndex *consumedLength, void *dst, CFIndex maxLength, CFIndex *filledLength, bool needToReorder, uint32_t dstFormat, bool isHFSPlus); CF_EXPORT bool CFUniCharDecomposeWithErrorLocation(const UTF16Char *src, CFIndex length, CFIndex *consumedLength, void *dst, CFIndex maxLength, CFIndex *filledLength, bool needToReorder, uint32_t dstFormat, bool isHFSPlus, CFIndex *charIndex); diff --git a/CoreFoundation/StringEncodings.subproj/CFUnicodePrecomposition.c b/CoreFoundation/StringEncodings.subproj/CFUnicodePrecomposition.c index 26a73bcc75..6051edf9e5 100644 --- a/CoreFoundation/StringEncodings.subproj/CFUnicodePrecomposition.c +++ b/CoreFoundation/StringEncodings.subproj/CFUnicodePrecomposition.c @@ -1,7 +1,7 @@ /* CFUnicodePrecomposition.c - Copyright (c) 1999-2017, Apple Inc. and the Swift project authors + Copyright (c) 1999-2018, Apple Inc. and the Swift project authors - Portions Copyright (c) 2014-2017, Apple Inc. and the Swift project authors + Portions Copyright (c) 2014-2018, Apple Inc. and the Swift project authors Licensed under Apache License v2.0 with Runtime Library Exception See http://swift.org/LICENSE.txt for license information See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors diff --git a/CoreFoundation/StringEncodings.subproj/CFUnicodePrecomposition.h b/CoreFoundation/StringEncodings.subproj/CFUnicodePrecomposition.h index 34acabf7e9..cb00434039 100644 --- a/CoreFoundation/StringEncodings.subproj/CFUnicodePrecomposition.h +++ b/CoreFoundation/StringEncodings.subproj/CFUnicodePrecomposition.h @@ -3,9 +3,9 @@ CoreFoundation Created by aki on Wed Oct 03 2001. - Copyright (c) 2001-2017, Apple Inc. and the Swift project authors + Copyright (c) 2001-2018, Apple Inc. and the Swift project authors - Portions Copyright (c) 2014-2017, Apple Inc. and the Swift project authors + Portions Copyright (c) 2014-2018, Apple Inc. and the Swift project authors Licensed under Apache License v2.0 with Runtime Library Exception See http://swift.org/LICENSE.txt for license information See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors @@ -18,9 +18,6 @@ CF_EXTERN_C_BEGIN -// As you can see, this function cannot precompose Hangul Jamo -CF_EXPORT UTF32Char CFUniCharPrecomposeCharacter(UTF32Char base, UTF32Char combining); - CF_EXPORT bool CFUniCharPrecompose(const UTF16Char *characters, CFIndex length, CFIndex *consumedLength, UTF16Char *precomposed, CFIndex maxLength, CFIndex *filledLength); CF_EXTERN_C_END diff --git a/CoreFoundation/URL.subproj/CFURL.c b/CoreFoundation/URL.subproj/CFURL.c index 3e25b4f756..be10d9d92b 100644 --- a/CoreFoundation/URL.subproj/CFURL.c +++ b/CoreFoundation/URL.subproj/CFURL.c @@ -1,7 +1,7 @@ /* CFURL.c - Copyright (c) 1998-2017, Apple Inc. and the Swift project authors + Copyright (c) 1998-2018, Apple Inc. and the Swift project authors - Portions Copyright (c) 2014-2017, Apple Inc. and the Swift project authors + Portions Copyright (c) 2014-2018, Apple Inc. and the Swift project authors Licensed under Apache License v2.0 with Runtime Library Exception See http://swift.org/LICENSE.txt for license information See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors @@ -13,7 +13,9 @@ #include #include #include "CFInternal.h" +#include "CFRuntime_Internal.h" #include +#include #include #include #include @@ -25,10 +27,10 @@ #include #include #include -#if __has_include() -#include -#else +#if __has_include() #include +#else +#include #endif #include #endif @@ -1631,9 +1633,7 @@ static void __CFURLDeallocate(CFTypeRef cf) { atomic_store(&((struct __CFURL *)url)->_resourceInfo, (void *)0xdeadbeef); // 20362546: catch anyone using URL after it was released } -static CFTypeID __kCFURLTypeID = _kCFRuntimeNotATypeID; - -static const CFRuntimeClass __CFURLClass = { +const CFRuntimeClass __CFURLClass = { 0, // version "CFURL", // className NULL, // init @@ -1654,9 +1654,7 @@ CF_INLINE CFURLRef _CFURLFromNSURL(CFURLRef url) { } CFTypeID CFURLGetTypeID(void) { - static dispatch_once_t initOnce; - dispatch_once(&initOnce, ^{ __kCFURLTypeID = _CFRuntimeRegisterClass(&__CFURLClass); }); - return __kCFURLTypeID; + return _kCFRuntimeIDCFURL; } CF_PRIVATE void CFShowURL(CFURLRef url) { @@ -4354,7 +4352,7 @@ static Boolean _fileSystemRepresentationHasFileIDPrefix(const UInt8 *buffer, CFI static Boolean _pathHasFileIDPrefix(CFStringRef path) { // path is not NULL, path has prefix "/.file/id=". -#ifdef __CONSTANT_STRINGS__ +#if defined(__CONSTANT_CFSTRINGS__) && !DEPLOYMENT_RUNTIME_SWIFT // see rdar://44356272 — the implementation of CFSTR() in Swift is not constexpr, but the compiler will miscompile it and allow it to be assigned to static variables anyway. static const #endif CFStringRef fileIDPreamble = CFSTR(FILE_ID_PREAMBLE); @@ -4374,7 +4372,7 @@ CF_EXPORT CFStringRef CFURLCopyFileSystemPath(CFURLRef anURL, CFURLPathStyle pat if ( (pathStyle == kCFURLPOSIXPathStyle) && (CFURLGetBaseURL(anURL) == NULL) ) { if ( !CF_IS_OBJC(CFURLGetTypeID(), anURL) ) { - // We can grope the ivars + // We can access the ivars isCanonicalFileURL = ((anURL->_flags & IS_CANONICAL_FILE_URL) != 0); if ( isCanonicalFileURL ) { CFIndex strLength = CFStringGetLength(CFURLGetString(anURL)); @@ -4415,7 +4413,7 @@ CFStringRef CFURLCreateStringWithFileSystemPath(CFAllocatorRef allocator, CFURLR CFStringRef relPath = NULL; if (!CF_IS_OBJC(CFURLGetTypeID(), anURL)) { - // We can grope the ivars + // We can access the ivars if (fsType == kCFURLPOSIXPathStyle) { if (anURL->_flags & POSIX_AND_URL_PATHS_MATCH) { relPath = _retainedComponentString(anURL, HAS_PATH, true, true); @@ -4497,7 +4495,7 @@ Boolean CFURLGetFileSystemRepresentation(CFURLRef url, Boolean resolveAgainstBas #if DEPLOYMENT_TARGET_MACOSX || DEPLOYMENT_TARGET_EMBEDDED || DEPLOYMENT_TARGET_EMBEDDED_MINI || DEPLOYMENT_TARGET_LINUX if ( !resolveAgainstBase || (CFURLGetBaseURL(url) == NULL) ) { if (!CF_IS_OBJC(CFURLGetTypeID(), url)) { - // We can grope the ivars + // We can access the ivars if ( url->_flags & IS_CANONICAL_FILE_URL ) { return CanonicalFileURLStringToFileSystemRepresentation(url->_string, buffer, bufLen); } diff --git a/CoreFoundation/URL.subproj/CFURL.h b/CoreFoundation/URL.subproj/CFURL.h index 11c96516d8..1e1346982b 100644 --- a/CoreFoundation/URL.subproj/CFURL.h +++ b/CoreFoundation/URL.subproj/CFURL.h @@ -1,7 +1,7 @@ /* CFURL.h - Copyright (c) 1998-2017, Apple Inc. and the Swift project authors + Copyright (c) 1998-2018, Apple Inc. and the Swift project authors - Portions Copyright (c) 2014-2017, Apple Inc. and the Swift project authors + Portions Copyright (c) 2014-2018, Apple Inc. and the Swift project authors Licensed under Apache License v2.0 with Runtime Library Exception See http://swift.org/LICENSE.txt for license information See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors diff --git a/CoreFoundation/URL.subproj/CFURL.inc.h b/CoreFoundation/URL.subproj/CFURL.inc.h index 0d3a97ddc0..78e4ed5652 100644 --- a/CoreFoundation/URL.subproj/CFURL.inc.h +++ b/CoreFoundation/URL.subproj/CFURL.inc.h @@ -1,7 +1,7 @@ /* CFURL.inc.h - Copyright (c) 2012-2017, Apple Inc. and the Swift project authors + Copyright (c) 2012-2018, Apple Inc. and the Swift project authors - Portions Copyright (c) 2014-2017, Apple Inc. and the Swift project authors + Portions Copyright (c) 2014-2018, Apple Inc. and the Swift project authors Licensed under Apache License v2.0 with Runtime Library Exception See http://swift.org/LICENSE.txt for license information See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors diff --git a/CoreFoundation/URL.subproj/CFURLAccess.c b/CoreFoundation/URL.subproj/CFURLAccess.c index 71808f1a23..29bae7b2d3 100644 --- a/CoreFoundation/URL.subproj/CFURLAccess.c +++ b/CoreFoundation/URL.subproj/CFURLAccess.c @@ -1,7 +1,7 @@ /* CFURLAccess.c - Copyright (c) 1999-2017, Apple Inc. and the Swift project authors + Copyright (c) 1999-2018, Apple Inc. and the Swift project authors - Portions Copyright (c) 2014-2017, Apple Inc. and the Swift project authors + Portions Copyright (c) 2014-2018, Apple Inc. and the Swift project authors Licensed under Apache License v2.0 with Runtime Library Exception See http://swift.org/LICENSE.txt for license information See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors diff --git a/CoreFoundation/URL.subproj/CFURLAccess.h b/CoreFoundation/URL.subproj/CFURLAccess.h index 28aa9d243d..e0de85fc62 100644 --- a/CoreFoundation/URL.subproj/CFURLAccess.h +++ b/CoreFoundation/URL.subproj/CFURLAccess.h @@ -1,7 +1,7 @@ /* CFURLAccess.h - Copyright (c) 1998-2017, Apple Inc. and the Swift project authors + Copyright (c) 1998-2018, Apple Inc. and the Swift project authors - Portions Copyright (c) 2014-2017, Apple Inc. and the Swift project authors + Portions Copyright (c) 2014-2018, Apple Inc. and the Swift project authors Licensed under Apache License v2.0 with Runtime Library Exception See http://swift.org/LICENSE.txt for license information See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors diff --git a/CoreFoundation/URL.subproj/CFURLComponents.c b/CoreFoundation/URL.subproj/CFURLComponents.c index bc71a27656..17ce894042 100644 --- a/CoreFoundation/URL.subproj/CFURLComponents.c +++ b/CoreFoundation/URL.subproj/CFURLComponents.c @@ -1,25 +1,19 @@ -// This source file is part of the Swift.org open source project -// -// Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors -// Licensed under Apache License v2.0 with Runtime Library Exception -// -// See http://swift.org/LICENSE.txt for license information -// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors -// - - /* CFURLComponents.c - Copyright (c) 2015, Apple Inc. All rights reserved. + Copyright (c) 2015-2018, Apple Inc. All rights reserved. + + Portions Copyright (c) 2014-2018, Apple Inc. and the Swift project authors + Licensed under Apache License v2.0 with Runtime Library Exception + See http://swift.org/LICENSE.txt for license information + See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors Responsibility: Jim Luther/Chris Linn */ #include #include "CFInternal.h" +#include "CFRuntime_Internal.h" #include "CFURLComponents_Internal.h" -static CFTypeID __kCFURLComponentsTypeID = _kCFRuntimeNotATypeID; - struct __CFURLComponents { CFRuntimeBase _base; @@ -61,13 +55,33 @@ struct __CFURLComponents { }; static Boolean __CFURLComponentsEqual(CFTypeRef left, CFTypeRef right); +static CFHashCode __CFURLComponentsHash(CFTypeRef cf); static CFStringRef __CFURLComponentsCopyDescription(CFTypeRef cf) { - return CFRetain(CFSTR("A really nice CFURLComponents object")); + CFURLComponentsRef components = (CFURLComponentsRef)cf; + CFStringRef scheme = _CFURLComponentsCopyScheme(components); + CFStringRef percentEncodedUser = _CFURLComponentsCopyPercentEncodedUser(components); + CFStringRef percentEncodedPassword = _CFURLComponentsCopyPercentEncodedPassword(components); + CFStringRef percentEncodedHost = _CFURLComponentsCopyPercentEncodedHost(components); + CFNumberRef port = _CFURLComponentsCopyPort(components); + CFStringRef percentEncodedPath = _CFURLComponentsCopyPercentEncodedPath(components); + CFStringRef percentEncodedQuery = _CFURLComponentsCopyPercentEncodedQuery(components); + CFStringRef percentEncodedFragment = _CFURLComponentsCopyPercentEncodedFragment(components); + CFStringRef result = CFStringCreateWithFormat(kCFAllocatorSystemDefault, NULL, CFSTR(" {scheme = %@, user = %@, password = %@, host = %@, port = %@, path = %@, query = %@, fragment = %@}"), cf, scheme, percentEncodedUser, percentEncodedPassword, percentEncodedHost, port, percentEncodedPath, percentEncodedQuery, percentEncodedFragment); + if ( scheme ) CFRelease(scheme); + if ( percentEncodedUser ) CFRelease(percentEncodedUser); + if ( percentEncodedPassword ) CFRelease(percentEncodedPassword); + if ( percentEncodedHost ) CFRelease(percentEncodedHost); + if ( port ) CFRelease(port); + if ( percentEncodedPath ) CFRelease(percentEncodedPath); + if ( percentEncodedQuery ) CFRelease(percentEncodedQuery); + if ( percentEncodedFragment ) CFRelease(percentEncodedFragment); + return ( result ); } -CF_CROSS_PLATFORM_EXPORT void __CFURLComponentsDeallocate(CFURLComponentsRef instance) { - __CFGenericValidateType(instance, _CFURLComponentsGetTypeID()); +CF_CROSS_PLATFORM_EXPORT void __CFURLComponentsDeallocate(CFTypeRef cf) { + CFURLComponentsRef instance = (CFURLComponentsRef)cf; + __CFGenericValidateType(cf, _CFURLComponentsGetTypeID()); if (instance->_urlString) CFRelease(instance->_urlString); if (instance->_schemeComponent) CFRelease(instance->_schemeComponent); @@ -78,25 +92,22 @@ CF_CROSS_PLATFORM_EXPORT void __CFURLComponentsDeallocate(CFURLComponentsRef ins if (instance->_pathComponent) CFRelease(instance->_pathComponent); if (instance->_queryComponent) CFRelease(instance->_queryComponent); if (instance->_fragmentComponent) CFRelease(instance->_fragmentComponent); - if (instance) CFAllocatorDeallocate(kCFAllocatorSystemDefault, instance); } -static const CFRuntimeClass __CFURLComponentsClass = { +const CFRuntimeClass __CFURLComponentsClass = { 0, "CFURLComponents", NULL, // init NULL, // copy __CFURLComponentsDeallocate, __CFURLComponentsEqual, - NULL, // hash + __CFURLComponentsHash, NULL, // __CFURLComponentsCopyDescription }; CFTypeID _CFURLComponentsGetTypeID(void) { - static dispatch_once_t initOnce; - dispatch_once(&initOnce, ^{ __kCFURLComponentsTypeID = _CFRuntimeRegisterClass(&__CFURLComponentsClass); }); - return __kCFURLComponentsTypeID; + return _kCFRuntimeIDCFURLComponents; } CF_EXPORT CFURLComponentsRef _CFURLComponentsCreate(CFAllocatorRef alloc) { @@ -182,7 +193,9 @@ CF_EXPORT CFURLComponentsRef _CFURLComponentsCreateWithString(CFAllocatorRef all if (memory->_parseInfo.paramExists) { CFStringRef path = _CFURLComponentsCopyPath(memory); _CFURLComponentsSetPath(memory, path); - CFRelease(path); + if ( path ) { + CFRelease(path); + } } return memory; @@ -198,12 +211,12 @@ CF_EXPORT CFURLComponentsRef _CFURLComponentsCreateCopy(CFAllocatorRef alloc, CF __CFLock(&components->_lock); memory->_lock = CFLockInit; memory->_urlString = components->_urlString ? CFStringCreateCopy(alloc, components->_urlString) : NULL; + memory->_parseInfo = components->_parseInfo; memory->_schemeComponentValid = components->_schemeComponentValid; memory->_userComponentValid = components->_userComponentValid; memory->_hostComponentValid = components->_hostComponentValid; - memory->_passwordComponentValid = components->_passwordComponentValid; memory->_portComponentValid = components->_portComponentValid; memory->_pathComponentValid = components->_pathComponentValid; memory->_queryComponentValid = components->_queryComponentValid; @@ -235,85 +248,102 @@ static Boolean __CFURLComponentsEqual(CFTypeRef cf1, CFTypeRef cf2) { CFURLComponentsRef left = (CFURLComponentsRef)cf1; CFURLComponentsRef right = (CFURLComponentsRef)cf2; - __CFGenericValidateType(left, CFURLGetTypeID()); - __CFGenericValidateType(right, CFURLGetTypeID()); + __CFGenericValidateType(left, _CFURLComponentsGetTypeID()); + __CFGenericValidateType(right, _CFURLComponentsGetTypeID()); if (left == right) { return true; } Boolean (^componentEqual)(CFTypeRef l, CFTypeRef r) = ^(CFTypeRef l, CFTypeRef r) { - // if pointers are equal (including both nil), they are equal; otherwise, use isEqual + // if pointers are equal (including both nil), they are equal; otherwise, use isEqual if both l and r are not NULL; otherwise return false if (l == r) { return (Boolean)true; - } else { - return CFEqual(left, r); + } else if ( l && r ){ + return CFEqual(l, r); + } + else { + return (Boolean)false; } }; + Boolean result = false; + + // check in the order of mostly likely to fail (or even exist) so that if they are different, we spend less time here. CFStringRef leftPath = _CFURLComponentsCopyPercentEncodedPath(left); CFStringRef rightPath = _CFURLComponentsCopyPercentEncodedPath(right); - - CFStringRef leftHost = _CFURLComponentsCopyPercentEncodedHost(left); - CFStringRef rightHost = _CFURLComponentsCopyPercentEncodedHost(right); - - CFStringRef leftQuery = _CFURLComponentsCopyPercentEncodedQuery(left); - CFStringRef rightQuery = _CFURLComponentsCopyPercentEncodedQuery(right); - - CFStringRef leftFragment = _CFURLComponentsCopyPercentEncodedFragment(left); - CFStringRef rightFragment = _CFURLComponentsCopyPercentEncodedFragment(right); - - CFStringRef leftUser = _CFURLComponentsCopyPercentEncodedUser(left); - CFStringRef rightUser = _CFURLComponentsCopyPercentEncodedUser(right); - - CFStringRef leftPassword = _CFURLComponentsCopyPercentEncodedPassword(left); - CFStringRef rightPassword = _CFURLComponentsCopyPercentEncodedPassword(right); - - - Boolean result = - componentEqual(left->_schemeComponent, right->_schemeComponent) && - componentEqual(leftPath, rightPath) && - componentEqual(leftHost, rightHost) && - componentEqual(left->_portComponent, right->_portComponent) && - componentEqual(leftQuery, rightQuery) && - componentEqual(leftFragment, rightFragment) && - componentEqual(leftUser, rightUser) && - componentEqual(leftPassword, rightPassword); - + if ( componentEqual(leftPath, rightPath) ) { + CFStringRef leftScheme = _CFURLComponentsCopyScheme(left); + CFStringRef rightScheme = _CFURLComponentsCopyScheme(right); + if ( componentEqual(leftScheme, rightScheme) ) { + CFStringRef leftHost = _CFURLComponentsCopyPercentEncodedHost(left); + CFStringRef rightHost = _CFURLComponentsCopyPercentEncodedHost(right); + if ( componentEqual(leftHost, rightHost) ) { + CFNumberRef leftPort = _CFURLComponentsCopyPort(left); + CFNumberRef rightPort = _CFURLComponentsCopyPort(right); + if ( componentEqual(leftPort, rightPort) ) { + CFStringRef leftQuery = _CFURLComponentsCopyPercentEncodedQuery(left); + CFStringRef rightQuery = _CFURLComponentsCopyPercentEncodedQuery(right); + if ( componentEqual(leftQuery, rightQuery) ) { + CFStringRef leftFragment = _CFURLComponentsCopyPercentEncodedFragment(left); + CFStringRef rightFragment = _CFURLComponentsCopyPercentEncodedFragment(right); + if ( componentEqual(leftFragment, rightFragment) ) { + CFStringRef leftUser = _CFURLComponentsCopyPercentEncodedUser(left); + CFStringRef rightUser = _CFURLComponentsCopyPercentEncodedUser(right); + if ( componentEqual(leftUser, rightUser) ) { + CFStringRef leftPassword = _CFURLComponentsCopyPercentEncodedPassword(left); + CFStringRef rightPassword = _CFURLComponentsCopyPercentEncodedPassword(right); + if ( componentEqual(leftPassword, rightPassword) ) { + result = true; + } + if (leftPassword) CFRelease(leftPassword); + if (rightPassword) CFRelease(rightPassword); + } + if (leftUser) CFRelease(leftUser); + if (rightUser) CFRelease(rightUser); + } + if (leftFragment) CFRelease(leftFragment); + if (rightFragment) CFRelease(rightFragment); + } + if (leftQuery) CFRelease(leftQuery); + if (rightQuery) CFRelease(rightQuery); + } + if (leftPort) CFRelease(leftPort); + if (rightPort) CFRelease(rightPort); + } + if (leftHost) CFRelease(leftHost); + if (rightHost) CFRelease(rightHost); + } + if (leftScheme) CFRelease(leftScheme); + if (rightScheme) CFRelease(rightScheme); + } if (leftPath) CFRelease(leftPath); if (rightPath) CFRelease(rightPath); - if (leftHost) CFRelease(leftHost); - if (rightHost) CFRelease(rightHost); - - if (leftQuery) CFRelease(leftQuery); - if (rightQuery) CFRelease(rightQuery); - - if (leftFragment) CFRelease(leftFragment); - if (rightFragment) CFRelease(rightFragment); - - if (leftUser) CFRelease(leftUser); - if (rightUser) CFRelease(rightUser); - - if (leftPassword) CFRelease(leftPassword); - if (rightPassword) CFRelease(rightPassword); - return result; } +static CFHashCode __CFURLComponentsHash(CFTypeRef cf) { + CFHashCode result = 0; + // there is always a path (it might be an empty string) and that's enough to get a hash + CFStringRef strComponent = _CFURLComponentsCopyPercentEncodedPath((CFURLComponentsRef)cf); + result = CFHash(strComponent); + CFRelease(strComponent); + return ( result ); +} + CF_EXPORT CFURLRef _CFURLComponentsCopyURL(CFURLComponentsRef components) { return _CFURLComponentsCopyURLRelativeToURL(components, NULL); } CF_EXPORT CFURLRef _CFURLComponentsCopyURLRelativeToURL(CFURLComponentsRef components, CFURLRef relativeToURL) { + CFURLRef result = NULL; CFStringRef urlString = _CFURLComponentsCopyString(components); if (urlString) { - CFURLRef url = CFURLCreateWithString(kCFAllocatorSystemDefault, urlString, relativeToURL); + result = CFURLCreateWithString(kCFAllocatorSystemDefault, urlString, relativeToURL); CFRelease(urlString); - return url; - } else { - return NULL; } + return ( result ); } CF_EXPORT CFStringRef _CFURLComponentsCopyString(CFURLComponentsRef components) { @@ -476,7 +506,23 @@ CF_EXPORT CFStringRef _CFURLComponentsCopyUser(CFURLComponentsRef components) { components->_userComponent = CreateComponentWithURLStringRange(components->_urlString, _CFURIParserGetUserinfoNameRange(&components->_parseInfo, false)); components->_userComponentValid = true; } - result = components->_userComponent ? _CFStringCreateByRemovingPercentEncoding(kCFAllocatorSystemDefault, components->_userComponent) : NULL; + if ( components->_userComponent ) { + result = _CFStringCreateByRemovingPercentEncoding(kCFAllocatorSystemDefault, components->_userComponent); + } + else { + // ensure the password subcomponent is valid + if ( !components->_passwordComponentValid ) { + components->_passwordComponent = CreateComponentWithURLStringRange(components->_urlString, _CFURIParserGetUserinfoPasswordRange(&components->_parseInfo, false)); + components->_passwordComponentValid = true; + } + if ( components->_passwordComponent ) { + // if there's a password subcomponent, then there has to be a user subcomponent + result = CFRetain(CFSTR("")); + } + else { + result = NULL; + } + } __CFUnlock(&components->_lock); return ( result ); @@ -496,6 +542,60 @@ CF_EXPORT CFStringRef _CFURLComponentsCopyPassword(CFURLComponentsRef components return ( result ); } +static void _SetValidPortComponent(CFURLComponentsRef components) { + enum { + kDefaultBuffersize = 20, // The maximum port number we can represent is 9223372036854775807 (LLONG_MAX) which is 19 digits, so the stack allocated buffer will work for all valid port numbers with no leading zeros + }; + if ( !components->_portComponentValid ) { + // if there's not a valid port, _portComponent should be nil + components->_portComponent = NULL; + + CFRange range = _CFURIParserGetPortRange(&components->_parseInfo, false); + // rfc3986 says URI producers should omit the port component and its ":" delimiter if port is empty. + if ( (range.location != kCFNotFound) && (range.length != 0) ) { + // _CFURIParserURLStringIsValid has already ensured the characters in the port range are valid DIGIT characters. + + // determine the buffer size needed, and use either the stack allocated buffer or a malloced buffer + CFIndex neededBufSize = CFStringGetMaximumSizeForEncoding(range.length, kCFStringEncodingASCII) + 1; + STACK_BUFFER_DECL(char, stackBuffer, kDefaultBuffersize); + char *buf = NULL; + CFIndex bufSize; + if ( neededBufSize <= kDefaultBuffersize ) { + // use stackBuffer + buf = &stackBuffer[0]; + bufSize = kDefaultBuffersize; + } + else { + // buf not big enough? malloc it. + buf = (char *)malloc(neededBufSize); + bufSize = neededBufSize; + } + + if ( buf ) { + // get the bytes into buf + CFIndex usedBufLen; + if ( CFStringGetBytes(components->_urlString, range, kCFStringEncodingASCII, 0, false, (UInt8 *)buf, bufSize, &usedBufLen) != 0 ) { + buf[usedBufLen] = '\0'; // null terminate the string + // convert to a long long + errno = 0; + long long value = strtoll(buf, NULL, 10); + // make sure there wasn't underflow or overflow (ERANGE), and value is not negative + if ( (errno != ERANGE) && (value >= 0) ) { + // create the port number + components->_portComponent = CFNumberCreate(kCFAllocatorSystemDefault, kCFNumberLongLongType, &value); + } + } + + // free the buf if malloced + if ( buf != stackBuffer ) { + free(buf); + } + } + } + components->_portComponentValid = true; + } +} + CF_EXPORT CFStringRef _CFURLComponentsCopyHost(CFURLComponentsRef components) { CFStringRef result; @@ -504,7 +604,45 @@ CF_EXPORT CFStringRef _CFURLComponentsCopyHost(CFURLComponentsRef components) { components->_hostComponent = CreateComponentWithURLStringRange(components->_urlString, _CFURIParserGetHostRange(&components->_parseInfo, false)); components->_hostComponentValid = true; } - result = components->_hostComponent ? _CFStringCreateByRemovingPercentEncoding(kCFAllocatorSystemDefault, components->_hostComponent) : NULL; + if ( components->_hostComponent ) { + result = _CFStringCreateByRemovingPercentEncoding(kCFAllocatorSystemDefault, components->_hostComponent); + } + else { + // force initialization of the other authority subcomponents in the order I think they are likely to be present: port, user, password + + // ensure the port subcomponent is valid + _SetValidPortComponent(components); + + if ( components->_portComponent ) { + // if there's a port subcomponent, then there has to be a host subcomponent + result = CFRetain(CFSTR("")); + } + else { + // ensure the user subcomponent is valid + if ( !components->_userComponentValid ) { + components->_userComponent = CreateComponentWithURLStringRange(components->_urlString, _CFURIParserGetUserinfoNameRange(&components->_parseInfo, false)); + components->_userComponentValid = true; + } + if ( components->_userComponent ) { + // if there's a user subcomponent, then there has to be a host subcomponent + result = CFRetain(CFSTR("")); + } + else { + // ensure the password subcomponent is valid + if ( !components->_passwordComponentValid ) { + components->_passwordComponent = CreateComponentWithURLStringRange(components->_urlString, _CFURIParserGetUserinfoPasswordRange(&components->_parseInfo, false)); + components->_passwordComponentValid = true; + } + if ( components->_passwordComponent ) { + // if there's a password subcomponent, then there has to be a host subcomponent + result = CFRetain(CFSTR("")); + } + else { + result = NULL; + } + } + } + } __CFUnlock(&components->_lock); return ( result ); @@ -514,33 +652,7 @@ CF_EXPORT CFNumberRef _CFURLComponentsCopyPort(CFURLComponentsRef components) { CFNumberRef result; __CFLock(&components->_lock); - if ( !components->_portComponentValid ) { - CFRange range = _CFURIParserGetPortRange(&components->_parseInfo, false); - // rfc3986 says URI producers should omit the port component and its ":" delimiter if port is empty. - if ( range.location != kCFNotFound && range.length != 0) { - CFStringRef portString = CFStringCreateWithSubstring(kCFAllocatorSystemDefault, components->_urlString, CFRangeMake(range.location, range.length)); - char buf[16]; - if (!CFStringGetCString(portString, buf, 16, kCFStringEncodingASCII)) { - HALT; - } - long long value; -#if DEPLOYMENT_TARGET_LINUX - if (sscanf(buf, "%lld", &value) != 1) { - HALT; - } -#else - if (sscanf_l(buf, NULL, "%lld", &value) != 1) { - HALT; - } -#endif - components->_portComponent = CFNumberCreate(kCFAllocatorSystemDefault, kCFNumberLongLongType, &value); - CFRelease(portString); - } - else { - components->_portComponent = nil; - } - components->_portComponentValid = true; - } + _SetValidPortComponent(components); result = components->_portComponent ? CFRetain(components->_portComponent) : NULL; __CFUnlock(&components->_lock); @@ -556,11 +668,11 @@ CF_EXPORT CFStringRef _CFURLComponentsCopyPath(CFURLComponentsRef components) { components->_pathComponentValid = true; } if (!components->_pathComponent) { - result = CFStringCreateCopy(kCFAllocatorSystemDefault, CFSTR("")); + result = CFRetain(CFSTR("")); } else { result = _CFStringCreateByRemovingPercentEncoding(kCFAllocatorSystemDefault, components->_pathComponent); if (!result) { - result = CFStringCreateCopy(kCFAllocatorSystemDefault, CFSTR("")); + result = CFRetain(CFSTR("")); } } __CFUnlock(&components->_lock); @@ -700,7 +812,23 @@ CF_EXPORT CFStringRef _CFURLComponentsCopyPercentEncodedUser(CFURLComponentsRef components->_userComponent = CreateComponentWithURLStringRange(components->_urlString, _CFURIParserGetUserinfoNameRange(&components->_parseInfo, false)); components->_userComponentValid = true; } - result = components->_userComponent ? CFRetain(components->_userComponent) : NULL; + if ( components->_userComponent ) { + result = CFRetain(components->_userComponent); + } + else { + // ensure the password subcomponent is valid + if ( !components->_passwordComponentValid ) { + components->_passwordComponent = CreateComponentWithURLStringRange(components->_urlString, _CFURIParserGetUserinfoPasswordRange(&components->_parseInfo, false)); + components->_passwordComponentValid = true; + } + if ( components->_passwordComponent ) { + // if there's a password subcomponent, then there has to be a user subcomponent + result = CFRetain(CFSTR("")); + } + else { + result = NULL; + } + } __CFUnlock(&components->_lock); return ( result ); @@ -728,7 +856,45 @@ CF_EXPORT CFStringRef _CFURLComponentsCopyPercentEncodedHost(CFURLComponentsRef components->_hostComponent = CreateComponentWithURLStringRange(components->_urlString, _CFURIParserGetHostRange(&components->_parseInfo, false)); components->_hostComponentValid = true; } - result = components->_hostComponent ? CFRetain(components->_hostComponent) : NULL; + if ( components->_hostComponent ) { + result = CFRetain(components->_hostComponent); + } + else { + // force initialization of the other authority subcomponents in the order I think they are likely to be present: port, user, password + + // ensure the port subcomponent is valid + _SetValidPortComponent(components); + + if ( components->_portComponent ) { + // if there's a port subcomponent, then there has to be a host subcomponent + result = CFRetain(CFSTR("")); + } + else { + // ensure the user subcomponent is valid + if ( !components->_userComponentValid ) { + components->_userComponent = CreateComponentWithURLStringRange(components->_urlString, _CFURIParserGetUserinfoNameRange(&components->_parseInfo, false)); + components->_userComponentValid = true; + } + if ( components->_userComponent ) { + // if there's a user subcomponent, then there has to be a host subcomponent + result = CFRetain(CFSTR("")); + } + else { + // ensure the password subcomponent is valid + if ( !components->_passwordComponentValid ) { + components->_passwordComponent = CreateComponentWithURLStringRange(components->_urlString, _CFURIParserGetUserinfoPasswordRange(&components->_parseInfo, false)); + components->_passwordComponentValid = true; + } + if ( components->_passwordComponent ) { + // if there's a password subcomponent, then there has to be a host subcomponent + result = CFRetain(CFSTR("")); + } + else { + result = NULL; + } + } + } + } __CFUnlock(&components->_lock); return ( result ); @@ -745,7 +911,7 @@ CF_EXPORT CFStringRef _CFURLComponentsCopyPercentEncodedPath(CFURLComponentsRef result = components->_pathComponent ? CFRetain(components->_pathComponent) : NULL; __CFUnlock(&components->_lock); - if (!result) result = CFStringCreateCopy(kCFAllocatorSystemDefault, CFSTR("")); + if (!result) result = CFRetain(CFSTR("")); return ( result ); } @@ -1018,8 +1184,12 @@ CF_EXPORT CFRange _CFURLComponentsGetRangeOfFragment(CFURLComponentsRef componen return ( _CFURIParserGetFragmentRange(theParseInfo, false) ); } -// Returns an array of dictionaries; each dictionary has two keys: "name", for the name, and "value" for the value. If one of the keys is missing then we did not populate that part of the entry. -CF_EXPORT CFArrayRef _CFURLComponentsCopyQueryItems(CFURLComponentsRef components) { +// keys for dictionaries returned by _CFURLComponentsCopyQueryItems +CONST_STRING_DECL(_kCFURLComponentsNameKey, "name") +CONST_STRING_DECL(_kCFURLComponentsValueKey, "value") + +// Returns an array of dictionaries; each dictionary has two keys: _kCFURLComponentsNameKey for the name, and _kCFURLComponentsValueKey for the value. If one of the keys is missing then we did not populate that part of the entry. +static CFArrayRef _CFURLComponentsCopyQueryItemsInternal(CFURLComponentsRef components, Boolean removePercentEncoding) { CFStringRef queryString = _CFURLComponentsCopyPercentEncodedQuery(components); CFArrayRef result = NULL; @@ -1046,15 +1216,21 @@ CF_EXPORT CFArrayRef _CFURLComponentsCopyQueryItems(CFURLComponentsRef component nameRange.length = idx - nameRange.location; if ( nameRange.length ) { nameString = CFStringCreateWithSubstring(kCFAllocatorSystemDefault, queryString, nameRange); - if ( sawPercent ) { + if ( removePercentEncoding && sawPercent ) { CFStringRef temp = _CFStringCreateByRemovingPercentEncoding(kCFAllocatorSystemDefault, nameString); CFRelease(nameString); - nameString = temp; + if ( temp ) { + nameString = temp; + } + else { + // the percent-decoded string had invalid UTF8 bytes - return an empty name string + nameString = CFRetain(CFSTR("")); + } sawPercent = false; } } else { - nameString = (CFStringRef)CFRetain(CFSTR("")); + nameString = CFRetain(CFSTR("")); } nameRange.location = kCFNotFound; valueRange.location = idx + 1; @@ -1068,7 +1244,7 @@ CF_EXPORT CFArrayRef _CFURLComponentsCopyQueryItems(CFURLComponentsRef component valueRange.length = idx - valueRange.location; if ( valueRange.length ) { valueString = CFStringCreateWithSubstring(kCFAllocatorSystemDefault, queryString, valueRange); - if ( sawPercent ) { + if ( removePercentEncoding && sawPercent ) { CFStringRef temp = _CFStringCreateByRemovingPercentEncoding(kCFAllocatorSystemDefault, valueString); CFRelease(valueString); valueString = temp; @@ -1076,35 +1252,42 @@ CF_EXPORT CFArrayRef _CFURLComponentsCopyQueryItems(CFURLComponentsRef component } } else { - valueString = (CFStringRef)CFRetain(CFSTR("")); + valueString = CFRetain(CFSTR("")); } - CFStringRef name = CFSTR("name"); - CFTypeRef keys[] = {name, CFSTR("value")}; + CFTypeRef keys[] = {_kCFURLComponentsNameKey, _kCFURLComponentsValueKey}; CFTypeRef values[] = {nameString, valueString}; - CFDictionaryRef entry = CFDictionaryCreate(kCFAllocatorSystemDefault, keys, values, 2, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks); + // valueString will be NULL if the percent-decoded string had invalid UTF8 bytes + CFDictionaryRef entry = CFDictionaryCreate(kCFAllocatorSystemDefault, keys, values, valueString ? 2 : 1, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks); CFArrayAppendValue(intermediateResult, entry); CFRelease(entry); valueRange.location = kCFNotFound; CFRelease(nameString); - CFRelease(valueString); + if ( valueString ) { + CFRelease(valueString); + } } else { // there was no value string, so this was the end of the name string nameRange.length = idx - nameRange.location; if ( nameRange.length ) { nameString = CFStringCreateWithSubstring(kCFAllocatorSystemDefault, queryString, nameRange); - if ( sawPercent ) { + if ( removePercentEncoding && sawPercent ) { CFStringRef temp = _CFStringCreateByRemovingPercentEncoding(kCFAllocatorSystemDefault, nameString); CFRelease(nameString); - nameString = temp; + if ( temp ) { + nameString = temp; + } + else { + // the percent-decoded string had invalid UTF8 bytes - return an empty name string + nameString = CFRetain(CFSTR("")); + } sawPercent = false; } } else { - nameString = (CFStringRef)CFRetain(CFSTR("")); + nameString = CFSTR(""); } - CFStringRef name = CFSTR("name"); - CFTypeRef keys[] = {name}; + CFTypeRef keys[] = {_kCFURLComponentsNameKey}; CFTypeRef values[] = {nameString}; CFDictionaryRef entry = CFDictionaryCreate(kCFAllocatorSystemDefault, keys, values, 1, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks); CFArrayAppendValue(intermediateResult, entry); @@ -1113,8 +1296,8 @@ CF_EXPORT CFArrayRef _CFURLComponentsCopyQueryItems(CFURLComponentsRef component } nameRange.location = idx + 1; } - else if ( ch == '%' ) { - sawPercent = YES; + else if ( removePercentEncoding && (ch == '%') ) { + sawPercent = true; } } @@ -1123,7 +1306,7 @@ CF_EXPORT CFArrayRef _CFURLComponentsCopyQueryItems(CFURLComponentsRef component valueRange.length = idx - valueRange.location; if ( valueRange.length ) { valueString = CFStringCreateWithSubstring(kCFAllocatorSystemDefault, queryString, valueRange); - if ( sawPercent ) { + if ( removePercentEncoding && sawPercent ) { CFStringRef temp = _CFStringCreateByRemovingPercentEncoding(kCFAllocatorSystemDefault, valueString); CFRelease(valueString); valueString = temp; @@ -1131,34 +1314,41 @@ CF_EXPORT CFArrayRef _CFURLComponentsCopyQueryItems(CFURLComponentsRef component } } else { - valueString = (CFStringRef)CFRetain(CFSTR("")); + valueString = CFRetain(CFSTR("")); } - CFStringRef name = CFSTR("name"); - CFTypeRef keys[] = {name, CFSTR("value")}; + CFTypeRef keys[] = {_kCFURLComponentsNameKey, _kCFURLComponentsValueKey}; CFTypeRef values[] = {nameString, valueString}; - CFDictionaryRef entry = CFDictionaryCreate(kCFAllocatorSystemDefault, keys, values, 2, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks); + // valueString will be NULL if the percent-decoded string had invalid UTF8 bytes + CFDictionaryRef entry = CFDictionaryCreate(kCFAllocatorSystemDefault, keys, values, valueString ? 2 : 1, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks); CFArrayAppendValue(intermediateResult, entry); CFRelease(entry); CFRelease(nameString); - CFRelease(valueString); + if ( valueString ) { + CFRelease(valueString); + } } else { // at end of query while parsing the name string nameRange.length = idx - nameRange.location; if ( nameRange.length ) { nameString = CFStringCreateWithSubstring(kCFAllocatorSystemDefault, queryString, nameRange); - if ( sawPercent ) { + if ( removePercentEncoding && sawPercent ) { CFStringRef temp = _CFStringCreateByRemovingPercentEncoding(kCFAllocatorSystemDefault, nameString); CFRelease(nameString); - nameString = temp; + if ( temp ) { + nameString = temp; + } + else { + // the percent-decoded string had invalid UTF8 bytes - return an empty name string + nameString = CFRetain(CFSTR("")); + } sawPercent = false; } } else { - nameString = (CFStringRef)CFRetain(CFSTR("")); + nameString = CFSTR(""); } - CFStringRef name = CFSTR("name"); - CFTypeRef keys[] = {name}; + CFTypeRef keys[] = {_kCFURLComponentsNameKey}; CFTypeRef values[] = {nameString}; CFDictionaryRef entry = CFDictionaryCreate(kCFAllocatorSystemDefault, keys, values, 1, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks); CFArrayAppendValue(intermediateResult, entry); @@ -1181,8 +1371,17 @@ CF_EXPORT CFArrayRef _CFURLComponentsCopyQueryItems(CFURLComponentsRef component return ( result ); } +CF_EXPORT CFArrayRef _CFURLComponentsCopyQueryItems(CFURLComponentsRef components) { + return ( _CFURLComponentsCopyQueryItemsInternal(components, true) ); +} + +CF_EXPORT CFArrayRef _CFURLComponentsCopyPercentEncodedQueryItems(CFURLComponentsRef components) { + return ( _CFURLComponentsCopyQueryItemsInternal(components, false) ); +} + // n.b. names and values must have the same length -CF_EXPORT void _CFURLComponentsSetQueryItems(CFURLComponentsRef components, CFArrayRef names, CFArrayRef values) { +static Boolean _CFURLComponentsSetQueryItemsInternal(CFURLComponentsRef components, CFArrayRef names, CFArrayRef values, Boolean addPercentEncoding ) { + Boolean result = true; if ( names != NULL ) { if ( CFArrayGetCount(names) != CFArrayGetCount(values) ) HALT; if ( CFArrayGetCount(names) ) { @@ -1208,22 +1407,47 @@ CF_EXPORT void _CFURLComponentsSetQueryItems(CFURLComponentsRef components, CFAr CFTypeRef name = CFArrayGetValueAtIndex(names, i); CFTypeRef value = CFArrayGetValueAtIndex(values, i); if ( name && name != kCFNull ) { - CFStringRef stringWithPercentEncoding = _CFStringCreateByAddingPercentEncodingWithAllowedCharacters(kCFAllocatorSystemDefault, name, queryNameValueAllowed); - CFStringAppendStringToAppendBuffer(&buf, stringWithPercentEncoding); - CFRelease(stringWithPercentEncoding); + if ( addPercentEncoding ) { + CFStringRef stringWithPercentEncoding = _CFStringCreateByAddingPercentEncodingWithAllowedCharacters(kCFAllocatorSystemDefault, name, queryNameValueAllowed); + CFStringAppendStringToAppendBuffer(&buf, stringWithPercentEncoding); + CFRelease(stringWithPercentEncoding); + } + else { + // verify name string contains no illegal characters + if ( !_CFURIParserValidateComponent(name, CFRangeMake(0, CFStringGetLength(name)), kURLQueryItemNameAllowed, true) ) { + result = false; + break; + } + CFStringAppendStringToAppendBuffer(&buf, name); + } } if ( value && value != kCFNull ) { chars[0] = '='; CFStringAppendCharactersToAppendBuffer(&buf, chars, 1); - CFStringRef stringWithPercentEncoding = _CFStringCreateByAddingPercentEncodingWithAllowedCharacters(kCFAllocatorSystemDefault, value, queryNameValueAllowed); - CFStringAppendStringToAppendBuffer(&buf, stringWithPercentEncoding); - CFRelease(stringWithPercentEncoding); + if ( addPercentEncoding ) { + CFStringRef stringWithPercentEncoding = _CFStringCreateByAddingPercentEncodingWithAllowedCharacters(kCFAllocatorSystemDefault, value, queryNameValueAllowed); + CFStringAppendStringToAppendBuffer(&buf, stringWithPercentEncoding); + CFRelease(stringWithPercentEncoding); + } + else { + // verify value string contains no illegal characters + if ( !_CFURIParserValidateComponent(value, CFRangeMake(0, CFStringGetLength(value)), kURLQueryAllowed, true) ) { + result = false; + break; + } + CFStringAppendStringToAppendBuffer(&buf, value); + } } // else the query item string will be simply "name" } + // even if the result is false, CFStringCreateMutableWithAppendBuffer has to be called so the CFStringAppendBuffer's string can be obtained and released CFStringRef queryString = CFStringCreateMutableWithAppendBuffer(&buf); - _CFURLComponentsSetPercentEncodedQuery(components, queryString); - CFRelease(queryString); + if ( result ) { + _CFURLComponentsSetPercentEncodedQuery(components, queryString); + } + if ( queryString ) { + CFRelease(queryString); + } } else { // If there's an array but the count is zero, set the query to a zero length string @@ -1234,4 +1458,13 @@ CF_EXPORT void _CFURLComponentsSetQueryItems(CFURLComponentsRef components, CFAr // If there is no items array, set the query to nil _CFURLComponentsSetPercentEncodedQuery(components, NULL); } + return ( result ); +} + +CF_EXPORT void _CFURLComponentsSetQueryItems(CFURLComponentsRef components, CFArrayRef names, CFArrayRef values ) { + (void)_CFURLComponentsSetQueryItemsInternal(components, names, values, true); // _CFURLComponentsSetQueryItemsInternal cannot fail if addPercentEncoding is true +} + +CF_EXPORT Boolean _CFURLComponentsSetPercentEncodedQueryItems(CFURLComponentsRef components, CFArrayRef names, CFArrayRef values ) { + return ( _CFURLComponentsSetQueryItemsInternal(components, names, values, false) ); } diff --git a/CoreFoundation/URL.subproj/CFURLComponents.h b/CoreFoundation/URL.subproj/CFURLComponents.h index 0938010b07..51e05529a8 100644 --- a/CoreFoundation/URL.subproj/CFURLComponents.h +++ b/CoreFoundation/URL.subproj/CFURLComponents.h @@ -1,15 +1,10 @@ -// This source file is part of the Swift.org open source project -// -// Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors -// Licensed under Apache License v2.0 with Runtime Library Exception -// -// See http://swift.org/LICENSE.txt for license information -// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors -// - - /* CFURLComponents.h - Copyright (c) 2015, Apple Inc. All rights reserved. + Copyright (c) 2015-2018, Apple Inc. All rights reserved. + + Portions Copyright (c) 2014-2018, Apple Inc. and the Swift project authors + Licensed under Apache License v2.0 with Runtime Library Exception + See http://swift.org/LICENSE.txt for license information + See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors */ #ifndef __COREFOUNDATION_CFURLCOMPONENTS__ @@ -26,20 +21,10 @@ CF_IMPLICIT_BRIDGING_ENABLED CF_EXTERN_C_BEGIN CF_ASSUME_NONNULL_BEGIN -#ifndef CF_CROSS_PLATFORM_EXPORT -#if DEPLOYMENT_RUNTIME_SWIFT -#define CF_CROSS_PLATFORM_EXPORT extern -#else -#define CF_CROSS_PLATFORM_EXPORT static __attribute__((used)) -#endif -#endif - -typedef struct __CFURLComponents *CFURLComponentsRef; +typedef struct CF_BRIDGED_TYPE(id) __CFURLComponents *CFURLComponentsRef; CF_EXPORT CFTypeID _CFURLComponentsGetTypeID(void); -CF_CROSS_PLATFORM_EXPORT void __CFURLComponentsDeallocate(CFURLComponentsRef); - // URLComponents are always mutable. CF_EXPORT _Nullable CFURLComponentsRef _CFURLComponentsCreate(CFAllocatorRef alloc); @@ -109,9 +94,16 @@ CF_EXPORT CFCharacterSetRef _CFURLComponentsGetURLPathAllowedCharacterSet(void); CF_EXPORT CFCharacterSetRef _CFURLComponentsGetURLQueryAllowedCharacterSet(void); CF_EXPORT CFCharacterSetRef _CFURLComponentsGetURLFragmentAllowedCharacterSet(void); +// keys for dictionaries returned by _CFURLComponentsCopyQueryItems +CF_EXPORT const CFStringRef _kCFURLComponentsNameKey; +CF_EXPORT const CFStringRef _kCFURLComponentsValueKey; + CF_EXPORT _Nullable CFArrayRef _CFURLComponentsCopyQueryItems(CFURLComponentsRef components); CF_EXPORT void _CFURLComponentsSetQueryItems(CFURLComponentsRef components, CFArrayRef names, CFArrayRef values); +CF_EXPORT _Nullable CFArrayRef _CFURLComponentsCopyPercentEncodedQueryItems(CFURLComponentsRef components); +CF_EXPORT Boolean _CFURLComponentsSetPercentEncodedQueryItems(CFURLComponentsRef components, CFArrayRef names, CFArrayRef values); + CF_ASSUME_NONNULL_END CF_EXTERN_C_END CF_IMPLICIT_BRIDGING_DISABLED diff --git a/CoreFoundation/URL.subproj/CFURLComponents_Internal.h b/CoreFoundation/URL.subproj/CFURLComponents_Internal.h index 2871c290c1..0ec96ad954 100644 --- a/CoreFoundation/URL.subproj/CFURLComponents_Internal.h +++ b/CoreFoundation/URL.subproj/CFURLComponents_Internal.h @@ -1,15 +1,10 @@ -// This source file is part of the Swift.org open source project -// -// Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors -// Licensed under Apache License v2.0 with Runtime Library Exception -// -// See http://swift.org/LICENSE.txt for license information -// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors -// - - /* CFURLComponents_Internal.h - Copyright (c) 2015, Apple Inc. All rights reserved. + Copyright (c) 2015-2018, Apple Inc. All rights reserved. + + Portions Copyright (c) 2014-2018, Apple Inc. and the Swift project authors + Licensed under Apache License v2.0 with Runtime Library Exception + See http://swift.org/LICENSE.txt for license information + See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors */ #ifndef CFURLComponents_Internal_h @@ -55,6 +50,7 @@ typedef CF_ENUM(unsigned short, _CFURIParserURLAllowedCharacter) { kURLFragmentAllowed = 0x0080, kURLHexDigAllowed = 0x0100, kURLAlphaAllowed = 0x0200, + kURLQueryItemNameAllowed = 0x0400, // the same as kURLQueryAllowed only '=' and '&' are not allowed }; CF_PRIVATE Boolean _CFURIParserParseURIReference(CFStringRef urlString, struct _URIParseInfo *parseInfo); diff --git a/CoreFoundation/URL.subproj/CFURLPriv.h b/CoreFoundation/URL.subproj/CFURLPriv.h index 733b12b5a2..b4e677fa50 100644 --- a/CoreFoundation/URL.subproj/CFURLPriv.h +++ b/CoreFoundation/URL.subproj/CFURLPriv.h @@ -1,7 +1,7 @@ /* CFURLPriv.h - Copyright (c) 2008-2017, Apple Inc. and the Swift project authors + Copyright (c) 2008-2018, Apple Inc. and the Swift project authors - Portions Copyright (c) 2014-2017, Apple Inc. and the Swift project authors + Portions Copyright (c) 2014-2018, Apple Inc. and the Swift project authors Licensed under Apache License v2.0 with Runtime Library Exception See http://swift.org/LICENSE.txt for license information See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors @@ -213,12 +213,22 @@ CF_EXPORT const CFStringRef _kCFURLApplicationArchitecturesKey API_AVAILABLE(macos(10.11), ios(9.0), watchos(2.0), tvos(9.0)); /* The complete list of executable architectures found in the application bundle's executable (Read-only, value type CFArray of CFString) */ +CF_EXPORT +const CFStringRef _kCFURLApplicationSupportedRegionsKey API_AVAILABLE(macos(10.14), ios(12.0), watchos(5.0), tvos(12.0)); + /* The complete list of regions supported by the application as found in the application bundle’s Info.plist (Read-only, value type CFArray of CFString) */ + CF_EXPORT const CFStringRef _kCFURLFaultLogicalFileIsHiddenKey API_AVAILABLE(macos(10.11), ios(9.0), watchos(2.0), tvos(9.0)); /* True if the fault logical file is hidden. (Read only, CFBoolean) */ CF_EXPORT const CFStringRef _kCFURLLocalizedNameComponentsKey API_AVAILABLE(macosx(10.13), ios(11.0), watchos(4.0), tvos(11.0)); /* An array containing the base name of the file and (if present) the extension to be used for display. Does not include extra Unicode visual ordering characters added by the system. For Finder use. (Read-only, value type CFArray of CFStrings) */ +CF_EXPORT const CFStringRef _kCFURLApplicationPrefersExternalGPUKey API_AVAILABLE(macos(10.14)) API_UNAVAILABLE(ios, watchos, tvos); + /* Default is false. True means the application will be steered towards the eGPU regardless of which displays it is attached to. (Read-write, CFBoolean) */ + +CF_EXPORT const CFStringRef _kCFURLCanSetApplicationPrefersExternalGPUKey API_AVAILABLE(macos(10.14)) API_UNAVAILABLE(ios, watchos, tvos); + /* False if app’s Info.plist specifies a eGPU policy, True if app does not specify an policy. Finder does not show a checkbox when this value is false. (Read-only, CFBoolean) */ + /* Additional volume properties */ CF_EXPORT const CFStringRef _kCFURLVolumeRefNumKey API_AVAILABLE(macos(10.6), ios(4.0), watchos(2.0), tvos(9.0)); diff --git a/Foundation.xcodeproj/project.pbxproj b/Foundation.xcodeproj/project.pbxproj index 37b4d64edc..dd616a2fe2 100644 --- a/Foundation.xcodeproj/project.pbxproj +++ b/Foundation.xcodeproj/project.pbxproj @@ -12,6 +12,14 @@ 1520469B1D8AEABE00D02E36 /* HTTPServer.swift in Sources */ = {isa = PBXBuildFile; fileRef = 1520469A1D8AEABE00D02E36 /* HTTPServer.swift */; }; 153E951120111DC500F250BE /* CFKnownLocations.h in Headers */ = {isa = PBXBuildFile; fileRef = 153E950F20111DC500F250BE /* CFKnownLocations.h */; settings = {ATTRIBUTES = (Private, ); }; }; 153E951220111DC500F250BE /* CFKnownLocations.c in Sources */ = {isa = PBXBuildFile; fileRef = 153E951020111DC500F250BE /* CFKnownLocations.c */; }; + 15496CF1212CAEBA00450F5A /* CFAttributedStringPriv.h in Headers */ = {isa = PBXBuildFile; fileRef = 15496CF0212CAEBA00450F5A /* CFAttributedStringPriv.h */; }; + 1578DA09212B4061003C9516 /* CFRuntime_Internal.h in Headers */ = {isa = PBXBuildFile; fileRef = 1578DA08212B4060003C9516 /* CFRuntime_Internal.h */; }; + 1578DA0D212B4070003C9516 /* CFMachPort_Internal.h in Headers */ = {isa = PBXBuildFile; fileRef = 1578DA0A212B406F003C9516 /* CFMachPort_Internal.h */; }; + 1578DA0E212B4070003C9516 /* CFMachPort_Lifetime.c in Sources */ = {isa = PBXBuildFile; fileRef = 1578DA0B212B406F003C9516 /* CFMachPort_Lifetime.c */; }; + 1578DA0F212B4070003C9516 /* CFMachPort_Lifetime.h in Headers */ = {isa = PBXBuildFile; fileRef = 1578DA0C212B406F003C9516 /* CFMachPort_Lifetime.h */; }; + 1578DA11212B407B003C9516 /* CFString_Internal.h in Headers */ = {isa = PBXBuildFile; fileRef = 1578DA10212B407B003C9516 /* CFString_Internal.h */; }; + 1578DA13212B4C35003C9516 /* CFOverflow.h in Headers */ = {isa = PBXBuildFile; fileRef = 1578DA12212B4C35003C9516 /* CFOverflow.h */; }; + 1578DA15212B6F33003C9516 /* CFCollections_Internal.h in Headers */ = {isa = PBXBuildFile; fileRef = 1578DA14212B6F33003C9516 /* CFCollections_Internal.h */; }; 159884921DCC877700E3314C /* TestHTTPCookieStorage.swift in Sources */ = {isa = PBXBuildFile; fileRef = 159884911DCC877700E3314C /* TestHTTPCookieStorage.swift */; }; 231503DB1D8AEE5D0061694D /* TestDecimal.swift in Sources */ = {isa = PBXBuildFile; fileRef = 231503DA1D8AEE5D0061694D /* TestDecimal.swift */; }; 294E3C1D1CC5E19300E4F44C /* TestNSAttributedString.swift in Sources */ = {isa = PBXBuildFile; fileRef = 294E3C1C1CC5E19300E4F44C /* TestNSAttributedString.swift */; }; @@ -521,6 +529,14 @@ 1520469A1D8AEABE00D02E36 /* HTTPServer.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = HTTPServer.swift; sourceTree = ""; }; 153E950F20111DC500F250BE /* CFKnownLocations.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = CFKnownLocations.h; sourceTree = ""; }; 153E951020111DC500F250BE /* CFKnownLocations.c */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.c; path = CFKnownLocations.c; sourceTree = ""; }; + 15496CF0212CAEBA00450F5A /* CFAttributedStringPriv.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CFAttributedStringPriv.h; sourceTree = ""; }; + 1578DA08212B4060003C9516 /* CFRuntime_Internal.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CFRuntime_Internal.h; sourceTree = ""; }; + 1578DA0A212B406F003C9516 /* CFMachPort_Internal.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CFMachPort_Internal.h; sourceTree = ""; }; + 1578DA0B212B406F003C9516 /* CFMachPort_Lifetime.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = CFMachPort_Lifetime.c; sourceTree = ""; }; + 1578DA0C212B406F003C9516 /* CFMachPort_Lifetime.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CFMachPort_Lifetime.h; sourceTree = ""; }; + 1578DA10212B407B003C9516 /* CFString_Internal.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CFString_Internal.h; sourceTree = ""; }; + 1578DA12212B4C35003C9516 /* CFOverflow.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CFOverflow.h; sourceTree = ""; }; + 1578DA14212B6F33003C9516 /* CFCollections_Internal.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CFCollections_Internal.h; sourceTree = ""; }; 159884911DCC877700E3314C /* TestHTTPCookieStorage.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TestHTTPCookieStorage.swift; sourceTree = ""; }; 22B9C1E01C165D7A00DECFF9 /* TestDate.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = TestDate.swift; sourceTree = ""; }; 231503DA1D8AEE5D0061694D /* TestDecimal.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = TestDecimal.swift; sourceTree = ""; }; @@ -1099,6 +1115,7 @@ 5B5D88711BBC951A00234F36 /* Base */ = { isa = PBXGroup; children = ( + 1578DA12212B4C35003C9516 /* CFOverflow.h */, F03A43161D48778200A7791E /* CFAsmMacros.h */, 5BDC3F721BCC60EF00ED97BB /* module.modulemap */, 5B5D88741BBC954000234F36 /* CFAvailability.h */, @@ -1112,6 +1129,7 @@ 5B5D88CC1BBC986300234F36 /* CFPriv.h */, 5B5D88C31BBC981C00234F36 /* CFRuntime.c */, 5B5D88C21BBC981C00234F36 /* CFRuntime.h */, + 1578DA08212B4060003C9516 /* CFRuntime_Internal.h */, 5B5D897D1BBDAEE600234F36 /* CFSortFunctions.c */, 5B5D89731BBDAD9900234F36 /* CFSystemDirectories.c */, 5B5D89601BBDABF400234F36 /* CFUtilities.c */, @@ -1134,6 +1152,7 @@ 5B5D88761BBC955900234F36 /* Collections */ = { isa = PBXGroup; children = ( + 1578DA14212B6F33003C9516 /* CFCollections_Internal.h */, 5B5D88781BBC956C00234F36 /* CFArray.c */, 5B5D88771BBC956C00234F36 /* CFArray.h */, 5B5D89161BBC9C5500234F36 /* CFBag.c */, @@ -1169,6 +1188,7 @@ 5B5D88911BBC969400234F36 /* CFCharacterSetPriv.h */, 5B5D887D1BBC960100234F36 /* CFString.c */, 5B5D887C1BBC960100234F36 /* CFString.h */, + 1578DA10212B407B003C9516 /* CFString_Internal.h */, 5B5D887E1BBC960100234F36 /* CFStringDefaultEncoding.h */, 5B5D890F1BBC9C1B00234F36 /* CFStringEncodingExt.h */, 5B5D887F1BBC960100234F36 /* CFStringEncodings.c */, @@ -1181,6 +1201,7 @@ 5B6228BC1C179049009587FE /* CFRunArray.h */, 5B6228BA1C179041009587FE /* CFRunArray.c */, 5B6228C01C17905B009587FE /* CFAttributedString.h */, + 15496CF0212CAEBA00450F5A /* CFAttributedStringPriv.h */, 5B6228BE1C179052009587FE /* CFAttributedString.c */, ); name = String; @@ -1261,6 +1282,9 @@ children = ( 5B5D88D01BBC9AAC00234F36 /* CFMachPort.c */, 5B5D88CF1BBC9AAC00234F36 /* CFMachPort.h */, + 1578DA0A212B406F003C9516 /* CFMachPort_Internal.h */, + 1578DA0B212B406F003C9516 /* CFMachPort_Lifetime.c */, + 1578DA0C212B406F003C9516 /* CFMachPort_Lifetime.h */, 5B5D88DC1BBC9AEC00234F36 /* CFMessagePort.c */, 5B5D88DB1BBC9AEC00234F36 /* CFMessagePort.h */, 5B5D88D81BBC9AD800234F36 /* CFRunLoop.c */, @@ -1916,10 +1940,12 @@ 5B7C8ADC1BEA80FC00C5B690 /* CFSocket.h in Headers */, 5B7C8ACC1BEA80FC00C5B690 /* CFDateFormatter.h in Headers */, 5B7C8AD41BEA80FC00C5B690 /* CFXMLParser.h in Headers */, + 1578DA09212B4061003C9516 /* CFRuntime_Internal.h in Headers */, 5B7C8AD11BEA80FC00C5B690 /* CFTimeZone.h in Headers */, 5B7C8AC31BEA80FC00C5B690 /* CFBag.h in Headers */, 5B7C8AE01BEA80FC00C5B690 /* CFStringEncodingExt.h in Headers */, 5B7C8AE11BEA80FC00C5B690 /* CFURL.h in Headers */, + 1578DA0D212B4070003C9516 /* CFMachPort_Internal.h in Headers */, 5B7C8ABF1BEA807A00C5B690 /* CFUtilities.h in Headers */, 5B7C8ADD1BEA80FC00C5B690 /* CFStream.h in Headers */, 5B40F9F01C125011000E72E3 /* CFXMLInterface.h in Headers */, @@ -1944,9 +1970,11 @@ 5B7C8B021BEA830200C5B690 /* CFBurstTrie.h in Headers */, 5B7C8AD61BEA80FC00C5B690 /* CFPlugIn.h in Headers */, 5B7C8AD81BEA80FC00C5B690 /* CFPreferences.h in Headers */, + 15496CF1212CAEBA00450F5A /* CFAttributedStringPriv.h in Headers */, 5B7C8AF11BEA81AC00C5B690 /* CFStreamAbstract.h in Headers */, 153E951120111DC500F250BE /* CFKnownLocations.h in Headers */, 5B7C8AFE1BEA81AC00C5B690 /* CFURLComponents.h in Headers */, + 1578DA11212B407B003C9516 /* CFString_Internal.h in Headers */, 5B7C8ABC1BEA805C00C5B690 /* CFAvailability.h in Headers */, 5B6E11A91DA45EB5009B48A3 /* CFDateFormatter_Private.h in Headers */, 5B7C8AF51BEA81AC00C5B690 /* CFStringDefaultEncoding.h in Headers */, @@ -1957,12 +1985,14 @@ 5B7C8AE21BEA80FC00C5B690 /* CFURLAccess.h in Headers */, F03A43181D4877DD00A7791E /* CFAsmMacros.h in Headers */, 5B7C8ACA1BEA80FC00C5B690 /* CFError.h in Headers */, + 1578DA0F212B4070003C9516 /* CFMachPort_Lifetime.h in Headers */, 5B7C8AE91BEA81AC00C5B690 /* CFLocaleInternal.h in Headers */, 5B7C8AE61BEA81AC00C5B690 /* ForSwiftFoundationOnly.h in Headers */, 5B7C8AC61BEA80FC00C5B690 /* CFData.h in Headers */, 5B7C8AC01BEA807A00C5B690 /* CFUUID.h in Headers */, 5B7C8AD31BEA80FC00C5B690 /* CFXMLNode.h in Headers */, 5B7C8AC21BEA80FC00C5B690 /* CFArray.h in Headers */, + 1578DA15212B6F33003C9516 /* CFCollections_Internal.h in Headers */, 5B7C8AFD1BEA81AC00C5B690 /* CFUnicodePrecomposition.h in Headers */, 5B7C8ADB1BEA80FC00C5B690 /* CFRunLoop.h in Headers */, 5B7C8AFC1BEA81AC00C5B690 /* CFUnicodeDecomposition.h in Headers */, @@ -1996,6 +2026,7 @@ 5B7C8AD01BEA80FC00C5B690 /* CFNumber.h in Headers */, 5B6228BD1C179049009587FE /* CFRunArray.h in Headers */, 5B7C8ACE1BEA80FC00C5B690 /* CFNumberFormatter.h in Headers */, + 1578DA13212B4C35003C9516 /* CFOverflow.h in Headers */, ); runOnlyForDeploymentPostprocessing = 0; }; @@ -2393,6 +2424,7 @@ 5B7C8A791BEA7FCE00C5B690 /* CFUUID.c in Sources */, 5B7C8A7F1BEA7FCE00C5B690 /* CFData.c in Sources */, 5B7C8A9C1BEA7FF900C5B690 /* CFBundle.c in Sources */, + 1578DA0E212B4070003C9516 /* CFMachPort_Lifetime.c in Sources */, 5BF9B8001FABD5DA00EE1A7C /* CFBundle_Main.c in Sources */, 5B7C8AB51BEA801700C5B690 /* CFUniChar.c in Sources */, 61E011811C1B5998000037DD /* CFMessagePort.c in Sources */, diff --git a/Foundation/NSData.swift b/Foundation/NSData.swift index ecee8c2531..4b416e98ab 100644 --- a/Foundation/NSData.swift +++ b/Foundation/NSData.swift @@ -1138,3 +1138,7 @@ extension NSData : _StructTypeBridgeable { return Data._unconditionallyBridgeFromObjectiveC(self) } } + +internal func _CFSwiftDataCreateCopy(_ data: AnyObject) -> Unmanaged { + return Unmanaged.passRetained((data as! NSDictionary).copy() as! NSObject) +} diff --git a/Foundation/NSPathUtilities.swift b/Foundation/NSPathUtilities.swift index fd38233fd6..5ba99de57e 100755 --- a/Foundation/NSPathUtilities.swift +++ b/Foundation/NSPathUtilities.swift @@ -585,7 +585,7 @@ public func NSUserName() -> String { } public func NSFullUserName() -> String { - let userName = CFCopyFullUserName().takeRetainedValue() + let userName = CFCopyFullUserName() return userName._swiftObject } diff --git a/Foundation/NSSwiftRuntime.swift b/Foundation/NSSwiftRuntime.swift index 6d3c852727..4e03109996 100644 --- a/Foundation/NSSwiftRuntime.swift +++ b/Foundation/NSSwiftRuntime.swift @@ -286,6 +286,8 @@ internal func __CFInitializeSwift() { __CFSwiftBridge.NSNumber._getValue = _CFSwiftNumberGetValue __CFSwiftBridge.NSNumber.boolValue = _CFSwiftNumberGetBoolValue + __CFSwiftBridge.NSData.copy = _CFSwiftDataCreateCopy + // __CFDefaultEightBitStringEncoding = UInt32(kCFStringEncodingUTF8) } diff --git a/Foundation/NSURL.swift b/Foundation/NSURL.swift index a6ffb2bd6c..2e80edbad3 100644 --- a/Foundation/NSURL.swift +++ b/Foundation/NSURL.swift @@ -958,14 +958,8 @@ open class NSURLQueryItem : NSObject, NSSecureCoding, NSCopying { } open class NSURLComponents: NSObject, NSCopying { - private let _components : CFURLComponentsRef! + private let _components : CFURLComponents! - deinit { - if let component = _components { - __CFURLComponentsDeallocate(component) - } - } - open override func copy() -> Any { return copy(with: nil) } diff --git a/Foundation/ProcessInfo.swift b/Foundation/ProcessInfo.swift index 0b5f82a67a..92aa9e1b82 100644 --- a/Foundation/ProcessInfo.swift +++ b/Foundation/ProcessInfo.swift @@ -74,7 +74,7 @@ open class ProcessInfo: NSObject { open var processName: String = _CFProcessNameString()._swiftObject open var processIdentifier: Int32 { - return __CFGetPid() + return Int32(getpid()) } open var globallyUniqueString: String { diff --git a/Foundation/UserDefaults.swift b/Foundation/UserDefaults.swift index fc1eef79db..d699b728af 100644 --- a/Foundation/UserDefaults.swift +++ b/Foundation/UserDefaults.swift @@ -295,11 +295,8 @@ open class UserDefaults: NSObject { private func _dictionaryRepresentation(includingVolatileDomains: Bool) -> [String: Any] { let registeredDefaultsIfAllowed = includingVolatileDomains ? registeredDefaults : [:] - guard let defaultsFromDiskCF = CFPreferencesCopyMultiple(nil, suite?._cfObject ?? kCFPreferencesCurrentApplication, kCFPreferencesCurrentUser, kCFPreferencesAnyHost) else { - return registeredDefaultsIfAllowed - } - - let defaultsFromDiskWithNumbersBoxed = __SwiftValue.fetch(defaultsFromDiskCF) as? [String: Any] ?? [:] + let defaultsFromDiskCF = CFPreferencesCopyMultiple(nil, suite?._cfObject ?? kCFPreferencesCurrentApplication, kCFPreferencesCurrentUser, kCFPreferencesAnyHost) + let defaultsFromDiskWithNumbersBoxed = _SwiftValue.fetch(defaultsFromDiskCF) as? [String: Any] ?? [:] if registeredDefaultsIfAllowed.isEmpty { return UserDefaults._unboxingNSNumbers(defaultsFromDiskWithNumbersBoxed) as! [String: Any] diff --git a/TestFoundation/TestDateFormatter.swift b/TestFoundation/TestDateFormatter.swift index 98c636f620..ffbfddf123 100644 --- a/TestFoundation/TestDateFormatter.swift +++ b/TestFoundation/TestDateFormatter.swift @@ -9,7 +9,7 @@ class TestDateFormatter: XCTestCase { - let DEFAULT_LOCALE = "en_US" + let DEFAULT_LOCALE = "en_US_POSIX" let DEFAULT_TIMEZONE = "GMT" static var allTests : [(String, (TestDateFormatter) -> () throws -> Void)] { diff --git a/TestFoundation/TestNSString.swift b/TestFoundation/TestNSString.swift index 272c30d007..31f120485d 100755 --- a/TestFoundation/TestNSString.swift +++ b/TestFoundation/TestNSString.swift @@ -95,7 +95,7 @@ class TestNSString: LoopbackServerTest { ("test_commonPrefix", test_commonPrefix) ] } - + func test_boolValue() { let trueStrings: [NSString] = ["t", "true", "TRUE", "tRuE", "yes", "YES", "1", "+000009"] for string in trueStrings { @@ -190,25 +190,25 @@ class TestNSString: LoopbackServerTest { } func test_doubleValue() { - XCTAssertEqual(NSString(".2").doubleValue, 0.2) - XCTAssertEqual(NSString("+.2").doubleValue, 0.2) - XCTAssertEqual(NSString("-.2").doubleValue, -0.2) - XCTAssertEqual(NSString("1.23015e+3").doubleValue, 1230.15) - XCTAssertEqual(NSString("12.3015e+02").doubleValue, 1230.15) - XCTAssertEqual(NSString("+1.23015e+3").doubleValue, 1230.15) - XCTAssertEqual(NSString("+12.3015e+02").doubleValue, 1230.15) - XCTAssertEqual(NSString("-1.23015e+3").doubleValue, -1230.15) - XCTAssertEqual(NSString("-12.3015e+02").doubleValue, -1230.15) - XCTAssertEqual(NSString("-12.3015e02").doubleValue, -1230.15) - XCTAssertEqual(NSString("-31.25e-04").doubleValue, -0.003125) - - XCTAssertEqual(NSString(".e12").doubleValue, 0) - XCTAssertEqual(NSString("2e3.12").doubleValue, 2000) - XCTAssertEqual(NSString("1e2.3").doubleValue, 100) - XCTAssertEqual(NSString("12.e4").doubleValue, 120000) - XCTAssertEqual(NSString("1.2.3.4").doubleValue, 1.2) - XCTAssertEqual(NSString("1e2.3").doubleValue, 100) - XCTAssertEqual(NSString("1E3").doubleValue, 1000) + XCTAssertEqual(NSString(string: ".2").doubleValue, 0.2) + XCTAssertEqual(NSString(string: "+.2").doubleValue, 0.2) + XCTAssertEqual(NSString(string: "-.2").doubleValue, -0.2) + XCTAssertEqual(NSString(string: "1.23015e+3").doubleValue, 1230.15) + XCTAssertEqual(NSString(string: "12.3015e+02").doubleValue, 1230.15) + XCTAssertEqual(NSString(string: "+1.23015e+3").doubleValue, 1230.15) + XCTAssertEqual(NSString(string: "+12.3015e+02").doubleValue, 1230.15) + XCTAssertEqual(NSString(string: "-1.23015e+3").doubleValue, -1230.15) + XCTAssertEqual(NSString(string: "-12.3015e+02").doubleValue, -1230.15) + XCTAssertEqual(NSString(string: "-12.3015e02").doubleValue, -1230.15) + XCTAssertEqual(NSString(string: "-31.25e-04").doubleValue, -0.003125) + + XCTAssertEqual(NSString(string: ".e12").doubleValue, 0) + XCTAssertEqual(NSString(string: "2e3.12").doubleValue, 2000) + XCTAssertEqual(NSString(string: "1e2.3").doubleValue, 100) + XCTAssertEqual(NSString(string: "12.e4").doubleValue, 120000) + XCTAssertEqual(NSString(string: "1.2.3.4").doubleValue, 1.2) + XCTAssertEqual(NSString(string: "1e2.3").doubleValue, 100) + XCTAssertEqual(NSString(string: "1E3").doubleValue, 1000) } func test_isEqualToStringWithSwiftString() { diff --git a/build.py b/build.py index 5f221f4e6c..c04996a130 100755 --- a/build.py +++ b/build.py @@ -227,6 +227,13 @@ 'CoreFoundation/Locale.subproj/CFLocale_Private.h', 'CoreFoundation/Parsing.subproj/CFPropertyList_Private.h', 'CoreFoundation/Base.subproj/CFKnownLocations.h', + 'CoreFoundation/Base.subproj/CFOverflow.h', + 'CoreFoundation/Base.subproj/CFRuntime_Internal.h', + 'CoreFoundation/Collections.subproj/CFCollections_Internal.h', + 'CoreFoundation/RunLoop.subproj/CFMachPort_Internal.h', + 'CoreFoundation/RunLoop.subproj/CFMachPort_Lifetime.h', + 'CoreFoundation/String.subproj/CFAttributedStringPriv.h', + 'CoreFoundation/String.subproj/CFString_Internal.h', ], project = [ ]) @@ -293,6 +300,7 @@ 'CoreFoundation/Preferences.subproj/CFXMLPreferencesDomain.c', # 'CoreFoundation/RunLoop.subproj/CFMachPort.c', # 'CoreFoundation/RunLoop.subproj/CFMessagePort.c', + # 'CoreFoundation/RunLoop.subproj/CFMachPort_Lifetime.c', 'CoreFoundation/RunLoop.subproj/CFRunLoop.c', 'CoreFoundation/RunLoop.subproj/CFSocket.c', 'CoreFoundation/Stream.subproj/CFConcreteStreams.c', From 9d7c9f5f43f9c97bc9bcb06af1d6b9a65b8167e9 Mon Sep 17 00:00:00 2001 From: Lily Vulcano Date: Wed, 26 Sep 2018 13:52:16 -0700 Subject: [PATCH 02/12] _SwiftValue was renamed to __SwiftValue after the merge began. Fix the merge issue. --- Foundation/UserDefaults.swift | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Foundation/UserDefaults.swift b/Foundation/UserDefaults.swift index d699b728af..0a3464efdd 100644 --- a/Foundation/UserDefaults.swift +++ b/Foundation/UserDefaults.swift @@ -296,7 +296,7 @@ open class UserDefaults: NSObject { let registeredDefaultsIfAllowed = includingVolatileDomains ? registeredDefaults : [:] let defaultsFromDiskCF = CFPreferencesCopyMultiple(nil, suite?._cfObject ?? kCFPreferencesCurrentApplication, kCFPreferencesCurrentUser, kCFPreferencesAnyHost) - let defaultsFromDiskWithNumbersBoxed = _SwiftValue.fetch(defaultsFromDiskCF) as? [String: Any] ?? [:] + let defaultsFromDiskWithNumbersBoxed = __SwiftValue.fetch(defaultsFromDiskCF) as? [String: Any] ?? [:] if registeredDefaultsIfAllowed.isEmpty { return UserDefaults._unboxingNSNumbers(defaultsFromDiskWithNumbersBoxed) as! [String: Any] From 3d7295535e065a4fb29bb4cf24ea2a4ceff142ea Mon Sep 17 00:00:00 2001 From: Lily Vulcano Date: Wed, 26 Sep 2018 15:04:55 -0700 Subject: [PATCH 03/12] Un-revert ICU 55-or-previous compatibility fixes. --- CoreFoundation/Locale.subproj/CFLocale.c | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/CoreFoundation/Locale.subproj/CFLocale.c b/CoreFoundation/Locale.subproj/CFLocale.c index ec52965166..e47ea5d51c 100644 --- a/CoreFoundation/Locale.subproj/CFLocale.c +++ b/CoreFoundation/Locale.subproj/CFLocale.c @@ -1486,8 +1486,12 @@ STATIC_CONST_STRING_DECL(_temperatureUnitKey, "AppleTemperatureUnit"); static bool __CFLocaleGetMeasurementSystemForPreferences(CFTypeRef metricPref, CFTypeRef measurementPref, UMeasurementSystem *outMeasurementSystem) { if (metricPref || measurementPref) { +#if U_ICU_VERSION_MAJOR_NUM >= 55 if (metricPref == kCFBooleanTrue && measurementPref && CFEqual(measurementPref, _measurementUnitsInches)) { *outMeasurementSystem = UMS_UK; +#else + return false; +#endif } else if (metricPref == kCFBooleanFalse) { *outMeasurementSystem = UMS_US; } else { @@ -1554,10 +1558,12 @@ static bool __CFLocaleGetMeasurementSystemForName(CFStringRef name, UMeasuremen *outMeasurementSystem = UMS_US; return true; } +#if U_ICU_VERSION_MAJOR_NUM >= 55 if (CFEqual(name, kCFLocaleMeasurementSystemUK)) { *outMeasurementSystem = UMS_UK; return true; } +#endif } return false; } From fa3991d09a9c7469c487bdaf9282570bd99a098d Mon Sep 17 00:00:00 2001 From: Lily Vulcano Date: Fri, 28 Sep 2018 12:01:58 -0700 Subject: [PATCH 04/12] Restore CFTimeZone.c as it was, modulo the static class definition changes. --- .../NumberDate.subproj/CFTimeZone.c | 110 ++++++++++++------ Foundation/NSSwiftRuntime.swift | 1 + 2 files changed, 73 insertions(+), 38 deletions(-) diff --git a/CoreFoundation/NumberDate.subproj/CFTimeZone.c b/CoreFoundation/NumberDate.subproj/CFTimeZone.c index 68b1953b18..beeaa7c063 100644 --- a/CoreFoundation/NumberDate.subproj/CFTimeZone.c +++ b/CoreFoundation/NumberDate.subproj/CFTimeZone.c @@ -34,9 +34,12 @@ #endif #if DEPLOYMENT_TARGET_MACOSX || DEPLOYMENT_TARGET_EMBEDDED #include +#define MACOS_TZDIR1 "/usr/share/zoneinfo/" // 10.12 and earlier +#define MACOS_TZDIR2 "/var/db/timezone/zoneinfo/" // 10.13 onwards + #elif DEPLOYMENT_TARGET_LINUX || DEPLOYMENT_TARGET_FREEBSD #ifndef TZDIR -#define TZDIR "/usr/share/zoneinfo" /* Time zone object file directory */ +#define TZDIR "/usr/share/zoneinfo/" /* Time zone object file directory */ #endif /* !defined TZDIR */ #ifndef TZDEFAULT @@ -57,16 +60,9 @@ struct tzhead { #include -#if DEPLOYMENT_TARGET_MACOSX || DEPLOYMENT_TARGET_EMBEDDED || DEPLOYMENT_TARGET_LINUX || DEPLOYMENT_TARGET_FREEBSD -#define TZZONELINK TZDEFAULT -#define TZZONEINFO TZDIR "/" -#elif DEPLOYMENT_TARGET_WINDOWS static CFStringRef __tzZoneInfo = NULL; static char *__tzDir = NULL; static void __InitTZStrings(void); -#else -#error Unknown or unspecified DEPLOYMENT_TARGET -#endif CONST_STRING_DECL(kCFTimeZoneSystemTimeZoneDidChangeNotification, "kCFTimeZoneSystemTimeZoneDidChangeNotification") @@ -148,13 +144,9 @@ static CFMutableArrayRef __CFCopyWindowsTimeZoneList() { #elif DEPLOYMENT_TARGET_MACOSX || DEPLOYMENT_TARGET_EMBEDDED || DEPLOYMENT_TARGET_WINDOWS || DEPLOYMENT_TARGET_LINUX || DEPLOYMENT_TARGET_FREEBSD static CFMutableArrayRef __CFCopyRecursiveDirectoryList() { CFMutableArrayRef result = CFArrayCreateMutable(kCFAllocatorSystemDefault, 0, &kCFTypeArrayCallBacks); -#if DEPLOYMENT_TARGET_WINDOWS if (!__tzDir) __InitTZStrings(); if (!__tzDir) return result; int fd = open(__tzDir, O_RDONLY); -#else - int fd = open(TZDIR "/zone.tab", O_RDONLY); -#endif for (; 0 <= fd;) { uint8_t buffer[4096]; @@ -701,6 +693,50 @@ static void __InitTZStrings(void) { } __CFUnlock(&__CFTZDirLock); } + +#elif DEPLOYMENT_TARGET_MACOSX || DEPLOYMENT_TARGET_EMBEDDED +static void __InitTZStrings(void) { + static dispatch_once_t initOnce = 0; + + dispatch_once(&initOnce, ^{ + unsigned int major = 0, minor = 0, patch = 0; + + CFDictionaryRef dict = _CFCopySystemVersionDictionary(); + if (dict) { + CFStringRef version = CFDictionaryGetValue(dict, _kCFSystemVersionProductVersionKey); + if (version) { + const char *cStr = CFStringGetCStringPtr(version, kCFStringEncodingASCII); + if (cStr) { + if (sscanf(cStr, "%u.%u.%u", &major, &minor, &patch) != 3) { + major = 0; + minor = 0; + patch = 0; + } + } + } + CFRelease(dict); + } + + // Timezone files moved in High Sierra(10.13) + if (major == 10 && minor < 13) { + // older versions + __tzZoneInfo = CFSTR(MACOS_TZDIR1); + __tzDir = MACOS_TZDIR1 "zone.tab"; + } else { + __tzZoneInfo = CFSTR(MACOS_TZDIR2); + __tzDir = MACOS_TZDIR2 "zone.tab"; + } + }); +} + +#elif DEPLOYMENT_TARGET_LINUX || DEPLOYMENT_TARGET_FREEBSD +static void __InitTZStrings(void) { + __tzZoneInfo = CFSTR(TZDIR); + __tzDir = TZDIR "zone.tab"; +} + +#else +#error Unknown or unspecified DEPLOYMENT_TARGET #endif static CFTimeZoneRef __CFTimeZoneCreateSystem(void) { @@ -745,11 +781,16 @@ static CFTimeZoneRef __CFTimeZoneCreateSystem(void) { CFRelease(name); if (result) return result; } - ret = readlink(TZZONELINK, linkbuf, sizeof(linkbuf)); - if (0 < ret) { + + if (!__tzZoneInfo) __InitTZStrings(); + ret = readlink(TZDEFAULT, linkbuf, sizeof(linkbuf)); + if (__tzZoneInfo && (0 < ret)) { linkbuf[ret] = '\0'; - if (strncmp(linkbuf, TZZONEINFO, sizeof(TZZONEINFO) - 1) == 0) { - name = CFStringCreateWithBytes(kCFAllocatorSystemDefault, (uint8_t *)linkbuf + sizeof(TZZONEINFO) - 1, strlen(linkbuf) - sizeof(TZZONEINFO) + 1, kCFStringEncodingUTF8, false); + const char *tzZoneInfo = CFStringGetCStringPtr(__tzZoneInfo, kCFStringEncodingASCII); + size_t zoneInfoDirLen = CFStringGetLength(__tzZoneInfo); + if (strncmp(linkbuf, tzZoneInfo, zoneInfoDirLen) == 0) { + name = CFStringCreateWithBytes(kCFAllocatorSystemDefault, (uint8_t *)linkbuf + zoneInfoDirLen, + strlen(linkbuf) - zoneInfoDirLen + 1, kCFStringEncodingUTF8, false); } else { name = CFStringCreateWithBytes(kCFAllocatorSystemDefault, (uint8_t *)linkbuf, strlen(linkbuf), kCFStringEncodingUTF8, false); } @@ -769,6 +810,15 @@ static CFTimeZoneRef __CFTimeZoneCreateSystem(void) { CFRelease(name); if (result) return result; } +#if DEPLOYMENT_TARGET_ANDROID + // Timezone database by name not available on Android. + // Approximate with gmtoff - could be general default. + struct tm info; + time_t now = time(NULL); + if (NULL != localtime_r(&now, &info)) { + return CFTimeZoneCreateWithTimeIntervalFromGMT(kCFAllocatorSystemDefault, info.tm_gmtoff); + } +#endif return CFTimeZoneCreateWithTimeIntervalFromGMT(kCFAllocatorSystemDefault, 0.0); } @@ -838,6 +888,7 @@ void CFTimeZoneSetDefault(CFTimeZoneRef tz) { } static CFDictionaryRef __CFTimeZoneCopyCompatibilityDictionary(void); +static Boolean __nameStringOK(CFStringRef name); CFArrayRef CFTimeZoneCopyKnownNames(void) { CFArrayRef tzs; @@ -853,7 +904,7 @@ CFArrayRef CFTimeZoneCopyKnownNames(void) { CFIndex idx; for (idx = CFArrayGetCount(list); idx--; ) { CFStringRef item = (CFStringRef)CFArrayGetValueAtIndex(list, idx); - if (CFDictionaryContainsKey(dict, item)) { + if (CFDictionaryContainsKey(dict, item) || !__nameStringOK(item)) { CFArrayRemoveValueAtIndex(list, idx); } } @@ -959,8 +1010,6 @@ void CFTimeZoneSetAbbreviationDictionary(CFDictionaryRef dict) { __CFTimeZoneUnlockGlobal(); } -#if DEPLOYMENT_RUNTIME_SWIFT - CF_INLINE const UChar *STRING_to_UTF16(CFStringRef S) { // UTF16String CFIndex length = CFStringGetLength((CFStringRef)S); UChar *buffer = (UChar *)malloc((length + 1) * sizeof(UChar)); @@ -1130,12 +1179,12 @@ Boolean _CFTimeZoneInit(CFTimeZoneRef timeZone, CFStringRef name, CFDataRef data CFIndex length; Boolean result = false; -#if DEPLOYMENT_TARGET_WINDOWS if (!__tzZoneInfo) __InitTZStrings(); if (!__tzZoneInfo) return NULL; +#if DEPLOYMENT_TARGET_WINDOWS baseURL = CFURLCreateWithFileSystemPath(kCFAllocatorSystemDefault, __tzZoneInfo, kCFURLWindowsPathStyle, true); #else - baseURL = CFURLCreateWithFileSystemPath(kCFAllocatorSystemDefault, CFSTR(TZZONEINFO), kCFURLPOSIXPathStyle, true); + baseURL = CFURLCreateWithFileSystemPath(kCFAllocatorSystemDefault, __tzZoneInfo, kCFURLPOSIXPathStyle, true); #endif if (tryAbbrev) { CFDictionaryRef abbrevs = CFTimeZoneCopyAbbreviationDictionary(); @@ -1156,15 +1205,9 @@ Boolean _CFTimeZoneInit(CFTimeZoneRef timeZone, CFStringRef name, CFDataRef data CFStringRef mapping = CFDictionaryGetValue(dict, name); if (mapping) { name = mapping; -#if DEPLOYMENT_TARGET_WINDOWS } else if (CFStringHasPrefix(name, __tzZoneInfo)) { CFMutableStringRef unprefixed = CFStringCreateMutableCopy(kCFAllocatorSystemDefault, CFStringGetLength(name), name); CFStringDelete(unprefixed, CFRangeMake(0, CFStringGetLength(__tzZoneInfo))); -#else - } else if (CFStringHasPrefix(name, CFSTR(TZZONEINFO))) { - CFMutableStringRef unprefixed = CFStringCreateMutableCopy(kCFAllocatorSystemDefault, CFStringGetLength(name), name); - CFStringDelete(unprefixed, CFRangeMake(0, sizeof(TZZONEINFO))); -#endif mapping = CFDictionaryGetValue(dict, unprefixed); if (mapping) { name = mapping; @@ -1196,7 +1239,6 @@ Boolean _CFTimeZoneInit(CFTimeZoneRef timeZone, CFStringRef name, CFDataRef data } return false; } -#endif CFTimeZoneRef CFTimeZoneCreate(CFAllocatorRef allocator, CFStringRef name, CFDataRef data) { // assert: (NULL != name && NULL != data); @@ -1337,12 +1379,12 @@ CFTimeZoneRef CFTimeZoneCreateWithName(CFAllocatorRef allocator, CFStringRef nam void *bytes; CFIndex length; -#if DEPLOYMENT_TARGET_WINDOWS if (!__tzZoneInfo) __InitTZStrings(); if (!__tzZoneInfo) return NULL; +#if DEPLOYMENT_TARGET_WINDOWS baseURL = CFURLCreateWithFileSystemPath(kCFAllocatorSystemDefault, __tzZoneInfo, kCFURLWindowsPathStyle, true); #else - baseURL = CFURLCreateWithFileSystemPath(kCFAllocatorSystemDefault, CFSTR(TZZONEINFO), kCFURLPOSIXPathStyle, true); + baseURL = CFURLCreateWithFileSystemPath(kCFAllocatorSystemDefault, __tzZoneInfo, kCFURLPOSIXPathStyle, true); #endif if (tryAbbrev) { CFDictionaryRef abbrevs = CFTimeZoneCopyAbbreviationDictionary(); @@ -1363,15 +1405,9 @@ CFTimeZoneRef CFTimeZoneCreateWithName(CFAllocatorRef allocator, CFStringRef nam CFStringRef mapping = CFDictionaryGetValue(dict, name); if (mapping) { name = mapping; -#if DEPLOYMENT_TARGET_WINDOWS } else if (CFStringHasPrefix(name, __tzZoneInfo)) { CFMutableStringRef unprefixed = CFStringCreateMutableCopy(kCFAllocatorSystemDefault, CFStringGetLength(name), name); CFStringDelete(unprefixed, CFRangeMake(0, CFStringGetLength(__tzZoneInfo))); -#else - } else if (CFStringHasPrefix(name, CFSTR(TZZONEINFO))) { - CFMutableStringRef unprefixed = CFStringCreateMutableCopy(kCFAllocatorSystemDefault, CFStringGetLength(name), name); - CFStringDelete(unprefixed, CFRangeMake(0, sizeof(TZZONEINFO))); -#endif mapping = CFDictionaryGetValue(dict, unprefixed); if (mapping) { name = mapping; @@ -1546,6 +1582,4 @@ static CFDictionaryRef __CFTimeZoneCopyCompatibilityDictionary(void) { return dict; } -#undef TZZONEINFO -#undef TZZONELINK diff --git a/Foundation/NSSwiftRuntime.swift b/Foundation/NSSwiftRuntime.swift index 4e03109996..a9c8bab051 100644 --- a/Foundation/NSSwiftRuntime.swift +++ b/Foundation/NSSwiftRuntime.swift @@ -86,6 +86,7 @@ extension ObjCBool : CustomStringConvertible { } #endif +@usableFromInline internal class __NSCFType : NSObject { private var _cfinfo : Int32 From af0e80b93f012de32d9fd2469284dc1579729ab7 Mon Sep 17 00:00:00 2001 From: Lily Vulcano Date: Fri, 28 Sep 2018 14:09:19 -0700 Subject: [PATCH 05/12] Ensure __CFEnv still reads XDG-related variables at startup when compiled off ObjC OSes. --- CoreFoundation/Base.subproj/CFRuntime.c | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/CoreFoundation/Base.subproj/CFRuntime.c b/CoreFoundation/Base.subproj/CFRuntime.c index e62ea7adba..0d37d578f7 100644 --- a/CoreFoundation/Base.subproj/CFRuntime.c +++ b/CoreFoundation/Base.subproj/CFRuntime.c @@ -1042,6 +1042,15 @@ static struct { {"CFNumberDisableCache", NULL}, {"__CFPREFERENCES_AVOID_DAEMON", NULL}, {"APPLE_FRAMEWORKS_ROOT", NULL}, +#if !DEPLOYMENT_RUNTIME_OBJC + {"HOME", NULL}, + {"XDG_DATA_HOME", NULL}, + {"XDG_CONFIG_HOME", NULL}, + {"XDG_DATA_DIRS", NULL}, + {"XDG_CONFIG_DIRS", NULL}, + {"XDG_CACHE_HOME", NULL}, + {"XDG_RUNTIME_DIR", NULL}, +#endif {NULL, NULL}, // the last one is for optional "COMMAND_MODE" "legacy", do not use this slot, insert before }; From c4fc02af1360545a1fbe58f21666435aaa82909b Mon Sep 17 00:00:00 2001 From: Lily Vulcano Date: Fri, 28 Sep 2018 14:20:07 -0700 Subject: [PATCH 06/12] =?UTF-8?q?Address=20the=20rest=20of=20@parkera?= =?UTF-8?q?=E2=80=99s=20feedback.?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- CoreFoundation/Base.subproj/CFUtilities.c | 4 ++-- CoreFoundation/Collections.subproj/CFData.c | 3 ++- CoreFoundation/Collections.subproj/CFStorage.c | 9 ++++----- 3 files changed, 8 insertions(+), 8 deletions(-) diff --git a/CoreFoundation/Base.subproj/CFUtilities.c b/CoreFoundation/Base.subproj/CFUtilities.c index 77d083598b..fcbb922930 100644 --- a/CoreFoundation/Base.subproj/CFUtilities.c +++ b/CoreFoundation/Base.subproj/CFUtilities.c @@ -572,13 +572,13 @@ CF_EXPORT void _CFGetUGIDs(uid_t *euid, gid_t *egid) { __CFGetUGIDs(euid, egid); } -CF_EXPORT uid_t _CFGetEUID() { +CF_EXPORT uid_t _CFGetEUID(void) { uid_t euid; __CFGetUGIDs(&euid, NULL); return euid; } -CF_EXPORT uid_t _CFGetEGID() { +CF_EXPORT uid_t _CFGetEGID(void) { uid_t egid; __CFGetUGIDs(NULL, &egid); return egid; diff --git a/CoreFoundation/Collections.subproj/CFData.c b/CoreFoundation/Collections.subproj/CFData.c index cdd305007f..883768d437 100644 --- a/CoreFoundation/Collections.subproj/CFData.c +++ b/CoreFoundation/Collections.subproj/CFData.c @@ -330,10 +330,11 @@ CFTypeID CFDataGetTypeID(void) { void _CFDataInit(CFMutableDataRef memory, CFOptionFlags variety, CFIndex capacity, const uint8_t *bytes, CFIndex length, Boolean noCopy) { Boolean isMutable = ((variety & __kCFMutableMask) != 0); Boolean isGrowable = ((variety & __kCFGrowableMask) != 0); + Boolean isDontDeallocate = ((variety & __kCFDontDeallocate) != 0); __CFDataSetNumBytesUsed(memory, 0); __CFDataSetLength(memory, 0); - __CFDataSetDontDeallocate(memory, true); + __CFDataSetDontDeallocate(memory, isDontDeallocate); if (isMutable && isGrowable) { __CFDataSetCapacity(memory, __CFDataRoundUpCapacity(1)); diff --git a/CoreFoundation/Collections.subproj/CFStorage.c b/CoreFoundation/Collections.subproj/CFStorage.c index 273b3a84b7..54e36a18ce 100644 --- a/CoreFoundation/Collections.subproj/CFStorage.c +++ b/CoreFoundation/Collections.subproj/CFStorage.c @@ -38,8 +38,7 @@ #endif #if DEPLOYMENT_TARGET_WINDOWS -// No C99 support -#define restrict +// Remember to use _CF_RESTRICT instead of restrict, which is correctly defined for DEPLOYMENT_TARGET_WINDOWS elsewhere. // Replace bzero #define bzero(dst, size) ZeroMemory(dst, size) @@ -245,7 +244,7 @@ static inline void __CFStorageSetChild(CFStorageNode *parentNode, CFIndex childI *((void **)&parentNode->info.notLeaf.child[childIndex]) = newChild; } -static inline void __CFStorageGetChildren(const CFStorageNode *parent, CFStorageNode ** restrict resultArray, bool shouldRetain, bool shouldFreeze) { +static inline void __CFStorageGetChildren(const CFStorageNode *parent, CFStorageNode ** _CF_RESTRICT resultArray, bool shouldRetain, bool shouldFreeze) { ASSERT(! parent->isLeaf); CFIndex i; for (i=0; i < 3; i++) { @@ -273,7 +272,7 @@ CF_INLINE void __CFStorageSetCache(CFStorageRef storage, CFStorageNode *node, CF /* Gets the location for the specified absolute loc from the cached info. Returns NULL if the location is not in the cache. */ -CF_INLINE uint8_t *__CFStorageGetFromCache(CFStorageRef storage, CFIndex loc, CFRange * restrict validConsecutiveValueRange, bool requireUnfrozenNode) { +CF_INLINE uint8_t *__CFStorageGetFromCache(CFStorageRef storage, CFIndex loc, CFRange * _CF_RESTRICT validConsecutiveValueRange, bool requireUnfrozenNode) { CFStorageNode * const cachedNode = storage->cacheNode; /* It's important we read from this field no more than once, for thread safety with other concurrent reads; that is why the field is marked volatile. */ if (! cachedNode) return NULL; /* No cache */ @@ -308,7 +307,7 @@ CF_INLINE uint8_t *__CFStorageGetFromCache(CFStorageRef storage, CFIndex loc, CF relativeByteNum (not optional, for performance reasons) returns the relative byte number of the specified byte in the child. Don't call with leaf nodes! */ -CF_INLINE CFStorageNode *__CFStorageFindChild(const CFStorageNode * restrict node, CFIndex byteNum, bool forInsertionOrDeletion, CFIndex * restrict childNum, CFIndex * restrict relativeByteNum) { +CF_INLINE CFStorageNode *__CFStorageFindChild(const CFStorageNode * _CF_RESTRICT node, CFIndex byteNum, bool forInsertionOrDeletion, CFIndex * _CF_RESTRICT childNum, CFIndex * _CF_RESTRICT relativeByteNum) { if (forInsertionOrDeletion) byteNum--; /* If for insertion, we do <= checks, not <, so this accomplishes the same thing */ CFStorageNode *result; result = node->info.notLeaf.child[0]; From ba09c4f93db19f669fed5ac71cf06a04cdc887a6 Mon Sep 17 00:00:00 2001 From: Lily Vulcano Date: Fri, 28 Sep 2018 14:20:47 -0700 Subject: [PATCH 07/12] Logical, not bitwise here. --- CoreFoundation/Base.subproj/CFPlatform.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CoreFoundation/Base.subproj/CFPlatform.c b/CoreFoundation/Base.subproj/CFPlatform.c index 87dd6e1bea..5f602bedb5 100644 --- a/CoreFoundation/Base.subproj/CFPlatform.c +++ b/CoreFoundation/Base.subproj/CFPlatform.c @@ -1383,7 +1383,7 @@ int _CFOpenFile(const char *path, int opts) { } CF_CROSS_PLATFORM_EXPORT void *_CFReallocf(void *ptr, size_t size) { -#if TARGET_OS_WIN32 | DEPLOYMENT_TARGET_LINUX +#if TARGET_OS_WIN32 || DEPLOYMENT_TARGET_LINUX void *mem = realloc(ptr, size); if (mem == NULL && ptr != NULL && size != 0) { free(ptr); From f76b5c7246528434ac0a3e687dee5b61cf11b3d0 Mon Sep 17 00:00:00 2001 From: Lily Vulcano Date: Fri, 28 Sep 2018 14:26:40 -0700 Subject: [PATCH 08/12] Reinstate __checkint_{u,}int32_mul in CFSortFunctions (prevent reverting of @uraimo's https://github.com/apple/swift-corelibs-foundation/pull/1396). --- CoreFoundation/Base.subproj/CFSortFunctions.c | 2 ++ 1 file changed, 2 insertions(+) diff --git a/CoreFoundation/Base.subproj/CFSortFunctions.c b/CoreFoundation/Base.subproj/CFSortFunctions.c index 0bac93d933..6b0aa1ddc0 100644 --- a/CoreFoundation/Base.subproj/CFSortFunctions.c +++ b/CoreFoundation/Base.subproj/CFSortFunctions.c @@ -52,6 +52,8 @@ enum { #define __checkint_int64_mul(x, y, err) (x * y) #define __checkint_uint64_add(x, y, err) (x + y) +#define __checkint_int32_mul(x,y,err) (x * y) +#define __checkint_uint32_add(x,y,err) (x + y) #endif From fb234f63f35e6ae2b1dd5b5167b7264d30af5c69 Mon Sep 17 00:00:00 2001 From: Lily Vulcano Date: Fri, 28 Sep 2018 14:29:12 -0700 Subject: [PATCH 09/12] Add Swift license header to CFRuntime_Internal.h. --- CoreFoundation/Base.subproj/CFRuntime_Internal.h | 14 ++++++++------ 1 file changed, 8 insertions(+), 6 deletions(-) diff --git a/CoreFoundation/Base.subproj/CFRuntime_Internal.h b/CoreFoundation/Base.subproj/CFRuntime_Internal.h index ce0c20f039..cc8db43ab0 100644 --- a/CoreFoundation/Base.subproj/CFRuntime_Internal.h +++ b/CoreFoundation/Base.subproj/CFRuntime_Internal.h @@ -1,9 +1,11 @@ -// -// CFRuntime_Internal.h -// CoreFoundation -// -// Created by Tony Parker on 4/21/18. -// +/* CFRuntime_Internal.h + Copyright (c) 2018, Apple Inc. and the Swift project authors + + Portions Copyright (c) 2014-2018, Apple Inc. and the Swift project authors + Licensed under Apache License v2.0 with Runtime Library Exception + See http://swift.org/LICENSE.txt for license information + See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors +*/ #ifndef CFRuntime_Internal_h #define CFRuntime_Internal_h From 867a4b2125f56b6c2fd398958efb7b3a7f3787b0 Mon Sep 17 00:00:00 2001 From: Lily Vulcano Date: Wed, 3 Oct 2018 14:50:32 -0700 Subject: [PATCH 10/12] Some changes from Foundation team review. Details in a PR comment. --- CoreFoundation/Base.subproj/CFBase.c | 10 ++-- CoreFoundation/Base.subproj/CFInternal.h | 4 +- CoreFoundation/Base.subproj/CFPlatform.c | 4 +- CoreFoundation/Base.subproj/CFPriv.h | 10 +--- CoreFoundation/Base.subproj/CFRuntime.c | 4 +- CoreFoundation/Base.subproj/CFSortFunctions.c | 4 +- CoreFoundation/Base.subproj/CFUtilities.c | 6 +-- .../Base.subproj/CoreFoundation_Prefix.h | 4 +- .../Base.subproj/ForFoundationOnly.h | 4 +- .../Collections.subproj/CFStorage.c | 4 +- CoreFoundation/Locale.subproj/CFLocale.c | 6 +-- .../NumberDate.subproj/CFTimeZone.c | 28 +++++------ CoreFoundation/PlugIn.subproj/CFBundle.c | 6 +-- .../PlugIn.subproj/CFBundle_InfoPlist.c | 46 +++++++++---------- .../PlugIn.subproj/CFBundle_Internal.h | 24 +++++----- .../Preferences.subproj/CFPreferences.c | 20 ++++---- .../CFXMLPreferencesDomain.c | 14 +++--- .../RunLoop.subproj/CFMessagePort.c | 2 +- CoreFoundation/RunLoop.subproj/CFRunLoop.c | 2 +- CoreFoundation/RunLoop.subproj/CFSocket.c | 2 +- .../Stream.subproj/CFConcreteStreams.c | 2 +- .../String.subproj/CFAttributedString.c | 2 +- CoreFoundation/String.subproj/CFBurstTrie.h | 2 +- CoreFoundation/String.subproj/CFString.h | 4 +- CoreFoundation/URL.subproj/CFURLComponents.h | 12 ++--- 25 files changed, 110 insertions(+), 116 deletions(-) diff --git a/CoreFoundation/Base.subproj/CFBase.c b/CoreFoundation/Base.subproj/CFBase.c index b828085399..bc2982c32e 100644 --- a/CoreFoundation/Base.subproj/CFBase.c +++ b/CoreFoundation/Base.subproj/CFBase.c @@ -22,8 +22,6 @@ #include #include -#include "ForFoundationOnly.h" - // -------- -------- -------- -------- -------- -------- -------- -------- struct __CFAllocator { @@ -746,8 +744,8 @@ void CFAllocatorGetContext(CFAllocatorRef allocator, CFAllocatorContext *context -static void __CFReallocationFailed(void *ptr, CFStringRef reason, void (^reallocationFailureHandler)(void *original, _Bool *outRecovered)) { - _Bool recovered = false; +static void __CFReallocationFailed(void *ptr, CFStringRef reason, void (^reallocationFailureHandler)(void *original, bool *outRecovered)) { + bool recovered = false; if (reallocationFailureHandler) { reallocationFailureHandler(ptr, &recovered); } @@ -759,7 +757,7 @@ static void __CFReallocationFailed(void *ptr, CFStringRef reason, void (^realloc } -void *__CFSafelyReallocate(void *destination, size_t newCapacity, void (^reallocationFailureHandler)(void *original, _Bool *outRecovered)) { +void *__CFSafelyReallocate(void *destination, size_t newCapacity, void (^reallocationFailureHandler)(void *original, bool *outRecovered)) { void *const reallocated = realloc(destination, newCapacity); if (__builtin_expect(reallocated == NULL, false)) { __CFReallocationFailed(destination, CFSTR("realloc"), reallocationFailureHandler); @@ -768,7 +766,7 @@ void *__CFSafelyReallocate(void *destination, size_t newCapacity, void (^realloc } -void *__CFSafelyReallocateWithAllocator(CFAllocatorRef allocator, void *destination, size_t newCapacity, CFOptionFlags options, void (^reallocationFailureHandler)(void *original, _Bool *outRecovered)) { +void *__CFSafelyReallocateWithAllocator(CFAllocatorRef allocator, void *destination, size_t newCapacity, CFOptionFlags options, void (^reallocationFailureHandler)(void *original, bool *outRecovered)) { void *reallocated = CFAllocatorReallocate(allocator, destination, newCapacity, options); // NOTE: important difference in behavior between realloc vs CFAllocateReallocate NULL+0 -> NULL for allocators! if (__builtin_expect(reallocated == NULL, false) && !(destination == NULL && newCapacity == 0)) { diff --git a/CoreFoundation/Base.subproj/CFInternal.h b/CoreFoundation/Base.subproj/CFInternal.h index 62d4a94f45..d8dcd5bf1e 100644 --- a/CoreFoundation/Base.subproj/CFInternal.h +++ b/CoreFoundation/Base.subproj/CFInternal.h @@ -95,7 +95,7 @@ CF_EXTERN_C_BEGIN #include #include -#if DEPLOYMENT_TARGET_MACOSX || DEPLOYMENT_TARGET_EMBEDDED || DEPLOYMENT_TARGET_EMBEDDED_MINI || DEPLOYMENT_TARGET_LINUX || DEPLOYMENT_TARGET_FREEBSD +#if TARGET_OS_MAC || TARGET_OS_LINUX || TARGET_OS_BSD #if !TARGET_OS_CYGWIN && !defined(__linux__) #include @@ -105,7 +105,7 @@ CF_EXTERN_C_BEGIN #include #include #include -#endif // DEPLOYMENT_TARGET_MACOSX || DEPLOYMENT_TARGET_EMBEDDED || DEPLOYMENT_TARGET_EMBEDDED_MINI || DEPLOYMENT_TARGET_LINUX || DEPLOYMENT_TARGET_FREEBSD +#endif // TARGET_OS_MAC || TARGET_OS_LINUX || TARGET_OS_BSD #include diff --git a/CoreFoundation/Base.subproj/CFPlatform.c b/CoreFoundation/Base.subproj/CFPlatform.c index 5f602bedb5..6cdc33dbd1 100644 --- a/CoreFoundation/Base.subproj/CFPlatform.c +++ b/CoreFoundation/Base.subproj/CFPlatform.c @@ -295,7 +295,7 @@ CF_EXPORT CFStringRef CFCopyUserName(void) { CF_CROSS_PLATFORM_EXPORT CFStringRef CFCopyFullUserName(void) { CFStringRef result = NULL; -#if DEPLOYMENT_TARGET_MACOSX || DEPLOYMENT_TARGET_EMBEDDED || DEPLOYMENT_TARGET_EMBEDDED_MINI || DEPLOYMENT_TARGET_LINUX || DEPLOYMENT_TARGET_FREEBSD +#if TARGET_OS_MAC || TARGET_OS_LINUX || TARGET_OS_BSD uid_t euid; __CFGetUGIDs(&euid, NULL); struct passwd *upwd = getpwuid(euid ? euid : getuid()); @@ -312,7 +312,7 @@ CF_CROSS_PLATFORM_EXPORT CFStringRef CFCopyFullUserName(void) { return result; } -#if DEPLOYMENT_TARGET_ANDROID +#if TARGET_OS_ANDROID #undef pw_gecos #endif diff --git a/CoreFoundation/Base.subproj/CFPriv.h b/CoreFoundation/Base.subproj/CFPriv.h index bffec48421..460923b6f0 100644 --- a/CoreFoundation/Base.subproj/CFPriv.h +++ b/CoreFoundation/Base.subproj/CFPriv.h @@ -26,15 +26,9 @@ #include #include -#ifndef CF_CROSS_PLATFORM_EXPORT - #if !DEPLOYMENT_RUNTIME_OBJC - #define CF_CROSS_PLATFORM_EXPORT extern - #else - #define CF_CROSS_PLATFORM_EXPORT static __attribute__((used)) - #endif -#endif +#define CF_CROSS_PLATFORM_EXPORT extern -#if DEPLOYMENT_TARGET_WINDOWS +#if TARGET_OS_WIN32 // No C99 support #define _CF_RESTRICT #else diff --git a/CoreFoundation/Base.subproj/CFRuntime.c b/CoreFoundation/Base.subproj/CFRuntime.c index 0d37d578f7..7a936f7f45 100644 --- a/CoreFoundation/Base.subproj/CFRuntime.c +++ b/CoreFoundation/Base.subproj/CFRuntime.c @@ -960,7 +960,7 @@ extern CFTypeID CFTreeGetTypeID(void); extern CFTypeID CFPlugInInstanceGetTypeID(void); extern CFTypeID CFStringTokenizerGetTypeID(void); extern CFTypeID CFStorageGetTypeID(void); -#if DEPLOYMENT_TARGET_LINUX || (DEPLOYMENT_TARGET_MACOSX && DEPLOYMENT_RUNTIME_SWIFT) +#if TARGET_OS_LINUX || (TARGET_OS_MAC && !DEPLOYMENT_RUNTIME_OBJC) CF_PRIVATE void __CFTSDInitialize(void); #endif #if DEPLOYMENT_TARGET_WINDOWS @@ -1124,7 +1124,7 @@ void __CFInitialize(void) { #if DEPLOYMENT_TARGET_WINDOWS // Must not call any CF functions __CFTSDWindowsInitialize(); -#elif DEPLOYMENT_TARGET_LINUX || (DEPLOYMENT_TARGET_MACOSX && !DEPLOYMENT_RUNTIME_OBJC) +#elif TARGET_OS_LINUX || (TARGET_OS_MAC && !DEPLOYMENT_RUNTIME_OBJC) __CFTSDInitialize(); #endif __CFProphylacticAutofsAccess = true; diff --git a/CoreFoundation/Base.subproj/CFSortFunctions.c b/CoreFoundation/Base.subproj/CFSortFunctions.c index 6b0aa1ddc0..674ff8e653 100644 --- a/CoreFoundation/Base.subproj/CFSortFunctions.c +++ b/CoreFoundation/Base.subproj/CFSortFunctions.c @@ -12,11 +12,11 @@ #include "CFInternal.h" #if __HAS_DISPATCH__ #include -#if (DEPLOYMENT_TARGET_MACOSX || DEPLOYMENT_TARGET_EMBEDDED) && __has_include() +#if TARGET_OS_MAC && __has_include() #include #else #define DISPATCH_APPLY_CURRENT_ROOT_QUEUE ((dispatch_queue_t _Nonnull)0) -#endif // (DEPLOYMENT_TARGET_MACOSX || DEPLOYMENT_TARGET_EMBEDDED) && __has_include() +#endif // TARGET_OS_MAC && __has_include() #endif // __HAS_DISPATCH__ #include "CFLogUtilities.h" #include "CFInternal.h" diff --git a/CoreFoundation/Base.subproj/CFUtilities.c b/CoreFoundation/Base.subproj/CFUtilities.c index fcbb922930..33a31995e1 100644 --- a/CoreFoundation/Base.subproj/CFUtilities.c +++ b/CoreFoundation/Base.subproj/CFUtilities.c @@ -1513,13 +1513,13 @@ CFDictionaryRef __CFGetEnvironment() { static dispatch_once_t once = 0L; static CFMutableDictionaryRef envDict = NULL; dispatch_once(&once, ^{ -#if DEPLOYMENT_TARGET_MACOSX || DEPLOYMENT_TARGET_EMBEDDED +#if TARGET_OS_MAC extern char ***_NSGetEnviron(void); char **envp = *_NSGetEnviron(); -#elif DEPLOYMENT_TARGET_FREEBSD || TARGET_OS_CYGWIN +#elif TARGET_OS_BSD || TARGET_OS_CYGWIN extern char **environ; char **envp = environ; -#elif DEPLOYMENT_TARGET_LINUX +#elif TARGET_OS_LINUX #if !defined(environ) && !TARGET_OS_ANDROID #define environ __environ #endif diff --git a/CoreFoundation/Base.subproj/CoreFoundation_Prefix.h b/CoreFoundation/Base.subproj/CoreFoundation_Prefix.h index 34b35e5aa7..35d00ff895 100644 --- a/CoreFoundation/Base.subproj/CoreFoundation_Prefix.h +++ b/CoreFoundation/Base.subproj/CoreFoundation_Prefix.h @@ -12,7 +12,9 @@ #define _DARWIN_UNLIMITED_SELECT 1 -#if (DEPLOYMENT_TARGET_MACOSX || DEPLOYMENT_TARGET_EMBEDDED || DEPLOYMENT_TARGET_EMBEDDED_MINI || DEPLOYMENT_TARGET_LINUX || DEPLOYMENT_TARGET_WINDOWS) +#include + +#if TARGET_OS_MAC || TARGET_OS_LINUX || TARGET_OS_WIN32 #if DEPLOYMENT_RUNTIME_SWIFT #if DEPLOYMENT_ENABLE_LIBDISPATCH #define __HAS_DISPATCH__ 1 diff --git a/CoreFoundation/Base.subproj/ForFoundationOnly.h b/CoreFoundation/Base.subproj/ForFoundationOnly.h index 2fe51d2435..7db02a5db8 100644 --- a/CoreFoundation/Base.subproj/ForFoundationOnly.h +++ b/CoreFoundation/Base.subproj/ForFoundationOnly.h @@ -65,8 +65,8 @@ CF_IMPLICIT_BRIDGING_DISABLED The outRecovered BOOL can be used to control what happens after the handler is called. If left unset, and the reallocationFailureHandler does unwind-the-stack/abort, we use the standard CF out-of-memory flow. If set to YES, then __CFSafelyReallocate{,WithAllocator} will return NULL. */ -CF_EXPORT void *_Nonnull __CFSafelyReallocate(void * _Nullable destination, size_t newCapacity, void (^_Nullable reallocationFailureHandler)(void *_Nonnull original, _Bool *_Nonnull outRecovered)); -CF_EXPORT void *_Nonnull __CFSafelyReallocateWithAllocator(CFAllocatorRef _Nullable, void * _Nullable destination, size_t newCapacity, CFOptionFlags options, void (^_Nullable reallocationFailureHandler)(void *_Nonnull original, _Bool *_Nonnull outRecovered)); +CF_EXPORT void *_Nonnull __CFSafelyReallocate(void * _Nullable destination, size_t newCapacity, void (^_Nullable reallocationFailureHandler)(void *_Nonnull original, bool *_Nonnull outRecovered)); +CF_EXPORT void *_Nonnull __CFSafelyReallocateWithAllocator(CFAllocatorRef _Nullable, void * _Nullable destination, size_t newCapacity, CFOptionFlags options, void (^_Nullable reallocationFailureHandler)(void *_Nonnull original, bool *_Nonnull outRecovered)); // ---- CFBundle material ---------------------------------------- diff --git a/CoreFoundation/Collections.subproj/CFStorage.c b/CoreFoundation/Collections.subproj/CFStorage.c index 54e36a18ce..6907abcbe8 100644 --- a/CoreFoundation/Collections.subproj/CFStorage.c +++ b/CoreFoundation/Collections.subproj/CFStorage.c @@ -37,8 +37,8 @@ #include #endif -#if DEPLOYMENT_TARGET_WINDOWS -// Remember to use _CF_RESTRICT instead of restrict, which is correctly defined for DEPLOYMENT_TARGET_WINDOWS elsewhere. +#if TARGET_OS_WIN32 +// Remember to use _CF_RESTRICT instead of restrict, which is correctly defined for TARGET_OS_WIN32 elsewhere. // Replace bzero #define bzero(dst, size) ZeroMemory(dst, size) diff --git a/CoreFoundation/Locale.subproj/CFLocale.c b/CoreFoundation/Locale.subproj/CFLocale.c index e47ea5d51c..112c0241b3 100644 --- a/CoreFoundation/Locale.subproj/CFLocale.c +++ b/CoreFoundation/Locale.subproj/CFLocale.c @@ -302,11 +302,11 @@ static void _setCachedCurrentLocale(CFLocaleRef newLocale) { } -#if DEPLOYMENT_TARGET_MACOSX && !DEPLOYMENT_RUNTIME_SWIFT +#if TARGET_OS_OSX && !DEPLOYMENT_RUNTIME_SWIFT #define FALLBACK_LOCALE_NAME CFSTR("") -#elif DEPLOYMENT_TARGET_EMBEDDED || DEPLOYMENT_TARGET_EMBEDDED_MINI +#elif TARGET_OS_IPHONE #define FALLBACK_LOCALE_NAME CFSTR("en_US") -#elif DEPLOYMENT_TARGET_WINDOWS || DEPLOYMENT_TARGET_LINUX || DEPLOYMENT_TARGET_FREEBSD || DEPLOYMENT_RUNTIME_SWIFT +#elif TARGET_OS_WINDOWS || TARGET_OS_LINUX || TARGET_OS_BSD || DEPLOYMENT_RUNTIME_SWIFT #define FALLBACK_LOCALE_NAME CFSTR("en_US") #endif diff --git a/CoreFoundation/NumberDate.subproj/CFTimeZone.c b/CoreFoundation/NumberDate.subproj/CFTimeZone.c index beeaa7c063..3b71b626f8 100644 --- a/CoreFoundation/NumberDate.subproj/CFTimeZone.c +++ b/CoreFoundation/NumberDate.subproj/CFTimeZone.c @@ -25,19 +25,19 @@ #include #include #include -#if DEPLOYMENT_TARGET_MACOSX || DEPLOYMENT_TARGET_EMBEDDED || DEPLOYMENT_TARGET_LINUX || DEPLOYMENT_TARGET_FREEBSD +#if TARGET_OS_MAC || TARGET_OS_LINUX || TARGET_OS_BSD #include #include #if !TARGET_OS_ANDROID #include #endif #endif -#if DEPLOYMENT_TARGET_MACOSX || DEPLOYMENT_TARGET_EMBEDDED +#if TARGET_OS_MAC #include #define MACOS_TZDIR1 "/usr/share/zoneinfo/" // 10.12 and earlier #define MACOS_TZDIR2 "/var/db/timezone/zoneinfo/" // 10.13 onwards -#elif DEPLOYMENT_TARGET_LINUX || DEPLOYMENT_TARGET_FREEBSD +#elif TARGET_OS_LINUX || TARGET_OS_BSD #ifndef TZDIR #define TZDIR "/usr/share/zoneinfo/" /* Time zone object file directory */ #endif /* !defined TZDIR */ @@ -76,7 +76,7 @@ static CFArrayRef __CFKnownTimeZoneList = NULL; static CFMutableDictionaryRef __CFTimeZoneCache = NULL; static CFLock_t __CFTimeZoneGlobalLock = CFLockInit; -#if DEPLOYMENT_TARGET_WINDOWS +#if TARGET_OS_WIN32 static CFDictionaryRef __CFTimeZoneWinToOlsonDict = NULL; static CFLock_t __CFTimeZoneWinToOlsonLock = CFLockInit; #endif @@ -105,7 +105,7 @@ CF_INLINE void __CFTimeZoneUnlockCompatibilityMapping(void) { __CFUnlock(&__CFTimeZoneCompatibilityMappingLock); } -#if DEPLOYMENT_TARGET_WINDOWS +#if TARGET_OS_WIN32 /* This function should be used for WIN32 instead of * __CFCopyRecursiveDirectoryList function. * It takes TimeZone names from the registry @@ -141,7 +141,7 @@ static CFMutableArrayRef __CFCopyWindowsTimeZoneList() { RegCloseKey(hkResult); return result; } -#elif DEPLOYMENT_TARGET_MACOSX || DEPLOYMENT_TARGET_EMBEDDED || DEPLOYMENT_TARGET_WINDOWS || DEPLOYMENT_TARGET_LINUX || DEPLOYMENT_TARGET_FREEBSD +#elif TARGET_OS_MAC || TARGET_OS_WIN32 || TARGET_OS_LINUX || TARGET_OS_BSD static CFMutableArrayRef __CFCopyRecursiveDirectoryList() { CFMutableArrayRef result = CFArrayCreateMutable(kCFAllocatorSystemDefault, 0, &kCFTypeArrayCallBacks); if (!__tzDir) __InitTZStrings(); @@ -457,7 +457,7 @@ CFTypeID CFTimeZoneGetTypeID(void) { return _kCFRuntimeIDCFTimeZone; } -#if DEPLOYMENT_TARGET_WINDOWS +#if TARGET_OS_WIN32 static const char *__CFTimeZoneWinToOlsonDefaults = /* Mappings to time zones in Windows Registry are best-guess */ "" @@ -694,7 +694,7 @@ static void __InitTZStrings(void) { __CFUnlock(&__CFTZDirLock); } -#elif DEPLOYMENT_TARGET_MACOSX || DEPLOYMENT_TARGET_EMBEDDED +#elif TARGET_OS_MAC static void __InitTZStrings(void) { static dispatch_once_t initOnce = 0; @@ -729,7 +729,7 @@ static void __InitTZStrings(void) { }); } -#elif DEPLOYMENT_TARGET_LINUX || DEPLOYMENT_TARGET_FREEBSD +#elif TARGET_OS_LINUX || TARGET_OS_BSD static void __InitTZStrings(void) { __tzZoneInfo = CFSTR(TZDIR); __tzDir = TZDIR "zone.tab"; @@ -744,7 +744,7 @@ static CFTimeZoneRef __CFTimeZoneCreateSystem(void) { CFStringRef name = NULL; -#if DEPLOYMENT_TARGET_WINDOWS +#if TARGET_OS_WIN32 TIME_ZONE_INFORMATION tzi = { 0 }; DWORD rval = GetTimeZoneInformation(&tzi); if (rval != TIME_ZONE_ID_INVALID) { @@ -810,7 +810,7 @@ static CFTimeZoneRef __CFTimeZoneCreateSystem(void) { CFRelease(name); if (result) return result; } -#if DEPLOYMENT_TARGET_ANDROID +#if TARGET_OS_ANDROID // Timezone database by name not available on Android. // Approximate with gmtoff - could be general default. struct tm info; @@ -1181,7 +1181,7 @@ Boolean _CFTimeZoneInit(CFTimeZoneRef timeZone, CFStringRef name, CFDataRef data if (!__tzZoneInfo) __InitTZStrings(); if (!__tzZoneInfo) return NULL; -#if DEPLOYMENT_TARGET_WINDOWS +#if TARGET_OS_WIN32 baseURL = CFURLCreateWithFileSystemPath(kCFAllocatorSystemDefault, __tzZoneInfo, kCFURLWindowsPathStyle, true); #else baseURL = CFURLCreateWithFileSystemPath(kCFAllocatorSystemDefault, __tzZoneInfo, kCFURLPOSIXPathStyle, true); @@ -1381,7 +1381,7 @@ CFTimeZoneRef CFTimeZoneCreateWithName(CFAllocatorRef allocator, CFStringRef nam if (!__tzZoneInfo) __InitTZStrings(); if (!__tzZoneInfo) return NULL; -#if DEPLOYMENT_TARGET_WINDOWS +#if TARGET_OS_WIN32 baseURL = CFURLCreateWithFileSystemPath(kCFAllocatorSystemDefault, __tzZoneInfo, kCFURLWindowsPathStyle, true); #else baseURL = CFURLCreateWithFileSystemPath(kCFAllocatorSystemDefault, __tzZoneInfo, kCFURLPOSIXPathStyle, true); @@ -1459,7 +1459,7 @@ CFDataRef CFTimeZoneGetData(CFTimeZoneRef tz) { /* This function converts CFAbsoluteTime to (Win32) SYSTEMTIME * (Aleksey Dukhnyakov) */ -#if DEPLOYMENT_TARGET_WINDOWS +#if TARGET_OS_WIN32 BOOL __CFTimeZoneGetWin32SystemTime(SYSTEMTIME * sys_time, CFAbsoluteTime time) { LONGLONG l; diff --git a/CoreFoundation/PlugIn.subproj/CFBundle.c b/CoreFoundation/PlugIn.subproj/CFBundle.c index a07923f98d..6a756d025b 100644 --- a/CoreFoundation/PlugIn.subproj/CFBundle.c +++ b/CoreFoundation/PlugIn.subproj/CFBundle.c @@ -135,7 +135,7 @@ static void _CFBundleEnsureBundlesExistForImagePaths(CFArrayRef imagePaths); #pragma mark - -#if !DEPLOYMENT_RUNTIME_OBJC && !DEPLOYMENT_TARGET_WINDOWS && !DEPLOYMENT_TARGET_ANDROID +#if !DEPLOYMENT_RUNTIME_OBJC && !TARGET_OS_WIN32 && !TARGET_OS_ANDROID // Functions and constants for FHS bundles: #define _CFBundleFHSDirectory_share CFSTR("share") @@ -160,7 +160,7 @@ static Boolean _CFBundleURLIsForFHSInstalledBundle(CFURLRef bundleURL) { return isFHSBundle; } -#endif // !DEPLOYMENT_RUNTIME_OBJC && !DEPLOYMENT_TARGET_WINDOWS && !DEPLOYMENT_TARGET_ANDROID +#endif // !DEPLOYMENT_RUNTIME_OBJC && !TARGET_OS_WIN32 && !TARGET_OS_ANDROID CF_CROSS_PLATFORM_EXPORT Boolean _CFBundleSupportsFHSBundles() { #if !DEPLOYMENT_RUNTIME_OBJC && !DEPLOYMENT_TARGET_WINDOWS && !DEPLOYMENT_TARGET_ANDROID @@ -726,7 +726,7 @@ static CFBundleRef _CFBundleCreate(CFAllocatorRef allocator, CFURLRef bundleURL, bundle->_url = newURL; -#if !DEPLOYMENT_RUNTIME_OBJC && !DEPLOYMENT_TARGET_WINDOWS && !DEPLOYMENT_TARGET_ANDROID +#if !DEPLOYMENT_RUNTIME_OBJC && !TARGET_OS_WIN32 && !TARGET_OS_ANDROID bundle->_isFHSInstalledBundle = _CFBundleURLIsForFHSInstalledBundle(newURL); #endif diff --git a/CoreFoundation/PlugIn.subproj/CFBundle_InfoPlist.c b/CoreFoundation/PlugIn.subproj/CFBundle_InfoPlist.c index e48c6857bf..8cf1710967 100644 --- a/CoreFoundation/PlugIn.subproj/CFBundle_InfoPlist.c +++ b/CoreFoundation/PlugIn.subproj/CFBundle_InfoPlist.c @@ -15,7 +15,7 @@ #include #include -#if (DEPLOYMENT_TARGET_MACOSX || DEPLOYMENT_TARGET_EMBEDDED || DEPLOYMENT_TARGET_LINUX || DEPLOYMENT_TARGET_EMBEDDED_MINI || DEPLOYMENT_TARGET_FREEBSD) && !TARGET_OS_CYGWIN +#if (TARGET_OS_MAC || TARGET_OS_LINUX || TARGET_OS_BSD) && !TARGET_OS_CYGWIN #include #if !TARGET_OS_ANDROID #include @@ -49,7 +49,7 @@ CF_PRIVATE void _CFBundleResourcesInitialize() { #else -#if DEPLOYMENT_TARGET_EMBEDDED || DEPLOYMENT_TARGET_EMBEDDED_MINI +#if TARGET_OS_IPHONE // On iOS, we only support one platform #define _CFBundleNumberOfPlatforms 1 static const CFStringRef _CFBundleSupportedPlatforms[_CFBundleNumberOfPlatforms] = { CFSTR("iphoneos") }; @@ -87,7 +87,7 @@ CF_PRIVATE void _CFBundleResourcesInitialize() { } #pragma mark Product and Platform Getters - Exported static CFStringRef _cfBundlePlatform = NULL; -#if DEPLOYMENT_TARGET_EMBEDDED || DEPLOYMENT_TARGET_EMBEDDED_MINI +#if TARGET_OS_IPHONE static CFStringRef _cfBundlePlatformSuffix = NULL; CF_PRIVATE CFStringRef _CFBundleGetProductNameSuffix(void); #endif @@ -96,7 +96,7 @@ CF_EXPORT void _CFSetProductName(CFStringRef str) { if (str) CFRetain(str); _cfBundlePlatform = str; -#if DEPLOYMENT_TARGET_EMBEDDED || DEPLOYMENT_TARGET_EMBEDDED_MINI +#if TARGET_OS_IPHONE // Reset the suffix version too _cfBundlePlatformSuffix = NULL; (void)_CFBundleGetProductNameSuffix(); @@ -109,7 +109,7 @@ CF_EXPORT void _CFSetProductName(CFStringRef str) { } CF_EXPORT CFStringRef _CFGetProductName(void) { -#if DEPLOYMENT_TARGET_EMBEDDED || DEPLOYMENT_TARGET_EMBEDDED_MINI +#if TARGET_OS_IPHONE if (!_cfBundlePlatform) { // We only honor the classic suffix if it is one of two preset values. Otherwise we fall back to the result of sysctlbyname. const char *classicSuffix = __CFgetenv("CLASSIC_SUFFIX"); @@ -153,7 +153,7 @@ CF_EXPORT CFStringRef _CFGetProductName(void) { } CF_PRIVATE CFStringRef _CFBundleGetProductNameSuffix(void) { -#if DEPLOYMENT_TARGET_EMBEDDED || DEPLOYMENT_TARGET_EMBEDDED_MINI +#if TARGET_OS_IPHONE // Not dispatch once, because this can be reset (by a rare API call). If a race happens, it just leaks one string. if (!_cfBundlePlatformSuffix) { CFStringRef productName = _CFGetProductName(); @@ -170,19 +170,19 @@ CF_PRIVATE CFStringRef _CFBundleGetProductNameSuffix(void) { } CF_PRIVATE CFStringRef _CFBundleGetPlatformNameSuffix(void) { -#if DEPLOYMENT_TARGET_MACOSX +#if TARGET_OS_OSX return _CFBundleMacOSXPlatformNameSuffix; -#elif DEPLOYMENT_TARGET_EMBEDDED || DEPLOYMENT_TARGET_EMBEDDED_MINI +#elif TARGET_OS_IPHONE return _CFBundleiPhoneOSPlatformNameSuffix; -#elif DEPLOYMENT_TARGET_WINDOWS +#elif TARGET_OS_WIN32 return _CFBundleWindowsPlatformNameSuffix; #elif DEPLOYMENT_TARGET_SOLARIS return _CFBundleSolarisPlatformNameSuffix; #elif DEPLOYMENT_TARGET_HPUX return _CFBundleHPUXPlatformNameSuffix; -#elif DEPLOYMENT_TARGET_LINUX +#elif TARGET_OS_LINUX return _CFBundleLinuxPlatformNameSuffix; -#elif DEPLOYMENT_TARGET_FREEBSD +#elif TARGET_OS_BSD return _CFBundleFreeBSDPlatformNameSuffix; #else #error Unknown or unspecified DEPLOYMENT_TARGET @@ -191,23 +191,23 @@ CF_PRIVATE CFStringRef _CFBundleGetPlatformNameSuffix(void) { // All new-style bundles will have these extensions. CF_EXPORT CFStringRef _CFGetPlatformName(void) { -#if DEPLOYMENT_TARGET_MACOSX +#if TARGET_OS_OSX return _CFBundleMacOSXPlatformName; -#elif DEPLOYMENT_TARGET_EMBEDDED || DEPLOYMENT_TARGET_EMBEDDED_MINI +#elif TARGET_OS_IPHONE return _CFBundleiPhoneOSPlatformName; -#elif DEPLOYMENT_TARGET_WINDOWS +#elif TARGET_OS_WIN32 return _CFBundleWindowsPlatformName; #elif DEPLOYMENT_TARGET_SOLARIS return _CFBundleSolarisPlatformName; #elif DEPLOYMENT_TARGET_HPUX return _CFBundleHPUXPlatformName; -#elif DEPLOYMENT_TARGET_LINUX +#elif TARGET_OS_LINUX #if TARGET_OS_CYGWIN return _CFBundleCygwinPlatformName; #else return _CFBundleLinuxPlatformName; #endif -#elif DEPLOYMENT_TARGET_FREEBSD +#elif TARGET_OS_BSD return _CFBundleFreeBSDPlatformName; #else #error Unknown or unspecified DEPLOYMENT_TARGET @@ -215,19 +215,19 @@ CF_EXPORT CFStringRef _CFGetPlatformName(void) { } CF_EXPORT CFStringRef _CFGetAlternatePlatformName(void) { -#if DEPLOYMENT_TARGET_MACOSX +#if TARGET_OS_OSX return _CFBundleAlternateMacOSXPlatformName; -#elif DEPLOYMENT_TARGET_EMBEDDED || DEPLOYMENT_TARGET_EMBEDDED_MINI +#elif TARGET_OS_IPHONE return _CFBundleMacOSXPlatformName; -#elif DEPLOYMENT_TARGET_WINDOWS +#elif TARGET_OS_WIN32 return CFSTR(""); -#elif DEPLOYMENT_TARGET_LINUX +#elif TARGET_OS_LINUX #if TARGET_OS_CYGWIN return CFSTR("Cygwin"); #else return CFSTR("Linux"); #endif -#elif DEPLOYMENT_TARGET_FREEBSD +#elif TARGET_OS_BSD return CFSTR("FreeBSD"); #else #error Unknown or unspecified DEPLOYMENT_TARGET @@ -1119,7 +1119,7 @@ static CFPropertyListRef _CFBundleCreateFilteredInfoPlistWithURL(CFURLRef infoPl void *bytes = NULL; CFIndex length = 0; -#if DEPLOYMENT_TARGET_MACOSX || DEPLOYMENT_TARGET_EMBEDDED || DEPLOYMENT_TARGET_EMBEDDED_MINI +#if TARGET_OS_MAC Boolean mapped = options & _CFBundleFilteredPlistMemoryMapped ? true : false; #else Boolean mapped = false; @@ -1148,7 +1148,7 @@ static CFPropertyListRef _CFBundleCreateFilteredInfoPlistWithURL(CFURLRef infoPl CFRelease(newKeyPaths); CFRelease(infoPlistData); if (mapped) { -#if DEPLOYMENT_TARGET_MACOSX || DEPLOYMENT_TARGET_EMBEDDED || DEPLOYMENT_TARGET_EMBEDDED_MINI +#if TARGET_OS_MAC munmap(bytes, length); #endif } else { diff --git a/CoreFoundation/PlugIn.subproj/CFBundle_Internal.h b/CoreFoundation/PlugIn.subproj/CFBundle_Internal.h index 93c973086a..140f0f0ac4 100644 --- a/CoreFoundation/PlugIn.subproj/CFBundle_Internal.h +++ b/CoreFoundation/PlugIn.subproj/CFBundle_Internal.h @@ -24,26 +24,26 @@ CF_EXTERN_C_BEGIN #define __kCFLogBundle 3 #define __kCFLogPlugIn 3 -#if DEPLOYMENT_TARGET_WINDOWS +#if TARGET_OS_WIN32 #define PLATFORM_PATH_STYLE kCFURLWindowsPathStyle #else #define PLATFORM_PATH_STYLE kCFURLPOSIXPathStyle #endif // FHS bundles are supported on the Swift and C runtimes, except on Windows. -#if !DEPLOYMENT_RUNTIME_OBJC && !DEPLOYMENT_TARGET_WINDOWS && !DEPLOYMENT_TARGET_ANDROID +#if !DEPLOYMENT_RUNTIME_OBJC && !TARGET_OS_WIN32 && !TARGET_OS_ANDROID -#if DEPLOYMENT_TARGET_LINUX || DEPLOYMENT_TARGET_FREEBSD +#if TARGET_OS_LINUX || TARGET_OS_BSD #define _CFBundleFHSSharedLibraryFilenamePrefix CFSTR("lib") #define _CFBundleFHSSharedLibraryFilenameSuffix CFSTR(".so") -#elif DEPLOYMENT_TARGET_MACOSX || DEPLOYMENT_TARGET_EMBEDDED || DEPLOYMENT_TARGET_EMBEDDED_MINI +#elif TARGET_OS_MAC #define _CFBundleFHSSharedLibraryFilenamePrefix CFSTR("lib") #define _CFBundleFHSSharedLibraryFilenameSuffix CFSTR(".dylib") #else // a non-covered DEPLOYMENT_TARGET… #error Disable FHS bundles or specify shared library prefixes and suffixes for this platform. #endif // DEPLOYMENT_TARGET_… -#endif // !DEPLOYMENT_RUNTIME_OBJC && !DEPLOYMENT_TARGET_WINDOWS && !DEPLOYMENT_TARGET_ANDROID +#endif // !DEPLOYMENT_RUNTIME_OBJC && !TARGET_OS_WIN32 && !TARGET_OS_ANDROID #define CFBundleExecutableNotFoundError 4 #define CFBundleExecutableNotLoadableError 3584 @@ -80,7 +80,7 @@ struct __CFBundle { CFURLRef _url; -#if !DEPLOYMENT_RUNTIME_OBJC && !DEPLOYMENT_TARGET_WINDOWS && !DEPLOYMENT_TARGET_ANDROID +#if !DEPLOYMENT_RUNTIME_OBJC && !TARGET_OS_WIN32 && !TARGET_OS_ANDROID Boolean _isFHSInstalledBundle; #endif @@ -190,7 +190,7 @@ CF_PRIVATE CFURLRef _CFBundleCopyResourcesDirectoryURLInDirectory(CFURLRef bundl CF_PRIVATE Boolean _CFBundleCouldBeBundle(CFURLRef url); CF_PRIVATE CFDictionaryRef _CFBundleCopyInfoDictionaryInResourceForkWithAllocator(CFAllocatorRef alloc, CFURLRef url); CF_PRIVATE CFStringRef _CFBundleCopyExecutableName(CFBundleRef bundle, CFURLRef url, CFDictionaryRef infoDict); -#if DEPLOYMENT_TARGET_MACOSX +#if TARGET_OS_OSX CF_PRIVATE CFStringRef _CFBundleCopyBundleDevelopmentRegionFromVersResource(CFBundleRef bundle); #endif CF_PRIVATE CFDictionaryRef _CFBundleCopyInfoDictionaryInExecutable(CFURLRef url); @@ -257,7 +257,7 @@ extern void _CFPlugInRemoveFactory(CFPlugInRef plugIn, _CFPFactoryRef factory); #define _CFBundleExecutablesDirectoryName CFSTR("Executables") #define _CFBundleNonLocalizedResourcesDirectoryName CFSTR("Non-localized Resources") -#if DEPLOYMENT_TARGET_WINDOWS +#if TARGET_OS_WIN32 #define _CFBundleSupportFilesDirectoryName1WithResources CFSTR("Support Files\\Resources") #define _CFBundleSupportFilesDirectoryName2WithResources CFSTR("Contents\\Resources") #else @@ -282,12 +282,12 @@ extern void _CFPlugInRemoveFactory(CFPlugInRef plugIn, _CFPFactoryRef factory); #define _CFBundleInfoURLFromBase3 CFSTR("Info.plist") #define _CFBundleInfoURLFromBaseNoExtension3 CFSTR("Info") -#if DEPLOYMENT_TARGET_MACOSX +#if TARGET_OS_OSX #define _CFBundlePlatformInfoURLFromBase0 CFSTR("Resources/Info-macos.plist") #define _CFBundlePlatformInfoURLFromBase1 CFSTR("Support%20Files/Info-macos.plist") #define _CFBundlePlatformInfoURLFromBase2 CFSTR("Contents/Info-macos.plist") #define _CFBundlePlatformInfoURLFromBase3 CFSTR("Info-macos.plist") -#elif DEPLOYMENT_TARGET_EMBEDDED || DEPLOYMENT_TARGET_EMBEDDED_MINI +#elif TARGET_OS_IPHONE #define _CFBundlePlatformInfoURLFromBase0 CFSTR("Resources/Info-iphoneos.plist") #define _CFBundlePlatformInfoURLFromBase1 CFSTR("Support%20Files/Info-iphoneos.plist") #define _CFBundlePlatformInfoURLFromBase2 CFSTR("Contents/Info-iphoneos.plist") @@ -302,9 +302,9 @@ extern void _CFPlugInRemoveFactory(CFPlugInRef plugIn, _CFPFactoryRef factory); #define _CFBundleInfoPlistName CFSTR("Info.plist") -#if DEPLOYMENT_TARGET_MACOSX +#if TARGET_OS_OSX #define _CFBundlePlatformInfoPlistName CFSTR("Info-macos.plist") -#elif DEPLOYMENT_TARGET_EMBEDDED || DEPLOYMENT_TARGET_EMBEDDED_MINI +#elif TARGET_OS_IPHONE #define _CFBundlePlatformInfoPlistName CFSTR("Info-iphoneos.plist") #else // No platform-specific Info.plist for these diff --git a/CoreFoundation/Preferences.subproj/CFPreferences.c b/CoreFoundation/Preferences.subproj/CFPreferences.c index 901ff4fec5..65d96f9801 100644 --- a/CoreFoundation/Preferences.subproj/CFPreferences.c +++ b/CoreFoundation/Preferences.subproj/CFPreferences.c @@ -10,18 +10,18 @@ #include #include -#if DEPLOYMENT_TARGET_MACOSX || DEPLOYMENT_TARGET_EMBEDDED +#if TARGET_OS_MAC #include #endif #include -#if DEPLOYMENT_TARGET_MACOSX || DEPLOYMENT_TARGET_EMBEDDED || DEPLOYMENT_TARGET_WINDOWS +#if TARGET_OS_MAC || TARGET_OS_WIN32 #include #endif #include #include #include "CFInternal.h" #include -#if DEPLOYMENT_TARGET_MACOSX +#if TARGET_OS_OSX #include #include #endif @@ -89,12 +89,12 @@ CF_EXPORT void CFPreferencesDumpMem(void) { } #endif -#if DEPLOYMENT_TARGET_MACOSX +#if TARGET_OS_OSX #pragma mark - #pragma mark Determining host UUID #endif -#if DEPLOYMENT_TARGET_MACOSX || DEPLOYMENT_TARGET_EMBEDDED +#if TARGET_OS_MAC // The entry point is in libSystem.B.dylib, but not actually declared // If this becomes available in a header (), I need to pull this out int gethostuuid(unsigned char *uuid_buf, const struct timespec *timeoutp); @@ -169,14 +169,14 @@ CF_PRIVATE CFStringRef _CFPreferencesGetByHostIdentifierString(void) { static unsigned long __CFSafeLaunchLevel = 0; -#if DEPLOYMENT_TARGET_WINDOWS +#if TARGET_OS_WIN32 #include #endif static CFURLRef _preferencesDirectoryForUserHostSafetyLevel(CFStringRef userName, CFStringRef hostName, unsigned long safeLevel) { CFAllocatorRef alloc = __CFPreferencesAllocator(); -#if DEPLOYMENT_TARGET_WINDOWS +#if TARGET_OS_WIN32 CFURLRef url = NULL; @@ -449,7 +449,7 @@ static CFStringRef _CFPreferencesStandardDomainCacheKey(CFStringRef domainName static CFURLRef _CFPreferencesURLForStandardDomainWithSafetyLevel(CFStringRef domainName, CFStringRef userName, CFStringRef hostName, unsigned long safeLevel) { CFURLRef theURL = NULL; CFAllocatorRef prefAlloc = __CFPreferencesAllocator(); -#if DEPLOYMENT_TARGET_MACOSX || DEPLOYMENT_TARGET_LINUX || DEPLOYMENT_TARGET_WINDOWS +#if TARGET_OS_OSX || TARGET_OS_LINUX || TARGET_OS_WIN32 CFURLRef prefDir = _preferencesDirectoryForUserHostSafetyLevel(userName, hostName, safeLevel); CFStringRef appName; CFStringRef fileName; @@ -483,9 +483,9 @@ static CFURLRef _CFPreferencesURLForStandardDomainWithSafetyLevel(CFStringRef do CFRelease(appName); } if (fileName) { -#if DEPLOYMENT_TARGET_MACOSX || DEPLOYMENT_TARGET_EMBEDDED || DEPLOYMENT_TARGET_LINUX +#if TARGET_OS_MAC || TARGET_OS_LINUX theURL = CFURLCreateWithFileSystemPathRelativeToBase(prefAlloc, fileName, kCFURLPOSIXPathStyle, false, prefDir); -#elif DEPLOYMENT_TARGET_WINDOWS +#elif TARGET_OS_WIN32 theURL = CFURLCreateWithFileSystemPathRelativeToBase(prefAlloc, fileName, kCFURLWindowsPathStyle, false, prefDir); #endif if (prefDir) CFRelease(prefDir); diff --git a/CoreFoundation/Preferences.subproj/CFXMLPreferencesDomain.c b/CoreFoundation/Preferences.subproj/CFXMLPreferencesDomain.c index 1b767091f0..4578dc242a 100644 --- a/CoreFoundation/Preferences.subproj/CFXMLPreferencesDomain.c +++ b/CoreFoundation/Preferences.subproj/CFXMLPreferencesDomain.c @@ -16,7 +16,7 @@ #include #include "CFInternal.h" #include -#if DEPLOYMENT_TARGET_MACOSX +#if TARGET_OS_OSX #include #include #include @@ -51,11 +51,11 @@ CF_PRIVATE CFAllocatorRef __CFPreferencesAllocator(void); // Directly ripped from Foundation.... static void __CFMilliSleep(uint32_t msecs) { -#if DEPLOYMENT_TARGET_WINDOWS +#if TARGET_OS_WIN32 SleepEx(msecs, false); #elif defined(__svr4__) || defined(__hpux__) sleep((msecs + 900) / 1000); -#elif DEPLOYMENT_TARGET_MACOSX || DEPLOYMENT_TARGET_LINUX +#elif TARGET_OS_OSX || TARGET_OS_LINUX struct timespec input; input.tv_sec = msecs / 1000; input.tv_nsec = (msecs - input.tv_sec * 1000) * 1000000; @@ -105,7 +105,7 @@ static Boolean _createDirectory(CFURLRef dirURL, Boolean worldReadable) { if (parentURL) CFRelease(parentURL); if (!parentExists) return false; -#if DEPLOYMENT_TARGET_MACOSX || DEPLOYMENT_TARGET_LINUX +#if TARGET_OS_OSX || TARGET_OS_LINUX mode = worldReadable ? S_IRWXU|S_IRWXG|S_IROTH|S_IXOTH : S_IRWXU; #else mode = 0666; @@ -213,7 +213,7 @@ static CFTypeRef fetchXMLValue(CFTypeRef context, void *xmlDomain, CFStringRef k } -#if DEPLOYMENT_TARGET_MACOSX +#if TARGET_OS_OSX #include /* __CFWriteBytesToFileWithAtomicity is a "safe save" facility. Write the bytes using the specified mode on the file to the provided URL. If the atomic flag is true, try to do it in a fashion that will enable a safe save. @@ -309,12 +309,12 @@ static Boolean _writeXMLFile(CFURLRef url, CFMutableDictionaryRef dict, Boolean CFDataRef data = CFPropertyListCreateData(alloc, dict, desiredFormat, 0, NULL); if (data) { SInt32 mode; -#if DEPLOYMENT_TARGET_MACOSX || DEPLOYMENT_TARGET_LINUX +#if TARGET_OS_OSX || TARGET_OS_LINUX mode = isWorldReadable ? S_IRUSR|S_IWUSR|S_IRGRP|S_IROTH : S_IRUSR|S_IWUSR; #else mode = 0666; #endif -#if DEPLOYMENT_TARGET_MACOSX +#if TARGET_OS_OSX { // Try quick atomic way first, then fallback to slower ways and error cases CFStringRef scheme = CFURLCopyScheme(url); if (!scheme) { diff --git a/CoreFoundation/RunLoop.subproj/CFMessagePort.c b/CoreFoundation/RunLoop.subproj/CFMessagePort.c index 8bb7b7826b..727e4f09c1 100644 --- a/CoreFoundation/RunLoop.subproj/CFMessagePort.c +++ b/CoreFoundation/RunLoop.subproj/CFMessagePort.c @@ -32,7 +32,7 @@ #endif #endif -#if (DEPLOYMENT_TARGET_MACOSX || DEPLOYMENT_TARGET_EMBEDDED) +#if TARGET_OS_MAC #include #endif diff --git a/CoreFoundation/RunLoop.subproj/CFRunLoop.c b/CoreFoundation/RunLoop.subproj/CFRunLoop.c index 152765b050..1652a60ce5 100644 --- a/CoreFoundation/RunLoop.subproj/CFRunLoop.c +++ b/CoreFoundation/RunLoop.subproj/CFRunLoop.c @@ -74,7 +74,7 @@ extern void os_release(void *object); extern mach_port_t _dispatch_get_main_queue_port_4CF(void); -#elif DEPLOYMENT_TARGET_WINDOWS || TARGET_OS_CYGWIN +#elif TARGET_OS_WIN32 || TARGET_OS_CYGWIN #include DISPATCH_EXPORT HANDLE _dispatch_get_main_queue_handle_4CF(void); DISPATCH_EXPORT void _dispatch_main_queue_callback_4CF(void); diff --git a/CoreFoundation/RunLoop.subproj/CFSocket.c b/CoreFoundation/RunLoop.subproj/CFSocket.c index 0b37772e9f..8ab026cd9e 100644 --- a/CoreFoundation/RunLoop.subproj/CFSocket.c +++ b/CoreFoundation/RunLoop.subproj/CFSocket.c @@ -2152,7 +2152,7 @@ manageSelectError() static void *__CFSocketManager(void * arg) { -#if (DEPLOYMENT_TARGET_LINUX && !TARGET_OS_CYGWIN) || DEPLOYMENT_TARGET_FREEBSD +#if (TARGET_OS_LINUX && !TARGET_OS_CYGWIN) || TARGET_OS_BSD pthread_setname_np(pthread_self(), "com.apple.CFSocket.private"); #elif TARGET_OS_CYGWIN #else diff --git a/CoreFoundation/Stream.subproj/CFConcreteStreams.c b/CoreFoundation/Stream.subproj/CFConcreteStreams.c index 4a722cb82e..f5892d1490 100644 --- a/CoreFoundation/Stream.subproj/CFConcreteStreams.c +++ b/CoreFoundation/Stream.subproj/CFConcreteStreams.c @@ -115,7 +115,7 @@ static Boolean constructFD(_CFFileStreamContext *fileStream, CFStreamError *erro } do { -#if DEPLOYMENT_TARGET_WINDOWS +#if TARGET_OS_WIN32 fileStream->fd = _wopen(path, flags, 0666); #else fileStream->fd = open((const char *)path, flags, 0666); diff --git a/CoreFoundation/String.subproj/CFAttributedString.c b/CoreFoundation/String.subproj/CFAttributedString.c index 5859aceebc..3fb9a611dc 100644 --- a/CoreFoundation/String.subproj/CFAttributedString.c +++ b/CoreFoundation/String.subproj/CFAttributedString.c @@ -16,7 +16,7 @@ #include "CFInternal.h" #include "CFRuntime_Internal.h" -#if (DEPLOYMENT_TARGET_MACOSX || DEPLOYMENT_TARGET_EMBEDDED || DEPLOYMENT_TARGET_WINDOWS) && DEPLOYMENT_RUNTIME_OBJC +#if (TARGET_OS_MAC || TARGET_OS_WIN32) && DEPLOYMENT_RUNTIME_OBJC #import @interface NSAttributedString (NSPrivate) - (NSAttributedString *)_createAttributedSubstringWithRange:(NSRange)range; diff --git a/CoreFoundation/String.subproj/CFBurstTrie.h b/CoreFoundation/String.subproj/CFBurstTrie.h index fd86e0cc90..ec1a28dacb 100644 --- a/CoreFoundation/String.subproj/CFBurstTrie.h +++ b/CoreFoundation/String.subproj/CFBurstTrie.h @@ -60,7 +60,7 @@ typedef CF_OPTIONS(CFOptionFlags, CFBurstTrieOpts) { typedef void (*CFBurstTrieTraversalCallback)(void* context, const UInt8* key, uint32_t keyLength, uint32_t payload, Boolean *stop); CF_EXPORT -CFBurstTrieRef CFBurstTrieCreate(void) API_AVAILABLE(macos(10.7), ios(4.2), watchos(2.0), tvos(9.0)); +CFBurstTrieRef CFBurstTrieCreate() API_AVAILABLE(macos(10.7), ios(4.2), watchos(2.0), tvos(9.0)); CF_EXPORT CFBurstTrieRef CFBurstTrieCreateWithOptions(CFDictionaryRef options) API_AVAILABLE(macos(10.8), ios(6.0), watchos(2.0), tvos(9.0)); diff --git a/CoreFoundation/String.subproj/CFString.h b/CoreFoundation/String.subproj/CFString.h index 1978646b9f..e7e7a43de4 100644 --- a/CoreFoundation/String.subproj/CFString.h +++ b/CoreFoundation/String.subproj/CFString.h @@ -179,11 +179,11 @@ struct __CFConstStr { #endif // defined(__LP64__) || defined(__LLP64__) }; -#if DEPLOYMENT_TARGET_LINUX +#if TARGET_OS_LINUX #define CONST_STRING_LITERAL_SECTION __attribute__((section(".cfstrlit.data"))) #else #define CONST_STRING_LITERAL_SECTION -#endif // DEPLOYMENT_TARGET_LINUX +#endif // TARGET_OS_LINUX #if __BIG_ENDIAN__ #define CFSTR(cStr) ({ \ diff --git a/CoreFoundation/URL.subproj/CFURLComponents.h b/CoreFoundation/URL.subproj/CFURLComponents.h index 51e05529a8..081ea63d2a 100644 --- a/CoreFoundation/URL.subproj/CFURLComponents.h +++ b/CoreFoundation/URL.subproj/CFURLComponents.h @@ -87,12 +87,12 @@ CF_EXPORT CFStringRef _CFStringCreateByAddingPercentEncodingWithAllowedCharacter CF_EXPORT CFStringRef _Nullable _CFStringCreateByRemovingPercentEncoding(CFAllocatorRef alloc, CFStringRef string); // These return singletons -CF_EXPORT CFCharacterSetRef _CFURLComponentsGetURLUserAllowedCharacterSet(void); -CF_EXPORT CFCharacterSetRef _CFURLComponentsGetURLPasswordAllowedCharacterSet(void); -CF_EXPORT CFCharacterSetRef _CFURLComponentsGetURLHostAllowedCharacterSet(void); -CF_EXPORT CFCharacterSetRef _CFURLComponentsGetURLPathAllowedCharacterSet(void); -CF_EXPORT CFCharacterSetRef _CFURLComponentsGetURLQueryAllowedCharacterSet(void); -CF_EXPORT CFCharacterSetRef _CFURLComponentsGetURLFragmentAllowedCharacterSet(void); +CF_EXPORT CFCharacterSetRef _CFURLComponentsGetURLUserAllowedCharacterSet(); +CF_EXPORT CFCharacterSetRef _CFURLComponentsGetURLPasswordAllowedCharacterSet(); +CF_EXPORT CFCharacterSetRef _CFURLComponentsGetURLHostAllowedCharacterSet(); +CF_EXPORT CFCharacterSetRef _CFURLComponentsGetURLPathAllowedCharacterSet(); +CF_EXPORT CFCharacterSetRef _CFURLComponentsGetURLQueryAllowedCharacterSet(); +CF_EXPORT CFCharacterSetRef _CFURLComponentsGetURLFragmentAllowedCharacterSet(); // keys for dictionaries returned by _CFURLComponentsCopyQueryItems CF_EXPORT const CFStringRef _kCFURLComponentsNameKey; From 808d7602e9e5a7615aecdce8f44cbe33e341c9eb Mon Sep 17 00:00:00 2001 From: Lily Vulcano Date: Thu, 4 Oct 2018 13:12:41 -0700 Subject: [PATCH 11/12] =?UTF-8?q?TARGET=5FOS=5FOSX=20was=20not=20defined.?= =?UTF-8?q?=20Since=20we=20(currently)=20do=20not=20support=20building=20S?= =?UTF-8?q?CF=20on=20iOS,=20it=E2=80=99s=20equivalent=20to=20TARGET=5FOS?= =?UTF-8?q?=5FMAC=20for=20Swift.?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- CoreFoundation/Base.subproj/SwiftRuntime/TargetConditionals.h | 1 + 1 file changed, 1 insertion(+) diff --git a/CoreFoundation/Base.subproj/SwiftRuntime/TargetConditionals.h b/CoreFoundation/Base.subproj/SwiftRuntime/TargetConditionals.h index 6d42b87305..4d21c0cc9c 100644 --- a/CoreFoundation/Base.subproj/SwiftRuntime/TargetConditionals.h +++ b/CoreFoundation/Base.subproj/SwiftRuntime/TargetConditionals.h @@ -118,6 +118,7 @@ #define TARGET_OS_WIN32 TARGET_OS_WINDOWS #define TARGET_OS_MAC TARGET_OS_DARWIN +#define TARGET_OS_OSX TARGET_OS_DARWIN #if __x86_64__ #define TARGET_CPU_PPC 0 From a629eb37198c5abc1127ec7cbc354cad2cd23630 Mon Sep 17 00:00:00 2001 From: Lily Vulcano Date: Thu, 4 Oct 2018 15:30:31 -0700 Subject: [PATCH 12/12] Correct feedback from @drodriguez. --- CoreFoundation/Locale.subproj/CFDateFormatter.c | 2 +- Foundation/NSData.swift | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/CoreFoundation/Locale.subproj/CFDateFormatter.c b/CoreFoundation/Locale.subproj/CFDateFormatter.c index 2f825ae087..bb9230c6b6 100644 --- a/CoreFoundation/Locale.subproj/CFDateFormatter.c +++ b/CoreFoundation/Locale.subproj/CFDateFormatter.c @@ -1524,7 +1524,7 @@ static UDate __CFDateFormatterCorrectTimeToARangeAroundCurrentDate(UCalendar *ca } } else { if (period < INT_MAX && futureMax > period) { - futureRange.location = 1, + futureRange.location = 1; futureRange.length = futureMax - period; } if (pastMin <= 0) { diff --git a/Foundation/NSData.swift b/Foundation/NSData.swift index 4b416e98ab..ec1bd4f8bb 100644 --- a/Foundation/NSData.swift +++ b/Foundation/NSData.swift @@ -1140,5 +1140,5 @@ extension NSData : _StructTypeBridgeable { } internal func _CFSwiftDataCreateCopy(_ data: AnyObject) -> Unmanaged { - return Unmanaged.passRetained((data as! NSDictionary).copy() as! NSObject) + return Unmanaged.passRetained((data as! NSData).copy() as! NSObject) }