[prev in list] [next in list] [prev in thread] [next in thread] 

List:       linux-hardening
Subject:    Re: replacing memcpy() calls with direct assignment
From:       Greg KH <gregkh () linuxfoundation ! org>
Date:       2022-06-21 20:43:11
Message-ID: YrItX5hVSdK6FCjv () kroah ! com
[Download RAW message or body]

On Tue, Jun 21, 2022 at 01:31:13PM -0700, Kees Cook wrote:
> On Tue, Jun 21, 2022 at 09:05:36PM +0200, Greg KH wrote:
> > On Tue, Jun 21, 2022 at 11:37:10AM -0700, Kees Cook wrote:
> > > Hello Coccinelle gurus! :)
> > > 
> > > I recently spent way too long looking at a weird bug in Clang that I
> > > eventually worked around by just replacing a memcpy() with a direct
> > > assignment. It really was very mechanical, and seems like it might be a
> > > common code pattern in the kernel. Swapping these would make the code
> > > much more readable, I think. Here's the example:
> > > 
> > > 
> > > https://lore.kernel.org/linux-hardening/20220616052312.292861-1-keescook@chromium.org/
> > > 
> > > -		memcpy(&host_image->image_section_info[i],
> > > -		       &fw_image->fw_section_info[i],
> > > -		       sizeof(struct fw_section_info_st));
> > > +		host_image->image_section_info[i] = fw_image->fw_section_info[i];
> > 
> > Ick, that hids the fact that you are doing a potentially huge memory
> > copy here.
> > 
> > And would it also prevent the compiler from using our optimized memcpy()
> > function and replacing it with whatever it wanted to use instead?
> 
> What? Uh, quite the reverse, in fact. The compiler is MUCH better about
> doing those kinds of optimizations. The commit log details that there's
> no binary difference, in fact, with this change.

Ah, so we are telling gcc to use our memcpy() implementations then,
otherwise it could use floating point for built-in things like this
without us knowing it.

So it's not an optimization either way.

> > What clang bug does this fix such that it warrants us hiding this
> > information away from the developers?
> 
> Hiding? This makes the code significantly more clear. Doing an assignment
> makes it clear they're the same type, etc, etc. Obscuring all that with
> a memcpy() makes no sense.

Doing a huge memory copy with a simple '=' assignment does have the
potential to hide things.  Yes, memory copies are so fast it's not even
funny these days, but it's like our use of typedef, we don't use it
because it makes it easier to hide what is really happening.

So do we want to hide this type of thing?  I vote no, but hey, this
isn't the part of the kernel that I maintain :)

thanks,

greg k-h
[prev in list] [next in list] [prev in thread] [next in thread] 

Configure | About | News | Add a list | Sponsored by KoreLogic