Skip to content

Warn when casts do no preserve qualifiers (-Wcast-qual) #10177

@jcarrano

Description

@jcarrano

Description

With the compiler options we are using now, explicit casts that discard a qualifier (like volatile or const) do not trigger a warning.

I propose to enable these warnings by adding the compiler flag -Wcast-qual.

I tried compiling a couple of simple examples to see how feasible it is and I found I found several violations. Some of them are in the kernel. That does not mean the kernel is buggy, read below.

Kernel

Before somebody says "we could disable this warning for stuff in /core". Yes, but we could also fix it, and in any case, the core is the most critical part, so we better have lots of checks there.

The kernel defines some stuff, like sched_active_thread as volatile, because the active thread can change at any moment.

Of course, when the kernel is running the thread is not changing because it is the kernel who changes threads, so in that situation it is "ok" to discard the qualifier.

I'd argue, however, that it is not that "it's ok to discard the qualifier", but rather that "in that situation the variable is not const". The hard part is how we explain that to the compiler.

containerof

When using GCC containerof is defined as:

#   define container_of(PTR, TYPE, MEMBER) \
        (__extension__ ({ \
            __extension__ const __typeof__ (((TYPE *) 0)->MEMBER) *__m____ = (PTR); \
            ((TYPE *) ((char *) __m____ - offsetof(TYPE, MEMBER))); \
        }))

Why is that const there? Is it necessary?

Other code

Do a WERROR=0 CFLAGS=-Wcast-qual make and you will see a number of violations, most of them discarding const.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Area: toolchainArea: toolchains; everything related to compilation, libc, linking, …State: staleState: The issue / PR has no activity for >185 daysType: enhancementThe issue suggests enhanceable parts / The PR enhances parts of the codebase / documentation

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions