Skip to content

Fix potentially undefined behavior in StringObject.nativeStorage and document Builtin.unsafeBitCast #63631

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 13 additions & 4 deletions stdlib/public/core/Builtin.swift
Original file line number Diff line number Diff line change
Expand Up @@ -72,14 +72,23 @@ func _canBeClass<T>(_: T.Type) -> Int8 {
/// `unsafeBitCast(_:to:)` with class or pointer types; doing so may
/// introduce undefined behavior.
///
/// - Warning: Calling this function breaks the guarantees of the Swift type
/// system; use with extreme care.
/// Warning: Calling this function breaks the guarantees of the Swift type
/// system; use with extreme care.
///
/// - Parameters:
/// Warning: Casting from an integer or a pointer type to a reference type
/// is undefined behavior. It may result in incorrect code in any future
/// compiler release. To convert a bit pattern to a reference type:
/// 1. convert the bit pattern to an UnsafeRawPointer.
/// 2. create an unmanaged reference using Unmanaged.fromOpaque()
/// 3. obtain a managed reference using Unmanaged.takeUnretainedValue()
/// The programmer must ensure that the resulting reference has already been
/// manually retained.
///
/// Parameters:
/// - x: The instance to cast to `type`.
/// - type: The type to cast `x` to. `type` and the type of `x` must have the
/// same size of memory representation and compatible memory layout.
/// - Returns: A new instance of type `U`, cast from `x`.
/// Returns: A new instance of type `U`, cast from `x`.
@inlinable // unsafe-performance
@_transparent
public func unsafeBitCast<T, U>(_ x: T, to type: U.Type) -> U {
Expand Down
5 changes: 4 additions & 1 deletion stdlib/public/core/StringObject.swift
Original file line number Diff line number Diff line change
Expand Up @@ -940,7 +940,10 @@ extension _StringObject {
return _unsafeUncheckedDowncast(storage, to: __StringStorage.self)
#else
_internalInvariant(hasNativeStorage)
return Builtin.reinterpretCast(largeAddressBits)
let storageAddress =
UnsafeRawPointer(bitPattern:largeAddressBits)._unsafelyUnwrappedUnchecked
let unmanagedRef = Unmanaged<__StringStorage>.fromOpaque(storageAddress)
return unmanagedRef.takeUnretainedValue()
#endif
}

Expand Down