Re: [PATCH 0/10] Use ARRAY_SIZE macro - v4.13-rc7

From: Joe Perches
Date: Sun Sep 03 2017 - 16:20:47 EST


On Sun, 2017-09-03 at 21:59 +0200, Thomas Meyer wrote:
> On Sun, Sep 03, 2017 at 08:36:02AM -0700, Joe Perches wrote:
> > On Sun, 2017-09-03 at 14:19 +0200, Thomas Meyer wrote:
> > > Use ARRAY_SIZE macro, rather than explicitly coding some variant of it
> > > yourself.
> > >
> > > Found with: find -type f -name "*.c" -o -name "*.h" | xargs perl -p -i -e
> > > 's/\bsizeof\s*\(\s*(\w+)\s*\)\s*\ /\s*sizeof\s*\(\s*\1\s*\[\s*0\s*\]\s*\)
> > > /ARRAY_SIZE(\1)/g' and manual check/verification.
> >
> > Hey Thomas.
>
> Hi Joe,
> >
> > There are some instances that span multiple lines that
> > the regex above misses.
> >
> > For instance:
> >
> > diff --git a/drivers/infiniband/hw/mlx5/odp.c b/drivers/infiniband/hw/mlx5/odp.c
> > index 3d701c7a4c91..26a825bd7581 100644
> > --- a/drivers/infiniband/hw/mlx5/odp.c
> > +++ b/drivers/infiniband/hw/mlx5/odp.c
> > @@ -929,8 +929,7 @@ static int mlx5_ib_mr_initiator_pfault_handler(
> >                 return -EFAULT;
> >         }
> >  
> > -       if (unlikely(opcode >= sizeof(mlx5_ib_odp_opcode_cap) /
> > -           sizeof(mlx5_ib_odp_opcode_cap[0]) ||
> > +       if (unlikely(opcode >= ARRAY_SIZE(mlx5_ib_odp_opcode_cap) ||
> >
> > Here is another perl command regex that fixes a few more:
> >
> > $ perl -i -e 'local $/; while (<>) { s/\bsizeof\s*\(\s*(\w+)\s*\)\s*\/\s*sizeof\s*\(\s*\1\s*\[\s*0\s*\]\s*\)/ARRAY_SIZE(\1)/g; print; }' $file
> >
> > This regex could still miss variants that
> > have a comment or that don't use parentheses
> > around the sizeof.
>
> Okay, fine, but I think this patch series is okay to go in anyway. I will
> re-run with above regex after the next rcX tag. Would that be fine for you?
> What do you think?

I think whatever you want to do is fine with me.

If you want, you could use the simple cocci script below
which is _much_ better than the perl regex as it can
find all the appropriate cases not just
sizeof(var)/sizeof(var[0])

$ cat array_size.cocci
@@
type T;
T[] E;
@@

(
- sizeof(E) /sizeof(*E)
+ ARRAY_SIZE(E)
|
- sizeof(E) /sizeof(E[...])
+ ARRAY_SIZE(E)
|
- sizeof(E) /sizeof(T)
+ ARRAY_SIZE(E)
)
$

and maybe this

$ spatch --in-place --all-includes --sp-file array_size.cocci .