Skip to content

[SR-8878] Using Mirror to access a weak reference results in object being retained indefinitely #51384

@swift-ci

Description

@swift-ci
Previous ID SR-8878
Radar rdar://problem/44872927
Original Reporter abrindamour (JIRA User)
Type Bug
Status Resolved
Resolution Done

Attachment: Download

Environment

Xcode Version 10.0 (10A255)

Does NOT happen in Xcode 9.4 (9F1027a)

Additional Detail from JIRA
Votes 0
Component/s Standard Library
Labels Bug, 4.2Regression, Leak
Assignee @mikeash
Priority Medium

md5: f2e7d2b8f34cc831eb5f63c6de45d673

is duplicated by:

  • SR-9282 Weak variables in structs leak on String(describing:) or print
  • SR-9400 Mirror make memory leak if children access to IBOutlet

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.

Metadata

Metadata

Assignees

Labels

bugA deviation from expected or documented behavior. Also: expected but undesirable behavior.memory leakbug: Memory leakregressionstandard libraryArea: Standard library umbrellaswift 4.2

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions