Skip to content

Fix use-after-free on substituting function type involving conditional ~Escapable with Escapable type #81678

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

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
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
28 changes: 28 additions & 0 deletions include/swift/AST/ExtInfo.h
Original file line number Diff line number Diff line change
Expand Up @@ -740,12 +740,19 @@ class ASTExtInfoBuilder {
globalActor, thrownError, lifetimeDependencies);
}

/// \p lifetimeDependencies should be arena allocated and not a temporary
/// Function types are allocated on the are arena and their ExtInfo should be
/// valid throughout their lifetime.
[[nodiscard]] ASTExtInfoBuilder withLifetimeDependencies(
llvm::ArrayRef<LifetimeDependenceInfo> lifetimeDependencies) const {
return ASTExtInfoBuilder(bits, clangTypeInfo, globalActor, thrownError,
lifetimeDependencies);
}

[[nodiscard]] ASTExtInfoBuilder withLifetimeDependencies(
SmallVectorImpl<LifetimeDependenceInfo> lifetimeDependencies) const =
delete;

[[nodiscard]]
ASTExtInfoBuilder withIsolation(FunctionTypeIsolation isolation) const {
return ASTExtInfoBuilder(
Expand Down Expand Up @@ -920,11 +927,18 @@ class ASTExtInfo {
.build();
}

/// \p lifetimeDependencies should be arena allocated and not a temporary
/// Function types are allocated on the are arena and their ExtInfo should be
/// valid throughout their lifetime.
[[nodiscard]] ASTExtInfo withLifetimeDependencies(
ArrayRef<LifetimeDependenceInfo> lifetimeDependencies) const {
return builder.withLifetimeDependencies(lifetimeDependencies).build();
}

[[nodiscard]] ASTExtInfo withLifetimeDependencies(
SmallVectorImpl<LifetimeDependenceInfo> lifetimeDependencies) const =
delete;

void Profile(llvm::FoldingSetNodeID &ID) const { builder.Profile(ID); }

bool isEqualTo(ASTExtInfo other, bool useClangTypes) const {
Expand Down Expand Up @@ -1227,11 +1241,19 @@ class SILExtInfoBuilder {
return SILExtInfoBuilder(bits, ClangTypeInfo(type).getCanonical(),
lifetimeDependencies);
}

/// \p lifetimeDependencies should be arena allocated and not a temporary
/// Function types are allocated on the are arena and their ExtInfo should be
/// valid throughout their lifetime.
[[nodiscard]] SILExtInfoBuilder withLifetimeDependencies(
ArrayRef<LifetimeDependenceInfo> lifetimeDependenceInfo) const {
return SILExtInfoBuilder(bits, clangTypeInfo, lifetimeDependenceInfo);
}

[[nodiscard]] ASTExtInfoBuilder withLifetimeDependencies(
SmallVectorImpl<LifetimeDependenceInfo> lifetimeDependencies) const =
delete;

void Profile(llvm::FoldingSetNodeID &ID) const {
ID.AddInteger(bits);
ID.AddPointer(clangTypeInfo.getType());
Expand Down Expand Up @@ -1368,11 +1390,17 @@ class SILExtInfo {
return builder.withUnimplementable(isUnimplementable).build();
}

/// \p lifetimeDependencies should be arena allocated and not a temporary
/// Function types are allocated on the are arena and their ExtInfo should be
/// valid throughout their lifetime.
SILExtInfo withLifetimeDependencies(
ArrayRef<LifetimeDependenceInfo> lifetimeDependencies) const {
return builder.withLifetimeDependencies(lifetimeDependencies);
}

SILExtInfo withLifetimeDependencies(SmallVectorImpl<LifetimeDependenceInfo>
lifetimeDependencies) const = delete;

void Profile(llvm::FoldingSetNodeID &ID) const { builder.Profile(ID); }

bool isEqualTo(SILExtInfo other, bool useClangTypes) const {
Expand Down
6 changes: 4 additions & 2 deletions include/swift/AST/TypeTransform.h
Original file line number Diff line number Diff line change
Expand Up @@ -358,7 +358,8 @@ case TypeKind::Id:
}
});
if (didRemoveLifetimeDependencies) {
extInfo = extInfo.withLifetimeDependencies(substDependenceInfos);
extInfo = extInfo.withLifetimeDependencies(
ctx.AllocateCopy(substDependenceInfos));
}
}

Expand Down Expand Up @@ -939,7 +940,8 @@ case TypeKind::Id:
});

if (didRemoveLifetimeDependencies) {
extInfo = extInfo->withLifetimeDependencies(substDependenceInfos);
extInfo = extInfo->withLifetimeDependencies(
ctx.AllocateCopy(substDependenceInfos));
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Maybe it's best to sink the AllocateCopy down into withLifetimeDependencies()

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is there some rule for when withLifetimeDependencies needs its own allocation? Could that at least be commented in the API?

We call this in several other places and I don't know which need an allocation and which don't. e.g.
SILFunctionType::getSubstLifetimeDependencies

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It needs its own allocation if the LifetimeDependencies that you pass in are themselves not in the global AST context arena. It's safest to move the AllocateCopy into withLifetimeDependencies() itself, so that callers don't have to worry about creating an ExtInfo with a dangling pointer in it.

Copy link
Contributor Author

@meg-gupta meg-gupta May 21, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I did not originally want to do this because withLifetimeDependencies is called from places with an already arena allocated pointer as the input arg, and proactively allocating within it would not allow sharing.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

perhaps the LifetimeDependencies objects should always be allocated and uniqued by the ASTContext then, so you'll pass them around by pointer and the pointer will always have global extent.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I was hoping to use something akin to llvm::BumpPtrAllocatorImpl::identifyObject to ensure the passed input arg is safe in assert builds. Not everything is plumbed through to try that out.

I added a C++ delete overload for withLifetimeDependencies when input argument is SmallVectorImpl for now.

Copy link
Contributor Author

@meg-gupta meg-gupta May 21, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

perhaps the LifetimeDependencies objects should always be allocated and uniqued by the ASTContext then

@slavapestov This sounds promising. But maybe a big refactor for release/6.2

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I created rdar://151811669 (LifetimeDependencies objects should always be allocated and uniqued by the ASTContext)

}
}

Expand Down
12 changes: 6 additions & 6 deletions include/swift/AST/Types.h
Original file line number Diff line number Diff line change
Expand Up @@ -5210,12 +5210,12 @@ class SILFunctionType final
/// Given an existing ExtInfo, and a set of interface parameters and results
/// destined for a new SILFunctionType, return a new ExtInfo with only the
/// lifetime dependencies relevant after substitution.
static ExtInfo
getSubstLifetimeDependencies(GenericSignature genericSig,
ExtInfo origExtInfo,
ArrayRef<SILParameterInfo> params,
ArrayRef<SILYieldInfo> yields,
ArrayRef<SILResultInfo> results);
static ExtInfo getSubstLifetimeDependencies(GenericSignature genericSig,
ExtInfo origExtInfo,
ASTContext &context,
ArrayRef<SILParameterInfo> params,
ArrayRef<SILYieldInfo> yields,
ArrayRef<SILResultInfo> results);

/// Return a structurally-identical function type with a slightly tweaked
/// ExtInfo.
Expand Down
23 changes: 11 additions & 12 deletions lib/SIL/IR/SILFunctionType.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -59,12 +59,10 @@ SILType SILFunctionType::substInterfaceType(SILModule &M,
return interfaceType;
}

SILFunctionType::ExtInfo
SILFunctionType::getSubstLifetimeDependencies(GenericSignature genericSig,
ExtInfo origExtInfo,
ArrayRef<SILParameterInfo> params,
ArrayRef<SILYieldInfo> yields,
ArrayRef<SILResultInfo> results) {
SILFunctionType::ExtInfo SILFunctionType::getSubstLifetimeDependencies(
GenericSignature genericSig, ExtInfo origExtInfo, ASTContext &context,
ArrayRef<SILParameterInfo> params, ArrayRef<SILYieldInfo> yields,
ArrayRef<SILResultInfo> results) {
if (origExtInfo.getLifetimeDependencies().empty()) {
return origExtInfo;
}
Expand All @@ -87,7 +85,8 @@ SILFunctionType::getSubstLifetimeDependencies(GenericSignature genericSig,
}
});
if (didRemoveLifetimeDependencies) {
return origExtInfo.withLifetimeDependencies(substLifetimeDependencies);
return origExtInfo.withLifetimeDependencies(
context.AllocateCopy(substLifetimeDependencies));
}
return origExtInfo;
}
Expand Down Expand Up @@ -131,10 +130,10 @@ CanSILFunctionType SILFunctionType::getUnsubstitutedType(SILModule &M) const {

auto signature = isPolymorphic() ? getInvocationGenericSignature()
: CanGenericSignature();
auto extInfo = getSubstLifetimeDependencies(signature, getExtInfo(),
params, yields, results);

auto extInfo = getSubstLifetimeDependencies(
signature, getExtInfo(), getASTContext(), params, yields, results);

return SILFunctionType::get(signature,
extInfo,
getCoroutineKind(),
Expand Down Expand Up @@ -2855,7 +2854,7 @@ static CanSILFunctionType getSILFunctionType(
.withSendable(isSendable)
.withAsync(isAsync)
.withUnimplementable(unimplementable)
.withLifetimeDependencies(loweredLifetimes)
.withLifetimeDependencies(TC.Context.AllocateCopy(loweredLifetimes))
.build();

return SILFunctionType::get(genericSig, silExtInfo, coroutineKind,
Expand Down
9 changes: 4 additions & 5 deletions lib/SIL/IR/SILTypeSubstitution.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -240,11 +240,10 @@ class SILTypeSubstituter :
auto genericSig = IFS.shouldSubstituteOpaqueArchetypes()
? origType->getInvocationGenericSignature()
: nullptr;

extInfo = SILFunctionType::getSubstLifetimeDependencies(genericSig, extInfo,
substParams,
substYields,
substResults);

extInfo = SILFunctionType::getSubstLifetimeDependencies(
genericSig, extInfo, TC.Context, substParams, substYields,
substResults);

return SILFunctionType::get(genericSig, extInfo,
origType->getCoroutineKind(),
Expand Down
98 changes: 98 additions & 0 deletions test/Serialization/Inputs/ne_types.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,98 @@
@_addressableForDependencies
public struct Something {
public struct View<T: BitwiseCopyable> : ~Copyable, ~Escapable {
var ptr: UnsafeBufferPointer<T>

@lifetime(borrow ptr)
public init(ptr: borrowing UnsafeBufferPointer<T>) {
self.ptr = copy ptr
}

public var span: Span<T> {
@lifetime(borrow self)
borrowing get {
Span(_unsafeElements: ptr)
}
}
}

public struct MutableView<T: BitwiseCopyable> : ~Copyable, ~Escapable {
var ptr: UnsafeMutableBufferPointer<T>

@lifetime(borrow ptr)
public init(ptr: borrowing UnsafeMutableBufferPointer<T>) {
self.ptr = copy ptr
}

public var mutableSpan: MutableSpan<T> {
@lifetime(&self)
mutating get {
MutableSpan(_unsafeElements: ptr)
}
}
}

var ptr: UnsafeMutableRawBufferPointer
public init(ptr: UnsafeMutableRawBufferPointer) {
self.ptr = ptr
}

@lifetime(borrow self)
public func view<T>(of type: T.Type = T.self) -> View<T> {
let tp = ptr.assumingMemoryBound(to: T.self)
return __overrideLifetime(View(ptr: .init(tp)), borrowing: self)
}

@lifetime(&self)
public mutating func mutableView<T>(of type: T.Type = T.self) -> MutableView<T> {
let tp = ptr.assumingMemoryBound(to: T.self)
return __overrideLifetime(MutableView(ptr: tp), mutating: &self)
}
}

@unsafe
@_unsafeNonescapableResult
@_alwaysEmitIntoClient
@_transparent
@lifetime(borrow source)
public func __overrideLifetime<
T: ~Copyable & ~Escapable, U: ~Copyable & ~Escapable
>(
_ dependent: consuming T, borrowing source: borrowing U
) -> T {
dependent
}

/// Unsafely discard any lifetime dependency on the `dependent` argument. Return
/// a value identical to `dependent` that inherits all lifetime dependencies from
/// the `source` argument.
@unsafe
@_unsafeNonescapableResult
@_alwaysEmitIntoClient
@_transparent
@lifetime(copy source)
public func __overrideLifetime<
T: ~Copyable & ~Escapable, U: ~Copyable & ~Escapable
>(
_ dependent: consuming T, copying source: borrowing U
) -> T {
dependent
}

/// Unsafely discard any lifetime dependency on the `dependent` argument.
/// Return a value identical to `dependent` with a lifetime dependency
/// on the caller's exclusive borrow scope of the `source` argument.
@unsafe
@_unsafeNonescapableResult
@_alwaysEmitIntoClient
@_transparent
@lifetime(&source)
public func __overrideLifetime<
T: ~Copyable & ~Escapable, U: ~Copyable & ~Escapable
>(
_ dependent: consuming T,
mutating source: inout U
) -> T {
dependent
}

26 changes: 26 additions & 0 deletions test/Serialization/non_escapable_subst_test.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
// RUN: %empty-directory(%t)
// RUN: %target-swift-frontend -emit-module -o %t %S/Inputs/ne_types.swift \
// RUN: -enable-experimental-feature LifetimeDependence \
// RUN: -enable-experimental-feature AddressableTypes \
// RUN: -enable-library-evolution \
// RUN: -emit-module-path %t/ne_types.swiftmodule

// RUN: %target-swift-frontend -emit-silgen -I %t %s \
// RUN: -enable-experimental-feature LifetimeDependence

// REQUIRES: swift_feature_LifetimeDependence
// REQUIRES: swift_feature_AddressableTypes

import ne_types

// Ensure no memory crashes during SILGen

struct NonEscapableFrameworkThingTests {
func example() async throws {
let ptr = UnsafeMutableRawBufferPointer.allocate(byteCount: 40, alignment: 1)
defer { ptr.deallocate() }
var something = Something(ptr: ptr)
var mutableView = something.mutableView(of: Float32.self)
var mutableSpan = mutableView.mutableSpan
}
}