open-telemetry / opentelemetry-swift

OpenTelemetry API for Swift
https://opentelemetry.io/docs/instrumentation/swift/
Apache License 2.0
207 stars 124 forks source link

Potential memory leak in ActivityContextManager #550

Closed atreat closed 4 weeks ago

atreat commented 1 month ago

There is concern over the use of using an UnsafeMutablePointer in the ActivityContextManager to hold a references to the #dsohandle

https://github.com/open-telemetry/opentelemetry-swift/blob/5429db445e2c8b6de4ff779f9db497c78b156397/Sources/OpenTelemetryApi/Context/ActivityContextManager.swift#L62

This pointer is never deallocated.


Initial investigation has not shown that this a cause of a memory leak but optimizations can be made to hold this reference statically so we don't create a new pointer with each call to the createActivityContext method.

atreat commented 4 weeks ago

Here's the method in full:

    func createActivityContext() -> (os_activity_id_t, os_activity_scope_state_s) {
        let dso = UnsafeMutableRawPointer(mutating: #dsohandle)
        let activity = _os_activity_create(dso, "ActivityContext", OS_ACTIVITY_CURRENT, OS_ACTIVITY_FLAG_DEFAULT)
        let currentActivityId = os_activity_get_identifier(activity, nil)
        var activityState = os_activity_scope_state_s()
        os_activity_scope_enter(activity, &activityState)
        return (currentActivityId, activityState)
    }

#dsohandle is a [Swift macro](https://developer.apple.com/documentation/swift/dsohandle()) that points at memory managed by the system.

When the createActivityContext creates the dso variable it creates an UnsafeMutableRawPointer that matches the underlying UnsafeRawPointer that #dsohandle returns. This variable is added to the stack as it has local scope to this function. When the function exits, this pointer will be removed from the stack.

This function is not allocating any memory when it retrieves a pointer to the dsohandle. It simply is referencing memory that is allocated by the system. We cannot/should not try to deallocate the memory at address where the #dsohandle points.