/ include / CoreFoundation / CFInternal.h
CFInternal.h
  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  /*	CFInternal.h
 25  	Copyright (c) 1998-2014, Apple Inc. All rights reserved.
 26  */
 27  
 28  /*
 29          NOT TO BE USED OUTSIDE CF!
 30  */
 31  
 32  #if !CF_BUILDING_CF
 33      #error The header file CFInternal.h is for the exclusive use of CoreFoundation. No other project should include it.
 34  #endif
 35  
 36  #if !defined(__COREFOUNDATION_CFINTERNAL__)
 37  #define __COREFOUNDATION_CFINTERNAL__ 1
 38  
 39  
 40  #define __CF_COMPILE_YEAR__	(__DATE__[7] * 1000 + __DATE__[8] * 100 + __DATE__[9] * 10 + __DATE__[10] - 53328)
 41  #define __CF_COMPILE_MONTH__	((__DATE__[1] + __DATE__[2] == 207) ? 1 : \
 42  				 (__DATE__[1] + __DATE__[2] == 199) ? 2 : \
 43  				 (__DATE__[1] + __DATE__[2] == 211) ? 3 : \
 44  				 (__DATE__[1] + __DATE__[2] == 226) ? 4 : \
 45  				 (__DATE__[1] + __DATE__[2] == 218) ? 5 : \
 46  				 (__DATE__[1] + __DATE__[2] == 227) ? 6 : \
 47  				 (__DATE__[1] + __DATE__[2] == 225) ? 7 : \
 48  				 (__DATE__[1] + __DATE__[2] == 220) ? 8 : \
 49  				 (__DATE__[1] + __DATE__[2] == 213) ? 9 : \
 50  				 (__DATE__[1] + __DATE__[2] == 215) ? 10 : \
 51  				 (__DATE__[1] + __DATE__[2] == 229) ? 11 : \
 52  				 (__DATE__[1] + __DATE__[2] == 200) ? 12 : 0)
 53  #define __CF_COMPILE_DAY__	(__DATE__[4] * 10 + __DATE__[5] - (__DATE__[4] == ' ' ? 368 : 528))
 54  #define __CF_COMPILE_DATE__	(__CF_COMPILE_YEAR__ * 10000 + __CF_COMPILE_MONTH__ * 100 + __CF_COMPILE_DAY__)
 55  
 56  #define __CF_COMPILE_HOUR__	(__TIME__[0] * 10 + __TIME__[1] - 528)
 57  #define __CF_COMPILE_MINUTE__	(__TIME__[3] * 10 + __TIME__[4] - 528)
 58  #define __CF_COMPILE_SECOND__	(__TIME__[6] * 10 + __TIME__[7] - 528)
 59  #define __CF_COMPILE_TIME__	(__CF_COMPILE_HOUR__ * 10000 + __CF_COMPILE_MINUTE__ * 100 + __CF_COMPILE_SECOND__)
 60  
 61  #define __CF_COMPILE_SECOND_OF_DAY__	(__CF_COMPILE_HOUR__ * 3600 + __CF_COMPILE_MINUTE__ * 60 + __CF_COMPILE_SECOND__)
 62  
 63  // __CF_COMPILE_DAY_OF_EPOCH__ works within Gregorian years 2001 - 2099; the epoch is of course CF's epoch
 64  #define __CF_COMPILE_DAY_OF_EPOCH__	((__CF_COMPILE_YEAR__ - 2001) * 365 + (__CF_COMPILE_YEAR__ - 2001) / 4 \
 65  					+ ((__DATE__[1] + __DATE__[2] == 207) ? 0 : \
 66  					   (__DATE__[1] + __DATE__[2] == 199) ? 31 : \
 67  					   (__DATE__[1] + __DATE__[2] == 211) ? 59 + (__CF_COMPILE_YEAR__ % 4 == 0) : \
 68  					   (__DATE__[1] + __DATE__[2] == 226) ? 90 + (__CF_COMPILE_YEAR__ % 4 == 0) : \
 69  					   (__DATE__[1] + __DATE__[2] == 218) ? 120 + (__CF_COMPILE_YEAR__ % 4 == 0) : \
 70  					   (__DATE__[1] + __DATE__[2] == 227) ? 151 + (__CF_COMPILE_YEAR__ % 4 == 0) : \
 71  					   (__DATE__[1] + __DATE__[2] == 225) ? 181 + (__CF_COMPILE_YEAR__ % 4 == 0) : \
 72  					   (__DATE__[1] + __DATE__[2] == 220) ? 212 + (__CF_COMPILE_YEAR__ % 4 == 0) : \
 73  					   (__DATE__[1] + __DATE__[2] == 213) ? 243 + (__CF_COMPILE_YEAR__ % 4 == 0) : \
 74  					   (__DATE__[1] + __DATE__[2] == 215) ? 273 + (__CF_COMPILE_YEAR__ % 4 == 0) : \
 75  					   (__DATE__[1] + __DATE__[2] == 229) ? 304 + (__CF_COMPILE_YEAR__ % 4 == 0) : \
 76  					   (__DATE__[1] + __DATE__[2] == 200) ? 334 + (__CF_COMPILE_YEAR__ % 4 == 0) : \
 77  					    365 + (__CF_COMPILE_YEAR__ % 4 == 0)) \
 78  					+ __CF_COMPILE_DAY__)
 79  
 80  
 81  CF_EXTERN_C_BEGIN
 82  
 83  #include <CoreFoundation/CFBase.h>
 84  #include <CoreFoundation/CFURL.h>
 85  #include <CoreFoundation/CFString.h>
 86  #include <CoreFoundation/CFDate.h>
 87  #include <CoreFoundation/CFArray.h>
 88  #include <CoreFoundation/CFLogUtilities.h>
 89  #include <CoreFoundation/CFRuntime.h>
 90  #include <limits.h>
 91  #if DEPLOYMENT_TARGET_MACOSX || DEPLOYMENT_TARGET_EMBEDDED || DEPLOYMENT_TARGET_EMBEDDED_MINI || DEPLOYMENT_TARGET_LINUX
 92  #include <xlocale.h>
 93  #include <unistd.h>
 94  #include <sys/time.h>
 95  #include <signal.h>
 96  #include <stdio.h>
 97  #endif
 98  #include <pthread.h>
 99  
100  
101  #if defined(__BIG_ENDIAN__)
102  #define __CF_BIG_ENDIAN__ 1
103  #define __CF_LITTLE_ENDIAN__ 0
104  #endif
105  
106  #if defined(__LITTLE_ENDIAN__)
107  #define __CF_LITTLE_ENDIAN__ 1
108  #define __CF_BIG_ENDIAN__ 0
109  #endif
110  
111  
112  #include <CoreFoundation/ForFoundationOnly.h>
113  
114  CF_EXPORT const char *_CFProcessName(void);
115  CF_EXPORT CFStringRef _CFProcessNameString(void);
116  
117  CF_EXPORT Boolean _CFGetCurrentDirectory(char *path, int maxlen);
118  
119  CF_EXPORT CFArrayRef _CFGetWindowsBinaryDirectories(void);
120  
121  CF_EXPORT CFStringRef _CFStringCreateHostName(void);
122  
123  #if DEPLOYMENT_TARGET_MACOSX || DEPLOYMENT_TARGET_EMBEDDED || DEPLOYMENT_TARGET_EMBEDDED_MINI
124  #include <CoreFoundation/CFRunLoop.h>
125  CF_EXPORT void _CFMachPortInstallNotifyPort(CFRunLoopRef rl, CFStringRef mode);
126  #endif
127  
128  
129  CF_PRIVATE CFIndex __CFActiveProcessorCount();
130  
131  #ifndef CLANG_ANALYZER_NORETURN
132  #if __has_feature(attribute_analyzer_noreturn)
133  #define CLANG_ANALYZER_NORETURN __attribute__((analyzer_noreturn))
134  #else
135  #define CLANG_ANALYZER_NORETURN
136  #endif
137  #endif
138  
139  #if DEPLOYMENT_TARGET_WINDOWS
140  #define __builtin_unreachable() do { } while (0)
141  #endif
142  
143  
144  #if defined(__GNUC__)
145      #if defined(__i386__) || defined(__x86_64__)
146          #define HALT do {asm __volatile__("int3"); kill(getpid(), 9); __builtin_unreachable(); } while (0)
147      #else
148          #define HALT do {__builtin_debugtrap(); kill(getpid(), 9); __builtin_unreachable(); } while (0)
149      #endif
150  #elif defined(_MSC_VER)
151      #define HALT do { DebugBreak(); abort(); __builtin_unreachable(); } while (0)
152  #else
153      #error Compiler not supported
154  #endif
155  
156  
157  #if defined(DEBUG)
158      #define __CFAssert(cond, prio, desc, a1, a2, a3, a4, a5)	\
159  	do {			\
160  	    if (!(cond)) {	\
161  		CFLog(prio, CFSTR(desc), a1, a2, a3, a4, a5); \
162  		/* HALT; */		\
163  	    }			\
164  	} while (0)
165  #else
166      #define __CFAssert(cond, prio, desc, a1, a2, a3, a4, a5)	\
167  	do {} while (0)
168  #endif
169  
170  #define CFAssert(condition, priority, description)			\
171      __CFAssert((condition), (priority), description, 0, 0, 0, 0, 0)
172  #define CFAssert1(condition, priority, description, a1)			\
173      __CFAssert((condition), (priority), description, (a1), 0, 0, 0, 0)
174  #define CFAssert2(condition, priority, description, a1, a2)		\
175      __CFAssert((condition), (priority), description, (a1), (a2), 0, 0, 0)
176  #define CFAssert3(condition, priority, description, a1, a2, a3)		\
177      __CFAssert((condition), (priority), description, (a1), (a2), (a3), 0, 0)
178  #define CFAssert4(condition, priority, description, a1, a2, a3, a4)	\
179      __CFAssert((condition), (priority), description, (a1), (a2), (a3), (a4), 0)
180  
181  #define __kCFLogAssertion	3
182  
183  // This CF-only log function uses no CF functionality, so it may be called anywhere within CF - including thread teardown or prior to full CF setup
184  CF_PRIVATE void _CFLogSimple(int32_t lev, char *format, ...);
185  
186  #if defined(DEBUG)
187  extern void __CFGenericValidateType_(CFTypeRef cf, CFTypeID type, const char *func);
188  #define __CFGenericValidateType(cf, type) __CFGenericValidateType_(cf, type, __PRETTY_FUNCTION__)
189  #else
190  #define __CFGenericValidateType(cf, type) ((void)0)
191  #endif
192  
193  #define CF_INFO_BITS (!!(__CF_BIG_ENDIAN__) * 3)
194  #define CF_RC_BITS (!!(__CF_LITTLE_ENDIAN__) * 3)
195  
196  /* Bit manipulation macros */
197  /* Bits are numbered from 31 on left to 0 on right */
198  /* May or may not work if you use them on bitfields in types other than UInt32, bitfields the full width of a UInt32, or anything else for which they were not designed. */
199  /* In the following, N1 and N2 specify an inclusive range N2..N1 with N1 >= N2 */
200  #define __CFBitfieldMask(N1, N2)	((((UInt32)~0UL) << (31UL - (N1) + (N2))) >> (31UL - N1))
201  #define __CFBitfieldGetValue(V, N1, N2)	(((V) & __CFBitfieldMask(N1, N2)) >> (N2))
202  #define __CFBitfieldSetValue(V, N1, N2, X)	((V) = ((V) & ~__CFBitfieldMask(N1, N2)) | (((X) << (N2)) & __CFBitfieldMask(N1, N2)))
203  #define __CFBitfieldMaxValue(N1, N2)	__CFBitfieldGetValue(0xFFFFFFFFUL, (N1), (N2))
204  
205  #define __CFBitIsSet(V, N)  (((V) & (1UL << (N))) != 0)
206  #define __CFBitSet(V, N)  ((V) |= (1UL << (N)))
207  #define __CFBitClear(V, N)  ((V) &= ~(1UL << (N)))
208  
209  // Foundation uses 20-40
210  // Foundation knows about the value of __CFTSDKeyAutoreleaseData1
211  enum {
212  	__CFTSDKeyAllocator = 1,
213  	__CFTSDKeyIsInCFLog = 2,
214  	__CFTSDKeyIsInNSCache = 3,
215  	__CFTSDKeyIsInGCDMainQ = 4,
216  	__CFTSDKeyICUConverter = 7,
217  	__CFTSDKeyCollatorLocale = 8,
218  	__CFTSDKeyCollatorUCollator = 9,
219  	__CFTSDKeyRunLoop = 10,
220  	__CFTSDKeyRunLoopCntr = 11,
221          __CFTSDKeyMachMessageBoost = 12, // valid only in the context of a CFMachPort callout
222          __CFTSDKeyMachMessageHasVoucher = 13,
223  	// autorelease pool stuff must be higher than run loop constants
224  	__CFTSDKeyAutoreleaseData2 = 61,
225  	__CFTSDKeyAutoreleaseData1 = 62,
226  	__CFTSDKeyExceptionData = 63,
227  };
228  
229  #define __kCFAllocatorTypeID_CONST	2
230  
231  CF_INLINE CFAllocatorRef __CFGetDefaultAllocator(void) {
232      CFAllocatorRef allocator = (CFAllocatorRef)_CFGetTSD(__CFTSDKeyAllocator);
233      if (NULL == allocator) {
234  	allocator = kCFAllocatorSystemDefault;
235      }
236      return allocator;
237  }
238  
239  
240  #if !defined(LLONG_MAX)
241      #if defined(_I64_MAX)
242  	#define LLONG_MAX	_I64_MAX
243      #else
244  	#warning Arbitrarily defining LLONG_MAX
245         #define LLONG_MAX	(int64_t)9223372036854775807
246      #endif
247  #endif /* !defined(LLONG_MAX) */
248  
249  #if !defined(LLONG_MIN)
250      #if defined(_I64_MIN)
251  	#define LLONG_MIN	_I64_MIN
252      #else
253  	#warning Arbitrarily defining LLONG_MIN
254  	#define LLONG_MIN	(-LLONG_MAX - (int64_t)1)
255      #endif
256  #endif /* !defined(LLONG_MIN) */
257  
258  #if defined(__GNUC__) && !defined(__STRICT_ANSI__)
259      #define __CFMin(A,B) ({__typeof__(A) __a = (A); __typeof__(B) __b = (B); __a < __b ? __a : __b; })
260      #define __CFMax(A,B) ({__typeof__(A) __a = (A); __typeof__(B) __b = (B); __a < __b ? __b : __a; })
261  #else /* __GNUC__ */
262      #define __CFMin(A,B) ((A) < (B) ? (A) : (B))
263      #define __CFMax(A,B) ((A) > (B) ? (A) : (B))
264  #endif /* __GNUC__ */
265  
266  /* Secret CFAllocator hint bits */
267  #define __kCFAllocatorTempMemory	0x2
268  #define __kCFAllocatorNoPointers	0x10
269  #define __kCFAllocatorDoNotRecordEvent	0x100
270  #define __kCFAllocatorGCScannedMemory 0x200     /* GC:  memory should be scanned. */
271  #define __kCFAllocatorGCObjectMemory 0x400      /* GC:  memory needs to be finalized. */
272  
273  CF_INLINE auto_memory_type_t CF_GET_GC_MEMORY_TYPE(CFOptionFlags flags) {
274  	auto_memory_type_t type = (flags & __kCFAllocatorGCScannedMemory ? 0 : AUTO_UNSCANNED) | (flags & __kCFAllocatorGCObjectMemory ? AUTO_OBJECT : 0);
275      return type;
276  }
277  
278  CF_INLINE void __CFAssignWithWriteBarrier(void **location, void *value) {
279      if (kCFUseCollectableAllocator) {
280          objc_assign_strongCast((id)value, (id *)location);
281      } else {
282          *location = value;
283      }
284  }
285  
286  // Zero-retain count CFAllocator functions, i.e. memory that will be collected, no dealloc necessary
287  CF_EXPORT void *_CFAllocatorAllocateGC(CFAllocatorRef allocator, CFIndex size, CFOptionFlags hint);
288  CF_EXPORT void *_CFAllocatorReallocateGC(CFAllocatorRef allocator, void *ptr, CFIndex newsize, CFOptionFlags hint);
289  CF_EXPORT void _CFAllocatorDeallocateGC(CFAllocatorRef allocator, void *ptr);
290  
291  CF_EXPORT CFAllocatorRef _CFTemporaryMemoryAllocator(void);
292  
293  extern uint64_t __CFTimeIntervalToTSR(CFTimeInterval ti);
294  extern CFTimeInterval __CFTSRToTimeInterval(uint64_t tsr);
295  // use this instead of attempting to subtract mach_absolute_time() directly, because that can underflow and give an unexpected answer
296  CF_PRIVATE CFTimeInterval __CFTimeIntervalUntilTSR(uint64_t tsr);
297  CF_PRIVATE dispatch_time_t __CFTSRToDispatchTime(uint64_t tsr);
298  CF_PRIVATE uint64_t __CFTSRToNanoseconds(uint64_t tsr);
299  
300  extern CFStringRef __CFCopyFormattingDescription(CFTypeRef cf, CFDictionaryRef formatOptions);
301  
302  /* Enhanced string formatting support
303   */
304  CF_PRIVATE CFDictionaryRef _CFStringGetFormatSpecifierConfiguration(CFStringRef aFormatString);
305  CF_PRIVATE CFStringRef _CFStringCopyWithFomatStringConfiguration(CFStringRef aFormatString, CFDictionaryRef formatConfiguration);
306  CF_PRIVATE CFStringRef _CFCopyResolvedFormatStringWithConfiguration(CFTypeRef anObject, CFDictionaryRef aConfiguration, CFDictionaryRef formatOptions);
307  
308  /* result is long long or int, depending on doLonglong
309  */
310  extern Boolean __CFStringScanInteger(CFStringInlineBuffer *buf, CFTypeRef locale, SInt32 *indexPtr, Boolean doLonglong, void *result);
311  extern Boolean __CFStringScanDouble(CFStringInlineBuffer *buf, CFTypeRef locale, SInt32 *indexPtr, double *resultPtr); 
312  extern Boolean __CFStringScanHex(CFStringInlineBuffer *buf, SInt32 *indexPtr, unsigned *result);
313  
314  extern const char *__CFgetenv(const char *n);
315  
316  CF_PRIVATE Boolean __CFProcessIsRestricted();
317  
318  // This is really about the availability of C99. We don't have that on Windows, but we should everywhere else.
319  #if DEPLOYMENT_TARGET_WINDOWS
320  #define STACK_BUFFER_DECL(T, N, C) T *N = (T *)_alloca((C) * sizeof(T))
321  #else
322  #define STACK_BUFFER_DECL(T, N, C) T N[C]
323  #endif
324  
325  
326  CF_EXPORT void * __CFConstantStringClassReferencePtr;
327  
328  #ifdef __CONSTANT_CFSTRINGS__
329  
330  #define CONST_STRING_DECL(S, V) const CFStringRef S = (const CFStringRef)__builtin___CFStringMakeConstantString(V);
331  #define PE_CONST_STRING_DECL(S, V) CF_PRIVATE const CFStringRef S = (const CFStringRef)__builtin___CFStringMakeConstantString(V);
332  
333  #else
334  
335  struct CF_CONST_STRING {
336      CFRuntimeBase _base;
337      uint8_t *_ptr;
338      uint32_t _length;
339  };
340  
341  CF_EXPORT int __CFConstantStringClassReference[];
342  
343  /* CFNetwork also has a copy of the CONST_STRING_DECL macro (for use on platforms without constant string support in cc); please warn cfnetwork-core@group.apple.com of any necessary changes to this macro. -- REW, 1/28/2002 */
344  
345  #if __CF_BIG_ENDIAN__
346  
347  #define CONST_STRING_DECL(S, V)			\
348  static struct CF_CONST_STRING __ ## S ## __ = {{(uintptr_t)&__CFConstantStringClassReference, {0x00, 0x00, 0x07, 0xc8}}, (uint8_t *)V, sizeof(V) - 1}; \
349  const CFStringRef S = (CFStringRef) & __ ## S ## __;
350  #define PE_CONST_STRING_DECL(S, V)			\
351  static struct CF_CONST_STRING __ ## S ## __ = {{(uintptr_t)&__CFConstantStringClassReference, {0x00, 0x00, 0x07, 0xc8}}, (uint8_t *)V, sizeof(V) - 1}; \
352  CF_PRIVATE const CFStringRef S = (CFStringRef) & __ ## S ## __;
353  
354  #elif __CF_LITTLE_ENDIAN__
355  
356  #define CONST_STRING_DECL(S, V)			\
357  static struct CF_CONST_STRING __ ## S ## __ = {{(uintptr_t)&__CFConstantStringClassReference, {0xc8, 0x07, 0x00, 0x00}}, (uint8_t *)(V), sizeof(V) - 1}; \
358  const CFStringRef S = (CFStringRef) & __ ## S ## __;
359  #define PE_CONST_STRING_DECL(S, V)			\
360  static struct CF_CONST_STRING __ ## S ## __ = {{(uintptr_t)&__CFConstantStringClassReference, {0xc8, 0x07, 0x00, 0x00}}, (uint8_t *)(V), sizeof(V) - 1}; \
361  CF_PRIVATE const CFStringRef S = (CFStringRef) & __ ## S ## __;
362  
363  #endif
364  
365  #endif // __CONSTANT_CFSTRINGS__
366  
367  CF_EXPORT bool __CFOASafe;
368  CF_EXPORT void __CFSetLastAllocationEventName(void *ptr, const char *classname);
369  
370  
371  
372  /* Comparators are passed the address of the values; this is somewhat different than CFComparatorFunction is used in public API usually. */
373  CF_EXPORT CFIndex	CFBSearch(const void *element, CFIndex elementSize, const void *list, CFIndex count, CFComparatorFunction comparator, void *context);
374  
375  CF_EXPORT CFHashCode	CFHashBytes(UInt8 *bytes, CFIndex length);
376  
377  CF_EXPORT CFStringEncoding CFStringFileSystemEncoding(void);
378  
379  CF_PRIVATE CFStringRef __CFStringCreateImmutableFunnel3(CFAllocatorRef alloc, const void *bytes, CFIndex numBytes, CFStringEncoding encoding, Boolean possiblyExternalFormat, Boolean tryToReduceUnicode, Boolean hasLengthByte, Boolean hasNullByte, Boolean noCopy, CFAllocatorRef contentsDeallocator, UInt32 converterFlags);
380  
381  extern const void *__CFStringCollectionCopy(CFAllocatorRef allocator, const void *ptr);
382  extern const void *__CFTypeCollectionRetain(CFAllocatorRef allocator, const void *ptr);
383  extern void __CFTypeCollectionRelease(CFAllocatorRef allocator, const void *ptr);
384  
385  extern CFTypeRef CFMakeUncollectable(CFTypeRef cf);
386  
387  CF_PRIVATE void _CFRaiseMemoryException(CFStringRef reason);
388  
389  extern CF_PRIVATE Boolean __CFProphylacticAutofsAccess;
390  
391  
392  #if DEPLOYMENT_TARGET_MACOSX
393  
394  typedef pthread_mutex_t CFLock_t;
395  
396  #define CFLockInit ((pthread_mutex_t)PTHREAD_ERRORCHECK_MUTEX_INITIALIZER)
397  #define CF_LOCK_INIT_FOR_STRUCTS(X) (X = CFLockInit)
398  
399  #define __CFLock(LP) ({ \
400      (void)pthread_mutex_lock(LP); })
401  
402  #define __CFUnlock(LP) ({ \
403      (void)pthread_mutex_unlock(LP); })
404  
405  #define __CFLockTry(LP) ({ \
406      pthread_mutex_trylock(LP) == 0; })
407  
408  #elif DEPLOYMENT_TARGET_EMBEDDED || DEPLOYMENT_TARGET_EMBEDDED_MINI
409  
410  typedef pthread_mutex_t CFLock_t;
411  
412  #define CFLockInit ((pthread_mutex_t)PTHREAD_ERRORCHECK_MUTEX_INITIALIZER)
413  #define CF_LOCK_INIT_FOR_STRUCTS(X) (X = CFLockInit)
414  
415  #define __CFLock(LP) ({ \
416      (void)pthread_mutex_lock(LP); })
417  
418  #define __CFUnlock(LP) ({ \
419      (void)pthread_mutex_unlock(LP); })
420  
421  #define __CFLockTry(LP) ({ \
422      pthread_mutex_trylock(LP) == 0; })
423  
424  #elif DEPLOYMENT_TARGET_WINDOWS
425  
426  typedef int32_t CFLock_t;
427  #define CFLockInit 0
428  #define CF_LOCK_INIT_FOR_STRUCTS(X) (X = CFLockInit)
429  
430  CF_INLINE void __CFLock(volatile CFLock_t *lock) {
431      while (InterlockedCompareExchange((LONG volatile *)lock, ~0, 0) != 0) {
432  	Sleep(0);
433      }
434  }
435  
436  CF_INLINE void __CFUnlock(volatile CFLock_t *lock) {
437      MemoryBarrier();
438      *lock = 0;
439  }
440  
441  CF_INLINE Boolean __CFLockTry(volatile CFLock_t *lock) {
442      return (InterlockedCompareExchange((LONG volatile *)lock, ~0, 0) == 0);
443  }
444  
445  #elif DEPLOYMENT_TARGET_LINUX
446  
447  typedef int32_t CFLock_t;
448  #define CFLockInit 0
449  #define CF_LOCK_INIT_FOR_STRUCTS(X) (X = CFLockInit)
450  
451  CF_INLINE void __CFLock(volatile CFLock_t *lock) {
452      while (__sync_val_compare_and_swap(lock, 0, ~0) != 0) {
453  	sleep(0);
454      }
455  }
456  
457  CF_INLINE void __CFUnlock(volatile CFLock_t *lock) {
458      __sync_synchronize();
459      *lock = 0;
460  }
461  
462  CF_INLINE Boolean __CFLockTry(volatile CFLock_t *lock) {
463      return (__sync_val_compare_and_swap(lock, 0, ~0) == 0);
464  }
465  
466  #else
467  
468  #warning CF locks not defined for this platform -- CF is not thread-safe
469  #define __CFLock(A)	do {} while (0)
470  #define __CFUnlock(A)	do {} while (0)
471  
472  #endif
473  
474  
475  #if DEPLOYMENT_TARGET_MACOSX || DEPLOYMENT_TARGET_EMBEDDED || DEPLOYMENT_TARGET_EMBEDDED_MINI
476  extern uint8_t __CF120293;
477  extern uint8_t __CF120290;
478  extern void __THE_PROCESS_HAS_FORKED_AND_YOU_CANNOT_USE_THIS_COREFOUNDATION_FUNCTIONALITY___YOU_MUST_EXEC__(void);
479  #define CHECK_FOR_FORK() do { __CF120290 = true; if (__CF120293) __THE_PROCESS_HAS_FORKED_AND_YOU_CANNOT_USE_THIS_COREFOUNDATION_FUNCTIONALITY___YOU_MUST_EXEC__(); } while (0)
480  #define CHECK_FOR_FORK_RET(...) do { CHECK_FOR_FORK(); if (__CF120293) return __VA_ARGS__; } while (0)
481  #define HAS_FORKED() (__CF120293)
482  #endif
483  
484  #if !defined(CHECK_FOR_FORK)
485  #define CHECK_FOR_FORK() do { } while (0)
486  #endif
487  
488  #if !defined(CHECK_FOR_FORK_RET)
489  #define CHECK_FOR_FORK_RET(...) do { } while (0)
490  #endif
491  
492  #if !defined(HAS_FORKED)
493  #define HAS_FORKED() 0
494  #endif
495  
496  #include <errno.h>
497  
498  #define thread_errno() errno
499  #define thread_set_errno(V) do {errno = (V);} while (0)
500  
501  extern void *__CFStartSimpleThread(void *func, void *arg);
502  
503  /* ==================== Simple file access ==================== */
504  /* For dealing with abstract types.  MF:!!! These ought to be somewhere else and public. */
505      
506  CF_EXPORT CFStringRef _CFCopyExtensionForAbstractType(CFStringRef abstractType);
507  
508  /* ==================== Simple file access ==================== */
509  /* These functions all act on a c-strings which must be in the file system encoding. */
510      
511  CF_PRIVATE Boolean _CFCreateDirectory(const char *path);
512  CF_PRIVATE Boolean _CFRemoveDirectory(const char *path);
513  CF_PRIVATE Boolean _CFDeleteFile(const char *path);
514  
515  CF_PRIVATE Boolean _CFReadBytesFromFile(CFAllocatorRef alloc, CFURLRef url, void **bytes, CFIndex *length, CFIndex maxLength, int extraOpenFlags);
516      /* resulting bytes are allocated from alloc which MUST be non-NULL. */
517      /* maxLength of zero means the whole file.  Otherwise it sets a limit on the number of bytes read. */
518  
519  CF_EXPORT Boolean _CFWriteBytesToFile(CFURLRef url, const void *bytes, CFIndex length);
520  
521  CF_PRIVATE CFMutableArrayRef _CFCreateContentsOfDirectory(CFAllocatorRef alloc, char *dirPath, void *dirSpec, CFURLRef dirURL, CFStringRef matchingAbstractType);
522      /* On Mac OS 8/9, one of dirSpec, dirPath and dirURL must be non-NULL */
523      /* On all other platforms, one of path and dirURL must be non-NULL */
524      /* If both are present, they are assumed to be in-synch; that is, they both refer to the same directory.  */
525      /* alloc may be NULL */
526      /* return value is CFArray of CFURLs */
527  
528  CF_PRIVATE SInt32 _CFGetPathProperties(CFAllocatorRef alloc, char *path, Boolean *exists, SInt32 *posixMode, SInt64 *size, CFDateRef *modTime, SInt32 *ownerID, CFArrayRef *dirContents);
529      /* alloc may be NULL */
530      /* any of exists, posixMode, size, modTime, and dirContents can be NULL.  Usually it is not a good idea to pass NULL for exists, since interpretting the other values sometimes requires that you know whether the file existed or not.  Except for dirContents, it is pretty cheap to compute any of these things as loing as one of them must be computed. */
531  
532  CF_PRIVATE SInt32 _CFGetFileProperties(CFAllocatorRef alloc, CFURLRef pathURL, Boolean *exists, SInt32 *posixMode, SInt64 *size, CFDateRef *modTime, SInt32 *ownerID, CFArrayRef *dirContents);
533      /* alloc may be NULL */
534      /* any of exists, posixMode, size, modTime, and dirContents can be NULL.  Usually it is not a good idea to pass NULL for exists, since interpretting the other values sometimes requires that you know whether the file existed or not.  Except for dirContents, it is pretty cheap to compute any of these things as loing as one of them must be computed. */
535  
536  
537  /* ==================== Simple path manipulation ==================== */
538  
539  CF_EXPORT UniChar _CFGetSlash();
540  CF_PRIVATE CFStringRef _CFGetSlashStr();
541  CF_EXPORT Boolean _CFIsAbsolutePath(UniChar *unichars, CFIndex length);
542  CF_PRIVATE void _CFAppendTrailingPathSlash2(CFMutableStringRef path);
543  CF_PRIVATE void _CFAppendConditionalTrailingPathSlash2(CFMutableStringRef path);
544  CF_EXPORT Boolean _CFAppendPathComponent(UniChar *unichars, CFIndex *length, CFIndex maxLength, UniChar *component, CFIndex componentLength);
545  CF_PRIVATE void _CFAppendPathComponent2(CFMutableStringRef path, CFStringRef component);
546  CF_PRIVATE Boolean _CFAppendPathExtension2(CFMutableStringRef path, CFStringRef extension);
547  CF_EXPORT Boolean _CFAppendPathExtension(UniChar *unichars, CFIndex *length, CFIndex maxLength, UniChar *extension, CFIndex extensionLength);
548  CF_EXPORT Boolean _CFTransmutePathSlashes(UniChar *unichars, CFIndex *length, UniChar replSlash);
549  CF_PRIVATE CFStringRef _CFCreateLastPathComponent(CFAllocatorRef alloc, CFStringRef path, CFIndex *slashIndex);
550  CF_EXPORT CFIndex _CFStartOfLastPathComponent(UniChar *unichars, CFIndex length);
551  CF_PRIVATE CFIndex _CFStartOfLastPathComponent2(CFStringRef path);
552  CF_EXPORT CFIndex _CFLengthAfterDeletingLastPathComponent(UniChar *unichars, CFIndex length);
553  CF_PRIVATE CFIndex _CFLengthAfterDeletingPathExtension2(CFStringRef path);
554  CF_EXPORT CFIndex _CFStartOfPathExtension(UniChar *unichars, CFIndex length);
555  CF_PRIVATE CFIndex _CFStartOfPathExtension2(CFStringRef path);
556  CF_EXPORT CFIndex _CFLengthAfterDeletingPathExtension(UniChar *unichars, CFIndex length);
557  
558  #if __BLOCKS__
559  #if DEPLOYMENT_TARGET_WINDOWS
560  #define	DT_DIR		 4
561  #define	DT_REG		 8
562  #define DT_LNK          10
563  #endif
564  
565  // This function automatically skips '.' and '..', and '._' files
566  CF_PRIVATE void _CFIterateDirectory(CFStringRef directoryPath, Boolean (^fileHandler)(CFStringRef fileName, uint8_t fileType));
567  #endif
568  
569  #define __CFMaxRuntimeTypes	65535
570  #define __CFRuntimeClassTableSize 1024
571  
572  extern uintptr_t __CFRuntimeObjCClassTable[];
573  
574  extern void _CFRuntimeSetInstanceTypeIDAndIsa(CFTypeRef cf, CFTypeID newTypeID);
575  
576  #ifdef DARLING
577  
578  #define CF_OBJC_FUNCDISPATCHV(typeID, ret, obj, ...) \
579  _Pragma("clang diagnostic push") \
580  _Pragma("clang diagnostic ignored \"-Wreturn-type\"") \
581  _Pragma("clang diagnostic ignored \"-Wobjc-method-access\"") \
582  _Pragma("clang diagnostic ignored \"-Wincompatible-pointer-types\"") \
583  if (CF_IS_OBJC(typeID, obj)) { \
584      return (ret)[(id)obj __VA_ARGS__]; \
585  } \
586  _Pragma("clang diagnostic pop")
587  
588  #define CF_OBJC_CALLV(obj, ...) [obj __VA_ARGS__]
589  
590  #include <objc/objc-internal.h>
591  
592  CF_INLINE Boolean _CFIsCFObject(const void *obj) {
593  #ifdef OBJC_HAVE_TAGGED_POINTERS
594  	if (_objc_taggedPointersEnabled() && _objc_isTaggedPointer(obj)) return 0;
595  #endif
596  	uintptr_t isa = ((CFRuntimeBase *)obj)->_cfisa;
597  	if (isa == 0) return 1;
598  	// at this point, it's definetely a valid objc object,
599  	// but we'd still like to return 1 for __NSCF types
600  	Class cls = object_getClass((id)obj);
601  	if (cls == __CFConstantStringClassReferencePtr) return 1;
602  
603  	uint32_t cfinfo = *(uint32_t *)&(((CFRuntimeBase *)obj)->_cfinfo);
604  	CFTypeID typeID = (cfinfo >> 8) & 0x03FF;
605  
606  	return typeID < __CFRuntimeClassTableSize && cls == (Class)__CFRuntimeObjCClassTable[typeID];
607  }
608  
609  #define CF_IS_OBJC(typeID, obj) (!_CFIsCFObject(obj))
610  
611  CF_INLINE uintptr_t __CFISAForTypeID(CFTypeID typeID) {
612      return (typeID < __CFRuntimeClassTableSize) ? __CFRuntimeObjCClassTable[typeID] : 0;
613  }
614  
615  #else
616  #define CF_OBJC_FUNCDISPATCHV(typeID, obj, ...) do { } while (0)
617  #define CF_OBJC_CALLV(obj, ...) (0)
618  #define CF_IS_OBJC(typeID, obj) (0)
619  #define __CFISAForTypeID(t) (0)
620  #endif
621  
622  /* See comments in CFBase.c
623  */
624  #define FAULT_CALLBACK(V)
625  #define INVOKE_CALLBACK1(P, A) (P)(A)
626  #define INVOKE_CALLBACK2(P, A, B) (P)(A, B)
627  #define INVOKE_CALLBACK3(P, A, B, C) (P)(A, B, C)
628  #define INVOKE_CALLBACK4(P, A, B, C, D) (P)(A, B, C, D)
629  #define INVOKE_CALLBACK5(P, A, B, C, D, E) (P)(A, B, C, D, E)
630  #define UNFAULT_CALLBACK(V) do { } while (0)
631  
632  /* For the support of functionality which needs CarbonCore or other frameworks */
633  // These macros define an upcall or weak "symbol-lookup" wrapper function.
634  // The parameters are:
635  //   R : the return type of the function
636  //   N : the name of the function (in the other library)
637  //   P : the parenthesized parameter list of the function
638  //   A : the parenthesized actual argument list to be passed
639  //  FAILACTION: (only for the _FAIL macros) additional code to be
640  //       run when the function cannot be found.
641  //  opt: a fifth optional argument can be passed in which is the
642  //       return value of the wrapper when the function cannot be
643  //       found; should be of type R, & can be a function call
644  // The name of the resulting wrapper function is:
645  //    __CFCarbonCore_N (where N is the second parameter)
646  //    __CFNetwork_N (where N is the second parameter)
647  //
648  // Example:
649  //   DEFINE_WEAK_CARBONCORE_FUNC(void, DisposeHandle, (Handle h), (h))
650  //
651  
652  #if DEPLOYMENT_TARGET_MACOSX || DEPLOYMENT_TARGET_EMBEDDED
653  
654  extern void *__CFLookupCFNetworkFunction(const char *name);
655  
656  #define DEFINE_WEAK_CFNETWORK_FUNC(R, N, P, A, ...)             \
657      typedef R (*dyfuncptr)P;                                    \
658      static dyfuncptr dyfunc = (dyfuncptr)(~(uintptr_t)0);	\
659      if ((dyfuncptr)(~(uintptr_t)0) == dyfunc) {			\
660          dyfunc = (dyfuncptr)__CFLookupCFNetworkFunction(#N); }	\
661      if (dyfunc) { return dyfunc A ; }				\
662      return __VA_ARGS__ ;					\
663  }
664  
665  #define DEFINE_WEAK_CFNETWORK_FUNC_FAIL(R, N, P, A, FAILACTION, ...)	\
666  static R __CFNetwork_ ## N P {                                  \
667      typedef R (*dyfuncptr)P;                                    \
668      static dyfuncptr dyfunc = (dyfuncptr)(~(uintptr_t)0);       \
669      if ((dyfuncptr)(~(uintptr_t)0) == dyfunc) {                 \
670          dyfunc = (dyfuncptr)__CFLookupCFNetworkFunction(#N); }  \
671      if (dyfunc) { return dyfunc A ; }                           \
672      FAILACTION ;                                                \
673      return __VA_ARGS__ ;                                        \
674  }
675  
676  #else
677  #define DEFINE_WEAK_CFNETWORK_FUNC(R, N, P, A, ...)
678  #define DEFINE_WEAK_CFNETWORK_FUNC_FAIL(R, N, P, A, ...)
679  #endif
680  
681  #define DEFINE_WEAK_CARBONCORE_FUNC(R, N, P, A, ...)
682  
683  #if DEPLOYMENT_TARGET_MACOSX || DEPLOYMENT_TARGET_EMBEDDED
684  
685  extern void *__CFLookupCoreServicesInternalFunction(const char *name);
686  
687  #define DEFINE_WEAK_CORESERVICESINTERNAL_FUNC(R, N, P, A, ...)              \
688      static R __CFCoreServicesInternal_ ## N P {                             \
689          typedef R (*dyfuncptr)P;                                            \
690          static dyfuncptr dyfunc = (dyfuncptr)(~(uintptr_t)0);               \
691          if ((dyfuncptr)(~(uintptr_t)0) == dyfunc) {                         \
692              dyfunc = (dyfuncptr)__CFLookupCoreServicesInternalFunction(#N); \
693          }                                                                   \
694          if (dyfunc) {                                                       \
695              return dyfunc A ;                                               \
696          }                                                                   \
697          return __VA_ARGS__ ;                                                \
698      }
699  
700  #else
701  #define DEFINE_WEAK_CORESERVICESINTERNAL_FUNC(R, N, P, A, ...)
702  #endif
703  
704  CF_PRIVATE CFComparisonResult _CFCompareStringsWithLocale(CFStringInlineBuffer *str1, CFRange str1Range, CFStringInlineBuffer *str2, CFRange str2Range, CFOptionFlags options, const void *compareLocale);
705  
706  
707  CF_PRIVATE CFArrayRef _CFBundleCopyUserLanguages();
708  
709  
710  // This should only be used in CF types, not toll-free bridged objects!
711  // It should not be used with CFAllocator arguments!
712  // Use CFGetAllocator() in the general case, and this inline function in a few limited (but often called) situations.
713  CF_INLINE CFAllocatorRef __CFGetAllocator(CFTypeRef cf) {	// !!! Use with CF types only, and NOT WITH CFAllocator!
714  #if OBJC_HAVE_TAGGED_POINTERS
715      if (_objc_isTaggedPointer(cf)) {
716          return kCFAllocatorSystemDefault;
717      }
718  #endif
719      if (__builtin_expect(__CFBitfieldGetValue(((const CFRuntimeBase *)cf)->_cfinfo[CF_INFO_BITS], 7, 7), 1)) {
720  	return kCFAllocatorSystemDefault;
721      }
722      return *(CFAllocatorRef *)((char *)cf - sizeof(CFAllocatorRef));
723  }
724  
725  /* !!! Avoid #importing objc.h; e.g. converting this to a .m file */
726  struct __objcFastEnumerationStateEquivalent {
727      unsigned long state;
728      unsigned long *itemsPtr;
729      unsigned long *mutationsPtr;
730      unsigned long extra[5];
731  };
732  
733  #if 0
734  #pragma mark -
735  #pragma mark Windows Compatability
736  #endif
737  
738  // Need to use the _O_BINARY flag on Windows to get the correct behavior
739  #if DEPLOYMENT_TARGET_WINDOWS
740  #define CF_OPENFLGS	(_O_BINARY|_O_NOINHERIT)
741  #else
742  #define CF_OPENFLGS	(0)
743  #endif
744  
745  #if DEPLOYMENT_TARGET_WINDOWS
746  
747  // These are replacements for pthread calls on Windows
748  CF_EXPORT int _NS_pthread_main_np();
749  CF_EXPORT int _NS_pthread_setspecific(pthread_key_t key, const void *val);
750  CF_EXPORT void* _NS_pthread_getspecific(pthread_key_t key);
751  CF_EXPORT int _NS_pthread_key_init_np(int key, void (*destructor)(void *));
752  CF_EXPORT void _NS_pthread_setname_np(const char *name);
753  
754  // map use of pthread_set/getspecific to internal API
755  #define pthread_setspecific _NS_pthread_setspecific
756  #define pthread_getspecific _NS_pthread_getspecific
757  #define pthread_key_init_np _NS_pthread_key_init_np
758  #define pthread_main_np _NS_pthread_main_np
759  #define pthread_setname_np _NS_pthread_setname_np
760  #endif
761  
762  #if DEPLOYMENT_TARGET_WINDOWS
763  // replacement for DISPATCH_QUEUE_OVERCOMMIT until we get a bug fix in dispatch on Windows
764  // <rdar://problem/7923891> dispatch on Windows: Need queue_private.h
765  #define DISPATCH_QUEUE_OVERCOMMIT 2
766  #endif
767  
768  #if DEPLOYMENT_TARGET_WINDOWS
769  CF_PRIVATE const wchar_t *_CFDLLPath(void);
770  #endif
771  
772  /* Buffer size for file pathname */
773  #if DEPLOYMENT_TARGET_WINDOWS
774  #define CFMaxPathSize ((CFIndex)262)
775  #define CFMaxPathLength ((CFIndex)260)
776  #define PATH_SEP '\\'
777  #define PATH_SEP_STR CFSTR("\\")
778  #define PATH_MAX MAX_PATH
779  #else
780  #define CFMaxPathSize ((CFIndex)1026)
781  #define CFMaxPathLength ((CFIndex)1024)
782  #define PATH_SEP '/'
783  #define PATH_SEP_STR CFSTR("/")
784  #endif
785  
786  CF_INLINE const char *CFPathRelativeToAppleFrameworksRoot(const char *path, Boolean *allocated) {
787      if (path) {
788          const char *platformRoot = __CFgetenv("APPLE_FRAMEWORKS_ROOT");
789          if (platformRoot) {
790              char *newPath = NULL;
791              asprintf(&newPath, "%s%s", platformRoot, path);
792              if (allocated && newPath) {
793                  *allocated = true;
794              }
795              return newPath;
796          }
797      }
798      if (allocated) {
799          *allocated = false;
800      }
801      return path;
802  }
803  
804  #include <dispatch/dispatch.h>
805  #include <dispatch/private.h>
806  
807  #if (DEPLOYMENT_TARGET_MACOSX || DEPLOYMENT_TARGET_EMBEDDED)
808  
809  // Returns a generic dispatch queue for when you want to just throw some work
810  // into the concurrent pile to execute, and don't care about specifics except
811  // to match the QOS of the main thread.
812  CF_INLINE dispatch_queue_t __CFDispatchQueueGetGenericMatchingMain(void) {
813      return dispatch_get_global_queue(qos_class_main(), DISPATCH_QUEUE_OVERCOMMIT);
814  }
815  
816  // Returns a generic dispatch queue for when you want to just throw some work
817  // into the concurrent pile to execute, and don't care about specifics except
818  // to match the QOS of the current thread.
819  CF_INLINE dispatch_queue_t __CFDispatchQueueGetGenericMatchingCurrent(void) {
820      return dispatch_get_global_queue(qos_class_self(), 0); // DISPATCH_QUEUE_OVERCOMMIT left out intentionally at this point
821  }
822  
823  // Returns a generic dispatch queue for when you want to just throw some work
824  // into the concurrent pile to execute, and don't care about specifics except
825  // that it should be in background QOS.
826  CF_INLINE dispatch_queue_t __CFDispatchQueueGetGenericBackground(void) {
827      // Don't ACTUALLY use BACKGROUND, because of unknowable and unfavorable interactions like (<rdar://problem/16319229>)
828      return dispatch_get_global_queue(QOS_CLASS_UTILITY, DISPATCH_QUEUE_OVERCOMMIT);
829  }
830  
831  #else
832  
833  CF_INLINE dispatch_queue_t __CFDispatchQueueGetGenericMatchingMain(void) {
834      return dispatch_get_global_queue(QOS_CLASS_USER_INTERACTIVE, DISPATCH_QUEUE_OVERCOMMIT);
835  }
836  
837  CF_INLINE dispatch_queue_t __CFDispatchQueueGetGenericMatchingCurrent(void) {
838      return dispatch_get_global_queue(QOS_CLASS_USER_INTERACTIVE, 0); // DISPATCH_QUEUE_OVERCOMMIT left out intentionally at this point
839  }
840  
841  CF_INLINE dispatch_queue_t __CFDispatchQueueGetGenericBackground(void) {
842      return dispatch_get_global_queue(QOS_CLASS_UTILITY, DISPATCH_QUEUE_OVERCOMMIT);
843  }
844  
845  #endif
846  
847  CF_PRIVATE void __CFAttributedStringInitialize(void);
848  
849  CF_EXTERN_C_END
850  
851  #endif /* ! __COREFOUNDATION_CFINTERNAL__ */
852