]> git.saurik.com Git - apple/cf.git/blob - CFError.c
CF-1153.18.tar.gz
[apple/cf.git] / CFError.c
1 /*
2 * Copyright (c) 2015 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-2014, 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 */
40 CONST_STRING_DECL(kCFErrorLocalizedDescriptionKey, "NSLocalizedDescription");
41 CONST_STRING_DECL(kCFErrorLocalizedFailureReasonKey, "NSLocalizedFailureReason");
42 CONST_STRING_DECL(kCFErrorLocalizedRecoverySuggestionKey, "NSLocalizedRecoverySuggestion");
43 CONST_STRING_DECL(kCFErrorDescriptionKey, "NSDescription");
44 CONST_STRING_DECL(kCFErrorDebugDescriptionKey, "NSDebugDescription");
45 CONST_STRING_DECL(kCFErrorUnderlyingErrorKey, "NSUnderlyingError");
46 CONST_STRING_DECL(kCFErrorURLKey, "NSURL");
47 CONST_STRING_DECL(kCFErrorFilePathKey, "NSFilePath");
48
49 /* Pre-defined error domains
50 */
51 CONST_STRING_DECL(kCFErrorDomainPOSIX, "NSPOSIXErrorDomain");
52 CONST_STRING_DECL(kCFErrorDomainOSStatus, "NSOSStatusErrorDomain");
53 CONST_STRING_DECL(kCFErrorDomainMach, "NSMachErrorDomain");
54 CONST_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
58 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.")
59 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.")
60 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.")
61 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.")
62 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.")
63 */
64
65
66
67 /* Forward declarations
68 */
69 static CFDictionaryRef _CFErrorGetUserInfo(CFErrorRef err);
70 static CFStringRef _CFErrorCopyUserInfoKey(CFErrorRef err, CFStringRef key);
71 static CFDictionaryRef _CFErrorCreateEmptyDictionary(CFAllocatorRef allocator);
72
73 /* Assertions and other macros/inlines
74 */
75 #define __CFAssertIsError(cf) __CFGenericValidateType(cf, CFErrorGetTypeID())
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 */
79 static CFLock_t _CFErrorSpinlock = CFLockInit;
80
81
82
83
84 /**** CFError CF runtime stuff ****/
85
86 struct __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 */
95 static 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 */
123 static 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 */
131 static 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 */
137 static 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
142 static void __CFErrorDeallocate(CFTypeRef cf) {
143 CFErrorRef err = (CFErrorRef)cf;
144 CFRelease(err->domain);
145 CFRelease(err->userInfo);
146 }
147
148
149 static CFTypeID __kCFErrorTypeID = _kCFRuntimeNotATypeID;
150
151 static 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
163 CFTypeID CFErrorGetTypeID(void) {
164 static dispatch_once_t initOnce;
165 dispatch_once(&initOnce, ^{ __kCFErrorTypeID = _CFRuntimeRegisterClass(&__CFErrorClass); });
166 return __kCFErrorTypeID;
167 }
168
169
170
171
172 /**** CFError support functions ****/
173
174 /* Returns a shared empty dictionary (unless the allocator is not kCFAllocatorSystemDefault, in which case returns a newly allocated one).
175 */
176 static CFDictionaryRef _CFErrorCreateEmptyDictionary(CFAllocatorRef allocator) {
177 if (allocator == NULL) allocator = __CFGetDefaultAllocator();
178 if (_CFAllocatorIsSystemDefault(allocator)) {
179 static CFDictionaryRef emptyErrorDictionary = NULL;
180 if (emptyErrorDictionary == NULL) {
181 CFDictionaryRef tmp = CFDictionaryCreate(allocator, NULL, NULL, 0, &kCFCopyStringDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks);
182 __CFLock(&_CFErrorSpinlock);
183 if (emptyErrorDictionary == NULL) {
184 emptyErrorDictionary = tmp;
185 __CFUnlock(&_CFErrorSpinlock);
186 } else {
187 __CFUnlock(&_CFErrorSpinlock);
188 CFRelease(tmp);
189 }
190 }
191 return (CFDictionaryRef)CFRetain(emptyErrorDictionary);
192 } else {
193 return CFDictionaryCreate(allocator, NULL, NULL, 0, &kCFCopyStringDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks);
194 }
195 }
196
197 /* 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.
198 */
199 static CFDictionaryRef _CFErrorGetUserInfo(CFErrorRef err) {
200 CF_OBJC_FUNCDISPATCHV(CFErrorGetTypeID(), CFDictionaryRef, (NSError *)err, userInfo);
201 __CFAssertIsError(err);
202 return err->userInfo;
203 }
204
205 /* This function retrieves the value of the specified key from the userInfo, or from the callback. It works with a CF or NSError.
206 */
207 static CFStringRef _CFErrorCopyUserInfoKey(CFErrorRef err, CFStringRef key) {
208 CFStringRef result = NULL;
209 // First consult the userInfo dictionary
210 CFDictionaryRef userInfo = _CFErrorGetUserInfo(err);
211 if (userInfo) result = (CFStringRef)CFDictionaryGetValue(userInfo, key);
212 // If that doesn't work, consult the callback
213 if (result) {
214 CFRetain(result);
215 } else {
216 CFErrorUserInfoKeyCallBack callBack = CFErrorGetCallBackForDomain(CFErrorGetDomain(err));
217 if (callBack) result = (CFStringRef)callBack(err, key);
218 }
219 return result;
220 }
221
222 /* 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.
223 */
224 CFStringRef _CFErrorCreateLocalizedDescription(CFErrorRef err) {
225 // First look for kCFErrorLocalizedDescriptionKey; if non-NULL, return that as-is.
226 CFStringRef localizedDesc = _CFErrorCopyUserInfoKey(err, kCFErrorLocalizedDescriptionKey);
227 if (localizedDesc) return localizedDesc;
228
229
230 #if DEPLOYMENT_TARGET_MACOSX || DEPLOYMENT_TARGET_EMBEDDED || DEPLOYMENT_TARGET_WINDOWS
231 // Cache the CF bundle since we will be using it for localized strings.
232 CFBundleRef cfBundle = CFBundleGetBundleWithIdentifier(CFSTR("com.apple.CoreFoundation"));
233
234 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.
235 #endif
236
237 CFStringRef result = NULL, reasonOrDesc;
238
239 if ((reasonOrDesc = _CFErrorCopyUserInfoKey(err, kCFErrorLocalizedFailureReasonKey))) { // First look for kCFErrorLocalizedFailureReasonKey
240 result = CFStringCreateWithFormat(kCFAllocatorSystemDefault, NULL, CFSTR("The operation couldn\\U2019t be completed. %@"), reasonOrDesc);
241 } else if ((reasonOrDesc = _CFErrorCopyUserInfoKey(err, kCFErrorDescriptionKey))) { // Then try kCFErrorDescriptionKey
242 result = CFStringCreateWithFormat(kCFAllocatorSystemDefault, NULL, CFSTR("The operation couldn\\U2019t be completed. (%@ error %ld - %@)"), CFErrorGetDomain(err), (long)CFErrorGetCode(err), reasonOrDesc);
243 } else { // Last resort, just the domain and code
244 result = CFStringCreateWithFormat(kCFAllocatorSystemDefault, NULL, CFSTR("The operation couldn\\U2019t be completed. (%@ error %ld.)"), CFErrorGetDomain(err), (long)CFErrorGetCode(err));
245 }
246 if (reasonOrDesc) CFRelease(reasonOrDesc);
247 return result;
248 #if DEPLOYMENT_TARGET_MACOSX || DEPLOYMENT_TARGET_EMBEDDED || DEPLOYMENT_TARGET_WINDOWS
249 }
250 #endif
251
252 #if DEPLOYMENT_TARGET_MACOSX || DEPLOYMENT_TARGET_EMBEDDED || DEPLOYMENT_TARGET_WINDOWS
253 // Then look for kCFErrorLocalizedFailureReasonKey; if there, create a full sentence from that.
254 CFStringRef reason = _CFErrorCopyUserInfoKey(err, kCFErrorLocalizedFailureReasonKey);
255 if (reason) {
256 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.");
257 CFStringRef result = CFStringCreateWithFormat(kCFAllocatorSystemDefault, NULL, operationFailedStr, reason);
258 CFRelease(operationFailedStr);
259 CFRelease(reason);
260 return result;
261 }
262
263 // Otherwise, generate a semi-user presentable string from the domain, code, and if available, the presumably non-localized kCFErrorDescriptionKey.
264 CFStringRef result;
265 CFStringRef desc = _CFErrorCopyUserInfoKey(err, kCFErrorDescriptionKey);
266 CFStringRef localizedDomain = CFCopyLocalizedStringFromTableInBundle(CFErrorGetDomain(err), CFSTR("Error"), cfBundle, "These are localized in the comment above");
267 if (desc) { // We have kCFErrorDescriptionKey, so include that with the error domain and code
268 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.");
269 result = CFStringCreateWithFormat(kCFAllocatorSystemDefault, NULL, operationFailedStr, localizedDomain, (long)CFErrorGetCode(err), desc);
270 CFRelease(operationFailedStr);
271 CFRelease(desc);
272 } else { // We don't have kCFErrorDescriptionKey, so just use error domain and code
273 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.");
274 result = CFStringCreateWithFormat(kCFAllocatorSystemDefault, NULL, operationFailedStr, localizedDomain, (long)CFErrorGetCode(err));
275 CFRelease(operationFailedStr);
276 }
277 CFRelease(localizedDomain);
278 return result;
279 #endif
280 }
281
282 /* 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.
283 */
284 CFStringRef _CFErrorCreateLocalizedFailureReason(CFErrorRef err) {
285 // We simply return the value of kCFErrorLocalizedFailureReasonKey; no other searching takes place
286 return _CFErrorCopyUserInfoKey(err, kCFErrorLocalizedFailureReasonKey);
287 }
288
289 /* 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.
290 */
291 CFStringRef _CFErrorCreateLocalizedRecoverySuggestion(CFErrorRef err) {
292 // We simply return the value of kCFErrorLocalizedRecoverySuggestionKey; no other searching takes place
293 return _CFErrorCopyUserInfoKey(err, kCFErrorLocalizedRecoverySuggestionKey);
294 }
295
296 /* The "debug" description, used by CFCopyDescription and -[NSObject description].
297 */
298 static void userInfoKeyValueShow(const void *key, const void *value, void *context) {
299 CFStringRef desc;
300 if (CFEqual(key, kCFErrorUnderlyingErrorKey) && (desc = CFErrorCopyDescription((CFErrorRef)value))) { // We check desc, see <rdar://problem/8415727>
301 CFStringAppendFormat((CFMutableStringRef)context, NULL, CFSTR("%@=%p \"%@\", "), key, value, desc);
302 CFRelease(desc);
303 } else {
304 CFStringAppendFormat((CFMutableStringRef)context, NULL, CFSTR("%@=%@, "), key, value);
305 }
306 }
307
308 CFStringRef _CFErrorCreateDebugDescription(CFErrorRef err) {
309 CFStringRef desc = CFErrorCopyDescription(err);
310 CFStringRef debugDesc = _CFErrorCopyUserInfoKey(err, kCFErrorDebugDescriptionKey);
311 CFDictionaryRef userInfo = _CFErrorGetUserInfo(err);
312 CFMutableStringRef result = CFStringCreateMutable(kCFAllocatorSystemDefault, 0);
313 CFStringAppendFormat(result, NULL, CFSTR("Error Domain=%@ Code=%ld"), CFErrorGetDomain(err), (long)CFErrorGetCode(err));
314 CFStringAppendFormat(result, NULL, CFSTR(" \"%@\""), desc);
315 if (debugDesc && CFStringGetLength(debugDesc) > 0) CFStringAppendFormat(result, NULL, CFSTR(" (%@)"), debugDesc);
316 if (userInfo && CFDictionaryGetCount(userInfo)) {
317 CFStringAppendFormat(result, NULL, CFSTR(" UserInfo=%p {"), userInfo);
318 CFDictionaryApplyFunction(userInfo, userInfoKeyValueShow, (void *)result);
319 CFIndex commaLength = (CFStringHasSuffix(result, CFSTR(", "))) ? 2 : 0;
320 CFStringReplace(result, CFRangeMake(CFStringGetLength(result)-commaLength, commaLength), CFSTR("}"));
321 }
322 if (debugDesc) CFRelease(debugDesc);
323 if (desc) CFRelease(desc);
324 return result;
325 }
326
327
328
329
330 /**** CFError API/SPI ****/
331
332 /* Note that there are two entry points for creating CFErrors. This one does it with a presupplied userInfo dictionary.
333 */
334 CFErrorRef CFErrorCreate(CFAllocatorRef allocator, CFStringRef domain, CFIndex code, CFDictionaryRef userInfo) {
335 __CFGenericValidateType(domain, CFStringGetTypeID());
336 if (userInfo) __CFGenericValidateType(userInfo, CFDictionaryGetTypeID());
337
338 CFErrorRef err = (CFErrorRef)_CFRuntimeCreateInstance(allocator, CFErrorGetTypeID(), sizeof(struct __CFError) - sizeof(CFRuntimeBase), NULL);
339 if (NULL == err) return NULL;
340
341 ((struct __CFError *)err)->domain = CFStringCreateCopy(allocator, domain);
342 ((struct __CFError *)err)->code = code;
343 ((struct __CFError *)err)->userInfo = userInfo ? CFDictionaryCreateCopy(allocator, userInfo) : _CFErrorCreateEmptyDictionary(allocator);
344
345 return err;
346 }
347
348 /* 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.
349 */
350 CFErrorRef CFErrorCreateWithUserInfoKeysAndValues(CFAllocatorRef allocator, CFStringRef domain, CFIndex code, const void *const *userInfoKeys, const void *const *userInfoValues, CFIndex numUserInfoValues) {
351 __CFGenericValidateType(domain, CFStringGetTypeID());
352
353 CFErrorRef err = (CFErrorRef)_CFRuntimeCreateInstance(allocator, CFErrorGetTypeID(), sizeof(struct __CFError) - sizeof(CFRuntimeBase), NULL);
354 if (NULL == err) return NULL;
355
356 ((struct __CFError *)err)->domain = CFStringCreateCopy(allocator, domain);
357 ((struct __CFError *)err)->code = code;
358 ((struct __CFError *)err)->userInfo = CFDictionaryCreate(allocator, (const void **)userInfoKeys, (const void **)userInfoValues, numUserInfoValues, &kCFCopyStringDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks);
359
360 return err;
361 }
362
363 CFStringRef CFErrorGetDomain(CFErrorRef err) {
364 CF_OBJC_FUNCDISPATCHV(CFErrorGetTypeID(), CFStringRef, (NSError *)err, domain);
365 __CFAssertIsError(err);
366 return err->domain;
367 }
368
369 CFIndex CFErrorGetCode(CFErrorRef err) {
370 CF_OBJC_FUNCDISPATCHV(CFErrorGetTypeID(), CFIndex, (NSError *)err, code);
371 __CFAssertIsError(err);
372 return err->code;
373 }
374
375 /* This accessor never returns NULL. For usage inside this file, consider __CFErrorGetUserInfo().
376 */
377 CFDictionaryRef CFErrorCopyUserInfo(CFErrorRef err) {
378 CFDictionaryRef userInfo = _CFErrorGetUserInfo(err);
379 return userInfo ? (CFDictionaryRef)CFRetain(userInfo) : _CFErrorCreateEmptyDictionary(CFGetAllocator(err));
380 }
381
382 CFStringRef CFErrorCopyDescription(CFErrorRef err) {
383 if (CF_IS_OBJC(CFErrorGetTypeID(), err)) { // Since we have to return a retained result, we need to treat the toll-free bridging specially
384 CFStringRef desc = (CFStringRef) CF_OBJC_CALLV((NSError *)err, localizedDescription);
385 return desc ? (CFStringRef)CFRetain(desc) : NULL; // !!! It really should never return nil.
386 }
387 __CFAssertIsError(err);
388 return _CFErrorCreateLocalizedDescription(err);
389 }
390
391 CFStringRef CFErrorCopyFailureReason(CFErrorRef err) {
392 if (CF_IS_OBJC(CFErrorGetTypeID(), err)) { // Since we have to return a retained result, we need to treat the toll-free bridging specially
393 CFStringRef str = (CFStringRef) CF_OBJC_CALLV((NSError *)err, localizedFailureReason);
394 return str ? (CFStringRef)CFRetain(str) : NULL; // It's possible for localizedFailureReason to return nil
395 }
396 __CFAssertIsError(err);
397 return _CFErrorCreateLocalizedFailureReason(err);
398 }
399
400 CFStringRef CFErrorCopyRecoverySuggestion(CFErrorRef err) {
401 if (CF_IS_OBJC(CFErrorGetTypeID(), err)) { // Since we have to return a retained result, we need to treat the toll-free bridging specially
402 CFStringRef str = (CFStringRef) CF_OBJC_CALLV((NSError *)err, localizedRecoverySuggestion);
403 return str ? (CFStringRef)CFRetain(str) : NULL; // It's possible for localizedRecoverySuggestion to return nil
404 }
405 __CFAssertIsError(err);
406 return _CFErrorCreateLocalizedRecoverySuggestion(err);
407 }
408
409
410 /**** CFError CallBack management ****/
411
412 /* Domain-to-callback mapping dictionary
413 */
414 static CFMutableDictionaryRef _CFErrorCallBackTable = NULL;
415
416
417 /* 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.
418 */
419 static CFTypeRef _CFErrorPOSIXCallBack(CFErrorRef err, CFStringRef key) {
420 if (!CFEqual(key, kCFErrorDescriptionKey) && !CFEqual(key, kCFErrorLocalizedFailureReasonKey)) return NULL;
421
422 const char *errCStr = strerror(CFErrorGetCode(err));
423 CFStringRef errStr = (errCStr && strlen(errCStr)) ? CFStringCreateWithCString(kCFAllocatorSystemDefault, errCStr, kCFStringEncodingUTF8) : NULL;
424
425 if (!errStr) return NULL;
426 if (CFEqual(key, kCFErrorDescriptionKey)) return errStr; // If all we wanted was the non-localized description, we're done
427
428 #if DEPLOYMENT_TARGET_MACOSX || DEPLOYMENT_TARGET_EMBEDDED || DEPLOYMENT_TARGET_WINDOWS
429 // We need a kCFErrorLocalizedFailureReasonKey, so look up a possible localization for the error message
430 // Look for the bundle in /System/Library/CoreServices/CoreTypes.bundle
431 CFArrayRef paths = CFCopySearchPathForDirectoriesInDomains(kCFLibraryDirectory, kCFSystemDomainMask, false);
432 if (paths) {
433 if (CFArrayGetCount(paths) > 0) {
434 CFStringRef fileSystemPath = CFURLCopyFileSystemPath((CFURLRef)CFArrayGetValueAtIndex(paths, 0), kCFURLPOSIXPathStyle);
435 if (fileSystemPath) {
436 CFStringRef path = CFStringCreateWithFormat(kCFAllocatorSystemDefault, NULL, CFSTR("%@/CoreServices/CoreTypes.bundle"), fileSystemPath);
437 CFURLRef url = CFURLCreateWithFileSystemPath(kCFAllocatorSystemDefault, path, kCFURLPOSIXPathStyle, false /* not a directory */);
438 CFRelease(fileSystemPath);
439 if (url) {
440 CFBundleRef bundle = CFBundleCreate(kCFAllocatorSystemDefault, url);
441 if (bundle) {
442 // We only want to return a result if there was a localization
443 CFStringRef localizedErrStr = CFBundleCopyLocalizedString(bundle, errStr, errStr, CFSTR("ErrnoErrors"));
444 if (localizedErrStr == errStr) {
445 CFRelease(localizedErrStr);
446 CFRelease(errStr);
447 errStr = NULL;
448 } else {
449 CFRelease(errStr);
450 errStr = localizedErrStr;
451 }
452 CFRelease(bundle);
453 }
454 CFRelease(url);
455 }
456 CFRelease(path);
457 }
458 }
459 CFRelease(paths);
460 }
461 #endif
462
463 return errStr;
464 }
465
466 #if DEPLOYMENT_TARGET_MACOSX || DEPLOYMENT_TARGET_EMBEDDED
467 /* Built-in callback for Mach domain.
468 */
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);
473 }
474 return NULL;
475 }
476 #endif
477
478
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.
480 */
481 static void _CFErrorInitializeCallBackTable(void) {
482 // Create the table outside the lock
483 CFMutableDictionaryRef table = CFDictionaryCreateMutable(kCFAllocatorSystemDefault, 0, &kCFCopyStringDictionaryKeyCallBacks, NULL);
484 __CFLock(&_CFErrorSpinlock);
485 if (!_CFErrorCallBackTable) {
486 _CFErrorCallBackTable = table;
487 __CFUnlock(&_CFErrorSpinlock);
488 } else {
489 __CFUnlock(&_CFErrorSpinlock);
490 CFRelease(table);
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.
492 }
493 CFErrorSetCallBackForDomain(kCFErrorDomainPOSIX, _CFErrorPOSIXCallBack);
494 #if DEPLOYMENT_TARGET_MACOSX || DEPLOYMENT_TARGET_EMBEDDED
495 CFErrorSetCallBackForDomain(kCFErrorDomainMach, _CFErrorMachCallBack);
496 #endif
497 }
498
499 void CFErrorSetCallBackForDomain(CFStringRef domainName, CFErrorUserInfoKeyCallBack callBack) {
500 if (!_CFErrorCallBackTable) _CFErrorInitializeCallBackTable();
501 __CFLock(&_CFErrorSpinlock);
502 if (callBack) {
503 CFDictionarySetValue(_CFErrorCallBackTable, domainName, (void *)callBack);
504 } else {
505 CFDictionaryRemoveValue(_CFErrorCallBackTable, domainName);
506 }
507 __CFUnlock(&_CFErrorSpinlock);
508 }
509
510 CFErrorUserInfoKeyCallBack CFErrorGetCallBackForDomain(CFStringRef domainName) {
511 if (!_CFErrorCallBackTable) _CFErrorInitializeCallBackTable();
512 __CFLock(&_CFErrorSpinlock);
513 CFErrorUserInfoKeyCallBack callBack = (CFErrorUserInfoKeyCallBack)CFDictionaryGetValue(_CFErrorCallBackTable, domainName);
514 __CFUnlock(&_CFErrorSpinlock);
515 return callBack;
516 }
517
518
519