Hi Michael! On 12/23/18 8:46 PM, Michael Cree wrote: >> static inline u64bits _ioa_ntoh64(u64bits v) >> { >> #if BYTE_ORDER == LITTLE_ENDIAN >> u08bits *src = (u08bits*) &v; >> u08bits* dst = src + 7; >> while (src < dst) { >> u08bits vdst = *dst; >> *(dst--) = *src; >> *(src++) = vdst; >> } >> #elif BYTE_ORDER == BIG_ENDIAN >> /* OK */ >> #else >> #error WRONG BYTE_ORDER SETTING >> #endif >> return v; >> } > > It's casting to a (unsigned) char pointer (assuming that is what > u08bits is typedefed to) and reading and writing through that. > A char can have any alignment so there is no alignment issue in > this code.
Hmm, good point. > The code above is an arsed-about-way of doing byte reversal. > On a register-based arch the code will force the argument passed > in a register to be written to the stack, byte order reversed by > reading and writing bytes, then re-reading from the stack to pass > back the result in the return register. That's assuming the > compiler isn't smart enough to work out what the the hell the > programmer intends; but if it is it might simplify it down to > register based logical and shift operations, thereby avoiding any > memory accesses. > > This suggestion is somewhat concerning: > >> The copying here needs to be done with memcpy(). > > Which will fail to reverse the order of bytes and thus break the > code. The code above is *not* doing a straight memory copy. Well, I have to admit I didn't read the code properly and using memcpy() is my go-to solution for this kind of problem. >> Just casting pointers >> and using plain assignment is a guarantee for unaligned access. > > Untrue. It is not a guarantee for unaligned access. There are > other conditions that must be met for the gaurantee, and I don't > see why the code above---despite being written by a neophyte--- > would cause unaligned accessess. Ok, "guarantee" is too much of a hard word. I just usually avoid these types of casts. But I think you are right because the type it's being cast to is an unsigned char which can have any alignment. Steve's analysis is probably more accurate than mine then, see [1]. Adrian > [1] https://bugs.debian.org/cgi-bin/bugreport.cgi?bug=916919#5 -- .''`. John Paul Adrian Glaubitz : :' : Debian Developer - glaub...@debian.org `. `' Freie Universitaet Berlin - glaub...@physik.fu-berlin.de `- GPG: 62FF 8A75 84E0 2956 9546 0006 7426 3B37 F5B5 F913