https://gcc.gnu.org/bugzilla/show_bug.cgi?id=87028

--- Comment #4 from Martin Sebor <msebor at gcc dot gnu.org> ---
The test case in pr84474 uses strncpy to needlessly exclude the terminating nul
from the copy only to then add it explicitly.  That's not what the function is
meant to be used for -- when it's safe to copy the whole string using strcpy is
more appropriate.

The test case in this bug is different because it uses strncpy to copy only the
leading part of a string, up to the size of the destination, excluding more
than just the terminating nul.  In general, that is one of the valid use cases
for strncpy, but in designing the warning and faced with the GCC strncpy to
memcpy transformation, I considered the constant case to be more likely a
mistake than not.  To help me gauge the priority of this report, how common is
it intended in your experience (and how much software does that represent)?

I have been working with Miguel and others on fixing false positives exposed by
the kernel.  I believe they decided that the warning is useful despite some
lingering instances of it and have been putting it to good use (in conjunction
with the new nonstring attribute).

There are a few ways to avoid the warning in the constant case:

1) use a different function
2) use __attribute__ ((nonstring))
3) suppress the diagnostic using #pargma GCC ignore

(1) might be:

    memcpy (s->dest, src, min (sizeof (s->dest) - 1, strlen (src)));

(2) would look like this:

    __attribute__ ((nonstring)) char *d = s->dest;
    strncpy (d, src, sizeof (s->dest) - 1);

I realize these are workarounds and that getting the suppression to work in GCC
would be ideal.  It's trivial to do:

@@ -1653,6 +1654,9 @@ gimple_fold_builtin_strncpy (gimple_stmt_iterator
                             tree dest, tree src, tree len)
 {
   gimple *stmt = gsi_stmt (*gsi);
+  if (!gimple_bb (stmt))
+    return false;
+
   location_t loc = gimple_location (stmt);

but because it defers the strncpy folding it will likely be controversial.

Reply via email to