https://gcc.gnu.org/bugzilla/show_bug.cgi?id=114217

--- Comment #6 from Akihiko Odaki <akihiko.odaki at daynix dot com> ---
(In reply to Andrew Pinski from comment #4)
> https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/tree/
> include/asm-generic/unaligned.h?h=v6.7
> 
> is correct except it should not expose get_unaligned/put_unaligned since the
> undefined code happens way before.
> 
> The problem is with the btrfs code in btrfs_filldir:
> ```
> static int btrfs_filldir(void *addr, int entries, struct dir_context *ctx)
> {
>       while (entries--) {
>               struct dir_entry *entry = addr; /// THIS IS BROKEN and causes 
> the
> -fsanitize=alignment error
>               char *name = (char *)(entry + 1);
> 
>               ctx->pos = get_unaligned(&entry->offset);
>               if (!dir_emit(ctx, name, get_unaligned(&entry->name_len),
>                                        get_unaligned(&entry->ino),
>                                        get_unaligned(&entry->type)))
>                       return 1;
>               addr += sizeof(struct dir_entry) +
>                       get_unaligned(&entry->name_len);
>               ctx->pos++;
>       }
>       return 0;
> }
> ```
> 
> Added comment on where the error comes from. The get_unaligned macro really
> should not be used here. What should be used here is an unaligned version of
> `struct dir_entry` instead.

With looking at this comment, I did another experiment to see if it's specific
to struct members, 
Also, note that this behavior of UBSan is specific to struct members. Think of
the following functions:

u64 f2(u64 *offset)
{
    return get_unaligned(offset);
}

u64 g2(u64 *offset)
{
    return *offset;
}

f2() and g2() correspond to f() and g(). The only difference is that it does
not involve struct member access. Nevertheless, GCC changes its behavior and
doesn't emit alignment checks for f2().

If casting a pointer with a strict alignment requirement to one with a relaxed
alignment requirement doesn't relax the alignment requirement, UBSan should
emit an error for f2().

Reply via email to