On Wed, Jun 26, 2024 at 05:33:55PM GMT, Paul Eggert wrote: > On 6/26/24 07:57, Bruno Haible wrote: > > Po Lu wrote: > > > I believe that the semantics of the POSIX specification of this GNU > > > function omit the implied guarantee that strnlen will never examine > > > bytes beyond the first null byte > > > > There is no such guarantee, not even implied. > > There seems to be some confusion here. Here's what POSIX.1-2024 says: > > "The strnlen() function shall compute the smaller of the number of bytes in > the array to which s points, not including any terminating NUL character, or > the value of the maxlen argument. The strnlen() function shall never examine > more than maxlen bytes of the array pointed to by s."
Revisiting this again after today's Austin Group meeting. As mentioned before, the POSIX 2024 wording is known to be buggy (https://austingroupbugs.net/view.php?id=1834) and we want to coordinate with the C committee since they are considering standardizing strnlen(). But based on today's discussion, it was pointed out that... > > This means it's OK to call strnlen ("", SIZE_MAX), because the second arg of > strnlen can be larger than the number of bytes in the byte array that the > first arg points to, so long as that array contains a null byte. strnlen is > unusual in this sense. > > In contrast, it's not OK to call memchr ("", 0, SIZE_MAX). ...this claim appears to be unsupported. Both C23 and POSIX 2024 state that memchr() "...shall behave as if it reads the characters sequentially and stops as soon as a matching character is found", meaning that this should ALWAYS return the address of "" and not NULL. The Austin Group is hoping that the next draft of N3252 will add a similar guarantee of linear access to strnlen("", SIZE_MAX), so that it will be well-defined to stop early as you desire (rather than the current POSIX 2024 wording where access beyond the end of the string but within the size limit is not forbidden, and thereby risks a crash if size is large enough to cross memory boundaries when coupled with an implementation that does not behave as-if it reads linearly) -- Eric Blake, Principal Software Engineer Red Hat, Inc. Virtualization: qemu.org | libguestfs.org