warning: cast increases required alignment of target type

Warner Losh imp at bsdimp.com
Tue Aug 28 13:31:55 UTC 2012


On Aug 28, 2012, at 7:28 AM, Konstantin Belousov wrote:

> On Tue, Aug 28, 2012 at 07:12:15AM -0600, Warner Losh wrote:
>> 
>> On Aug 28, 2012, at 2:57 AM, Andrey Zonov wrote:
>> 
>>> Hi,
>>> 
>>> Does anyone know how to correctly fix this warning for
>>> arm/ia64/mips/sparc64?
>>> 
>>> usr.bin/elf2aout/elf2aout.c: In function 'main':
>>> usr.bin/elf2aout/elf2aout.c:129: warning: cast increases required
>>> alignment of target type
>>> 
>>> I found this explanation from bde, but still don't understand how to
>>> correctly fix this issue.
>>> 
>>> ------------------------------------------------------------------------
>>> r99799 | bde | 2002-07-11 22:06:09 +0400 (Thu, 11 Jul 2002) | 10 lines
>>> 
>>> Set NO_WERROR to ignore the following warning which is emitted on
>>> alphas:
>>>   .../elf2aout.c:130: warning: cast increases required alignment of
>>>   target type
>>> The warning is about casting ((char *)e + phoff) to a struct pointer,
>>> where e is aligned but phoff might be garbage, so I think the warning
>>> should be emitted on most machines (even on i386's, alignment checking
>>> might be on) and the correct fix would involve validation phoff before
>>> using it.
>>> 
>>> Is this fix correct?
>> 
>> No. You need to tell the compiler that e has the alignment you think
>> it has so that it can check to make sure that you are actually right.
>> Just casting like this defeats the purpose of the check and will break
>> on other architectures.
> 
> Does compiler ever checks the alignment ? I thought that it is hardware that
> performs (transparent) checks, like elfags.AC bit on x86.

Yes. Hence the warning.  The hardware does *NOT* transparently fix misaligned accesses, which causes core dumps which is why this warning is in place.

> IMO hardware checks are good enough, since having program headers
> not aligned as required by ELF standard/ABI means that incoming ELF file
> is corrupted.

It is alignment in the source code.  Telling the compiler about these alignments is what I'm suggesting.

> Note that the same code is present in
> libexec/rtld-elf/map_object.c:map_object(), and there it might indeed
> make sense to introduce manual check for the alignment, to avoid hw
> triggering trap. Instead, rtld could gracefully refuse to load the
> mis-formed object.

In the rtld case, we should know if things are properly aligned or not as part of the ABI.  A check wouldn't hurt too much, but it is done at every program execution and too many sanity checks that are never happens can cause performance hits.

Warner


More information about the freebsd-arch mailing list