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