swiftlang / swift-corelibs-foundation

The Foundation Project, providing core utilities, internationalization, and OS independence
swift.org
Apache License 2.0
5.29k stars 1.13k forks source link

[SR-14420] NSData.bytes is very hard to hold safely, especially on non-Apple platforms #3229

Open Lukasa opened 3 years ago

Lukasa commented 3 years ago
Previous ID SR-14420
Radar rdar://problem/76010121
Original Reporter @Lukasa
Type Bug
Additional Detail from JIRA | | | |------------------|-----------------| |Votes | 1 | |Component/s | Foundation | |Labels | Bug | |Assignee | None | |Priority | Medium | md5: b40c2cee60a72f9c6e5ee6f3a3ac56b7

Issue Description:

NSData.bytes is a straightforward translation of the Objective-C [NSData bytes] property accessor from Objective-C. The method returns an interior pointer to the buffer of an NSData object.

Recent improvements to the copy propagation optimization pass have made this property very dangerous on non-Apple platforms, including breaking [swift-corelibs-foundation| https://github.com/apple/swift-corelibs-foundation/pull/2994] in recent top-of-tree Swift versions.

To use this property safely will almost invariably require the use of withExtendedLifetime to keep the parent NSData object alive. We should consider deprecating this in favour of Data.withUnsafeBytes, or providing a diagnostic for using NSData.bytes as the last usage point, or at the very least making it clear that this Objective-C-ism is potentially much more dangerous than it looks.

typesanitizer commented 3 years ago

@swift-ci create