Skip to content

Commit

Permalink
string: use __builtin_memcpy() in strlcpy/strlcat
Browse files Browse the repository at this point in the history
lib/string.c is built with -ffreestanding, which prevents the compiler
from replacing certain functions with calls to their library versions.

On the other hand, this also prevents Clang and GCC from instrumenting
calls to memcpy() when building with KASAN, KCSAN or KMSAN:
 - KASAN normally replaces memcpy() with __asan_memcpy() with the
   additional cc-param,asan-kernel-mem-intrinsic-prefix=1;
 - KCSAN and KMSAN replace memcpy() with __tsan_memcpy() and
   __msan_memcpy() by default.

To let the tools catch memory accesses from strlcpy/strlcat, replace
the calls to memcpy() with __builtin_memcpy(), which KASAN, KCSAN and
KMSAN are able to replace even in -ffreestanding mode.

This preserves the behavior in normal builds (__builtin_memcpy() ends up
being replaced with memcpy()), and does not introduce new instrumentation
in unwanted places, as strlcpy/strlcat are already instrumented.

Suggested-by: Marco Elver <[email protected]>
Signed-off-by: Alexander Potapenko <[email protected]>
Reviewed-by: Marco Elver <[email protected]>
Link: https://lore.kernel.org/all/[email protected]/
Acked-by: Kees Cook <[email protected]>
Signed-off-by: Kees Cook <[email protected]>
Link: https://lore.kernel.org/r/[email protected]
  • Loading branch information
ramosian-glider authored and kees committed Jun 1, 2023
1 parent 2af4aa3 commit f9cfb19
Showing 1 changed file with 2 additions and 2 deletions.
4 changes: 2 additions & 2 deletions lib/string.c
Original file line number Diff line number Diff line change
Expand Up @@ -110,7 +110,7 @@ size_t strlcpy(char *dest, const char *src, size_t size)

if (size) {
size_t len = (ret >= size) ? size - 1 : ret;
memcpy(dest, src, len);
__builtin_memcpy(dest, src, len);
dest[len] = '\0';
}
return ret;
Expand Down Expand Up @@ -260,7 +260,7 @@ size_t strlcat(char *dest, const char *src, size_t count)
count -= dsize;
if (len >= count)
len = count-1;
memcpy(dest, src, len);
__builtin_memcpy(dest, src, len);
dest[len] = 0;
return res;
}
Expand Down

0 comments on commit f9cfb19

Please sign in to comment.