RE: [PATCH v2 1/2] system_data_types.7: Add 'void *'

2020-10-02 Thread David Laight via Gcc
From: Alejandro Colomar
> Sent: 02 October 2020 09:25
>  > For 'void *' you should also mention that one cannot use arithmetic on
>  > void * pointers, so they're special in that way too.
> 
> Good suggestion!

Except that is a gcc extension that is allowed in the kernel.

>  > Also, you should
>  > warn that because one can convert from any pointer type to void * and
>  > then to any other pointer type, it's a deliberate hole in C's
>  > type-checking.
> 
> Also good.  I'll talk about generic function parameters for this.

That isn't what the C standard says at all.
What is says is that you can cast any data pointer to 'void *'
and then cast it back to the same type.

This matters because the compiler will 'remember' structure
alignment through 'void *' casts.
So you can't use memcpy() to copy from a potentially misaligned
(typed) pointer.

'void *' should only be used for structures that are 'a sequence of bytes'.
(eg things that look a bit like read() or write()).

David

-
Registered Address Lakeside, Bramley Road, Mount Farm, Milton Keynes, MK1 1PT, 
UK
Registration No: 1397386 (Wales)


RE: problems with memory allocation and the alignment check

2021-02-23 Thread David Laight via Gcc
> > > I just wrote this little program to demonstrate a possible flaw in both 
> > > malloc and calloc.
> > >
> > > If I allocate a the simplest memory region from main(), one out of three 
> > > optimization flags fail.
> > > If I allocate the same region from a function, three out of three 
> > > optimization flags fail.
> > >
> > > Does someone know if this really is a flaw, and if so, is it a gcc or a 
> > > kernel flaw?
> >
> > There is no flaw.  GCC (kernel, glibc) all assume unaligned accesses
> > on x86 will not cause an exception.
> 
> Is this just an assumption or more like a fact? I agree with you that byte 
> aligned is more or less the
> same as unaligned.

They require that such accesses don't cause an exception.

While the misaligned accesses are slightly slower (apart from locked accesses
that cross page boundaries) the cost of avoiding them is typically higher.

This is particularly true for functions like strlen() which are often
called for short strings.
Care does have to be taken to stop strlen() reading across a page boundary.

David

-
Registered Address Lakeside, Bramley Road, Mount Farm, Milton Keynes, MK1 1PT, 
UK
Registration No: 1397386 (Wales)