Skip to content

Crashes due to race condition in swift bindings X.deinit vs X_copyFromCType/X_moveFromCType #1773

Description

@derolf

Let's look at gluecodium/src/test/resources/smoke/basic_types/output/swift/smoke/BasicTypes.swift as an example

smoke_BasicTypes_remove_swift_object_from_wrapper_cache(c_instance)

   deinit {
        smoke_BasicTypes_remove_swift_object_from_wrapper_cache(c_instance)   <--- HERE
        smoke_BasicTypes_release_handle(c_instance)
    }

if let swift_pointer = smoke_BasicTypes_get_swift_object_from_wrapper_cache(handle),

internal func BasicTypes_copyFromCType(_ handle: _baseRef) -> BasicTypes {
    if let swift_pointer = smoke_BasicTypes_get_swift_object_from_wrapper_cache(handle),   <--- HERE
        let re_constructed = Unmanaged<AnyObject>.fromOpaque(swift_pointer).takeUnretainedValue() as? BasicTypes {
        return re_constructed
    }
  • Thread A is just in deinit, but has not called smoke_BasicTypes_remove_swift_object_from_wrapper_cache yet, we have a dangling pointer to a dead swift object in the cache.
  • Thread B is just calling smoke_BasicTypes_get_swift_object_from_wrapper_cache at the same time and gets the dead swift object
  • Thread B will crash

To repro, have two threads doing:

  while true {
    // get some class from native side
    let foo = gluecodium.foo()
    // call some function on it 
    foo.bar()
    // foo.deinit() will now be called here due to ARC
  }

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions