Skip to content

Commit f3a6f50

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 f3a6f50

File tree

1 file changed

+3
-1
lines changed

1 file changed

+3
-1
lines changed

Foundation/NSData.swift

+3-1
Original file line numberDiff line numberDiff line change
@@ -599,10 +599,12 @@ open class NSData : NSObject, NSCopying, NSMutableCopying, NSSecureCoding {
599599

600600
let capacity = estimateBase64Size(length: dataLength)
601601
let ptr = UnsafeMutableRawPointer.allocate(byteCount: capacity, alignment: 1)
602+
defer { ptr.deallocate() }
602603
let buffer = UnsafeMutableRawBufferPointer(start: ptr, count: capacity)
603604
let length = NSData.base64EncodeBytes(self, options: options, buffer: buffer)
604605

605-
return String(bytesNoCopy: ptr, length: length, encoding: .ascii, freeWhenDone: true)!
606+
let utf8buffer = UnsafeBufferPointer<UInt8>(start: ptr.assumingMemoryBound(to: UInt8.self), count: length)
607+
return String(decoding: utf8buffer, as: UTF8.self)
606608
}
607609

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

0 commit comments

Comments
 (0)