Restoring MSP in vPortStartFirstTask

Hi, I don’t understand why are we restoring the main stack pointer in vPortStartFirstTask(IAR M3 PORT) its the same on other tool-chains as well.

Doesn’t resetting the SP to c_stack pointer corrupt the main()'s stack?

I’m trying to port FreeRTOS to c++. The above operation is corrupting my stack and objects on main()'s stack are no longer usable after a call to scheduler start.

Even though I don’t know the particular IAR port you’re using the main stack on Cortex-M3/4/7 ports is used resp. reserved as ISR stack.
Better follow the rule that the FreeRTOS runtime environment is defined by starting the scheduler and since it doesn’t return (to main) the bare metal C-runtime environment is let’s say discarded/reused. This is not directly related to C vs. C++.
For example in my applications running on Cortex-M family MCUs there is a context free (no arguments) main task which provides the FreeRTOS runtime environment. It creates all other (child) tasks usually with arguments provided also on (main task) stack.
Following this simple and generic paradigm eliminates any worries about low level port specifics e.g. usage of the MSP on Cortex-M MCUs because this is guaranteed to work by FreeRTOS on all platforms.
I think you can easily define a task as initial/main task for every application even if you don’t make use of (parent/child) task (object) relations.

Hey, thanks for your comment. It not specific to IAR this is the same implementation in GCC, ARMCC, and other toolchain ports as well.

That’s the same implementation that I’m going with as well. I couldn’t understand why we need to manipulate the MSP. Is it done just reuse the main stack? To decrease ram usage?

Yes – it is to recover the RAM that was used before the scheduler started but has no context after the scheduler is running.

Hi Richard Thanks, So by design the objects from the calling (call to start-scheduler) function’s stack will be not available.

At least for Cortex-M ports - yes.
Again I’d propose to take that as a general constraint or assumption to avoid dealing with port specifics more than really needed.

1 Like