1/*
2 * Copyright (c) 2014 Apple Inc. All rights reserved.
3 *
4 * @APPLE_LICENSE_HEADER_START@
5 *
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
11 * file.
12 *
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.
20 *
21 * @APPLE_LICENSE_HEADER_END@
22 */
23
24/*	CFError.c
25	Copyright (c) 2006-2013, Apple Inc. All rights reserved.
26	Responsibility: Ali Ozer
27*/
28
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>
35#endif
36
37
38/* Pre-defined userInfo keys
39*/
40CONST_STRING_DECL(kCFErrorLocalizedDescriptionKey,          "NSLocalizedDescription");
41CONST_STRING_DECL(kCFErrorLocalizedFailureReasonKey,        "NSLocalizedFailureReason");
42CONST_STRING_DECL(kCFErrorLocalizedRecoverySuggestionKey,   "NSLocalizedRecoverySuggestion");
43CONST_STRING_DECL(kCFErrorDescriptionKey,                   "NSDescription");
44CONST_STRING_DECL(kCFErrorDebugDescriptionKey,              "NSDebugDescription");
45CONST_STRING_DECL(kCFErrorUnderlyingErrorKey,               "NSUnderlyingError");
46CONST_STRING_DECL(kCFErrorURLKey,               	    "NSURL");
47CONST_STRING_DECL(kCFErrorFilePathKey,                      "NSFilePath");
48
49/* Pre-defined error domains
50*/
51CONST_STRING_DECL(kCFErrorDomainPOSIX,              "NSPOSIXErrorDomain");
52CONST_STRING_DECL(kCFErrorDomainOSStatus,           "NSOSStatusErrorDomain");
53CONST_STRING_DECL(kCFErrorDomainMach,               "NSMachErrorDomain");
54CONST_STRING_DECL(kCFErrorDomainCocoa,              "NSCocoaErrorDomain");
55
56/* 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
58CFCopyLocalizedStringWithDefaultValue(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.")
59CFCopyLocalizedStringWithDefaultValue(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.")
60CFCopyLocalizedStringWithDefaultValue(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.")
61CFCopyLocalizedStringWithDefaultValue(CFSTR("NSOSStatusErrorDomain"), CFSTR("Error"), NULL, CFSTR("OSStatus"), "Name of the 'OSStatus' error domain when showing to user. Very likely this will not get localized.")
62CFCopyLocalizedStringWithDefaultValue(CFSTR("NSCocoaErrorDomain"), CFSTR("Error"), NULL, CFSTR("Cocoa"), "Name of the 'Cocoa' error domain when showing to user. Very likely this will not get localized.")
63*/
64
65
66
67/* Forward declarations
68*/
69static CFDictionaryRef _CFErrorGetUserInfo(CFErrorRef err);
70static CFStringRef _CFErrorCopyUserInfoKey(CFErrorRef err, CFStringRef key);
71static CFDictionaryRef _CFErrorCreateEmptyDictionary(CFAllocatorRef allocator);
72
73/* Assertions and other macros/inlines
74*/
75#define __CFAssertIsError(cf) __CFGenericValidateType(cf, __kCFErrorTypeID)
76
77/* 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*/
79static CFSpinLock_t _CFErrorSpinlock = CFSpinLockInit;
80
81
82
83
84/**** CFError CF runtime stuff ****/
85
86struct __CFError {		// Potentially interesting to keep layout same as NSError (but currently not a requirement)
87    CFRuntimeBase _base;
88    CFIndex code;
89    CFStringRef domain;		// !!! Could compress well-known domains down to few bits, but probably not worth its weight in code since CFErrors are rare
90    CFDictionaryRef userInfo;	// !!! Could avoid allocating this slot if userInfo is NULL, but probably not worth its weight in code since CFErrors are rare
91};
92
93/* CFError equal checks for equality of domain, code, and userInfo.
94*/
95static Boolean __CFErrorEqual(CFTypeRef cf1, CFTypeRef cf2) {
96    CFErrorRef err1 = (CFErrorRef)cf1;
97    CFErrorRef err2 = (CFErrorRef)cf2;
98
99    // First do quick checks of code and domain (in that order for performance)
100    if (CFErrorGetCode(err1) != CFErrorGetCode(err2)) return false;
101    if (!CFEqual(CFErrorGetDomain(err1), CFErrorGetDomain(err2))) return false;
102
103    // If those are equal, then check the dictionaries
104    CFDictionaryRef dict1 = CFErrorCopyUserInfo(err1);
105    CFDictionaryRef dict2 = CFErrorCopyUserInfo(err2);
106
107    Boolean result = false;
108
109    if (dict1 == dict2) {
110        result = true;
111    } else if (dict1 && dict2 && CFEqual(dict1, dict2)) {
112        result = true;
113    }
114
115    if (dict1) CFRelease(dict1);
116    if (dict2) CFRelease(dict2);
117
118    return result;
119}
120
121/* CFError hash code is hash(domain) + code
122*/
123static CFHashCode __CFErrorHash(CFTypeRef cf) {
124    CFErrorRef err = (CFErrorRef)cf;
125    /* !!! We do not need an assertion here, as this is called by the CFBase runtime only */
126    return CFHash(err->domain) + err->code;
127}
128
129/* 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*/
131static CFStringRef __CFErrorCopyDescription(CFTypeRef cf) {
132    return _CFErrorCreateDebugDescription((CFErrorRef)cf);
133}
134
135/* This is the description you get for %@; we tone it down a bit from what you get in __CFErrorCopyDescription().
136*/
137static CFStringRef __CFErrorCopyFormattingDescription(CFTypeRef cf, CFDictionaryRef formatOptions) {
138    CFErrorRef err = (CFErrorRef)cf;
139    return CFErrorCopyDescription(err);     // No need to release, since we are returning from a Copy function
140}
141
142static void __CFErrorDeallocate(CFTypeRef cf) {
143    CFErrorRef err = (CFErrorRef)cf;
144    CFRelease(err->domain);
145    CFRelease(err->userInfo);
146}
147
148
149static CFTypeID __kCFErrorTypeID = _kCFRuntimeNotATypeID;
150
151static const CFRuntimeClass __CFErrorClass = {
152    0,
153    "CFError",
154    NULL,      // init
155    NULL,      // copy
156    __CFErrorDeallocate,
157    __CFErrorEqual,
158    __CFErrorHash,
159    __CFErrorCopyFormattingDescription,
160    __CFErrorCopyDescription
161};
162
163CF_PRIVATE void __CFErrorInitialize(void) {
164    __kCFErrorTypeID = _CFRuntimeRegisterClass(&__CFErrorClass);
165}
166
167CFTypeID CFErrorGetTypeID(void) {
168    return __kCFErrorTypeID;
169}
170
171
172
173
174/**** CFError support functions ****/
175
176/* Returns a shared empty dictionary (unless the allocator is not kCFAllocatorSystemDefault, in which case returns a newly allocated one).
177*/
178static CFDictionaryRef _CFErrorCreateEmptyDictionary(CFAllocatorRef allocator) {
179    if (allocator == NULL) allocator = __CFGetDefaultAllocator();
180    if (_CFAllocatorIsSystemDefault(allocator)) {
181        static CFDictionaryRef emptyErrorDictionary = NULL;
182        if (emptyErrorDictionary == NULL) {
183            CFDictionaryRef tmp = CFDictionaryCreate(allocator, NULL, NULL, 0, &kCFCopyStringDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks);
184            __CFSpinLock(&_CFErrorSpinlock);
185            if (emptyErrorDictionary == NULL) {
186                emptyErrorDictionary = tmp;
187                __CFSpinUnlock(&_CFErrorSpinlock);
188            } else {
189                __CFSpinUnlock(&_CFErrorSpinlock);
190                CFRelease(tmp);
191            }
192        }
193        return (CFDictionaryRef)CFRetain(emptyErrorDictionary);
194    } else {
195        return CFDictionaryCreate(allocator, NULL, NULL, 0, &kCFCopyStringDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks);
196    }
197}
198
199/* 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*/
201static CFDictionaryRef _CFErrorGetUserInfo(CFErrorRef err) {
202    CF_OBJC_FUNCDISPATCHV(__kCFErrorTypeID, CFDictionaryRef, (NSError *)err, userInfo);
203    __CFAssertIsError(err);
204    return err->userInfo;
205}
206
207/* This function retrieves the value of the specified key from the userInfo, or from the callback. It works with a CF or NSError.
208*/
209static CFStringRef _CFErrorCopyUserInfoKey(CFErrorRef err, CFStringRef key) {
210    CFStringRef result = NULL;
211    // First consult the userInfo dictionary
212    CFDictionaryRef userInfo = _CFErrorGetUserInfo(err);
213    if (userInfo) result = (CFStringRef)CFDictionaryGetValue(userInfo, key);
214    // If that doesn't work, consult the callback
215    if (result) {
216        CFRetain(result);
217    } else {
218        CFErrorUserInfoKeyCallBack callBack = CFErrorGetCallBackForDomain(CFErrorGetDomain(err));
219        if (callBack) result = (CFStringRef)callBack(err, key);
220    }
221    return result;
222}
223
224/* 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*/
226CFStringRef _CFErrorCreateLocalizedDescription(CFErrorRef err) {
227    // First look for kCFErrorLocalizedDescriptionKey; if non-NULL, return that as-is.
228    CFStringRef localizedDesc = _CFErrorCopyUserInfoKey(err, kCFErrorLocalizedDescriptionKey);
229    if (localizedDesc) return localizedDesc;
230
231
232#if DEPLOYMENT_TARGET_MACOSX || DEPLOYMENT_TARGET_EMBEDDED || DEPLOYMENT_TARGET_WINDOWS
233    // Cache the CF bundle since we will be using it for localized strings.
234    CFBundleRef cfBundle = CFBundleGetBundleWithIdentifier(CFSTR("com.apple.CoreFoundation"));
235
236    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.
237#endif
238
239	CFStringRef result = NULL, reasonOrDesc;
240
241	if ((reasonOrDesc = _CFErrorCopyUserInfoKey(err, kCFErrorLocalizedFailureReasonKey))) {	    // First look for kCFErrorLocalizedFailureReasonKey
242	    result = CFStringCreateWithFormat(kCFAllocatorSystemDefault, NULL, CFSTR("The operation couldn\\U2019t be completed. %@"), reasonOrDesc);
243	} else if ((reasonOrDesc = _CFErrorCopyUserInfoKey(err, kCFErrorDescriptionKey))) {	    // Then try kCFErrorDescriptionKey
244	    result = CFStringCreateWithFormat(kCFAllocatorSystemDefault, NULL, CFSTR("The operation couldn\\U2019t be completed. (%@ error %ld - %@)"), CFErrorGetDomain(err), (long)CFErrorGetCode(err), reasonOrDesc);
245	} else {	// Last resort, just the domain and code
246	    result = CFStringCreateWithFormat(kCFAllocatorSystemDefault, NULL, CFSTR("The operation couldn\\U2019t be completed. (%@ error %ld.)"), CFErrorGetDomain(err), (long)CFErrorGetCode(err));
247	}
248	if (reasonOrDesc) CFRelease(reasonOrDesc);
249	return result;
250#if DEPLOYMENT_TARGET_MACOSX || DEPLOYMENT_TARGET_EMBEDDED || DEPLOYMENT_TARGET_WINDOWS
251    }
252#endif
253
254#if DEPLOYMENT_TARGET_MACOSX || DEPLOYMENT_TARGET_EMBEDDED || DEPLOYMENT_TARGET_WINDOWS
255    // Then look for kCFErrorLocalizedFailureReasonKey; if there, create a full sentence from that.
256    CFStringRef reason = _CFErrorCopyUserInfoKey(err, kCFErrorLocalizedFailureReasonKey);
257    if (reason) {
258	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.");
259        CFStringRef result = CFStringCreateWithFormat(kCFAllocatorSystemDefault, NULL, operationFailedStr, reason);
260	CFRelease(operationFailedStr);
261        CFRelease(reason);
262	return result;
263    }
264
265    // Otherwise, generate a semi-user presentable string from the domain, code, and if available, the presumably non-localized kCFErrorDescriptionKey.
266    CFStringRef result;
267    CFStringRef desc = _CFErrorCopyUserInfoKey(err, kCFErrorDescriptionKey);
268    CFStringRef localizedDomain = CFCopyLocalizedStringFromTableInBundle(CFErrorGetDomain(err), CFSTR("Error"), cfBundle, "These are localized in the comment above");
269    if (desc) {     // We have kCFErrorDescriptionKey, so include that with the error domain and code
270	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.");
271	result = CFStringCreateWithFormat(kCFAllocatorSystemDefault, NULL, operationFailedStr, localizedDomain, (long)CFErrorGetCode(err), desc);
272	CFRelease(operationFailedStr);
273        CFRelease(desc);
274    } else {        // We don't have kCFErrorDescriptionKey, so just use error domain and code
275	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.");
276	result = CFStringCreateWithFormat(kCFAllocatorSystemDefault, NULL, operationFailedStr, localizedDomain, (long)CFErrorGetCode(err));
277	CFRelease(operationFailedStr);
278    }
279    CFRelease(localizedDomain);
280    return result;
281#endif
282}
283
284/* 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*/
286CFStringRef _CFErrorCreateLocalizedFailureReason(CFErrorRef err) {
287    // We simply return the value of kCFErrorLocalizedFailureReasonKey; no other searching takes place
288    return _CFErrorCopyUserInfoKey(err, kCFErrorLocalizedFailureReasonKey);
289}
290
291/* 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*/
293CFStringRef _CFErrorCreateLocalizedRecoverySuggestion(CFErrorRef err) {
294    // We simply return the value of kCFErrorLocalizedRecoverySuggestionKey; no other searching takes place
295    return _CFErrorCopyUserInfoKey(err, kCFErrorLocalizedRecoverySuggestionKey);
296}
297
298/* The "debug" description, used by CFCopyDescription and -[NSObject description].
299*/
300static void userInfoKeyValueShow(const void *key, const void *value, void *context) {
301    CFStringRef desc;
302    if (CFEqual(key, kCFErrorUnderlyingErrorKey) && (desc = CFErrorCopyDescription((CFErrorRef)value))) {	// We check desc, see <rdar://problem/8415727>
303	CFStringAppendFormat((CFMutableStringRef)context, NULL, CFSTR("%@=%p \"%@\", "), key, value, desc);
304	CFRelease(desc);
305    } else {
306	CFStringAppendFormat((CFMutableStringRef)context, NULL, CFSTR("%@=%@, "), key, value);
307    }
308}
309
310CFStringRef _CFErrorCreateDebugDescription(CFErrorRef err) {
311    CFStringRef desc = CFErrorCopyDescription(err);
312    CFStringRef debugDesc = _CFErrorCopyUserInfoKey(err, kCFErrorDebugDescriptionKey);
313    CFDictionaryRef userInfo = _CFErrorGetUserInfo(err);
314    CFMutableStringRef result = CFStringCreateMutable(kCFAllocatorSystemDefault, 0);
315    CFStringAppendFormat(result, NULL, CFSTR("Error Domain=%@ Code=%ld"), CFErrorGetDomain(err), (long)CFErrorGetCode(err));
316    CFStringAppendFormat(result, NULL, CFSTR(" \"%@\""), desc);
317    if (debugDesc && CFStringGetLength(debugDesc) > 0) CFStringAppendFormat(result, NULL, CFSTR(" (%@)"), debugDesc);
318    if (userInfo && CFDictionaryGetCount(userInfo)) {
319        CFStringAppendFormat(result, NULL, CFSTR(" UserInfo=%p {"), userInfo);
320	CFDictionaryApplyFunction(userInfo, userInfoKeyValueShow, (void *)result);
321	CFIndex commaLength = (CFStringHasSuffix(result, CFSTR(", "))) ? 2 : 0;
322	CFStringReplace(result, CFRangeMake(CFStringGetLength(result)-commaLength, commaLength), CFSTR("}"));
323    }
324    if (debugDesc) CFRelease(debugDesc);
325    if (desc) CFRelease(desc);
326    return result;
327}
328
329
330
331
332/**** CFError API/SPI ****/
333
334/* Note that there are two entry points for creating CFErrors. This one does it with a presupplied userInfo dictionary.
335*/
336CFErrorRef CFErrorCreate(CFAllocatorRef allocator, CFStringRef domain, CFIndex code, CFDictionaryRef userInfo) {
337    __CFGenericValidateType(domain, CFStringGetTypeID());
338    if (userInfo) __CFGenericValidateType(userInfo, CFDictionaryGetTypeID());
339
340    CFErrorRef err = (CFErrorRef)_CFRuntimeCreateInstance(allocator, __kCFErrorTypeID, sizeof(struct __CFError) - sizeof(CFRuntimeBase), NULL);
341    if (NULL == err) return NULL;
342
343    err->domain = CFStringCreateCopy(allocator, domain);
344    err->code = code;
345    err->userInfo = userInfo ? CFDictionaryCreateCopy(allocator, userInfo) : _CFErrorCreateEmptyDictionary(allocator);
346
347    return err;
348}
349
350/* 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*/
352CFErrorRef CFErrorCreateWithUserInfoKeysAndValues(CFAllocatorRef allocator, CFStringRef domain, CFIndex code, const void *const *userInfoKeys, const void *const *userInfoValues, CFIndex numUserInfoValues) {
353    __CFGenericValidateType(domain, CFStringGetTypeID());
354
355    CFErrorRef err = (CFErrorRef)_CFRuntimeCreateInstance(allocator, __kCFErrorTypeID, sizeof(struct __CFError) - sizeof(CFRuntimeBase), NULL);
356    if (NULL == err) return NULL;
357
358    err->domain = CFStringCreateCopy(allocator, domain);
359    err->code = code;
360    err->userInfo = CFDictionaryCreate(allocator, (const void **)userInfoKeys, (const void **)userInfoValues, numUserInfoValues, &kCFCopyStringDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks);
361
362    return err;
363}
364
365CFStringRef CFErrorGetDomain(CFErrorRef err) {
366    CF_OBJC_FUNCDISPATCHV(__kCFErrorTypeID, CFStringRef, (NSError *)err, domain);
367    __CFAssertIsError(err);
368    return err->domain;
369}
370
371CFIndex CFErrorGetCode(CFErrorRef err) {
372    CF_OBJC_FUNCDISPATCHV(__kCFErrorTypeID, CFIndex, (NSError *)err, code);
373    __CFAssertIsError(err);
374    return err->code;
375}
376
377/* This accessor never returns NULL. For usage inside this file, consider __CFErrorGetUserInfo().
378*/
379CFDictionaryRef CFErrorCopyUserInfo(CFErrorRef err) {
380    CFDictionaryRef userInfo = _CFErrorGetUserInfo(err);
381    return userInfo ? (CFDictionaryRef)CFRetain(userInfo) : _CFErrorCreateEmptyDictionary(CFGetAllocator(err));
382}
383
384CFStringRef CFErrorCopyDescription(CFErrorRef err) {
385    if (CF_IS_OBJC(__kCFErrorTypeID, err)) {  // Since we have to return a retained result, we need to treat the toll-free bridging specially
386        CFStringRef desc = (CFStringRef) CF_OBJC_CALLV((NSError *)err, localizedDescription);
387        return desc ? (CFStringRef)CFRetain(desc) : NULL;    // !!! It really should never return nil.
388    }
389    __CFAssertIsError(err);
390    return _CFErrorCreateLocalizedDescription(err);
391}
392
393CFStringRef 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
395        CFStringRef str = (CFStringRef) CF_OBJC_CALLV((NSError *)err, localizedFailureReason);
396        return str ? (CFStringRef)CFRetain(str) : NULL;    // It's possible for localizedFailureReason to return nil
397    }
398    __CFAssertIsError(err);
399    return _CFErrorCreateLocalizedFailureReason(err);
400}
401
402CFStringRef CFErrorCopyRecoverySuggestion(CFErrorRef err) {
403    if (CF_IS_OBJC(__kCFErrorTypeID, err)) {  // Since we have to return a retained result, we need to treat the toll-free bridging specially
404        CFStringRef str = (CFStringRef) CF_OBJC_CALLV((NSError *)err, localizedRecoverySuggestion);
405        return str ? (CFStringRef)CFRetain(str) : NULL;    // It's possible for localizedRecoverySuggestion to return nil
406    }
407    __CFAssertIsError(err);
408    return _CFErrorCreateLocalizedRecoverySuggestion(err);
409}
410
411
412/**** CFError CallBack management ****/
413
414/* Domain-to-callback mapping dictionary
415*/
416static CFMutableDictionaryRef _CFErrorCallBackTable = NULL;
417
418
419/* 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.
420*/
421static CFTypeRef _CFErrorPOSIXCallBack(CFErrorRef err, CFStringRef key) {
422    if (!CFEqual(key, kCFErrorDescriptionKey) && !CFEqual(key, kCFErrorLocalizedFailureReasonKey)) return NULL;
423
424    const char *errCStr = strerror(CFErrorGetCode(err));
425    CFStringRef errStr = (errCStr && strlen(errCStr)) ? CFStringCreateWithCString(kCFAllocatorSystemDefault, errCStr, kCFStringEncodingUTF8) : NULL;
426
427    if (!errStr) return NULL;
428    if (CFEqual(key, kCFErrorDescriptionKey)) return errStr;	// If all we wanted was the non-localized description, we're done
429
430#if DEPLOYMENT_TARGET_MACOSX || DEPLOYMENT_TARGET_EMBEDDED || DEPLOYMENT_TARGET_WINDOWS
431    // We need a kCFErrorLocalizedFailureReasonKey, so look up a possible localization for the error message
432    // Look for the bundle in /System/Library/CoreServices/CoreTypes.bundle
433    CFArrayRef paths = CFCopySearchPathForDirectoriesInDomains(kCFLibraryDirectory, kCFSystemDomainMask, false);
434    if (paths) {
435	if (CFArrayGetCount(paths) > 0) {
436            CFStringRef fileSystemPath = CFURLCopyFileSystemPath((CFURLRef)CFArrayGetValueAtIndex(paths, 0), kCFURLPOSIXPathStyle);
437            if (fileSystemPath) {
438                CFStringRef path = CFStringCreateWithFormat(kCFAllocatorSystemDefault, NULL, CFSTR("%@/CoreServices/CoreTypes.bundle"), fileSystemPath);
439                CFURLRef url = CFURLCreateWithFileSystemPath(kCFAllocatorSystemDefault, path, kCFURLPOSIXPathStyle, false /* not a directory */);
440                CFRelease(fileSystemPath);
441                if (url) {
442                    CFBundleRef bundle = CFBundleCreate(kCFAllocatorSystemDefault, url);
443                    if (bundle) {
444                        // We only want to return a result if there was a localization
445                        CFStringRef localizedErrStr = CFBundleCopyLocalizedString(bundle, errStr, errStr, CFSTR("ErrnoErrors"));
446                        if (localizedErrStr == errStr) {
447                            CFRelease(localizedErrStr);
448                            CFRelease(errStr);
449                            errStr = NULL;
450                        } else {
451                            CFRelease(errStr);
452                            errStr = localizedErrStr;
453                        }
454                        CFRelease(bundle);
455                    }
456                    CFRelease(url);
457                }
458                CFRelease(path);
459            }
460	}
461	CFRelease(paths);
462    }
463#endif
464
465    return errStr;
466}
467
468#if DEPLOYMENT_TARGET_MACOSX || DEPLOYMENT_TARGET_EMBEDDED
469/* Built-in callback for Mach domain.
470*/
471static CFTypeRef _CFErrorMachCallBack(CFErrorRef err, CFStringRef key) {
472    if (CFEqual(key, kCFErrorDescriptionKey)) {
473        const char *errStr = mach_error_string(CFErrorGetCode(err));
474        if (errStr && strlen(errStr)) return CFStringCreateWithCString(kCFAllocatorSystemDefault, errStr, kCFStringEncodingUTF8);
475    }
476    return NULL;
477}
478#endif
479
480
481/* 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.
482*/
483static void _CFErrorInitializeCallBackTable(void) {
484    // Create the table outside the lock
485    CFMutableDictionaryRef table = CFDictionaryCreateMutable(kCFAllocatorSystemDefault, 0, &kCFCopyStringDictionaryKeyCallBacks, NULL);
486    __CFSpinLock(&_CFErrorSpinlock);
487    if (!_CFErrorCallBackTable) {
488        _CFErrorCallBackTable = table;
489        __CFSpinUnlock(&_CFErrorSpinlock);
490    } else {
491        __CFSpinUnlock(&_CFErrorSpinlock);
492        CFRelease(table);
493        // 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.
494    }
495    CFErrorSetCallBackForDomain(kCFErrorDomainPOSIX, _CFErrorPOSIXCallBack);
496#if DEPLOYMENT_TARGET_MACOSX || DEPLOYMENT_TARGET_EMBEDDED
497    CFErrorSetCallBackForDomain(kCFErrorDomainMach, _CFErrorMachCallBack);
498#endif
499}
500
501void CFErrorSetCallBackForDomain(CFStringRef domainName, CFErrorUserInfoKeyCallBack callBack) {
502    if (!_CFErrorCallBackTable) _CFErrorInitializeCallBackTable();
503    __CFSpinLock(&_CFErrorSpinlock);
504    if (callBack) {
505        CFDictionarySetValue(_CFErrorCallBackTable, domainName, (void *)callBack);
506    } else {
507        CFDictionaryRemoveValue(_CFErrorCallBackTable, domainName);
508    }
509    __CFSpinUnlock(&_CFErrorSpinlock);
510}
511
512CFErrorUserInfoKeyCallBack CFErrorGetCallBackForDomain(CFStringRef domainName) {
513    if (!_CFErrorCallBackTable) _CFErrorInitializeCallBackTable();
514    __CFSpinLock(&_CFErrorSpinlock);
515    CFErrorUserInfoKeyCallBack callBack = (CFErrorUserInfoKeyCallBack)CFDictionaryGetValue(_CFErrorCallBackTable, domainName);
516    __CFSpinUnlock(&_CFErrorSpinlock);
517    return callBack;
518}
519
520
521
522