Re: printing the values of arguments for strcpy(3), memmove(3), ...

John Reiser <[email protected]>
Newsgroups gmane.comp.debugging.valgrind
Message-ID <[email protected]>
> The reason was at the end of debugging that we replaced in some central
> place of the server a function call (due to vg messages about
> overlapping args)
> 
> 	strncpy(dst, src, n);
> 
> by
> 
> 	memset(dst, 0, n);
> 	memmove(dst, src, n);
> 
> which is not fully equivalent because strncpy(3) will stop at the first
> \0 byte in src, while memmove(3) will copy n bytes, regardles if they
> are valid bytes in src. As this was in some low level function, it
> generated a mass of the above vg messages.
[[snip]]
> Any thoughts about this?

You may have a much bigger problem than you realize.  Take paper
and pencil; write TEN TIMES (this is not a joke!):

      strncpy(dst, src, n) always over-writes exactly n bytes
      (namely dst[0..(n-1)]), regardless of strlen(src).

A large fraction of lexical calls to strncpy are incorrect;
the code just happens to work "by accident".

First, if there is any overlap between the intervals dst[0..(n-1)]
and src[0..(n-1)] then the result is undefined.  The implementation
of strncpy is allowed to read and write bytes in ANY order: lowest
index first, highest index first, single byte at a time, multiple
bytes at a time, interleaving Read and Write in any order (including
writing into the same byte multiple times, or writing an incorrect
value but correcting it later), etc.  Also, all str* functions are
allowed to fetch beyond src[1+ strlen(src)] as long as there can be
no SIGSEGV; and to store into dst[n] and beyond, as long as there is
no change there.  So any byte that is within the memory words or
cache lines that cover src[] or dst[] is fair game to be included
in a memory operation of strncpy.

Second, if (strlen(src) < n) then strncpy zeroes the remaining bytes
through dst[n-1].

Third, if (strlen(src) >= n) then dst is not NUL terminated.

Recommendation: search all the source code of all the projects
of your entire team/department/company for strncpy, and fix the bugs.

--
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.