Skip to content

Assigning a non-nil value to a weak SWIFT_SHARED_REFERENCE variable crashes at runtime #83080

@maddyadams

Description

@maddyadams

Description

No response

Reproduction

struct SharedRef {
    static inline SharedRef*_Nonnull makeSharedRef() SWIFT_RETURNS_RETAINED {
        return new SharedRef();
    }
    
private:
    SharedRef() : _refCount(1) {}
    
    SharedRef(const SharedRef& other) = delete;
    SharedRef& operator=(const SharedRef& other) = delete;
    friend inline void retainSharedRef(SharedRef*_Nonnull x) {
        x->_refCount += 1;
    }
    friend inline void releaseSharedRef(SharedRef*_Nonnull x) {
        x->_refCount -= 1;
        if (x->_refCount == 0) {
            delete x;
        }
    }
    
    int _refCount;
} SWIFT_SHARED_REFERENCE(retainSharedRef, releaseSharedRef);
func foo() {
    weak var x: SharedRef?
    
    let y: SharedRef = SharedRef.makeSharedRef()
    x = y // runtime crash!
}

foo()

Stack dump

(lldb) bt
* thread #1, stop reason = EXC_BAD_ACCESS (code=1, address=0x20)
    frame #0: 0x00000001921143c8 libswiftCore.dylib`swift::WeakReference::unknownAssign(void*) + 72
    frame #1: 0x0000000192114370 libswiftCore.dylib`swift_unknownObjectWeakAssign + 24
  * frame #2: 0x0000000100000ca4 WeakFRTCrash`foo() at main.swift:16:7
    frame #3: 0x0000000100000bbc WeakFRTCrash`main at main.swift:19:1
    frame #4: 0x0000000180532b4c dyld`start + 6000

Expected behavior

I expected the runtime crash would not occur. (Using weak or unowned with SWIFT_SHARED_REFERENCE should probably be a compiler error, since I don't think there's a way for the Swift runtime to weakly hold C++ reference types, so this code should probably not compile at all.)

Environment

swift-driver version: 1.120.5 Apple Swift version 6.1 (swiftlang-6.1.0.110.21 clang-1700.0.13.3)
Target: arm64-apple-macosx15.0

Additional information

rdar://124040825

Metadata

Metadata

Assignees

Labels

bugA deviation from expected or documented behavior. Also: expected but undesirable behavior.c++ interopFeature: Interoperability with C++crashBug: A crash, i.e., an abnormal termination of software

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions