Re: [PATCH] sched/fair: Replace zero-length array with flexible-array member

From: Joe Perches
Date: Thu Feb 13 2020 - 21:06:36 EST


On Fri, 2020-02-14 at 00:25 +0000, Valentin Schneider wrote:
> On 13/02/2020 22:02, Joe Perches wrote:
> > That might be a somewhat difficult thing to add to checkpatch
> > as it is effectively a per-line scanner:
> >
> > Try something like:
> >
> > $ git grep -P -A1 '^\s*(?!return)(\w+\s+){1,3}\w+\[0\];' -- '*.[ch]'
> >
> > and look at the results.
> >
> > In checkpatch that could be something like:
> >
> > if ($line =~ /^.\s*$Type\s+$Ident\s*\[\s*0\s*\]\s*;/) {
> > warn...
> > }
> >
>
> So FWIW I felt like doing some coccinelle and ended up with this:
>
> This patches up valid ZLAs:
> $ spatch -D patch zero_length_array.cocci kernel/sched/fair.c
>
> This prints out the location of invalid ZLAs:
> $ spatch -D report zero_length_array.cocci kernel/sched/fair.c
>
> ---
> virtual patch
> virtual report
>
> @valid_zla depends on patch@
> identifier struct_name;
> type T;
> identifier zla;
> position pos;
> @@
> struct struct_name {
> ...
> T zla@pos
> - [0];
> + [];
> };
>
> @invalid_zla depends on report@
> identifier struct_name;
> type T1;
> identifier zla;
> type T2;
> identifier tail;
> position pos;
> @@
> struct struct_name {
> ...
> T1 zla[0]@pos;
> T2 tail;
> ...
> };
>
> @script:python depends on invalid_zla@
> pos << invalid_zla.pos;
> @@
> coccilib.report.print_report(pos[0], "Invalid ZLA!");
> ---

Nice.
It would miss a few forms like:

typedef struct tagfoo {
...
type t[0];
} foo;

and

struct {
...
type t[0];
} foo;

and

struct foo {
...
type t[0];
} *foo;

etc...