[<prev] [next>] [<thread-prev] [thread-next>] [day] [month] [year] [list]
Message-ID: <CAH5fLgiPdBEN7mjgK64u19VGE_AWghTnCCHYuQQuwnTdvDaYkw@mail.gmail.com>
Date: Mon, 12 Jan 2026 12:20:43 +0100
From: Alice Ryhl <aliceryhl@...gle.com>
To: Fushuai Wang <fushuai.wang@...ux.dev>
Cc: akpm@...ux-foundation.org, bp@...en8.de, brauner@...nel.org,
cyphar@...har.com, dave.hansen@...ux.intel.com, hpa@...or.com, jack@...e.cz,
kees@...nel.org, linux-kernel@...r.kernel.org,
linux-trace-kernel@...r.kernel.org, luto@...nel.org,
mathieu.desnoyers@...icios.com, mhiramat@...nel.org, mingo@...hat.com,
peterz@...radead.org, rostedt@...dmis.org, tglx@...nel.org, vmalik@...hat.com,
wangfushuai@...du.com, x86@...nel.org, yury.norov@...il.com
Subject: Re: [PATCH v2 1/6] uaccess: Add copy_from_user_nul helper
On Mon, Jan 12, 2026 at 11:01 AM Fushuai Wang <fushuai.wang@...ux.dev> wrote:
>
> >> From: Fushuai Wang <wangfushuai@...du.com>
> >>
> >> Many places call copy_from_user() to copy a buffer from user space,
> >> and then manually add a NULL terminator to the destination buffer,
> >> e.g.:
> >>
> >> if (copy_from_user(dest, src, len))
> >> return -EFAULT;
> >> dest[len] = '\0';
> >>
> >> This is repetitive and error-prone. Add a copy_from_user_nul() helper to
> >> simplify such patterns. It copied n bytes from user space to kernel space,
> >> and NUL-terminates the destination buffer.
> >>
> >> Signed-off-by: Fushuai Wang <wangfushuai@...du.com>
> >
> > Hmm, this function is very very similar to strncpy_from_user(). Should
> > they be using that instead?
> >
> > Alice
>
> The strncpy_from_user() is for NUL-terminated strings and stops at the
> first NUL in userspace. But copy_from_user_nul() always copies a fixed length
> and adds a NUL at the end in kernel space, even if userspace data doesn’t
> contain a NUL.
>
> So I think they are for different cases and can’t replace each other.
strncpy_from_user() succeeds even if userspace data does not contain a
nul. Then it reads length bytes.
As far as I can tell, when a nul byte is present, none of these kernel
use-cases use data after the nul byte. So the behavior is identical
except that copy_from_user_nul() may result in EFAULT if there are
unmapped bytes between the first nul byte in `src` and `src+len`.
Alice
Powered by blists - more mailing lists