say i have some hardware mmio structure, that has two fields for a pointer, hi and lo

is it defined behavior in c to:
cast my pointer to uintptr_t
split it and assign across those two fields

and later in another function:
bitwise join the two fields in a uintptr_t
cast the result back to the original pointer type that i've allocated beforehand

since the value representation should be the same after rebuilding the uintptr, and uintptr is defined as surviving roundtrips, i think it's all good?

@navi Yes, these are the things which uintptr is for. (I have heard the absurd claim that because the standard only says that the pointer converted back compares equal, it is not guaranteed that you can actually use it. TS 6010 would have made it clearly legal.)

@uecker @navi This definitely will not work under CHERI, but the C standard isn't really written to support environments like CHERI, and obviously there would be significant disadvantages to doing so.

A different thing you can do with uintptr_t, one which doesn't require this kind of round-trip, is to write a portable implementation of a function like memmove. It isn't needed to write memmove itself, because you can just call the standard memmove, but it turns out to be helpful for things like bitblt.

@xentrac @navi I don't see how you can use it to implement memmove. uintptr_t could work also in CHERI, but not in the way they implemented it as a capability-carrying fake pointer type.

Follow

@uecker @navi Oh, well, the difficult part of memmove is that if the destination pointer points into the same array or aggregate object as the source pointer, but further down, you need to copy starting at the end and moving toward the beginning. But comparing unrelated pointers is undefined behavior (§6.5.8 of the ISO 9899:202x draft at open-std.org/jtc1/sc22/wg14/ww) and so you really, really don't want to do that as the first step in your memmove.

However, uintptr_t allows you to do the comparison safely.

Sign in to participate in the conversation
CleverLibre Social

CleverLibre Social is an inclusive social instance for open discussion, learning, and community.
All cultures welcome.
Hate speech and harassment strictly forbidden.