.. _safety_stack_checking:

Safety Stack Checking
=====================

To ensure correct operation of the controller, the stack is continuously monitored. For this, the :ref:`firmware_safety` checks the stack in each run.
These checks include:

1. Checking of used stack space and limit to end of stack
2. Checking a protection area between heap and stack for memory corruption

Any detected error will set the :ref:`safety_flags_stack` error flag.

Stack Pointer Checking
----------------------

The stack pointer is checked using :c:func:`stack_check_get_free`. The returned value for the remaining stack space is checked against

.. doxygendefine:: SAFETY_MIN_STACK_FREE

.. doxygenfunction:: stack_check_get_free 


Stack and Heap Corruption Checking
----------------------------------

A section of memory is located between the stack and the heap. It is defined inside the linker script. It's size is configured by the linker script parameter ``__stack_corruption_area_size``, which is set to ``128`` by default.
This section is filled at the initializazion of the safety controller by a call to

.. doxygenfunction:: stack_check_init_corruption_detect_area

On each run of the safety controller's handling function (:c:func:`safety_controller_handle`) the following function is called:

.. doxygenfunction:: stack_check_corruption_detect_area


This function checks the memory area for write modifications, and therefore detects, if the stack or heap have grown outside their boundaries. This canary approach does, however, not guarantee a full protection against heap or stack overflows. 


