p-x9 / AssociatedObject

🔗 Swift Macro for allowing variable declarations even in class extensions
MIT License
126 stars 3 forks source link

There may be a problem when other third-party framework use `get_return_address()`.... #39

Open mlch911 opened 5 months ago

mlch911 commented 5 months ago

I found the associated object will become nil after some time in Release mode. I definitely did not set it.

I can only assume there may be some other third-party framework which uses get_return_address() as their key as well. 🤣

p-x9 commented 5 months ago

get_return_address is actually a C macro that uses the __builtin_return_address function to obtain the return address of the function that called it.

https://github.com/p-x9/AssociatedObject/blob/18f87a7cb2b13145daf2a46f4cbacd59b63fc976/Sources/AssociatedObjectC/include/associated_object_key.h#L16

The AssociatedObject macro creates the following function that wraps this and generates a unique key.

@inline(never) 
static var __associated_intKey: UnsafeRawPointer {
  _associated_object_key()
}

If the function is expanded inline in a release build, the index passed to __builtin_return_address may be misaligned and uniqueness may not be preserved. I had set up an attribute to prevent this from happening, but it may not be working properly.

If the problem occurs only in RELEASE builds, then this is the most likely cause. However, if the problem also occurs in DEBUG builds, it is possible that the policy settings are incorrect.

mlch911 commented 5 months ago

get_return_address is actually a C macro that uses the __builtin_return_address function to obtain the return address of the function that called it.

https://github.com/p-x9/AssociatedObject/blob/18f87a7cb2b13145daf2a46f4cbacd59b63fc976/Sources/AssociatedObjectC/include/associated_object_key.h#L16

The AssociatedObject macro creates the following function that wraps this and generates a unique key.

@inline(never) 
static var __associated_intKey: UnsafeRawPointer {
  _associated_object_key()
}

If the function is expanded inline in a release build, the index passed to __builtin_return_address may be misaligned and uniqueness may not be preserved. I had set up an attribute to prevent this from happening, but it may not be working properly.

If the problem occurs only in RELEASE builds, then this is the most likely cause. However, if the problem also occurs in DEBUG builds, it is possible that the policy settings are incorrect.

It only occurs in RELEASE build.

p-x9 commented 5 months ago

Fixed Key generation method.

https://github.com/p-x9/AssociatedObject/releases/tag/0.10.3