Boost logo

Boost :

From: Pavol Droba (droba_at_[hidden])
Date: 2002-11-25 08:46:24


On Sun, Nov 24, 2002 at 11:18:10PM +0100, Terje Sletteb? wrote:
> > On Sun, Nov 24, 2002 at 07:27:42PM +0100, Terje Sletteb? wrote:
> > > >From: "Pavol Droba" <droba_at_[hidden]>
> > > >
> > > > Reinterpret-cast could be avoided like this:
> > > >
> > > > template< typename T >
> > > > inline T* offset_cast( void* p, unsigned int offset=0 )
> > > > {
> > > > return static_cast<T*>(
> > > > static_cast< void* >( static_cast<unsigned char*> p )+offset )
> > > > );
> > > > }
> > >
> > > Yes, but that wouldn't make it any more safe, as it would still depend
> on
> > > the alignment requirements, etc. that you mention.
> >
> > Alignment dependency is quite natural here. I'm talking about analysis of
> binary data.
> > I don't see a way how to map a c-like structure onto binary data if you
> don't know what's
> > the bineary representation of the structure and if if does not match the
> required
> > pattern.
>
> What you say here is one of the aspects, the layout in the struct, and any
> internal padding (for internal alignment). However, that's not all. Even if
> you have the same alignment between the components in the struct, as in the
> buffer, you still have the "external alignment" to consider, that is, if the
> struct, in the buffer, starts at the right alignment. If the struct was
> written to the same buffer, then it will be correct. However, if the buffer
> is read from an external source, like a stream, then that is far from
> guaranteed.
>
> For example, if you have a buffer like this (starting at an aligned
> address):
>
> +0 - One byte
> +1 - Number 1
> +5 - Number 2
> +9 - Number 3
>
> Even if you have a struct with three 32-bit ints, no internal padding, if
> you try to map it to the above buffer (at offset 1), on a platform that
> requires 4-byte alignments for ints, it won't work.
>

I see your point now. I'have used offset_cast mostly on x86 platform where to
misalignment is tolerated. I have used it also on ARM processor and we have to
make some sort of special arrangements to make it work. For network strutures,
however it worked fine, because most of them are internaly aligned.

Anyway now I see that in the current implementation offset_cast is too dangerous
and unpredictable and so it is not usable for general purpose.

I have mentioned before, that binary analysis could be done also using a more
complicated framework. Would it make sense to create one?

Regards,

Pavol


Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk