Re: [PATCH v4] libbpf: Replace strncpy() with strnlen()+memcpy() in skel_map_create()

From: Alexei Starovoitov

Date: Fri Apr 03 2026 - 12:30:38 EST


On Fri, Apr 3, 2026 at 8:54 AM Kees Cook <kees@xxxxxxxxxx> wrote:
> > > - strncpy(attr.map_name, map_name, sizeof(attr.map_name));
> > > + /* attr.map_name must be NUL-terminated, like bpf_obj_name_cpy() */
> > > + map_name_len = strnlen(map_name, sizeof(attr.map_name));
> > > + if (map_name_len == sizeof(attr.map_name))
> > > + return -EINVAL;
> > > + memcpy(attr.map_name, map_name, map_name_len);
> >
> > this is plain ugly and inefficient.
> > Just #ifdef kernel and use strscpy in that branch.
>
> I think you're asking for:
>
> #ifdef __KERNEL__
> if (strscpy(attr.map_name, map_name) < 0)
> return -EINVAL;
> #else
> strncpy(attr.map_name, map_name, sizeof(attr.map_name));
> #endif
>
> Is that right?

yes.