Thread (92 messages) 92 messages, 7 authors, 2021-08-11

Re: [PATCH 30/32] strlen.3, wcslen.3: Add recommendations for safer variants

From: Alejandro Colomar (man-pages) <hidden>
Date: 2021-08-08 00:04:45

Hi, Michael!

On 8/8/21 1:45 AM, Michael Kerrisk (man-pages) wrote:
Hello Alex,

I see there was a rather long mail thread that led
to this patch. The patch definitely deserves a commit
message.
Maybe this:

[
strlen() is normally used as a first step
in a series involving usage of strings.

However, if the input string can possibly not include a terminating null
byte '\0', it's safer to use strnlen().

Since there's not much overhead,
and the compiler might already optimize some cases
where it knows it can use strlen(),
it's probably wise to recommend strnlen() over strlen(),
and be on the safe side, to avoid bugs.

Code coud even be safe in the present,
but in the future start using non-terminated strings
and then introduce a bug, if strlen() is used.
]

See also below.
On 7/28/21 10:20 PM, Alejandro Colomar wrote:
quoted
Reported-by: Jonny Grant <redacted>
Signed-off-by: Alejandro Colomar <redacted>
---
 man3/strlen.3 | 6 ++++++
 man3/wcslen.3 | 9 ++++++++-
 2 files changed, 14 insertions(+), 1 deletion(-)
diff --git a/man3/strlen.3 b/man3/strlen.3
index dea4c1050..78783c446 100644
--- a/man3/strlen.3
+++ b/man3/strlen.3
@@ -66,6 +66,12 @@ T}	Thread safety	MT-Safe
 .sp 1
 .SH CONFORMING TO
 POSIX.1-2001, POSIX.1-2008, C89, C99, C11, SVr4, 4.3BSD.
+.SH NOTES
+.SS strnlen(3)
+If the input buffer size is known,
+it is probably better to use
+.BR strnlen (3),
+which can prevent reading past the end of the array.
I hesitate slightly about this. strlen() is in the C standard, but
strnlen() is not. What do you think; do we need to care?
I think POSIX.1-2008 is enough of a standard.  Don't you?


Cheers,

Alex
quoted
 .SH SEE ALSO
 .BR string (3),
 .BR strnlen (3),
diff --git a/man3/wcslen.3 b/man3/wcslen.3
index af3fcb9ca..fe1d6331b 100644
--- a/man3/wcslen.3
+++ b/man3/wcslen.3
@@ -58,5 +58,12 @@ T}	Thread safety	MT-Safe
 .sp 1
 .SH CONFORMING TO
 POSIX.1-2001, POSIX.1-2008, C99.
+.SH NOTES
+.SS wcsnlen(3)
+If the input buffer size is known,
+it is probably better to use
+.BR wcsnlen (3),
+which can prevent reading past the end of the array.
 .SH SEE ALSO
-.BR strlen (3)
+.BR strlen (3),
+.BR wcsnlen (3)
-- 
Alejandro Colomar
Linux man-pages comaintainer; https://www.kernel.org/doc/man-pages/
http://www.alejandro-colomar.es/
Keyboard shortcuts
hback out one level
jnext message in thread
kprevious message in thread
ldrill in
Escclose help / fold thread tree
?toggle this help