Skip to content

Commit

Permalink
add a real explicit_bzero implementation
Browse files Browse the repository at this point in the history
Clang, GCC and other compilers special-case standard C functions like
memset. Calls to memset will be optimized out.

OpenBSD provides explicit_bzero to work around this but Android simply
defines it as memset so nothing prevents it from being optimized away.

This implementation uses a memory read constraint via empty inline
assembly rather than something that may be broken via link-time
optimization in the future.
  • Loading branch information
thestinger committed Jun 7, 2021
1 parent 6aaff2a commit 5412c37
Show file tree
Hide file tree
Showing 5 changed files with 10 additions and 2 deletions.
1 change: 1 addition & 0 deletions libc/Android.bp
Original file line number Diff line number Diff line change
Expand Up @@ -1028,6 +1028,7 @@ cc_library_static {
"bionic/error.cpp",
"bionic/eventfd.cpp",
"bionic/exec.cpp",
"bionic/explicit_bzero.cpp",
"bionic/faccessat.cpp",
"bionic/fchmod.cpp",
"bionic/fchmodat.cpp",
Expand Down
7 changes: 7 additions & 0 deletions libc/bionic/explicit_bzero.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
#include <string.h>

void* explicit_bzero(void* s, size_t n) {
void *ptr = memset(s, 0, n);
__asm__ __volatile__("" : : "r"(ptr) : "memory");
return ptr;
}
1 change: 1 addition & 0 deletions libc/include/string.h
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,7 @@ void* mempcpy(void* __dst, const void* __src, size_t __n) __INTRODUCED_IN(23);
#endif
void* memmove(void* __dst, const void* __src, size_t __n);
void* memset(void* __dst, int __ch, size_t __n);
void* explicit_bzero(void *s, size_t n);
void* memmem(const void* __haystack, size_t __haystack_size, const void* __needle, size_t __needle_size) __attribute_pure__;

char* strchr(const char* __s, int __ch) __attribute_pure__;
Expand Down
1 change: 1 addition & 0 deletions libc/libc.map.txt
Original file line number Diff line number Diff line change
Expand Up @@ -332,6 +332,7 @@ LIBC {
execvp;
execvpe; # introduced=21
exit;
explicit_bzero; # introduced=30
faccessat;
fallocate; # introduced=21
fallocate64; # introduced=21
Expand Down
2 changes: 0 additions & 2 deletions libc/upstream-openbsd/android/include/openbsd-compat.h
Original file line number Diff line number Diff line change
Expand Up @@ -53,8 +53,6 @@ extern const char* __progname;
/* OpenBSD has this, but we can't really implement it correctly on Linux. */
#define issetugid() 0

#define explicit_bzero(p, s) memset(p, 0, s)

/* OpenBSD has these in <sys/param.h>, but "ALIGN" isn't something we want to reserve. */
#define ALIGNBYTES (sizeof(uintptr_t) - 1)
#define ALIGN(p) (((uintptr_t)(p) + ALIGNBYTES) &~ ALIGNBYTES)
Expand Down

0 comments on commit 5412c37

Please sign in to comment.