Skip to content

Commit

Permalink
core/thread: "fix" valgrind erros in thread_measure_stack_free()
Browse files Browse the repository at this point in the history
The dark magic used used in thread_measure_stack_free() is frowned upon
by valgrind. E.g. valgrind may deduce (by monitoring the stack pointer)
that a specific value was at some point allocated on the stack, but has
gone out of scope. When that value is now read again to estimate stack
usage, it does look a lot like someone passed a pointer to a stack
allocated value, and that pointer is referenced after that value has
gone out of scope.

This is "fixed" by temporarily disabling valgrind error reporting while
iterating over the stack.
  • Loading branch information
maribu committed Jun 4, 2024
1 parent 5b73294 commit e1d61ae
Showing 1 changed file with 26 additions and 0 deletions.
26 changes: 26 additions & 0 deletions core/thread.c
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,16 @@
#define ENABLE_DEBUG 0
#include "debug.h"

#if defined(HAVE_VALGRIND_H)
# include <valgrind.h>
# define USE_VALGRIND 1
#elif defined(HAVE_VALGRIND_VALGRIND_H)
# include <valgrind/valgrind.h>
# define USE_VALGRIND 1
#else
# define USE_VALGRIND 0
#endif

thread_status_t thread_getstatus(kernel_pid_t pid)
{
thread_t *thread = thread_get(pid);
Expand Down Expand Up @@ -178,11 +188,27 @@ uintptr_t measure_stack_free_internal(const char *stack, size_t size)
uintptr_t *stackp = (uintptr_t *)(uintptr_t)stack;
uintptr_t end = (uintptr_t)stack + size;

#if USE_VALGRIND
/* HACK: This will affect native/native64 only.
*
* The dark magic used here is frowned upon by valgrind. E.g. valgrind may
* deduce that a specific value was at some point allocated on the stack,
* but has gone out of scope. When that value is now read again to
* estimate stack usage, it does look a lot like someone passed a pointer
* to a stack allocated value, and that pointer is referenced after that
* value has gone out of scope. */
VALGRIND_DISABLE_ERROR_REPORTING;
#endif

/* assume that the stack grows "downwards" */
while (((uintptr_t)stackp < end) && (*stackp == (uintptr_t)stackp)) {
stackp++;
}

#if USE_VALGRIND
VALGRIND_ENABLE_ERROR_REPORTING;
#endif

uintptr_t space_free = (uintptr_t)stackp - (uintptr_t)stack;

return space_free;
Expand Down

0 comments on commit e1d61ae

Please sign in to comment.