Skip to content

Commit 871e288

Browse files
authored
Disallow creation of CFStrings from non-8bit c-strings (#5165)
1 parent 0129358 commit 871e288

File tree

1 file changed

+10
-0
lines changed

1 file changed

+10
-0
lines changed

Sources/CoreFoundation/CFString.c

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1294,6 +1294,12 @@ CF_PRIVATE CFStringRef __CFStringCreateImmutableFunnel3(
12941294
Boolean possiblyExternalFormat, Boolean tryToReduceUnicode, Boolean hasLengthByte, Boolean hasNullByte, Boolean noCopy,
12951295
CFAllocatorRef contentsDeallocator, UInt32 converterFlags) {
12961296

1297+
if (hasNullByte && !__CFStringEncodingIsSupersetOfASCII(encoding)) {
1298+
// Non-8bit encodings cannot be safely read as c-strings because they may contain many null bytes
1299+
// This was documented as invalid previously, but now we validate that eagerly here to prevent creating truncated strings or strings that incorrectly assume 8bit representation
1300+
HALT_MSG("CFStringCreateWithCString can only be called with an 8-bit encoding");
1301+
}
1302+
12971303
CFMutableStringRef str = NULL;
12981304
CFVarWidthCharBuffer vBuf;
12991305
CFIndex size;
@@ -2232,6 +2238,10 @@ static inline const char * _CFStringGetCStringPtrInternal(CFStringRef str, CFStr
22322238

22332239
__CFAssertIsString(str);
22342240

2241+
// __CFStrHasNullByte(str) implies the string was created from a c-string
2242+
// All strings created from c-strings must be 8bit since c-strings are not possible with non-8bit encodings
2243+
// CFStringCreateWithCString validates that all strings created must have been created from bytes of an 8bit encoding, so __CFStrHasNullByte alone is sufficient here since it implies __CFStrIsEightBit
2244+
// For the non-null-terminated case, we must still validate that the underlying contents are an 8bit representation
22352245
if ((!requiresNullTermination && __CFStrIsEightBit(str)) || __CFStrHasNullByte(str)) {
22362246
// Note: this is called a lot, 27000 times to open a small xcode project with one file open.
22372247
// Of these uses about 1500 are for cStrings/utf8strings.

0 commit comments

Comments
 (0)