Re: [PATCH] x86: Fixes warning: cast removes address space '__user' of expression in uaccess_64.h

From: Dmitry Torokhov
Date: Wed Jan 24 2024 - 01:08:40 EST


On Fri, Nov 17, 2023 at 07:19:12AM -0800, Dave Hansen wrote:
> On 11/16/23 09:38, Dipendra Khadka wrote:
> > Sparse has identified a warning as follows:
> >
> > ./arch/x86/include/asm/uaccess_64.h:88:24: warning: cast removes address space '__user' of expression.
> >
> > Since the valid_user_address(x) macro implicitly casts the argument
> > to long and compares the converted value of x to zero, casting ptr
> > to unsigned long has no functional impact and does not trigger a
> > Sparse warning either.
>
> Why does sparse complain about a cast to 'long' but not 'unsigned long'?
> Both remove the '__user' address space from the expression. Were there
> just so many __user pointers being cast to 'unsigned long' that there's
> an exception in sparse for 'void __user *' => 'unsigned long'?

Yes, unsigned long is special:

commit 7816e4c4a2dba6fef24c9a52c6b17a8cde0c8138
Author: Linus Torvalds <torvalds@xxxxxxxxxxxxxxx>
Date: Mon May 31 13:18:57 2004 -0700

Allow casting of user pointers to "unsigned long".

It's reasonably common to do special pointer arithmetic
in unsigned long, and making people force the cast just
adds noise.


I wonder if we should have:

#define valid_user_address(x) ((__force long)(x) >= 0)

or

#define valid_user_address(x) ((long)(unsigned long)(x) >= 0)

Thanks.

--
Dmitry