Skip to content

Do not derive Clone/Copy/etc for opaque types #1656

New issue

Have a question about this project? # for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “#”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? # to your account

Open
VeaaC opened this issue Oct 24, 2019 · 2 comments · May be fixed by #3110
Open

Do not derive Clone/Copy/etc for opaque types #1656

VeaaC opened this issue Oct 24, 2019 · 2 comments · May be fixed by #3110

Comments

@VeaaC
Copy link
Contributor

VeaaC commented Oct 24, 2019

Currently bindgen will generate code that derives for opaque types, e.g.:

typedef struct MyOpaqueStruct MyOpaqueStruct;
#[derive(Copy, Clone, Debug)]
pub struct MyOpaqueStruct {
    _unused: [u8; 0],
}

This has several problems:

  • If a user can obtain a reference to a type they can clone it, even though that is normally only possible through FFI calls, and will almost always result in UB
  • It prevents a user from implementing those traits on their own

The only current solution seems to be to turn of those derivations completely, forcing a user to implement them manually on the non-opaque types.

I would suggest to just not derive any of these in case of an opaque struct (since I cannot come up with a use-case were they would actually work)

@emilio
Copy link
Contributor

emilio commented Oct 28, 2019

This makes sense... I can see a few cases where it'd work, but yeah, it's sketchy at best.

@jschwe
Copy link
Contributor

jschwe commented Feb 5, 2025

#[derive(Copy, Clone, Debug)]
pub struct MyOpaqueStruct {
    _unused: [u8; 0],
}

Probably worth mentioning that in the bindgen code, these are "forward declared types".
E.g. the opaque annotation does not cause bindgen to generate a struct like the above.

# for free to join this conversation on GitHub. Already have an account? # to comment
Projects
None yet
Development

Successfully merging a pull request may close this issue.

3 participants