Re: [PATCH v2] docs: deprecated.rst: Clarify open-coded arithmetic with literals

From: Len Baker
Date: Sat Sep 18 2021 - 05:11:59 EST


Hi,

On Tue, Sep 14, 2021 at 03:07:00PM -0600, Jonathan Corbet wrote:
> Len Baker <len.baker@xxxxxxx> writes:
>
> > Although using literals for size calculation in allocator arguments may
> > be harmless due to compiler warnings in case of overflows, it is better
> > to refactor the code to avoid the use of open-coded math idiom.
> >
> > So, clarify the preferred way in these cases.
> >
> > Suggested-by: Kees Cook <keescook@xxxxxxxxxxxx>
> > Signed-off-by: Len Baker <len.baker@xxxxxxx>
> > ---
> > Changelog v1 -> v2
> > - Clarify the sentence by changing "keep <foo> out" with "avoid <foo>"
> > (Joe Perches).
> >
> > Documentation/process/deprecated.rst | 3 ++-
> > 1 file changed, 2 insertions(+), 1 deletion(-)
> >
> > diff --git a/Documentation/process/deprecated.rst b/Documentation/process/deprecated.rst
> > index 9d83b8db8874..b5a8be914178 100644
> > --- a/Documentation/process/deprecated.rst
> > +++ b/Documentation/process/deprecated.rst
> > @@ -60,7 +60,8 @@ smaller allocation being made than the caller was expecting. Using those
> > allocations could lead to linear overflows of heap memory and other
> > misbehaviors. (One exception to this is literal values where the compiler
> > can warn if they might overflow. Though using literals for arguments as
> > -suggested below is also harmless.)
> > +suggested below is also harmless. So, the preferred way in these cases is
> > +to refactor the code to avoid the open-coded math idiom.)
>
> Sorry for being so slow to get to this...

Don't worry.

> honestly, though, I've been
> staring at it for a bit and cannot figure out what you are trying to
> communicate. What does "math idiom" mean here? If you are trying to
> say that using literals is *not* harmless, then perhaps the first part
> of the parenthetical should be taken out?
>
> Confused...

The "open-coded arithmetic in allocator arguments" section in the documentation
explains that dynamic syze calculations should not be performed in memory
allocator function arguments. Then, the text in parenthesis explains an
exception to this rule: when the calculus is made using literals for all the
operands. However, the text in parenthesis also tells that using the same
literals in the recommended helpers or purpose specific functions is harmless.

So, there are two options for size calculations using literals:

1.- Leave it as is.
2.- Refactor the code to use purpose specific functions or helpers.

What I try to explain with this patch is that when the calculus is done using
only literals, the preferred way is the second option. In this manner the
open-coded calulation (multiplication, addition, ...) is avoided.

The "math idiom" refers to the open-coded arithmetic.

I hope this clarify things a bit.

Regards,
Len