[PATCH 2/2] sha1/sha256: use be32_to_cpu and cpu_to_be32

Sascha Hauer s.hauer at pengutronix.de
Fri Sep 24 07:15:12 EDT 2010


On Fri, Sep 24, 2010 at 01:00:45PM +0200, Jean-Christophe PLAGNIOL-VILLARD wrote:
> > >>>>-	    | ( (uint32_t) (b)[(i) + 3]       );	\
> > >>>>-}
> > >>>>-#endif
> > >>>>-
> > >>>>-#ifndef PUT_UINT32_BE
> > >>>>-#define PUT_UINT32_BE(n,b,i) {				\
> > >>>>-	(b)[(i)    ] = (unsigned char) ( (n)>>   24 );	\
> > >>>>-	(b)[(i) + 1] = (unsigned char) ( (n)>>   16 );	\
> > >>>>-	(b)[(i) + 2] = (unsigned char) ( (n)>>    8 );	\
> > >>>>-	(b)[(i) + 3] = (unsigned char) ( (n)       );	\
> > >>>>-}
> > >>>>-#endif
> > >>>>+#define GET_UINT32_BE(n,b,i) (n) = be32_to_cpu(((uint32_t*)(b))[i / 4])
> > >>>>+#define PUT_UINT32_BE(n,b,i) ((uint32_t*)(b))[i / 4] = cpu_to_be32(n)
> > >>>>
> > >>>>
> > >>>
> > >>>The previous macros served two purposes: endian swapping and performing
> > >>>the memory accesses byte-by-byte. New versions are unsafe for CPUs which
> > >>>do not support misaligned 32bit memory accesses.
> > >>
> > >>Indeed. We have get_unaligned_be32() / put_unaligned_be32(). These should be
> > >>the correct functions, right?
> > >
> > >no-nned IIRC as be32_to_cpu and cpu_to_be32 already handle this
> > >depending on the arch
> > >
> > 
> > I think get_unaligned_be32() / put_unaligned_be32() are correct in
> > this case. be32_to_cpu / cpu_to_be32 perform endian swapping (if
> > required) with source and destination both being 32bit variables,
> > not memory locations ?
> no the arch have to handle this

No. As Andre mentioned cpu_to_be32 operates on variables, not on
pointers. with ((uint32_t*)(b))[i / 4] you cast b to a pointer to
uint32_t which you dereference with [i / 4]. This has nothing to do
with cpu_to_be32 and will crash if the architecture does not allow
unaligned accesses.

Sascha


-- 
Pengutronix e.K.                           |                             |
Industrial Linux Solutions                 | http://www.pengutronix.de/  |
Peiner Str. 6-8, 31137 Hildesheim, Germany | Phone: +49-5121-206917-0    |
Amtsgericht Hildesheim, HRA 2686           | Fax:   +49-5121-206917-5555 |



More information about the barebox mailing list