Skip to content

Commit 3534d99

Browse files
committed
Foundation: fix missing string terminator
The computation of the base64encoding would trim the trailing nul terminator on the rendered string. This would result in invalid string manipulation leading to heap corruptions on Windows. Thanks to Simon Evans for spotting the issue and proposing the fix! (And a thank you for spotting a leak that I was accidentally introducing.)
1 parent 6167997 commit 3534d99

File tree

1 file changed

+5
-2
lines changed

1 file changed

+5
-2
lines changed

Foundation/NSData.swift

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -597,12 +597,15 @@ open class NSData : NSObject, NSCopying, NSMutableCopying, NSSecureCoding {
597597
let dataLength = self.length
598598
if dataLength == 0 { return "" }
599599

600-
let capacity = estimateBase64Size(length: dataLength)
600+
let capacity = estimateBase64Size(length: dataLength) + 1
601601
let ptr = UnsafeMutableRawPointer.allocate(byteCount: capacity, alignment: 1)
602602
let buffer = UnsafeMutableRawBufferPointer(start: ptr, count: capacity)
603603
let length = NSData.base64EncodeBytes(self, options: options, buffer: buffer)
604604

605-
return String(bytesNoCopy: ptr, length: length, encoding: .ascii, freeWhenDone: true)!
605+
buffer[length] = 0
606+
let string = String(validatingUTF8: ptr.assumingMemoryBound(to: CChar.self))!
607+
ptr.deallocate()
608+
return string
606609
}
607610

608611
/// Creates a Base64, UTF-8 encoded Data from the data object using the given options.

0 commit comments

Comments
 (0)