Re: [RFC PATCH 3/4] selftests/binderfs: Macro argument 'fd' may be better as '(fd)' to avoid precedence issues

From: Bill Wendling
Date: Wed May 15 2024 - 14:33:19 EST


On Tue, May 14, 2024 at 6:08 PM Abhinav Saxena <xandfury@xxxxxxxxx> wrote:
>
> Change the macro argument 'fd' to '(fd)' to avoid potential precedence
> issues. Without parentheses, the macro expansion could lead to
> unexpected behavior when used with an expression having different
> precedence levels.
>
> Example Code:
>
> #define CALC_SQR_BAD(x) (x*x)
> #define CALC_SQR_GOOD(x) ((x)*(x))
>
> CALC_SQR_BAD(2+3) expands to 2+(3*3)+2, giving 11 as the incorrect
> answer. Enclosing with parathesis CALC_SQR_GOOD(2+3) sets the correct

s/parathesis/parentheses/

> order of precedence and expands to (2+3)*(2+3), giving 25 as the
> correct answer.
>
> Signed-off-by: Abhinav Saxena <xandfury@xxxxxxxxx>
> ---
> .../testing/selftests/filesystems/binderfs/binderfs_test.c | 6 +++---
> 1 file changed, 3 insertions(+), 3 deletions(-)
>
> diff --git a/tools/testing/selftests/filesystems/binderfs/binderfs_test.c b/tools/testing/selftests/filesystems/binderfs/binderfs_test.c
> index 4a149e3d4ba4..d5dba6c1e07f 100644
> --- a/tools/testing/selftests/filesystems/binderfs/binderfs_test.c
> +++ b/tools/testing/selftests/filesystems/binderfs/binderfs_test.c
> @@ -30,11 +30,11 @@
>
> #define close_prot_errno_disarm(fd) \
> do { \
> - if (fd >= 0) { \
> + if ((fd) >= 0) { \
> int _e_ = errno; \
> - close(fd); \
> + close((fd)); \
> errno = _e_; \
> - fd = -EBADF; \
> + (fd) = -EBADF; \

While I agree that it's generally good to add parentheses in macros,
this line ensures that 'fd' must be an lvalue and not an arithmetic
expression.

-bw

> } \
> } while (false)
>
> --
> 2.34.1
>