Skip to content
This repository has been archived by the owner on Apr 5, 2024. It is now read-only.

container_of / offset_of #35

Closed
diwic opened this issue Oct 19, 2016 · 3 comments
Closed

container_of / offset_of #35

diwic opened this issue Oct 19, 2016 · 3 comments

Comments

@diwic
Copy link
Contributor

diwic commented Oct 19, 2016

There is some uncertainty about how to create a Rust version of container_of that is never UB, which is currently needed in order to create Arc::from_raw here: rust-lang/rust#37192

Since there is a warning in ptr.offset saying this:

Both the starting and resulting pointer must be either in bounds or one byte past the end of an 
allocated object. If either pointer is out of bounds or arithmetic overflow occurs then any further
use of the returned value will result in undefined behavior.

...the idea has come up to create a temporary object like this:

let t: T = mem::uninitialized(); // or mem::zeroed()
// do pointer arithmetic on t 
mem::forget(t);

...but this seems risky; in case do pointer arithmetic on t would panic for some unforeseen reason,
we'll try to drop an uninitialized object.

The other version is to start off with a null pointer, like this: https://github.com/alexcrichton/ctest/blob/2839e49847a6adca6e96cc81c46a1f03f8562ac0/src/lib.rs#L731 - but I'm not sure if that's better.

@Amanieu
Copy link
Member

Amanieu commented Oct 19, 2016

Originally I used a null pointer in my offset_of! macro, but after some discussion with @ubsan we decided that this can trigger UB because it creates a null reference.

@diwic
Copy link
Contributor Author

diwic commented Oct 19, 2016

Yeah, this seems hard to get right, that's why I wanted to bring it up in this context as well.
It would be good to have some "blessed" version of doing it - either in std or in some rust-lang-nursery crate.

@RalfJung
Copy link
Member

Closing as duplicate of #19, rust-lang/unsafe-code-guidelines#243.

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants