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/*	ForFoundationOnly.h
25	Copyright (c) 1998-2013, Apple Inc. All rights reserved.
26*/
27
28#if !CF_BUILDING_CF && !NSBUILDINGFOUNDATION
29    #error The header file ForFoundationOnly.h is for the exclusive use of the
30    #error CoreFoundation and Foundation projects.  No other project should include it.
31#endif
32
33#if !defined(__COREFOUNDATION_FORFOUNDATIONONLY__)
34#define __COREFOUNDATION_FORFOUNDATIONONLY__ 1
35
36#include <CoreFoundation/CFBase.h>
37#include <CoreFoundation/CFString.h>
38#include <CoreFoundation/CFArray.h>
39#include <CoreFoundation/CFData.h>
40#include <CoreFoundation/CFDictionary.h>
41#include <CoreFoundation/CFSet.h>
42#include <CoreFoundation/CFPriv.h>
43#include <CoreFoundation/CFPropertyList.h>
44#include <CoreFoundation/CFError.h>
45#include <CoreFoundation/CFStringEncodingExt.h>
46#include <limits.h>
47
48// NOTE: miscellaneous declarations are at the end
49
50// ---- CFRuntime material ----------------------------------------
51
52CF_EXTERN_C_BEGIN
53
54#if DEPLOYMENT_TARGET_LINUX
55#include <malloc.h>
56#elif DEPLOYMENT_TARGET_MACOSX || DEPLOYMENT_TARGET_EMBEDDED || DEPLOYMENT_TARGET_EMBEDDED_MINI
57#include <malloc/malloc.h>
58#endif
59
60CF_EXTERN_C_END
61
62// ---- CFBundle material ----------------------------------------
63
64#if DEPLOYMENT_TARGET_MACOSX || DEPLOYMENT_TARGET_EMBEDDED || DEPLOYMENT_TARGET_EMBEDDED_MINI || DEPLOYMENT_TARGET_WINDOWS
65#include <CoreFoundation/CFBundlePriv.h>
66
67CF_EXTERN_C_BEGIN
68
69CF_EXPORT const CFStringRef _kCFBundleExecutablePathKey;
70CF_EXPORT const CFStringRef _kCFBundleInfoPlistURLKey;
71CF_EXPORT const CFStringRef _kCFBundleRawInfoPlistURLKey;
72CF_EXPORT const CFStringRef _kCFBundleNumericVersionKey;
73CF_EXPORT const CFStringRef _kCFBundleResourcesFileMappedKey;
74CF_EXPORT const CFStringRef _kCFBundleAllowMixedLocalizationsKey;
75CF_EXPORT const CFStringRef _kCFBundleInitialPathKey;
76CF_EXPORT const CFStringRef _kCFBundleResolvedPathKey;
77CF_EXPORT const CFStringRef _kCFBundlePrincipalClassKey;
78
79#if __BLOCKS__
80CF_EXPORT CFTypeRef _CFBundleCopyFindResources(CFBundleRef bundle, CFURLRef bundleURL, CFArrayRef languages, CFStringRef resourceName, CFStringRef resourceType, CFStringRef subPath, CFStringRef lproj, Boolean returnArray, Boolean localized, Boolean (^predicate)(CFStringRef filename, Boolean *stop));
81#endif
82
83CF_EXPORT CFArrayRef _CFBundleGetLanguageSearchList(CFBundleRef bundle);
84
85CF_EXPORT Boolean _CFBundleLoadExecutableAndReturnError(CFBundleRef bundle, Boolean forceGlobal, CFErrorRef *error);
86CF_EXPORT CFErrorRef _CFBundleCreateError(CFAllocatorRef allocator, CFBundleRef bundle, CFIndex code);
87
88CF_EXTERN_C_END
89
90#endif
91
92// ---- CFPreferences material ----------------------------------------
93
94#define DEBUG_PREFERENCES_MEMORY 0
95
96#if DEBUG_PREFERENCES_MEMORY
97#include "../Tests/CFCountingAllocator.h"
98#endif
99
100CF_EXTERN_C_BEGIN
101
102extern void _CFPreferencesPurgeDomainCache(void);
103
104typedef struct {
105    void *	(*createDomain)(CFAllocatorRef allocator, CFTypeRef context);
106    void	(*freeDomain)(CFAllocatorRef allocator, CFTypeRef context, void *domain);
107    CFTypeRef	(*fetchValue)(CFTypeRef context, void *domain, CFStringRef key); // Caller releases
108    void	(*writeValue)(CFTypeRef context, void *domain, CFStringRef key, CFTypeRef value);
109    Boolean	(*synchronize)(CFTypeRef context, void *domain);
110    void	(*getKeysAndValues)(CFAllocatorRef alloc, CFTypeRef context, void *domain, void **buf[], CFIndex *numKeyValuePairs);
111    CFDictionaryRef (*copyDomainDictionary)(CFTypeRef context, void *domain);
112    /* HACK - see comment on _CFPreferencesDomainSetIsWorldReadable(), below */
113    void	(*setIsWorldReadable)(CFTypeRef context, void *domain, Boolean isWorldReadable);
114} _CFPreferencesDomainCallBacks;
115
116CF_EXPORT CFAllocatorRef __CFPreferencesAllocator(void);
117CF_EXPORT  const _CFPreferencesDomainCallBacks __kCFVolatileDomainCallBacks;
118CF_EXPORT const _CFPreferencesDomainCallBacks __kCFXMLPropertyListDomainCallBacks;
119
120typedef struct __CFPreferencesDomain * CFPreferencesDomainRef;
121
122CF_EXPORT CFPreferencesDomainRef _CFPreferencesDomainCreate(CFTypeRef context, const _CFPreferencesDomainCallBacks *callBacks);
123CF_EXPORT CFPreferencesDomainRef _CFPreferencesStandardDomain(CFStringRef domainName, CFStringRef userName, CFStringRef hostName);
124
125CF_EXPORT CFTypeRef _CFPreferencesDomainCreateValueForKey(CFPreferencesDomainRef domain, CFStringRef key);
126CF_EXPORT void _CFPreferencesDomainSet(CFPreferencesDomainRef domain, CFStringRef key, CFTypeRef value);
127CF_EXPORT Boolean _CFPreferencesDomainSynchronize(CFPreferencesDomainRef domain);
128
129CF_EXPORT CFArrayRef _CFPreferencesCreateDomainList(CFStringRef userName, CFStringRef hostName);
130CF_EXPORT Boolean _CFSynchronizeDomainCache(void);
131
132CF_EXPORT void _CFPreferencesDomainSetDictionary(CFPreferencesDomainRef domain, CFDictionaryRef dict);
133CF_EXPORT CFDictionaryRef _CFPreferencesDomainDeepCopyDictionary(CFPreferencesDomainRef domain);
134CF_EXPORT Boolean _CFPreferencesDomainExists(CFStringRef domainName, CFStringRef userName, CFStringRef hostName);
135
136/* HACK - this is to work around the fact that individual domains lose the information about their user/host/app triplet at creation time.  We should find a better way to propogate this information.  REW, 1/13/00 */
137CF_EXPORT void _CFPreferencesDomainSetIsWorldReadable(CFPreferencesDomainRef domain, Boolean isWorldReadable);
138
139typedef struct {
140    CFMutableArrayRef _search;  // the search list; an array of _CFPreferencesDomains
141    CFMutableDictionaryRef _dictRep; // Mutable; a collapsed view of the search list, expressed as a single dictionary
142    CFStringRef _appName;
143} _CFApplicationPreferences;
144
145CF_EXPORT _CFApplicationPreferences *_CFStandardApplicationPreferences(CFStringRef appName);
146CF_EXPORT _CFApplicationPreferences *_CFApplicationPreferencesCreateWithUser(CFStringRef userName, CFStringRef appName);
147CF_EXPORT void _CFDeallocateApplicationPreferences(_CFApplicationPreferences *self);
148CF_EXPORT CFTypeRef _CFApplicationPreferencesCreateValueForKey(_CFApplicationPreferences *prefs, CFStringRef key);
149CF_EXPORT void _CFApplicationPreferencesSet(_CFApplicationPreferences *self, CFStringRef defaultName, CFTypeRef value);
150CF_EXPORT void _CFApplicationPreferencesRemove(_CFApplicationPreferences *self, CFStringRef defaultName);
151CF_EXPORT Boolean _CFApplicationPreferencesSynchronize(_CFApplicationPreferences *self);
152CF_EXPORT void _CFApplicationPreferencesUpdate(_CFApplicationPreferences *self); // same as updateDictRep
153CF_EXPORT CFDictionaryRef _CFApplicationPreferencesCopyRepresentation3(_CFApplicationPreferences *self, CFDictionaryRef hint, CFDictionaryRef insertion, CFPreferencesDomainRef afterDomain);
154CF_EXPORT CFDictionaryRef _CFApplicationPreferencesCopyRepresentationWithHint(_CFApplicationPreferences *self, CFDictionaryRef hint); // same as dictRep
155CF_EXPORT void _CFApplicationPreferencesSetStandardSearchList(_CFApplicationPreferences *appPreferences);
156CF_EXPORT void _CFApplicationPreferencesSetCacheForApp(_CFApplicationPreferences *appPrefs, CFStringRef appName);
157CF_EXPORT void _CFApplicationPreferencesAddSuitePreferences(_CFApplicationPreferences *appPrefs, CFStringRef suiteName);
158CF_EXPORT void _CFApplicationPreferencesRemoveSuitePreferences(_CFApplicationPreferences *appPrefs, CFStringRef suiteName);
159
160CF_EXPORT void _CFApplicationPreferencesAddDomain(_CFApplicationPreferences *self, CFPreferencesDomainRef domain, Boolean addAtTop);
161CF_EXPORT Boolean _CFApplicationPreferencesContainsDomain(_CFApplicationPreferences *self, CFPreferencesDomainRef domain);
162CF_EXPORT void _CFApplicationPreferencesRemoveDomain(_CFApplicationPreferences *self, CFPreferencesDomainRef domain);
163
164CF_EXPORT CFTypeRef _CFApplicationPreferencesSearchDownToDomain(_CFApplicationPreferences *self, CFPreferencesDomainRef stopper, CFStringRef key);
165
166
167CF_EXTERN_C_END
168
169
170
171// ---- CFString material ----------------------------------------
172
173#include <CoreFoundation/CFStringEncodingExt.h>
174
175#define NSSTRING_BOUNDSERROR \
176    [NSException raise:NSRangeException format:@"%@: Range or index out of bounds", __CFExceptionProem((id)self, _cmd)]
177
178#define NSSTRING_RANGEERROR(range, len) \
179    [NSException raise:NSRangeException format:@"%@: Range {%lu, %lu} out of bounds; string length %lu", __CFExceptionProem((id)self, _cmd), (unsigned long)range.location, (unsigned long)range.length, (unsigned long)len]
180
181#define NSSTRING_INDEXERROR(index, len) \
182    [NSException raise:NSRangeException format:@"%@: Index %lu out of bounds; string length %lu", __CFExceptionProem((id)self, _cmd), (unsigned long)index, (unsigned long)len]
183
184// This can be made into an exception for post-10.9 apps
185#define NSSTRING_POSSIBLE_RANGEERROR(range, len)     \
186    if (__CFStringNoteErrors()) {       \
187        static bool warnonce = false;   \
188        if (!warnonce) {                \
189            warnonce = true;            \
190            CFLog(kCFLogLevelWarning, CFSTR("*** %@: Range {%lu, %lu} out of bounds; string length %lu. This will become an exception for apps linked after 10.9. Warning shown once per app execution."), __CFExceptionProem((id)self, _cmd), (unsigned long)range.location, (unsigned long)range.length, (unsigned long)len);        \
191    }   \
192}
193
194#define NSSTRING_ILLEGALREQUESTERROR \
195    [NSException raise:NSInvalidArgumentException format:@"Can't call %s in %@", sel_getName(_cmd), object_getClass((id)self)]
196
197#define NSSTRING_INVALIDMUTATIONERROR \
198    [NSException raise:NSInvalidArgumentException format:@"Attempt to mutate immutable object with %s", sel_getName(_cmd)]
199
200#define NSSTRING_NULLCSTRINGERROR \
201    [NSException raise:NSInvalidArgumentException format:@"%@: NULL cString", __CFExceptionProem((id)self, _cmd)]
202
203#define NSSTRING_NILSTRINGERROR \
204    [NSException raise:NSInvalidArgumentException format:@"%@: nil argument", __CFExceptionProem((id)self, _cmd)]
205
206
207CF_EXTERN_C_BEGIN
208
209/* Create a byte stream from a CFString backing. Can convert a string piece at a
210   time into a fixed size buffer. Returns number of characters converted.
211   Characters that cannot be converted to the specified encoding are represented
212   with the char specified by lossByte; if 0, then lossy conversion is not allowed
213   and conversion stops, returning partial results.
214   generatingExternalFile indicates that any extra stuff to allow this data to be
215   persistent (for instance, BOM) should be included.
216   Pass buffer==NULL if you don't care about the converted string (but just the
217   convertability, or number of bytes required, indicated by usedBufLen).
218   Does not zero-terminate. If you want to create Pascal or C string, allow one
219   extra byte at start or end.
220*/
221CF_EXPORT CFIndex __CFStringEncodeByteStream(CFStringRef string, CFIndex rangeLoc, CFIndex rangeLen, Boolean generatingExternalFile, CFStringEncoding encoding, char lossByte, UInt8 *buffer, CFIndex max, CFIndex *usedBufLen);
222
223CF_EXPORT CFStringRef __CFStringCreateImmutableFunnel2(CFAllocatorRef alloc, const void *bytes, CFIndex numBytes, CFStringEncoding encoding, Boolean possiblyExternalFormat, Boolean tryToReduceUnicode, Boolean hasLengthByte, Boolean hasNullByte, Boolean noCopy, CFAllocatorRef contentsDeallocator);
224
225CF_EXPORT void __CFStringAppendBytes(CFMutableStringRef str, const char *cStr, CFIndex appendedLength, CFStringEncoding encoding);
226
227CF_INLINE Boolean __CFStringEncodingIsSupersetOfASCII(CFStringEncoding encoding) {
228    switch (encoding & 0x0000FF00) {
229	case 0x0: // MacOS Script range
230            // Symbol & bidi encodings are not ASCII superset
231            if (encoding == kCFStringEncodingMacJapanese || encoding == kCFStringEncodingMacArabic || encoding == kCFStringEncodingMacHebrew || encoding == kCFStringEncodingMacUkrainian || encoding == kCFStringEncodingMacSymbol || encoding == kCFStringEncodingMacDingbats) return false;
232            return true;
233
234        case 0x100: // Unicode range
235            if (encoding != kCFStringEncodingUTF8) return false;
236            return true;
237
238        case 0x200: // ISO range
239            if (encoding == kCFStringEncodingISOLatinArabic) return false;
240            return true;
241
242        case 0x600: // National standards range
243            if (encoding != kCFStringEncodingASCII) return false;
244            return true;
245
246        case 0x800: // ISO 2022 range
247            return false; // It's modal encoding
248
249        case 0xA00: // Misc standard range
250            if ((encoding == kCFStringEncodingShiftJIS) || (encoding == kCFStringEncodingHZ_GB_2312) || (encoding == kCFStringEncodingUTF7_IMAP)) return false;
251            return true;
252
253        case 0xB00:
254            if (encoding == kCFStringEncodingNonLossyASCII) return false;
255            return true;
256
257        case 0xC00: // EBCDIC
258            return false;
259
260        default:
261            return ((encoding & 0x0000FF00) > 0x0C00 ? false : true);
262    }
263}
264
265
266/* Desperately using extern here */
267CF_EXPORT CFStringEncoding __CFDefaultEightBitStringEncoding;
268CF_EXPORT CFStringEncoding __CFStringComputeEightBitStringEncoding(void);
269
270CF_INLINE CFStringEncoding __CFStringGetEightBitStringEncoding(void) {
271    if (__CFDefaultEightBitStringEncoding == kCFStringEncodingInvalidId) __CFStringComputeEightBitStringEncoding();
272    return __CFDefaultEightBitStringEncoding;
273}
274
275enum {
276     __kCFVarWidthLocalBufferSize = 1008
277};
278
279typedef struct {      /* A simple struct to maintain ASCII/Unicode versions of the same buffer. */
280     union {
281        UInt8 *ascii;
282	UniChar *unicode;
283    } chars;
284    Boolean isASCII;	/* This really does mean 7-bit ASCII, not _NSDefaultCStringEncoding() */
285    Boolean shouldFreeChars;	/* If the number of bytes exceeds __kCFVarWidthLocalBufferSize, bytes are allocated */
286    Boolean _unused1;
287    Boolean _unused2;
288    CFAllocatorRef allocator;	/* Use this allocator to allocate, reallocate, and deallocate the bytes */
289    CFIndex numChars;	/* This is in terms of ascii or unicode; that is, if isASCII, it is number of 7-bit chars; otherwise it is number of UniChars; note that the actual allocated space might be larger */
290    UInt8 localBuffer[__kCFVarWidthLocalBufferSize];	/* private; 168 ISO2022JP chars, 504 Unicode chars, 1008 ASCII chars */
291} CFVarWidthCharBuffer;
292
293
294/* Convert a byte stream to ASCII (7-bit!) or Unicode, with a CFVarWidthCharBuffer struct on the stack. false return indicates an error occured during the conversion. Depending on .isASCII, follow .chars.ascii or .chars.unicode.  If .shouldFreeChars is returned as true, free the returned buffer when done with it.  If useClientsMemoryPtr is provided as non-NULL, and the provided memory can be used as is, this is set to true, and the .ascii or .unicode buffer in CFVarWidthCharBuffer is set to bytes.
295!!! If the stream is Unicode and has no BOM, the data is assumed to be big endian! Could be trouble on Intel if someone didn't follow that assumption.
296!!! __CFStringDecodeByteStream2() needs to be deprecated and removed post-Jaguar.
297*/
298CF_EXPORT Boolean __CFStringDecodeByteStream2(const UInt8 *bytes, UInt32 len, CFStringEncoding encoding, Boolean alwaysUnicode, CFVarWidthCharBuffer *buffer, Boolean *useClientsMemoryPtr);
299CF_EXPORT Boolean __CFStringDecodeByteStream3(const UInt8 *bytes, CFIndex len, CFStringEncoding encoding, Boolean alwaysUnicode, CFVarWidthCharBuffer *buffer, Boolean *useClientsMemoryPtr, UInt32 converterFlags);
300
301
302/* Convert single byte to Unicode; assumes one-to-one correspondence (that is, can only be used with 1-byte encodings). You can use the function if it's not NULL.
303*/
304CF_EXPORT Boolean (*__CFCharToUniCharFunc)(UInt32 flags, UInt8 ch, UniChar *unicodeChar);
305
306/* Character class functions UnicodeData-2_1_5.txt
307*/
308CF_INLINE Boolean __CFIsWhitespace(UniChar theChar) {
309    return ((theChar < 0x21) || (theChar > 0x7E && theChar < 0xA1) || (theChar >= 0x2000 && theChar <= 0x200B) || (theChar == 0x3000)) ? true : false;
310}
311
312/* Same as CFStringGetCharacterFromInlineBuffer() but returns 0xFFFF on out of bounds access
313*/
314CF_INLINE UniChar __CFStringGetCharacterFromInlineBufferAux(CFStringInlineBuffer *buf, CFIndex idx) {
315    if (idx < 0 || idx >= buf->rangeToBuffer.length) return 0xFFFF;
316    if (buf->directUniCharBuffer) return buf->directUniCharBuffer[idx + buf->rangeToBuffer.location];
317    if (buf->directCStringBuffer) return (UniChar)(buf->directCStringBuffer[idx + buf->rangeToBuffer.location]);
318    if (idx >= buf->bufferedRangeEnd || idx < buf->bufferedRangeStart) {
319	if ((buf->bufferedRangeStart = idx - 4) < 0) buf->bufferedRangeStart = 0;
320	buf->bufferedRangeEnd = buf->bufferedRangeStart + __kCFStringInlineBufferLength;
321	if (buf->bufferedRangeEnd > buf->rangeToBuffer.length) buf->bufferedRangeEnd = buf->rangeToBuffer.length;
322	CFStringGetCharacters(buf->theString, CFRangeMake(buf->rangeToBuffer.location + buf->bufferedRangeStart, buf->bufferedRangeEnd - buf->bufferedRangeStart), buf->buffer);
323    }
324    return buf->buffer[idx - buf->bufferedRangeStart];
325}
326
327/* Same as CFStringGetCharacterFromInlineBuffer(), but without the bounds checking (will return garbage or crash)
328*/
329CF_INLINE UniChar __CFStringGetCharacterFromInlineBufferQuick(CFStringInlineBuffer *buf, CFIndex idx) {
330    if (buf->directUniCharBuffer) return buf->directUniCharBuffer[idx + buf->rangeToBuffer.location];
331    if (buf->directCStringBuffer) return (UniChar)(buf->directCStringBuffer[idx + buf->rangeToBuffer.location]);
332    if (idx >= buf->bufferedRangeEnd || idx < buf->bufferedRangeStart) {
333	if ((buf->bufferedRangeStart = idx - 4) < 0) buf->bufferedRangeStart = 0;
334	buf->bufferedRangeEnd = buf->bufferedRangeStart + __kCFStringInlineBufferLength;
335	if (buf->bufferedRangeEnd > buf->rangeToBuffer.length) buf->bufferedRangeEnd = buf->rangeToBuffer.length;
336	CFStringGetCharacters(buf->theString, CFRangeMake(buf->rangeToBuffer.location + buf->bufferedRangeStart, buf->bufferedRangeEnd - buf->bufferedRangeStart), buf->buffer);
337    }
338    return buf->buffer[idx - buf->bufferedRangeStart];
339}
340
341
342/* These two allow specifying an alternate description function (instead of CFCopyDescription); used by NSString
343*/
344CF_EXPORT void _CFStringAppendFormatAndArgumentsAux(CFMutableStringRef outputString, CFStringRef (*copyDescFunc)(void *, const void *loc), CFDictionaryRef formatOptions, CFStringRef formatString, va_list args);
345CF_EXPORT CFStringRef  _CFStringCreateWithFormatAndArgumentsAux(CFAllocatorRef alloc, CFStringRef (*copyDescFunc)(void *, const void *loc), CFDictionaryRef formatOptions, CFStringRef format, va_list arguments);
346
347/* For NSString (and NSAttributedString) usage, mutate with isMutable check
348*/
349enum {_CFStringErrNone = 0, _CFStringErrNotMutable = 1, _CFStringErrNilArg = 2, _CFStringErrBounds = 3};
350CF_EXPORT int __CFStringCheckAndReplace(CFMutableStringRef str, CFRange range, CFStringRef replacement);
351CF_EXPORT Boolean __CFStringNoteErrors(void);		// Should string errors raise?
352
353/* For NSString usage, guarantees that the contents can be extracted as 8-bit bytes in the __CFStringGetEightBitStringEncoding().
354*/
355CF_EXPORT Boolean __CFStringIsEightBit(CFStringRef str);
356
357/* For NSCFString usage, these do range check (where applicable) but don't check for ObjC dispatch
358*/
359CF_EXPORT int _CFStringCheckAndGetCharacterAtIndex(CFStringRef str, CFIndex idx, UniChar *ch);
360CF_EXPORT int _CFStringCheckAndGetCharacters(CFStringRef str, CFRange range, UniChar *buffer);
361CF_EXPORT CFIndex _CFStringGetLength2(CFStringRef str);
362CF_EXPORT CFHashCode __CFStringHash(CFTypeRef cf);
363CF_EXPORT CFHashCode CFStringHashISOLatin1CString(const uint8_t *bytes, CFIndex len);
364CF_EXPORT CFHashCode CFStringHashCString(const uint8_t *bytes, CFIndex len);
365CF_EXPORT CFHashCode CFStringHashCharacters(const UniChar *characters, CFIndex len);
366CF_EXPORT CFHashCode CFStringHashNSString(CFStringRef str);
367
368
369CF_EXTERN_C_END
370
371
372// ---- Binary plist material ----------------------------------------
373
374typedef const struct __CFKeyedArchiverUID * CFKeyedArchiverUIDRef;
375CF_EXPORT CFTypeID _CFKeyedArchiverUIDGetTypeID(void);
376CF_EXPORT CFKeyedArchiverUIDRef _CFKeyedArchiverUIDCreate(CFAllocatorRef allocator, uint32_t value);
377CF_EXPORT uint32_t _CFKeyedArchiverUIDGetValue(CFKeyedArchiverUIDRef uid);
378
379
380enum {
381    kCFBinaryPlistMarkerNull = 0x00,
382    kCFBinaryPlistMarkerFalse = 0x08,
383    kCFBinaryPlistMarkerTrue = 0x09,
384    kCFBinaryPlistMarkerFill = 0x0F,
385    kCFBinaryPlistMarkerInt = 0x10,
386    kCFBinaryPlistMarkerReal = 0x20,
387    kCFBinaryPlistMarkerDate = 0x33,
388    kCFBinaryPlistMarkerData = 0x40,
389    kCFBinaryPlistMarkerASCIIString = 0x50,
390    kCFBinaryPlistMarkerUnicode16String = 0x60,
391    kCFBinaryPlistMarkerUID = 0x80,
392    kCFBinaryPlistMarkerArray = 0xA0,
393    kCFBinaryPlistMarkerSet = 0xC0,
394    kCFBinaryPlistMarkerDict = 0xD0
395};
396
397typedef struct {
398    uint8_t	_magic[6];
399    uint8_t	_version[2];
400} CFBinaryPlistHeader;
401
402typedef struct {
403    uint8_t	_unused[5];
404    uint8_t     _sortVersion;
405    uint8_t	_offsetIntSize;
406    uint8_t	_objectRefSize;
407    uint64_t	_numObjects;
408    uint64_t	_topObject;
409    uint64_t	_offsetTableOffset;
410} CFBinaryPlistTrailer;
411
412
413CF_EXPORT bool __CFBinaryPlistGetTopLevelInfo(const uint8_t *databytes, uint64_t datalen, uint8_t *marker, uint64_t *offset, CFBinaryPlistTrailer *trailer);
414CF_EXPORT bool __CFBinaryPlistGetOffsetForValueFromArray2(const uint8_t *databytes, uint64_t datalen, uint64_t startOffset, const CFBinaryPlistTrailer *trailer, CFIndex idx, uint64_t *offset, CFMutableDictionaryRef objects);
415CF_EXPORT bool __CFBinaryPlistGetOffsetForValueFromDictionary3(const uint8_t *databytes, uint64_t datalen, uint64_t startOffset, const CFBinaryPlistTrailer *trailer, CFTypeRef key, uint64_t *koffset, uint64_t *voffset, Boolean unused, CFMutableDictionaryRef objects);
416CF_EXPORT bool __CFBinaryPlistCreateObject(const uint8_t *databytes, uint64_t datalen, uint64_t startOffset, const CFBinaryPlistTrailer *trailer, CFAllocatorRef allocator, CFOptionFlags mutabilityOption, CFMutableDictionaryRef objects, CFPropertyListRef *plist);
417CF_EXPORT CFIndex __CFBinaryPlistWriteToStream(CFPropertyListRef plist, CFTypeRef stream);
418CF_EXPORT CFIndex __CFBinaryPlistWriteToStreamWithEstimate(CFPropertyListRef plist, CFTypeRef stream, uint64_t estimate); // will be removed soon
419CF_EXPORT CFIndex __CFBinaryPlistWriteToStreamWithOptions(CFPropertyListRef plist, CFTypeRef stream, uint64_t estimate, CFOptionFlags options); // will be removed soon
420CF_EXPORT CFIndex __CFBinaryPlistWrite(CFPropertyListRef plist, CFTypeRef stream, uint64_t estimate, CFOptionFlags options, CFErrorRef *error);
421
422// ---- Used by property list parsing in Foundation
423
424CF_EXPORT CFTypeRef _CFPropertyListCreateFromXMLData(CFAllocatorRef allocator, CFDataRef xmlData, CFOptionFlags option, CFStringRef *errorString, Boolean allowNewTypes, CFPropertyListFormat *format);
425
426CF_EXPORT CFTypeRef _CFPropertyListCreateFromXMLString(CFAllocatorRef allocator, CFStringRef xmlString, CFOptionFlags option, CFStringRef *errorString, Boolean allowNewTypes, CFPropertyListFormat *format);
427
428// ---- Sudden Termination material ----------------------------------------
429
430#if DEPLOYMENT_TARGET_MACOSX
431
432CF_EXPORT void _CFSuddenTerminationDisable(void);
433CF_EXPORT void _CFSuddenTerminationEnable(void);
434CF_EXPORT void _CFSuddenTerminationExitIfTerminationEnabled(int exitStatus);
435CF_EXPORT void _CFSuddenTerminationExitWhenTerminationEnabled(int exitStatus);
436CF_EXPORT size_t _CFSuddenTerminationDisablingCount(void);
437
438#endif
439
440// ---- Thread-specific data --------------------------------------------
441
442// Get some thread specific data from a pre-assigned slot.
443CF_EXPORT void *_CFGetTSD(uint32_t slot);
444
445// Set some thread specific data in a pre-assigned slot. Don't pick a random value. Make sure you're using a slot that is unique. Pass in a destructor to free this data, or NULL if none is needed. Unlike pthread TSD, the destructor is per-thread.
446CF_EXPORT void *_CFSetTSD(uint32_t slot, void *newVal, void (*destructor)(void *));
447
448#if DEPLOYMENT_TARGET_WINDOWS
449// ---- Windows-specific material ---------------------------------------
450
451// These are replacements for POSIX calls on Windows, ensuring that the UTF8 parameters are converted to UTF16 before being passed to Windows
452CF_EXPORT int _NS_stat(const char *name, struct _stat *st);
453CF_EXPORT int _NS_mkdir(const char *name);
454CF_EXPORT int _NS_rmdir(const char *name);
455CF_EXPORT int _NS_chmod(const char *name, int mode);
456CF_EXPORT int _NS_unlink(const char *name);
457CF_EXPORT char *_NS_getcwd(char *dstbuf, size_t size);     // Warning: this doesn't support dstbuf as null even though 'getcwd' does
458CF_EXPORT char *_NS_getenv(const char *name);
459CF_EXPORT int _NS_rename(const char *oldName, const char *newName);
460CF_EXPORT int _NS_open(const char *name, int oflag, int pmode);
461CF_EXPORT int _NS_mkstemp(char *name, int bufSize);
462#endif
463
464// ---- Miscellaneous material ----------------------------------------
465
466#include <CoreFoundation/CFBag.h>
467#include <CoreFoundation/CFSet.h>
468#include <math.h>
469
470CF_EXTERN_C_BEGIN
471
472CF_EXPORT CFTypeID CFTypeGetTypeID(void);
473
474CF_EXPORT void _CFArraySetCapacity(CFMutableArrayRef array, CFIndex cap);
475CF_EXPORT void _CFBagSetCapacity(CFMutableBagRef bag, CFIndex cap);
476CF_EXPORT void _CFDictionarySetCapacity(CFMutableDictionaryRef dict, CFIndex cap);
477CF_EXPORT void _CFSetSetCapacity(CFMutableSetRef set, CFIndex cap);
478
479CF_EXPORT void CFCharacterSetCompact(CFMutableCharacterSetRef theSet);
480CF_EXPORT void CFCharacterSetFast(CFMutableCharacterSetRef theSet);
481
482CF_EXPORT const void *_CFArrayCheckAndGetValueAtIndex(CFArrayRef array, CFIndex idx);
483CF_EXPORT void _CFArrayReplaceValues(CFMutableArrayRef array, CFRange range, const void **newValues, CFIndex newCount);
484
485
486/* Enumeration
487 Call CFStartSearchPathEnumeration() once, then call
488 CFGetNextSearchPathEnumeration() one or more times with the returned state.
489 The return value of CFGetNextSearchPathEnumeration() should be used as
490 the state next time around.
491 When CFGetNextSearchPathEnumeration() returns 0, you're done.
492*/
493typedef CFIndex CFSearchPathEnumerationState;
494CF_EXPORT CFSearchPathEnumerationState __CFStartSearchPathEnumeration(CFSearchPathDirectory dir, CFSearchPathDomainMask domainMask);
495CF_EXPORT CFSearchPathEnumerationState __CFGetNextSearchPathEnumeration(CFSearchPathEnumerationState state, UInt8 *path, CFIndex pathSize);
496
497/* For use by NSNumber and CFNumber.
498  Hashing algorithm for CFNumber:
499  M = Max CFHashCode (assumed to be unsigned)
500  For positive integral values: (N * HASHFACTOR) mod M
501  For negative integral values: ((-N) * HASHFACTOR) mod M
502  For floating point numbers that are not integral: hash(integral part) + hash(float part * M)
503  HASHFACTOR is 2654435761, from Knuth's multiplicative method
504*/
505#define HASHFACTOR 2654435761U
506
507CF_INLINE CFHashCode _CFHashInt(long i) {
508    return ((i > 0) ? (CFHashCode)(i) : (CFHashCode)(-i)) * HASHFACTOR;
509}
510
511CF_INLINE CFHashCode _CFHashDouble(double d) {
512    double dInt;
513    if (d < 0) d = -d;
514    dInt = floor(d+0.5);
515    CFHashCode integralHash = HASHFACTOR * (CFHashCode)fmod(dInt, (double)ULONG_MAX);
516    return (CFHashCode)(integralHash + (CFHashCode)((d - dInt) * ULONG_MAX));
517}
518
519
520/* These four functions are used by NSError in formatting error descriptions. They take NS or CFError as arguments and return a retained CFString or NULL.
521*/
522CF_EXPORT CFStringRef _CFErrorCreateLocalizedDescription(CFErrorRef err);
523CF_EXPORT CFStringRef _CFErrorCreateLocalizedFailureReason(CFErrorRef err);
524CF_EXPORT CFStringRef _CFErrorCreateLocalizedRecoverySuggestion(CFErrorRef err);
525CF_EXPORT CFStringRef _CFErrorCreateDebugDescription(CFErrorRef err);
526
527CF_EXPORT CFURLRef _CFURLAlloc(CFAllocatorRef allocator);
528CF_EXPORT Boolean _CFURLInitWithURLString(CFURLRef uninitializedURL, CFStringRef string, Boolean checkForLegalCharacters, CFURLRef baseURL);
529CF_EXPORT Boolean _CFURLInitWithFileSystemPath(CFURLRef uninitializedURL, CFStringRef fileSystemPath, CFURLPathStyle pathStyle, Boolean isDirectory, CFURLRef baseURL);
530CF_EXPORT Boolean _CFURLInitWithFileSystemRepresentation(CFURLRef uninitializedURL, const UInt8 *buffer, CFIndex bufLen, Boolean isDirectory, CFURLRef baseURL);
531CF_EXPORT void *__CFURLReservedPtr(CFURLRef  url);
532CF_EXPORT void __CFURLSetReservedPtr(CFURLRef  url, void *ptr);
533CF_EXPORT CFStringEncoding _CFURLGetEncoding(CFURLRef url);
534
535#if DEPLOYMENT_TARGET_MACOSX || DEPLOYMENT_TARGET_EMBEDDED || DEPLOYMENT_TARGET_EMBEDDED_MINI || DEPLOYMENT_TARGET_WINDOWS
536CF_EXPORT Boolean _CFRunLoopFinished(CFRunLoopRef rl, CFStringRef mode);
537#endif
538
539CF_EXPORT CFIndex _CFStreamInstanceSize(void);
540
541#if DEPLOYMENT_TARGET_MACOSX || DEPLOYMENT_TARGET_EMBEDDED
542typedef struct {
543    mach_vm_address_t address;
544    mach_vm_size_t size;
545    mach_port_t port;
546    bool purgeable;
547    bool corporeal;
548    bool volatyle;
549    uintptr_t reserved;
550} CFDiscorporateMemory;
551
552extern kern_return_t _CFDiscorporateMemoryAllocate(CFDiscorporateMemory *hm, size_t size, bool purgeable);
553extern kern_return_t _CFDiscorporateMemoryDeallocate(CFDiscorporateMemory *hm);
554extern kern_return_t _CFDiscorporateMemoryDematerialize(CFDiscorporateMemory *hm);
555extern kern_return_t _CFDiscorporateMemoryMaterialize(CFDiscorporateMemory *hm);
556#endif
557
558enum {
559    kCFNumberFormatterOrdinalStyle = 6,
560    kCFNumberFormatterDurationStyle = 7,
561};
562
563CF_EXPORT CFRange _CFDataFindBytes(CFDataRef data, CFDataRef dataToFind, CFRange searchRange, CFDataSearchFlags compareOptions);
564
565
566#if DEPLOYMENT_TARGET_MACOSX || DEPLOYMENT_TARGET_EMBEDDED || DEPLOYMENT_TARGET_EMBEDDED_MINI
567    #if !defined(__CFReadTSR)
568    #include <mach/mach_time.h>
569    #define __CFReadTSR() mach_absolute_time()
570    #endif
571#elif DEPLOYMENT_TARGET_WINDOWS
572#if 0
573CF_INLINE UInt64 __CFReadTSR(void) {
574    LARGE_INTEGER freq;
575    QueryPerformanceCounter(&freq);
576    return freq.QuadPart;
577}
578#endif
579#endif
580
581
582CF_EXTERN_C_END
583
584#endif /* ! __COREFOUNDATION_FORFOUNDATIONONLY__ */
585
586