Call function with external stack

Overview

A given function can be executed with a user allocated stack space which is independent of current task stack, this mechanism can be used to save stack space wasted by tasks which call a common function with intensive stack usage such as printf. The given function can be called inside the macro ESP_EXECUTE_EXPRESSION_WITH_STACK() it will redirect the target function to be executed using the space allocated by the user.

Usage

ESP_EXECUTE_EXPRESSION_WITH_STACK() takes three arguments, a mutex object allocated by the caller, which is used to protect if the same function shares its allocated stack, a pointer to the top of stack used to that fuction, and the function itself, note the function is passed exactly in the same way as do when you call it on a regular way.

The usage may looks like the code below:

//Let's suppose we wanting to call printf using a separated stack space
//allowing app to reduce its stack size.
void app_main()
{
    //Allocate a stack buffer, from heap or as a static form:
    portSTACK_TYPE *shared_stack = malloc(8192 * sizeof(portSTACK_TYPE));
    assert(shared_stack != NULL);

    //Allocate a mutex to protect its usage:
    SemaphoreHandle_t printf_lock = xSemaphoreCreateMutex();
    assert(printf_lock != NULL);

    //Call the desired function using the macro helper:
    ESP_EXECUTE_EXPRESSION_WITH_STACK(printf_lock,
                                    shared_stack,
                                    printf("Executing this from external stack! \n"));
    vSemaphoreDelete(printf_lock);
    free(shared_stack);
}

API Reference

Functions

StackType_t *esp_switch_stack_setup(StackType_t *stack, size_t stack_size)

Fill stack frame with CPU-specifics value before use.

Return

New pointer to the top of stack

Note

Application must not call this function directly

Parameters
  • stack: Caller allocated stack pointer

  • stack_size: Size of stack in bytes

void esp_switch_stack_enter(StackType_t *stack, uint32_t *backup_stack)

Changes CPU sp-register to use another stack space and save the previous one.

Note

Application must not call this function directly

Parameters
  • stack: Caller allocated stack pointer

  • backup_stack: Pointer to a place to save the current stack

void esp_switch_stack_exit(uint32_t *backup_stack)

Restores the previous CPU sp-register.

Note

Application must not call this function directly

Parameters
  • backup_stack: Pointer to the place where stack was saved

Macros

ESP_EXECUTE_EXPRESSION_WITH_STACK(lock, stack, stack_size, expression)

Executes a 1-line expression with a application alocated stack.

Note

if either lock, stack or stack size is invalid, the expression will be called using the current stack.

Parameters
  • lock: Mutex object to protect in case of shared stack

  • stack: Pointer to user alocated stack

  • stack_size: Size of current stack in bytes

  • expression: Expression or function to be executed using the stack