How do closures work (memory management)

Hello,

thanks for the reply! :slight_smile:

I have the general idea how the “Closure” variable may look like. I have based much of my research on The Swift Runtime: Heap Objects // -dealloc and responses and threads mentioned in Hacking Swift runtime.

I have hooked a function into void * _swift_retain(void *) and I use functions like swift_OpaqueSumary (swift/ReflectionMirror.cpp at 2c920c932a55f9ebecc4bb12764d03a0be704569 · apple/swift · GitHub) (and others) to inspect each retained heap object.

I can observe only null values (which are all instances of a class, for example __StringStorage) and Heap local variable. But I was unable to confirm nor deny, that the Heap local variable values are in fact closure contexts.

Therefore I am currently working with three possibilities:
a) The closure context is in fact Heap local variable and I need to find a proof
b) The closure context is not the Heap local variable and since no other retain is performed, Swift does not perform _swift_retain in order to reference count closure context
c) Somehow I have failed to create an escaping closure and closures were optimized as a part of guaranteed optimizations (I know exists, but I have no understanding of).

1 Like