Mark Shoe

Stack Analyzer

Discussion created by Mark Shoe on Apr 4, 2018
Latest reply on Apr 4, 2018 by Clive One

Thanks Andrew. Here i share my stack/ heap Analyzer. 

As i understand the heap is on top of the ram. However the __bss_end__ is not the starting adress of the Heap. That is why i allocate 4 bytes and find the adress.

The heap will reserve memory until it collapse into the stack. Malloc does not check it memory is available. The variable stack_size is not used.

The stack is at the end of ram. an growing down. Will this grow beyond the stacksize?

/*!
* \brief Call this function at startup to calculate the Heap startposition
* \brief This function counts the free Stack and Heap
* \brief Stack is located at he top of memory
* \brief Heap is all space between Ram and Stack
* \brief Insert filler to .s file
*
* \param -
*
* \return - size and free in bytes
*/

void get_freespace(free_size_t * fs)
{
     extern uint32_t _estack;
     extern uint32_t _Min_Stack_Size;
     extern uint32_t _Min_Heap_Size;  // raported Heap size
     static uint32_t HeapAddr = 0;
     uint32_t * p_addr;
     uint32_t StackAddr = (uint32_t) &_estack;

     fs->stacksize = (uint32_t) &_Min_Stack_Size;
     fs->heapsize = (uint32_t) &_Min_Heap_Size;

     fs->free_stack = fs->free_heap = 0;
     p_addr = StackAddr - fs->stacksize;

     // count the empty stack
     while (*p_addr++ == 0x0E)
          fs->free_stack +=4; // 32bit increase

     // find HEAP address once at startup
     if (HeapAddr == 0)
     {
          uint32_t *f = malloc(0x04);
          HeapAddr = (uint32_t) f;
          free(f);
     }

     // measure the Heap
     for (uint32_t *p_mem = (uint32_t *)HeapAddr; p_mem < (uint32_t *)(StackAddr - fs->stacksize); p_mem++)
     {
          if (*p_mem == 0x0E)
               fs->free_heap += 4; // 32bit increase
     }
}

 

typedef struct
{
     uint32_t stacksize; // bytes
     uint32_t heapsize;
     uint32_t free_stack;
     uint32_t free_heap;
} free_size_t;

void get_freespace(free_size_t * fs);

Insert this to the .s file:

 

/* Fill the rest of ram segment. */
  ldr r2, = __bss_end__
  ldr r4, = _estack
  movs r3, #0x0E
  b SLoopFillZerobss

SFillZerobss:
  str  r3, [r2]
  adds r2, r2, #4

SLoopFillZerobss:
  cmp r2, r4
  bcc SFillZerobss

Outcomes