Page 1 of 1

how to check the thread memory stack

Posted: Thu Mar 10, 2011 11:42 am
by albi
Hi everybody,
here an simple method to check and print the thead stack usage at runtime.
Note: the option CH_DBG_FILL_THREADS in chconf.h must be TRUE

Code: Select all

#define stk_siprintf(b,s,n,z)                                       \
          siprintf(b, "%s free stack memory : %u%% of %u bytes",    \
                   s, (n)*100/((z) - sizeof(Thread)), ((z) - sizeof(Thread)));

size_t get_thd_free_stack(void *wsp, size_t size)
{
  size_t n = 0;
#if CH_DBG_FILL_THREADS
  uint8_t *startp = (uint8_t *)wsp + sizeof(Thread);
  uint8_t *endp = (uint8_t *)wsp + size;
  while (startp < endp)
    if(*startp++ == STACK_FILL_VALUE) ++n;
#endif
  return n;
}

static WORKING_AREA(waStcThread, 2000);
static msg_t StcThread(void *arg);

#define  DYN_THD_WA_SIZE   THD_WA_SIZE(2048)
static Thread *dynThreadp  = NULL;

void print_mem(BaseChannel *chp, int argc, char *argv[]) {
  size_t n;
  char buf[80];

// check stack of an dynamic Thread
  if(dynThreadp != NULL){
    n = get_thd_free_stack(dynThreadp , DYN_THD_WA_SIZE);
    stk_siprintf(buf, "dynThread   ", n,  DYN_THD_WA_SIZE);
    shellPrintLine(buf);
  }

// check stack of an static Thread
  n = get_thd_free_stack(waStcThread, sizeof(waStcThread));
  stk_siprintf(buf, "StcThread    ", n, sizeof(waStcThread));
  shellPrintLine(buf);
}


Alberto

Re: how to check the thread memory stack

Posted: Fri Jul 12, 2019 6:14 am
by wurstnase
Quite old thread but somehow helpful.

My modified version checks the stack until the first none fill value.

Code: Select all

static size_t get_thd_free_stk(void *wsp, size_t size)
{
    size_t n        = 0;
    uint8_t *startp = (uint8_t *)wsp + sizeof(thread_t);
    uint8_t *endp   = (uint8_t *)wsp + size + sizeof(thread_t);
    while (*startp++ == CH_DBG_STACK_FILL_VALUE) {
        ++n;
        if (startp == endp)
            break;
    }
    return n;
}


You could add it like:

Code: Select all

// main.c init the shell
static THD_WORKING_AREA(waShellThread, 1024);
stkalign_t *wa_shell_thd_p = waShellThread;

// my_shell.c
extern stkalign_t *wa_shell_thd_p;
static void cmd_ctrl_stk(BaseSequentialStream *chp, int argc, char *argv[])
{
    (void)argv;

    if (argc == 2) {
        size_t size = atol(argv[1]);
        size_t n    = 0;
        void *wap   = NULL;
        if (strcmp(argv[0], "shell") == 0) {
            wap = wa_shell_thd_p;
        }
        if (wap != NULL)
            n = get_thd_free_stk(wap, size);
        chprintf(chp, "%s: %u of %u\r\n", argv[0], n, size);
    }
}


In your shell hit: stk shell 1024. The number should be at least the stack size.