Re: Usage of strncpy in the kernel

RVP <[email protected]>
Newsgroups gmane.os.netbsd.devel.kernel
Message-ID <[email protected]>
On Wed, 8 Jan 2025, Martin Husemann wrote:

> Indeed, and also they can't be dead stores in the context this came up
> because we copyout() the result (or the (non-)initialized parts would not
> leak to userspace.
>

Right, but, I thought had drifted to discussing str{n,l}cpy()... :)

Anyway, just to show what modern compilers can do now:

DSE is not the only optimization that could happen. The compiler can do other
transformations. For example, substituting in-line, equivalent code, and so
eliminating calls to the standard library functions:

```
$ cc --version
cc (Ubuntu 13.3.0-6ubuntu2~24.04) 13.3.0
Copyright (C) 2023 Free Software Foundation, Inc.
This is free software; see the source for copying conditions.  There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

$ cat s.c
#include <stdio.h>
#include <string.h>

int main(void) {
 	char buf[233];

 	strncpy(buf, "hello, world", sizeof buf);
 	printf("%s\n", buf);
 	return 0;
}
$ cc -O2 -march=native -S s.c 
$ egrep 'strncpy|printf' s.s
$
```

You can see what GCC's done here (this being almost a textbook optimization
case for it: small code; auto var.; constant string):

- Created a 256 byte stack.
- At compile-time, converted "hello, world" into a number (see hex).
- Copied this number onto the stack using AVX instructions.
- Zero-filled the rest of stack using the same.
and
- Substituted puts() for the printf() in the code.


We've seen GCC doing this sort of thing before on the list:
https://mail-index.netbsd.org/tech-userlevel/2024/09/15/msg014402.html

-RVP
lmpx.com only provides a reader for public news (NNTP) servers. It is not affiliated with the servers or forums shown here and is not responsible for the content of articles, which is written by their respective authors.