2 * Copyright (c) 2011 Apple Inc. All rights reserved.
4 * @APPLE_LICENSE_HEADER_START@
6 * This file contains Original Code and/or Modifications of Original Code
7 * as defined in and that are subject to the Apple Public Source License
8 * Version 2.0 (the 'License'). You may not use this file except in
9 * compliance with the License. Please obtain a copy of the License at
10 * http://www.opensource.apple.com/apsl/ and read it before using this
13 * The Original Code and all software distributed under the License are
14 * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
15 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
16 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
17 * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
18 * Please see the License for the specific language governing rights and
19 * limitations under the License.
21 * @APPLE_LICENSE_HEADER_END@
25 Copyright (c) 2006-2011, Apple Inc. All rights reserved.
26 Responsibility: Ali Ozer
29 #include <CoreFoundation/CFError.h>
30 #include <CoreFoundation/CFError_Private.h>
31 #include "CFInternal.h"
32 #include <CoreFoundation/CFPriv.h>
33 #if DEPLOYMENT_TARGET_MACOSX || DEPLOYMENT_TARGET_EMBEDDED
34 #include <mach/mach_error.h>
37 /* Pre-defined userInfo keys
39 CONST_STRING_DECL(kCFErrorLocalizedDescriptionKey
, "NSLocalizedDescription");
40 CONST_STRING_DECL(kCFErrorLocalizedFailureReasonKey
, "NSLocalizedFailureReason");
41 CONST_STRING_DECL(kCFErrorLocalizedRecoverySuggestionKey
, "NSLocalizedRecoverySuggestion");
42 CONST_STRING_DECL(kCFErrorDescriptionKey
, "NSDescription");
43 CONST_STRING_DECL(kCFErrorDebugDescriptionKey
, "NSDebugDescription");
44 CONST_STRING_DECL(kCFErrorUnderlyingErrorKey
, "NSUnderlyingError");
45 CONST_STRING_DECL(kCFErrorURLKey
, "NSURL");
46 CONST_STRING_DECL(kCFErrorFilePathKey
, "NSFilePath");
48 /* Pre-defined error domains
50 CONST_STRING_DECL(kCFErrorDomainPOSIX
, "NSPOSIXErrorDomain");
51 CONST_STRING_DECL(kCFErrorDomainOSStatus
, "NSOSStatusErrorDomain");
52 CONST_STRING_DECL(kCFErrorDomainMach
, "NSMachErrorDomain");
53 CONST_STRING_DECL(kCFErrorDomainCocoa
, "NSCocoaErrorDomain");
55 /* We put the localized names of domain names here so genstrings can pick them out. Any additional domains that are added should be listed here if we'd like them localized.
57 CFCopyLocalizedStringWithDefaultValue(CFSTR("NSMachErrorDomain"), CFSTR("Error"), NULL, CFSTR("Mach"), "Name of the 'Mach' error domain when showing to user. This probably will not get localized, unless there is a generally recognized phrase for 'Mach' in the language.")
58 CFCopyLocalizedStringWithDefaultValue(CFSTR("NSCoreFoundationErrorDomain"), CFSTR("Error"), NULL, CFSTR("Core Foundation"), "Name of the 'Core Foundation' error domain when showing to user. Very likely this will not get localized differently in other languages.")
59 CFCopyLocalizedStringWithDefaultValue(CFSTR("NSPOSIXErrorDomain"), CFSTR("Error"), NULL, CFSTR("POSIX"), "Name of the 'POSIX' error domain when showing to user. This probably will not get localized, unless there is a generally recognized phrase for 'POSIX' in the language.")
60 CFCopyLocalizedStringWithDefaultValue(CFSTR("NSOSStatusErrorDomain"), CFSTR("Error"), NULL, CFSTR("OSStatus"), "Name of the 'OSStatus' error domain when showing to user. Very likely this will not get localized.")
61 CFCopyLocalizedStringWithDefaultValue(CFSTR("NSCocoaErrorDomain"), CFSTR("Error"), NULL, CFSTR("Cocoa"), "Name of the 'Cocoa' error domain when showing to user. Very likely this will not get localized.")
66 /* Forward declarations
68 static CFDictionaryRef
_CFErrorGetUserInfo(CFErrorRef err
);
69 static CFStringRef
_CFErrorCopyUserInfoKey(CFErrorRef err
, CFStringRef key
);
70 static CFDictionaryRef
_CFErrorCreateEmptyDictionary(CFAllocatorRef allocator
);
72 /* Assertions and other macros/inlines
74 #define __CFAssertIsError(cf) __CFGenericValidateType(cf, __kCFErrorTypeID)
76 /* This lock is used in the few places in CFError where we create and access shared static objects. Should only be around tiny snippets of code; no recursion
78 static CFSpinLock_t _CFErrorSpinlock
= CFSpinLockInit
;
83 /**** CFError CF runtime stuff ****/
85 struct __CFError
{ // Potentially interesting to keep layout same as NSError (but currently not a requirement)
88 CFStringRef domain
; // !!! Could compress well-known domains down to few bits, but probably not worth its weight in code since CFErrors are rare
89 CFDictionaryRef userInfo
; // !!! Could avoid allocating this slot if userInfo is NULL, but probably not worth its weight in code since CFErrors are rare
92 /* CFError equal checks for equality of domain, code, and userInfo.
94 static Boolean
__CFErrorEqual(CFTypeRef cf1
, CFTypeRef cf2
) {
95 CFErrorRef err1
= (CFErrorRef
)cf1
;
96 CFErrorRef err2
= (CFErrorRef
)cf2
;
98 // First do quick checks of code and domain (in that order for performance)
99 if (CFErrorGetCode(err1
) != CFErrorGetCode(err2
)) return false;
100 if (!CFEqual(CFErrorGetDomain(err1
), CFErrorGetDomain(err2
))) return false;
102 // If those are equal, then check the dictionaries
103 CFDictionaryRef dict1
= CFErrorCopyUserInfo(err1
);
104 CFDictionaryRef dict2
= CFErrorCopyUserInfo(err2
);
106 Boolean result
= false;
108 if (dict1
== dict2
) {
110 } else if (dict1
&& dict2
&& CFEqual(dict1
, dict2
)) {
114 if (dict1
) CFRelease(dict1
);
115 if (dict2
) CFRelease(dict2
);
120 /* CFError hash code is hash(domain) + code
122 static CFHashCode
__CFErrorHash(CFTypeRef cf
) {
123 CFErrorRef err
= (CFErrorRef
)cf
;
124 /* !!! We do not need an assertion here, as this is called by the CFBase runtime only */
125 return CFHash(err
->domain
) + err
->code
;
128 /* This is the full debug description. Shows the description (possibly localized), plus the domain, code, and userInfo explicitly. If there is a debug description, shows that as well.
130 static CFStringRef
__CFErrorCopyDescription(CFTypeRef cf
) {
131 return _CFErrorCreateDebugDescription((CFErrorRef
)cf
);
134 /* This is the description you get for %@; we tone it down a bit from what you get in __CFErrorCopyDescription().
136 static CFStringRef
__CFErrorCopyFormattingDescription(CFTypeRef cf
, CFDictionaryRef formatOptions
) {
137 CFErrorRef err
= (CFErrorRef
)cf
;
138 return CFErrorCopyDescription(err
); // No need to release, since we are returning from a Copy function
141 static void __CFErrorDeallocate(CFTypeRef cf
) {
142 CFErrorRef err
= (CFErrorRef
)cf
;
143 CFRelease(err
->domain
);
144 CFRelease(err
->userInfo
);
148 static CFTypeID __kCFErrorTypeID
= _kCFRuntimeNotATypeID
;
150 static const CFRuntimeClass __CFErrorClass
= {
158 __CFErrorCopyFormattingDescription
,
159 __CFErrorCopyDescription
162 __private_extern__
void __CFErrorInitialize(void) {
163 __kCFErrorTypeID
= _CFRuntimeRegisterClass(&__CFErrorClass
);
166 CFTypeID
CFErrorGetTypeID(void) {
167 return __kCFErrorTypeID
;
173 /**** CFError support functions ****/
175 /* Returns a shared empty dictionary (unless the allocator is not kCFAllocatorSystemDefault, in which case returns a newly allocated one).
177 static CFDictionaryRef
_CFErrorCreateEmptyDictionary(CFAllocatorRef allocator
) {
178 if (allocator
== NULL
) allocator
= __CFGetDefaultAllocator();
179 if (_CFAllocatorIsSystemDefault(allocator
)) {
180 static CFDictionaryRef emptyErrorDictionary
= NULL
;
181 if (emptyErrorDictionary
== NULL
) {
182 CFDictionaryRef tmp
= CFDictionaryCreate(allocator
, NULL
, NULL
, 0, &kCFCopyStringDictionaryKeyCallBacks
, &kCFTypeDictionaryValueCallBacks
);
183 __CFSpinLock(&_CFErrorSpinlock
);
184 if (emptyErrorDictionary
== NULL
) {
185 emptyErrorDictionary
= tmp
;
186 __CFSpinUnlock(&_CFErrorSpinlock
);
188 __CFSpinUnlock(&_CFErrorSpinlock
);
192 return (CFDictionaryRef
)CFRetain(emptyErrorDictionary
);
194 return CFDictionaryCreate(allocator
, NULL
, NULL
, 0, &kCFCopyStringDictionaryKeyCallBacks
, &kCFTypeDictionaryValueCallBacks
);
198 /* A non-retained accessor for the userInfo. Might return NULL in some cases, if the subclass of NSError returned nil for some reason. It works with a CF or NSError.
200 static CFDictionaryRef
_CFErrorGetUserInfo(CFErrorRef err
) {
201 CF_OBJC_FUNCDISPATCH0(__kCFErrorTypeID
, CFDictionaryRef
, err
, "userInfo");
202 __CFAssertIsError(err
);
203 return err
->userInfo
;
206 /* This function retrieves the value of the specified key from the userInfo, or from the callback. It works with a CF or NSError.
208 static CFStringRef
_CFErrorCopyUserInfoKey(CFErrorRef err
, CFStringRef key
) {
209 CFStringRef result
= NULL
;
210 // First consult the userInfo dictionary
211 CFDictionaryRef userInfo
= _CFErrorGetUserInfo(err
);
212 if (userInfo
) result
= (CFStringRef
)CFDictionaryGetValue(userInfo
, key
);
213 // If that doesn't work, consult the callback
217 CFErrorUserInfoKeyCallBack callBack
= CFErrorGetCallBackForDomain(CFErrorGetDomain(err
));
218 if (callBack
) result
= (CFStringRef
)callBack(err
, key
);
223 /* The real guts of the description creation functionality. See the header file for the steps this function goes through to compute the description. This function can take a CF or NSError. It's called by NSError for the localizedDescription computation.
225 CFStringRef
_CFErrorCreateLocalizedDescription(CFErrorRef err
) {
226 // First look for kCFErrorLocalizedDescriptionKey; if non-NULL, return that as-is.
227 CFStringRef localizedDesc
= _CFErrorCopyUserInfoKey(err
, kCFErrorLocalizedDescriptionKey
);
228 if (localizedDesc
) return localizedDesc
;
231 #if DEPLOYMENT_TARGET_MACOSX || DEPLOYMENT_TARGET_EMBEDDED || DEPLOYMENT_TARGET_WINDOWS
232 // Cache the CF bundle since we will be using it for localized strings.
233 CFBundleRef cfBundle
= CFBundleGetBundleWithIdentifier(CFSTR("com.apple.CoreFoundation"));
235 if (!cfBundle
) { // This should be rare, but has been observed in the wild, due to running out of file descriptors. Normally we might not go to such extremes, but since we want to be able to present reasonable errors even in the case of errors such as running out of file descriptors, why not. This is CFError after all. !!! Be sure to have the same logic here as below for going through various options for fetching the strings.
238 CFStringRef result
= NULL
, reasonOrDesc
;
240 if ((reasonOrDesc
= _CFErrorCopyUserInfoKey(err
, kCFErrorLocalizedFailureReasonKey
))) { // First look for kCFErrorLocalizedFailureReasonKey
241 result
= CFStringCreateWithFormat(kCFAllocatorSystemDefault
, NULL
, CFSTR("The operation couldn\\U2019t be completed. %@"), reasonOrDesc
);
242 } else if ((reasonOrDesc
= _CFErrorCopyUserInfoKey(err
, kCFErrorDescriptionKey
))) { // Then try kCFErrorDescriptionKey
243 result
= CFStringCreateWithFormat(kCFAllocatorSystemDefault
, NULL
, CFSTR("The operation couldn\\U2019t be completed. (%@ error %ld - %@)"), CFErrorGetDomain(err
), (long)CFErrorGetCode(err
), reasonOrDesc
);
244 } else { // Last resort, just the domain and code
245 result
= CFStringCreateWithFormat(kCFAllocatorSystemDefault
, NULL
, CFSTR("The operation couldn\\U2019t be completed. (%@ error %ld.)"), CFErrorGetDomain(err
), (long)CFErrorGetCode(err
));
247 if (reasonOrDesc
) CFRelease(reasonOrDesc
);
249 #if DEPLOYMENT_TARGET_MACOSX || DEPLOYMENT_TARGET_EMBEDDED || DEPLOYMENT_TARGET_WINDOWS
253 #if DEPLOYMENT_TARGET_MACOSX || DEPLOYMENT_TARGET_EMBEDDED || DEPLOYMENT_TARGET_WINDOWS
254 // Then look for kCFErrorLocalizedFailureReasonKey; if there, create a full sentence from that.
255 CFStringRef reason
= _CFErrorCopyUserInfoKey(err
, kCFErrorLocalizedFailureReasonKey
);
257 CFStringRef operationFailedStr
= CFCopyLocalizedStringFromTableInBundle(CFSTR("The operation couldn\\U2019t be completed. %@"), CFSTR("Error"), cfBundle
, "A generic error string indicating there was a problem. The %@ will be replaced by a second sentence which indicates why the operation failed.");
258 CFStringRef result
= CFStringCreateWithFormat(kCFAllocatorSystemDefault
, NULL
, operationFailedStr
, reason
);
259 CFRelease(operationFailedStr
);
264 // Otherwise, generate a semi-user presentable string from the domain, code, and if available, the presumably non-localized kCFErrorDescriptionKey.
266 CFStringRef desc
= _CFErrorCopyUserInfoKey(err
, kCFErrorDescriptionKey
);
267 CFStringRef localizedDomain
= CFCopyLocalizedStringFromTableInBundle(CFErrorGetDomain(err
), CFSTR("Error"), cfBundle
, "These are localized in the comment above");
268 if (desc
) { // We have kCFErrorDescriptionKey, so include that with the error domain and code
269 CFStringRef operationFailedStr
= CFCopyLocalizedStringFromTableInBundle(CFSTR("The operation couldn\\U2019t be completed. (%@ error %ld - %@)"), CFSTR("Error"), cfBundle
, "A generic error string indicating there was a problem, followed by a parenthetical sentence which indicates error domain, code, and a description when there is no other way to present an error to the user. The first %@ indicates the error domain, %ld indicates the error code, and the second %@ indicates the description; so this might become '(Mach error 42 - Server error.)' for instance.");
270 result
= CFStringCreateWithFormat(kCFAllocatorSystemDefault
, NULL
, operationFailedStr
, localizedDomain
, (long)CFErrorGetCode(err
), desc
);
271 CFRelease(operationFailedStr
);
273 } else { // We don't have kCFErrorDescriptionKey, so just use error domain and code
274 CFStringRef operationFailedStr
= CFCopyLocalizedStringFromTableInBundle(CFSTR("The operation couldn\\U2019t be completed. (%@ error %ld.)"), CFSTR("Error"), cfBundle
, "A generic error string indicating there was a problem, followed by a parenthetical sentence which indicates error domain and code when there is no other way to present an error to the user. The %@ indicates the error domain while %ld indicates the error code; so this might become '(Mach error 42.)' for instance.");
275 result
= CFStringCreateWithFormat(kCFAllocatorSystemDefault
, NULL
, operationFailedStr
, localizedDomain
, (long)CFErrorGetCode(err
));
276 CFRelease(operationFailedStr
);
278 CFRelease(localizedDomain
);
283 /* The real guts of the failure reason creation functionality. This function can take a CF or NSError. It's called by NSError for the localizedFailureReason computation.
285 CFStringRef
_CFErrorCreateLocalizedFailureReason(CFErrorRef err
) {
286 // We simply return the value of kCFErrorLocalizedFailureReasonKey; no other searching takes place
287 return _CFErrorCopyUserInfoKey(err
, kCFErrorLocalizedFailureReasonKey
);
290 /* The real guts of the recovery suggestion functionality. This function can take a CF or NSError. It's called by NSError for the localizedRecoverySuggestion computation.
292 CFStringRef
_CFErrorCreateLocalizedRecoverySuggestion(CFErrorRef err
) {
293 // We simply return the value of kCFErrorLocalizedRecoverySuggestionKey; no other searching takes place
294 return _CFErrorCopyUserInfoKey(err
, kCFErrorLocalizedRecoverySuggestionKey
);
297 /* The "debug" description, used by CFCopyDescription and -[NSObject description].
299 static void userInfoKeyValueShow(const void *key
, const void *value
, void *context
) {
301 if (CFEqual(key
, kCFErrorUnderlyingErrorKey
) && (desc
= CFErrorCopyDescription((CFErrorRef
)value
))) { // We check desc, see <rdar://problem/8415727>
302 CFStringAppendFormat((CFMutableStringRef
)context
, NULL
, CFSTR("%@=%p \"%@\", "), key
, value
, desc
);
305 CFStringAppendFormat((CFMutableStringRef
)context
, NULL
, CFSTR("%@=%@, "), key
, value
);
309 CFStringRef
_CFErrorCreateDebugDescription(CFErrorRef err
) {
310 CFStringRef desc
= CFErrorCopyDescription(err
);
311 CFStringRef debugDesc
= _CFErrorCopyUserInfoKey(err
, kCFErrorDebugDescriptionKey
);
312 CFDictionaryRef userInfo
= _CFErrorGetUserInfo(err
);
313 CFMutableStringRef result
= CFStringCreateMutable(kCFAllocatorSystemDefault
, 0);
314 CFStringAppendFormat(result
, NULL
, CFSTR("Error Domain=%@ Code=%d"), CFErrorGetDomain(err
), (long)CFErrorGetCode(err
));
315 CFStringAppendFormat(result
, NULL
, CFSTR(" \"%@\""), desc
);
316 if (debugDesc
&& CFStringGetLength(debugDesc
) > 0) CFStringAppendFormat(result
, NULL
, CFSTR(" (%@)"), debugDesc
);
318 CFStringAppendFormat(result
, NULL
, CFSTR(" UserInfo=%p {"), userInfo
);
319 CFDictionaryApplyFunction(userInfo
, userInfoKeyValueShow
, (void *)result
);
320 CFIndex commaLength
= (CFStringHasSuffix(result
, CFSTR(", "))) ? 2 : 0;
321 CFStringReplace(result
, CFRangeMake(CFStringGetLength(result
)-commaLength
, commaLength
), CFSTR("}"));
323 if (debugDesc
) CFRelease(debugDesc
);
324 if (desc
) CFRelease(desc
);
331 /**** CFError API/SPI ****/
333 /* Note that there are two entry points for creating CFErrors. This one does it with a presupplied userInfo dictionary.
335 CFErrorRef
CFErrorCreate(CFAllocatorRef allocator
, CFStringRef domain
, CFIndex code
, CFDictionaryRef userInfo
) {
336 __CFGenericValidateType(domain
, CFStringGetTypeID());
337 if (userInfo
) __CFGenericValidateType(userInfo
, CFDictionaryGetTypeID());
339 CFErrorRef err
= (CFErrorRef
)_CFRuntimeCreateInstance(allocator
, __kCFErrorTypeID
, sizeof(struct __CFError
) - sizeof(CFRuntimeBase
), NULL
);
340 if (NULL
== err
) return NULL
;
342 err
->domain
= CFStringCreateCopy(allocator
, domain
);
344 err
->userInfo
= userInfo
? CFDictionaryCreateCopy(allocator
, userInfo
) : _CFErrorCreateEmptyDictionary(allocator
);
349 /* Note that there are two entry points for creating CFErrors. This one does it with individual keys and values which are used to create the userInfo dictionary.
351 CFErrorRef
CFErrorCreateWithUserInfoKeysAndValues(CFAllocatorRef allocator
, CFStringRef domain
, CFIndex code
, const void *const *userInfoKeys
, const void *const *userInfoValues
, CFIndex numUserInfoValues
) {
352 __CFGenericValidateType(domain
, CFStringGetTypeID());
354 CFErrorRef err
= (CFErrorRef
)_CFRuntimeCreateInstance(allocator
, __kCFErrorTypeID
, sizeof(struct __CFError
) - sizeof(CFRuntimeBase
), NULL
);
355 if (NULL
== err
) return NULL
;
357 err
->domain
= CFStringCreateCopy(allocator
, domain
);
359 err
->userInfo
= CFDictionaryCreate(allocator
, (const void **)userInfoKeys
, (const void **)userInfoValues
, numUserInfoValues
, &kCFCopyStringDictionaryKeyCallBacks
, &kCFTypeDictionaryValueCallBacks
);
364 CFStringRef
CFErrorGetDomain(CFErrorRef err
) {
365 CF_OBJC_FUNCDISPATCH0(__kCFErrorTypeID
, CFStringRef
, err
, "domain");
366 __CFAssertIsError(err
);
370 CFIndex
CFErrorGetCode(CFErrorRef err
) {
371 CF_OBJC_FUNCDISPATCH0(__kCFErrorTypeID
, CFIndex
, err
, "code");
372 __CFAssertIsError(err
);
376 /* This accessor never returns NULL. For usage inside this file, consider __CFErrorGetUserInfo().
378 CFDictionaryRef
CFErrorCopyUserInfo(CFErrorRef err
) {
379 CFDictionaryRef userInfo
= _CFErrorGetUserInfo(err
);
380 return userInfo
? (CFDictionaryRef
)CFRetain(userInfo
) : _CFErrorCreateEmptyDictionary(CFGetAllocator(err
));
383 CFStringRef
CFErrorCopyDescription(CFErrorRef err
) {
384 if (CF_IS_OBJC(__kCFErrorTypeID
, err
)) { // Since we have to return a retained result, we need to treat the toll-free bridging specially
386 CF_OBJC_CALL0(CFStringRef
, desc
, err
, "localizedDescription");
387 return desc
? (CFStringRef
)CFRetain(desc
) : NULL
; // !!! It really should never return nil.
389 __CFAssertIsError(err
);
390 return _CFErrorCreateLocalizedDescription(err
);
393 CFStringRef
CFErrorCopyFailureReason(CFErrorRef err
) {
394 if (CF_IS_OBJC(__kCFErrorTypeID
, err
)) { // Since we have to return a retained result, we need to treat the toll-free bridging specially
396 CF_OBJC_CALL0(CFStringRef
, str
, err
, "localizedFailureReason");
397 return str
? (CFStringRef
)CFRetain(str
) : NULL
; // It's possible for localizedFailureReason to return nil
399 __CFAssertIsError(err
);
400 return _CFErrorCreateLocalizedFailureReason(err
);
403 CFStringRef
CFErrorCopyRecoverySuggestion(CFErrorRef err
) {
404 if (CF_IS_OBJC(__kCFErrorTypeID
, err
)) { // Since we have to return a retained result, we need to treat the toll-free bridging specially
406 CF_OBJC_CALL0(CFStringRef
, str
, err
, "localizedRecoverySuggestion");
407 return str
? (CFStringRef
)CFRetain(str
) : NULL
; // It's possible for localizedRecoverySuggestion to return nil
409 __CFAssertIsError(err
);
410 return _CFErrorCreateLocalizedRecoverySuggestion(err
);
414 /**** CFError CallBack management ****/
416 /* Domain-to-callback mapping dictionary
418 static CFMutableDictionaryRef _CFErrorCallBackTable
= NULL
;
421 /* Built-in callback for POSIX domain. Note that we will pick up localizations from ErrnoErrors.strings in /System/Library/CoreServices/CoreTypes.bundle, if the file happens to be there.
423 static CFTypeRef
_CFErrorPOSIXCallBack(CFErrorRef err
, CFStringRef key
) {
424 if (!CFEqual(key
, kCFErrorDescriptionKey
) && !CFEqual(key
, kCFErrorLocalizedFailureReasonKey
)) return NULL
;
426 const char *errCStr
= strerror(CFErrorGetCode(err
));
427 CFStringRef errStr
= (errCStr
&& strlen(errCStr
)) ? CFStringCreateWithCString(kCFAllocatorSystemDefault
, errCStr
, kCFStringEncodingUTF8
) : NULL
;
429 if (!errStr
) return NULL
;
430 if (CFEqual(key
, kCFErrorDescriptionKey
)) return errStr
; // If all we wanted was the non-localized description, we're done
432 #if DEPLOYMENT_TARGET_MACOSX || DEPLOYMENT_TARGET_EMBEDDED || DEPLOYMENT_TARGET_WINDOWS
433 // We need a kCFErrorLocalizedFailureReasonKey, so look up a possible localization for the error message
434 // Look for the bundle in /System/Library/CoreServices/CoreTypes.bundle
435 CFArrayRef paths
= CFCopySearchPathForDirectoriesInDomains(kCFLibraryDirectory
, kCFSystemDomainMask
, false);
437 if (CFArrayGetCount(paths
) > 0) {
438 CFStringRef path
= CFStringCreateWithFormat(kCFAllocatorSystemDefault
, NULL
, CFSTR("%@/CoreServices/CoreTypes.bundle"), CFArrayGetValueAtIndex(paths
, 0));
439 CFURLRef url
= CFURLCreateWithFileSystemPath(kCFAllocatorSystemDefault
, path
, kCFURLPOSIXPathStyle
, false /* not a directory */);
441 CFBundleRef bundle
= CFBundleCreate(kCFAllocatorSystemDefault
, url
);
443 // We only want to return a result if there was a localization
444 CFStringRef localizedErrStr
= CFBundleCopyLocalizedString(bundle
, errStr
, errStr
, CFSTR("ErrnoErrors"));
445 if (localizedErrStr
== errStr
) {
446 CFRelease(localizedErrStr
);
451 errStr
= localizedErrStr
;
466 #if DEPLOYMENT_TARGET_MACOSX || DEPLOYMENT_TARGET_EMBEDDED
467 /* Built-in callback for Mach domain.
469 static CFTypeRef
_CFErrorMachCallBack(CFErrorRef err
, CFStringRef key
) {
470 if (CFEqual(key
, kCFErrorDescriptionKey
)) {
471 const char *errStr
= mach_error_string(CFErrorGetCode(err
));
472 if (errStr
&& strlen(errStr
)) return CFStringCreateWithCString(kCFAllocatorSystemDefault
, errStr
, kCFStringEncodingUTF8
);
479 /* This initialize function is meant to be called lazily, the first time a callback is registered or requested. It creates the table and registers the built-in callbacks. Clearly doing this non-lazily in _CFErrorInitialize() would be simpler, but this is a fine example of something that should not have to happen at launch time.
481 static void _CFErrorInitializeCallBackTable(void) {
482 // Create the table outside the lock
483 CFMutableDictionaryRef table
= CFDictionaryCreateMutable(kCFAllocatorSystemDefault
, 0, &kCFCopyStringDictionaryKeyCallBacks
, NULL
);
484 __CFSpinLock(&_CFErrorSpinlock
);
485 if (!_CFErrorCallBackTable
) {
486 _CFErrorCallBackTable
= table
;
487 __CFSpinUnlock(&_CFErrorSpinlock
);
489 __CFSpinUnlock(&_CFErrorSpinlock
);
491 // Note, even though the table looks like it was initialized, we go on to register the items on this thread as well, since otherwise we might consult the table before the items are actually registered.
493 CFErrorSetCallBackForDomain(kCFErrorDomainPOSIX
, _CFErrorPOSIXCallBack
);
494 #if DEPLOYMENT_TARGET_MACOSX || DEPLOYMENT_TARGET_EMBEDDED
495 CFErrorSetCallBackForDomain(kCFErrorDomainMach
, _CFErrorMachCallBack
);
499 void CFErrorSetCallBackForDomain(CFStringRef domainName
, CFErrorUserInfoKeyCallBack callBack
) {
500 if (!_CFErrorCallBackTable
) _CFErrorInitializeCallBackTable();
501 __CFSpinLock(&_CFErrorSpinlock
);
503 CFDictionarySetValue(_CFErrorCallBackTable
, domainName
, callBack
);
505 CFDictionaryRemoveValue(_CFErrorCallBackTable
, domainName
);
507 __CFSpinUnlock(&_CFErrorSpinlock
);
510 CFErrorUserInfoKeyCallBack
CFErrorGetCallBackForDomain(CFStringRef domainName
) {
511 if (!_CFErrorCallBackTable
) _CFErrorInitializeCallBackTable();
512 __CFSpinLock(&_CFErrorSpinlock
);
513 CFErrorUserInfoKeyCallBack callBack
= (CFErrorUserInfoKeyCallBack
)CFDictionaryGetValue(_CFErrorCallBackTable
, domainName
);
514 __CFSpinUnlock(&_CFErrorSpinlock
);