Skip to content

[Runtime] Fatal error if self escapes from deinit. #62191

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

Merged
merged 1 commit into from
Dec 7, 2022
Merged
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
8 changes: 8 additions & 0 deletions stdlib/public/runtime/HeapObject.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -710,6 +710,13 @@ void swift::swift_rootObjCDealloc(HeapObject *self) {
void swift::swift_deallocClassInstance(HeapObject *object,
size_t allocatedSize,
size_t allocatedAlignMask) {
size_t retainCount = swift_retainCount(object);
if (SWIFT_UNLIKELY(retainCount > 1))
swift::fatalError(0,
"Object %p deallocated with retain count %zd, reference "
"may have escaped from deinit.\n",
object, retainCount);

#if SWIFT_OBJC_INTEROP
// We need to let the ObjC runtime clean up any associated objects or weak
// references associated with this object.
Expand All @@ -718,6 +725,7 @@ void swift::swift_deallocClassInstance(HeapObject *object,
#else
const bool fastDeallocSupported = true;
#endif

if (!fastDeallocSupported || !object->refCounts.getPureSwiftDeallocation()) {
objc_destructInstance((id)object);
}
Expand Down
26 changes: 26 additions & 0 deletions test/Runtime/deinit_escape.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
// RUN: %target-run-simple-swift

// REQUIRES: executable_test
// UNSUPPORTED: use_os_stdlib
// UNSUPPORTED: back_deployment_runtime

import StdlibUnittest

var DeinitEscapeTestSuite = TestSuite("DeinitEscape")

var globalObjects: [AnyObject] = []

DeinitEscapeTestSuite.test("deinit escapes self") {
expectCrashLater()

class C {
deinit {
globalObjects.append(self)
}
}
_ = C()

expectUnreachable()
}

runAllTests()