[SR-8878] Using Mirror to access a weak reference results in object being retained indefinitely #51384
Labels
bug
A deviation from expected or documented behavior. Also: expected but undesirable behavior.
memory leak
bug: Memory leak
regression
standard library
Area: Standard library umbrella
swift 4.2
Attachment: Download
Environment
Xcode Version 10.0 (10A255)
Does NOT happen in Xcode 9.4 (9F1027a)
Additional Detail from JIRA
md5: f2e7d2b8f34cc831eb5f63c6de45d673
is duplicated by:
Issue Description:
Please see attached example file "Bug.swift". This file creates an object "WeakHolderObject" which has a weak reference to another object, "AnObject" via the field "weakObject". A Mirror is then used to access the "weakObject" field. All of this is done in an autoreleasepool so that all memory should be released when the pool ends. However, when run in Xcode 10, "AnObject" is not deallocated and is retained indefinitely. Removing the Mirror operation OR running in Xcode 9.4 prevents this problem from occurring.
An additional trickier effect of this can be seen in "Bug2.swift" which is very similar, but we add a 2nd field "anotherField" to "WeakHolderObject" which is declared after the first field, and try to access that with a mirror instead. This still causes "AnObject" to not be deallocated. However, if you reorder the field declarations so that "anotherField" is declared first, then the problem does not occur.
This issue causes "Heisenbugs" in which just looking at an object's state can cause memory retention, which then can affect program correctness. In my company's application, we use Mirror to create a state dump when a user reports an issue. As a result of this, the act of reporting a bug can cause more bugs!
Steps to Reproduce
Run the attached examples "Bug.swift" and "Bug2.swift" in Xcode10.
Expected Results
Both examples should print "Released"
Actual Results
Both examples instead print "Retained". As noted above, running these examples in Xcode 9.4 produce expected results.
The text was updated successfully, but these errors were encountered: