[PATCH 1/1] string: Add stpecpy(3)
Wilco Dijkstra
Wilco.Dijkstra@arm.com
Fri Dec 23 14:59:20 GMT 2022
Hi Alex,
>> Given strlcpy and strlcat are in POSIX next and therefore bar
>> some extraordinary event will be in glibc, I think we should
>> probably wait until those two land, then see if there's still
>> an appetite for stpecpy in glibc.
>
> I disagree for the following reasons.
>
> strlcpy(3)/strlcat(3) are designed to be _slow_, in exchange for added
> simplicity and safety. That's what Theo told me about them. They didn't care
> about performance. The two performance issues are:
We'd need actual benchmarks to confirm there is a detectable performance
difference in typical scenarios. So calling strlcpy slow is premature. Looking
at the proposed stpecpy, it seems it has a lot more branches and special cases
compared to a typical strlcpy, and that adds extra overhead. Using memccpy
is risky too since that is often not optimized.
> - Traverse the entire input string, to make sure it's a string. stpecpy(3)
> instead only reads what's necessary for the copy; it stops reading after truncation.
Almost all strings are short and few cases need truncation, so I don't see the issue.
People concerned about performance wouldn't use the standard string functions
anyway.
> - strlcat(3) finds the terminating null byte; that's something you already know
> where it is, with functions that return a useful pointer (mempcpy(3), stpcpy(3),
> and stpecpy(3)).
If you know the end of the destination string then don't use concatenation. Easy!
In fact compilers could inline the 'dest += strlen (dest)' part of strcat and call
strcpy instead. This allows optimization of the strlen in case you know the size
of the destination string. This is true for strlcpy too, a compiler could just inline
it and optimize the strlen (src).
> The reason that triggered me wanting to add this function is seeing strncpy(3)
> used for a patch to some glibc internals themselves. Using strlcpy(3)/cat(3) in
> glibc internals would be bad for performance; I would hope that glibc uses the
> optimal internals, even if it also provides slow functions for users.
Most internal uses are unlikely to be performance critical, and correctness is kind
of important for libraries.
IMHO inventing many slightly different non-standard string functions is what
causes performance and correctness issues. People disagree about the semantics
(strlcpy has been argued over for a decade or so). Even if a library supports them,
you never know which implementations are actually well optimized (obviously
this varies between ISA and different libc's). So which non-standard string function
is safe to use across all targets and libraries?
In contrast we can be pretty sure that the standard strlen, memcpy etc are both
correct and efficient on all targets/libc's.
Cheers,
Wilco
More information about the Libc-alpha
mailing list