This is the mail archive of the
newlib@sourceware.org
mailing list for the newlib project.
Re: Bug in MIPS strncpy
Perry McFarlane wrote:
I found a bug in the MIPS-optimized strncpy
(newlib/libc/machine/mips/strncpy.c)
There is an unrolled loop to read from the source string 4 bytes at a
time, but this could read past the \0 and cause a SEGV.
The MIPS-optimized strncpy was added as part of this patch:
http://sourceware.org/ml/newlib/2001/msg00594.html
I suppose that it could be fixed by only reading groups of 4 bytes that
are word-alligned.
I have created a patch.
-- Jeff J.
Index: strncpy.c
===================================================================
RCS file: /cvs/src/src/newlib/libc/machine/mips/strncpy.c,v
retrieving revision 1.1
diff -u -p -r1.1 strncpy.c
--- strncpy.c 11 Mar 2002 15:44:35 -0000 1.1
+++ strncpy.c 27 Jun 2008 19:45:29 -0000
@@ -82,6 +82,26 @@ strncpy (char *dst0, const char *src0, s
dst = (unsigned char *)dst0;
src = (unsigned const char *)src0;
+ /* Take care of any odd bytes in the source data because we
+ * want to unroll where we read ahead 2 or 4 bytes at a time and then
+ * check each byte for the null terminator. This can result in
+ * a segfault for the case where the source pointer is unaligned,
+ * the null terminator is in valid memory, but reading 2 or 4 bytes at a
+ * time blindly eventually goes outside of valid memory. */
+ while ((src & (UNROLL_FACTOR - 1)) != 0 && count > 0)
+ {
+ *dst++ = ch = *src++;
+ --count;
+ if (ch == '\0')
+ {
+ end = dst + count;
+ while (dst != end)
+ *dst++ = '\0';
+
+ return dst0;
+ }
+ }
+
if (__builtin_expect (count >= 4, 1))
{
odd_bytes = (count & (UNROLL_FACTOR - 1));