SuperTinyKernel™ RTOS 1.08.x
Lightweight, high-performance, deterministic, bare-metal C++ RTOS for resource-constrained embedded systems. MIT Open Source License.
Loading...
Searching...
No Matches
blinky-trustzone-sc/example.cpp
Go to the documentation of this file.
1/*
2 * SuperTinyKernel(TM) RTOS: Lightweight High-Performance Deterministic C++ RTOS for Embedded Systems.
3 *
4 * Source: https://github.com/SuperTinyKernel-RTOS
5 *
6 * Copyright (c) 2022-2026 Neutron Code Limited <stk@neutroncode.com>. All Rights Reserved.
7 * License: MIT License, see LICENSE for a full text.
8 */
9
15
16/*
17 * Secure binary of the STK TrustZone example. It configures the SAU (Secure/Non-Secure/NSC memory split),
18 * exposes the NSC (Non-Secure Callable) entry points, runs a Secure task for handling hardware commands on
19 * behalf of the Non-Secure tasks and then starts the Non-Secure binary, see
20 * \ref blinky-trustzone-ns/example.cpp. See README.md in the example folder for the details.
21 */
22
23#include <setjmp.h>
24#include <stdio.h>
25#include <pico/runtime.h>
26#include <pico/stdio.h>
27#include <pico/unique_id.h>
28
29#include <stk.h>
30#include <time/stk_time.h>
31#include <sync/stk_sync.h>
32#include <arch/arm/cortex-m/stk_arch_arm-tz.h> // for Secure/Non-Secure-specific TrustZone API
33
34#include "example.h"
35
36#if (__ARM_FEATURE_CMSE & 1) == 0
37#error "Need ARMv8-M security extensions"
38#elif (__ARM_FEATURE_CMSE & 2) == 0
39#error "Compile with --mcmse"
40#endif
41
42// Size of the task's stack (number of stk::Word)
43// R2350 requires larger stack due to stack-memory heavy SDK API
44#ifdef _PICO_H
45static constexpr size_t TASK_STACK_SIZE = 1024U;
46#else
47static constexpr size_t TASK_STACK_SIZE = 256U;
48#endif
49
50// Tasks count.
51#define TASK_NS_COUNT (4U)
52#define TASK_S_COUNT (1U)
53#define TASK_COUNT (TASK_NS_COUNT + TASK_S_COUNT)
54
55// Kernel type.
56#define KERNEL_TYPE KERNEL_STATIC
57
58using namespace bsp;
59using namespace stk;
60
61// Allocate a global jump buffer in Secure memory.
62static jmp_buf s_NsExitEnv;
63
64// Hw commands.
66{
67 enum EId
68 {
71 };
72
75};
77
78// This is your NSC exit function.
80{
81 // Jump back to the point right before BLXNS happened,
82 // passing '1' as the return value for setjmp.
83 longjmp(s_NsExitEnv, 1);
84}
85
86// A demo function for exposing SDK functions to Non-Secure side of the binary.
87__stk_tz_nsc_entry void NSC_GetBoardUID(pico_unique_board_id_t *id_out)
88{
90}
91
92// A demo function for exposing some sensible data to Non-Secure side of the binary.
93__stk_tz_nsc_entry uint32_t NSC_GetKey(uint8_t key[], uint32_t size)
94{
95 uint32_t result = 0;
96
97 // Verify the entire buffer lies in Non-Secure memory and is writable
98 if (cmse_check_address_range(key, size, CMSE_NONSECURE | CMSE_MPU_READWRITE) != nullptr)
99 {
100 if (size == 4)
101 {
102 key[0] = 1;
103 key[1] = 2;
104 key[2] = 3;
105 key[3] = 4;
106
107 result = 4;
108 }
109 }
110
111 return result;
112}
113
114// A demo function for exposing some sensible data to Non-Secure state.
116{
117 // You can call hardware directly now, because execution is happening in a
118 // Secure world and Non-Secure task is Privileged.
120 {
122 }
123 else
124 {
125 // If Non-Secure task is not Privileged - direct hw calls are not possible, let Secure
126 // Privileged task handle all hw calls for such calling contexts.
127 s_HwCmdQueue.Write({ .id = HwCommand::CMD_LED_ON, led });
128 }
129}
130
131static void Configure_SAU(void)
132{
133 extern char __nsc_start[]; // = ORIGIN(FLASH_NSC)
134 extern char __nsc_end[]; // = ORIGIN(FLASH_NSC) + LENGTH(FLASH_NSC)
135 extern char __ns_ram_start[]; // = ORIGIN(RAM_NS)
136 //extern char __ns_ram_end[]; // = ORIGIN(RAM_NS) + LENGTH(RAM_NS)
137 extern char __ns_flash_start[]; // = __nsc_end
138 extern char __ns_flash_end[]; // = ORIGIN(FLASH_NS) + LENGTH(FLASH_NS)
139 extern char __ns_scratch_start[]; // = ORIGIN = 0x2007E000
140 extern char __ns_scratch_end[]; // = ORIGIN = 0x2007F000
141
142 // Disable SAU while programming regions.
143 SAU->CTRL = 0U;
144
145 // Region 0: NSC Gateway.
146 SAU->RNR = 0U;
147 SAU->RBAR = (uintptr_t)__nsc_start;
148 SAU->RLAR = (((uintptr_t)__nsc_end - 1U) & ~0x1FU) | 2U | 1U; // NSC + ENABLE
149
150 // Region 1: Non-Secure Flash (code + vector table).
151 SAU->RNR = 1U;
152 SAU->RBAR = (uintptr_t)__ns_flash_start;
153 SAU->RLAR = (((uintptr_t)__ns_flash_end - 1U) & ~0x1FU) | 0U | 1U; // NS + ENABLE
154
155 // Region 2: Non-Secure RAM (TASK STACKS ONLY).
156 SAU->RNR = 2U;
157 SAU->RBAR = (uintptr_t)__ns_ram_start; // 0x20040000
158 SAU->RLAR = (((uintptr_t)__ns_scratch_start - 1U) & ~0x1FU) | 0U | 1U; // NS + ENABLE
159
160 // Region 3: SCRATCH RAM (core stacks / special buffers).
161 SAU->RNR = 3U;
162 SAU->RBAR = (uintptr_t)__ns_scratch_start;
163 SAU->RLAR = (((uintptr_t)__ns_scratch_end - 1U) & ~0x1FU) | 0U | 1U; // NS + ENABLE
164
165 // Clear remaining SAU regions.
166 for (uint32_t i = 4U; i < 8U; ++i)
167 {
168 SAU->RNR = i;
169 SAU->RBAR = 0U;
170 SAU->RLAR = 0U;
171 }
172
173 // Enable SAU (default = Secure).
174 SAU->CTRL = 1U;
175
176 __DSB();
177 __ISB();
178}
179
181{
182 // Enable secure fault reporting.
183 SCB->SHCSR |= SCB_SHCSR_SECUREFAULTENA_Msk |
184 SCB_SHCSR_BUSFAULTENA_Msk |
185 SCB_SHCSR_USGFAULTENA_Msk |
186 SCB_SHCSR_MEMFAULTENA_Msk;
187
188 // 1. Configure SAU boundaries before any peripheral writes.
190
191 // 2. Do other initializations...
192}
193
195{
196 typedef __stk_tz_ns_call void (* NSFuncT)(void);
197
198 extern char __ns_flash_start[]; // = __nsc_end
199
200 // 1. Init PSP to 0.
201 __TZ_set_PSP_NS(0);
202 __set_PSP(0);
203
204 // 2. Read the initial Stack Pointer dynamically from Word 0 of the NS vector table
205 // (Instead of hardcoding to the start of RAM, this ensures it uses the stack top your NS app expects)
206 uint32_t *ns_vector_table = reinterpret_cast<uint32_t *>(__ns_flash_start);
207 uint32_t initial_msp_ns = ns_vector_table[0];
208 __TZ_set_MSP_NS(initial_msp_ns);
209
210 // 3. Point the NON-SECURE VTOR to the Non-Secure vector table
211 SCB_NS->VTOR = reinterpret_cast<uintptr_t>(__ns_flash_start);
212 __DSB();
213 __ISB();
214
215 // 4. Extract the Reset Handler address (Word 1 of the NS vector table)
216 uint32_t reset_handler_address = ns_vector_table[1];
217
218 // 5. Clear Bit 0 (LSB): required by BLXNS — signals Secure-to-NonSecure transition.
219 // The vector table stores Thumb addresses (LSB=1), but BLXNS needs LSB=0.
220 NSFuncT ResetHandler_ns = reinterpret_cast<NSFuncT>(reset_handler_address & ~1UL);
221
222 // Save the current Secure CPU state.
223 // The first time setjmp executes, it returns 0.
224 if (setjmp(s_NsExitEnv) == 0)
225 {
226 // 6. Jump into the Non-Secure World.
227 ResetHandler_ns();
228 }
229 else
230 {
231 // --- WE ARE BACK IN SECURE MODE PERMANENTLY ---
232
233 // The Non-Secure binary called NSC_Secure_HandleNSExit(), which triggered longjmp(),
234 // bypassing the standard C function return mechanism.
235
236 // Continue your Secure-only main loop or application logic here.
237
238 // Reset PSP_NS.
239 __TZ_set_PSP_NS(0);
240 }
241}
242
243// Secure task's core.
244template <stk::EAccessMode _AccessMode>
245class SecureHwCommandQueueTask : public stk::Task<TASK_STACK_SIZE, _AccessMode>
246{
247private:
248 void Run() override
249 {
250 while (true)
251 {
252 HwCommand cmd;
253 if (s_HwCmdQueue.Read(cmd))
254 {
255 switch (cmd.id)
256 {
259 break;
260 default:
261 STK_ASSERT(false);
262 break;
263 }
264 }
265 }
266 }
267};
268
270{
271 // Kernel-invoked fault handler: fires on MemManage faults (e.g. the Non-Secure LED
272 // tasks touching g_SecureCounter, or a stack-guard violation) and on generic hard
273 // faults. Dumps CPU/MPU state for diagnostics and halts via a debug breakpoint -
274 // this is intentionally non-recoverable diagnostic code, not a fault-recovery example.
275#ifdef DEBUG
276 bool OnException(stk::EHwException exc_id, stk::TId tid, const struct stk::FaultContext *const ctx) override
277 {
278 #ifdef DEBUG
279 if (exc_id == stk::HW_EXCEPT_MEMACCESS)
280 {
281 printf("\r\n================ MEMMANAGE FAULT DETECTED ================\r\n");
282 printf("(Sandbox Violation: a task's Run() reached outside the MPU\r\n");
283 printf(" regions granted to it - see region dump below for what\r\n");
284 printf(" WAS active for this task at fault time)\r\n");
285 }
286 else
287 {
288 printf("\r\n================== HARD FAULT DETECTED ===================\r\n");
289 }
290
291 printf("ITask *: 0x%08X:\r\n", (unsigned int)tid);
292
293 printf("EXC_RETURN: 0x%08X\r\n\r\n", (unsigned int)ctx->EXC_RETURN);
294
295 printf("--- Stacked CPU Registers ---\r\n");
296 printf("R0: 0x%08X R1: 0x%08X R2: 0x%08X\r\n", (unsigned int)ctx->frame.R0, (unsigned int)ctx->frame.R1, (unsigned int)ctx->frame.R2);
297 printf("R3: 0x%08X R12: 0x%08X LR: 0x%08X\r\n", (unsigned int)ctx->frame.R3, (unsigned int)ctx->frame.R12, (unsigned int)ctx->frame.LR);
298 printf("PC: 0x%08X xPSR: 0x%08X\r\n\r\n", (unsigned int)ctx->frame.PC, (unsigned int)ctx->frame.xPSR);
299
300 printf("--- System Control Registers ---\r\n");
301 printf("CFSR: 0x%08X HFSR: 0x%08X AFSR: 0x%08X\r\n", (unsigned int)ctx->CFSR, (unsigned int)ctx->HFSR, (unsigned int)ctx->AFSR);
302 printf("MMFAR: 0x%08X (%s)\r\n", (unsigned int)ctx->MMFAR, ctx->mmfar_valid ? "VALID" : "INVALID");
303 printf("BFAR: 0x%08X (%s)\r\n\r\n", (unsigned int)ctx->BFAR, ctx->bfar_valid ? "VALID" : "INVALID");
304 printf("CONTROL: 0x%08X (nPRIV=%u)\r\n", (unsigned int)ctx->CONTROL, (unsigned int)(ctx->CONTROL & 1U));
305
306#if STK_MPU
307 PrintMpuConfig((STK_ARCH_ARMV8_M && STK_TZ_SECURE) ? "Secure" : "Primary", ctx->mpu);
308
309 #if STK_ARCH_ARMV8_M && STK_TZ_SECURE
310 printf("\r\n");
311 PrintMpuConfig("Non-Secure", ctx->mpu_ns);
312 #endif
313#endif
314
315 printf("=====================================================\r\n");
316
318 #endif // DEBUG
319
320 return false;
321 }
322#endif
323};
324
325static void CreateKernel()
326{
327 Led::InitAll(false);
328
329 // Operating in Static + Sync mode (EventFlags requires KERNEL_SYNC) and optionally tickless.
330 const uint8_t KernelMode = KERNEL_TYPE | KERNEL_SYNC | (STK_TICKLESS_IDLE ? KERNEL_TICKLESS : 0);
331
332 // Allocate scheduling kernel for 3 threads (tasks) with Round-Robin scheduling strategy.
334
335 // for MPU configuration and MemFault/HardFault exceptions processing
336 static PlatformEventHandler event_overrider;
337 kernel.GetPlatform()->SetEventOverrider(&event_overrider);
338
339 // Init scheduling kernel.
340 kernel.Initialize();
341
342 // Register kernel instance with TrustZone interface.
343 tz::sec::SetKernel(0, &kernel);
344
345 // Add Secure tasks:
347 kernel.AddTask(&hw_cmd_task);
348}
349
351{
352 // For semihosting and logging to console.
353#ifdef DEBUG
354 stdio_init_all();
355#endif
356
357 // Init BSP.
358 Led::InitAll(false);
359
360 // Configure Secure state by partitioning FLASH and RAM via SAU. STK does not wrap this functionality
361 // to give more freedom and be less noisy in its API.
363
364 // Create scheduler and add Secure tasks.
365 CreateKernel();
366
367 // Invoke Non-Secure state which will drive logic further.
369
370 // CPU is now executing your Non-Secure application, execution will never return here.
371 while (true)
372 {
373 // KERNEL_STATIC does not support exit from scheduling, while it is possible with KERNEL_DYNAMIC
374 // when all tasks exit on both sides Non-secure and Secure.
375 #if (KERNEL_TYPE == KERNEL_STATIC)
376 STK_ASSERT(false);
377 #endif
378 }
379}
#define __stk_tz_ns_call
ARM TrustZone: attribute for calling Non-Secure functions from Secure state.
#define __stk_tz_nsc_entry
ARM TrustZone: attribute for Non-Secure callable gateway functions.
#define STK_ARCH_ARMV8_M
ARMv8-M platform (Cortex-M23, Cortex-M33, Cortex-M55, Cortex-M85).
Top-level STK include. Provides the Kernel class template and all built-in task-switching strategies.
#define STK_TZ_SECURE
ARM TrustZone: Defines Secure (1) build.
Definition stk_defs.h:180
#define STK_ASSERT(e)
Runtime assertion. Halts execution if the expression e evaluates to false.
Definition stk_defs.h:532
static void __stk_debug_break()
Definition stk_defs.h:495
Collection of synchronization primitives (stk::sync namespace).
Collection of time-related primitives (stk::time namespace).
Namespace of STK package.
uintptr_t Word
Native processor word type.
Definition stk_common.h:206
EHwException
Hardware exception id (see IPlatform::IEventOverrider::OnException).
Definition stk_common.h:194
@ HW_EXCEPT_MEMACCESS
MemManage on ARM / Page Fault or PMP violation on RISC-V.
Definition stk_common.h:196
Word TId
Task (thread) id.
Definition stk_common.h:211
@ KERNEL_TICKLESS
Tickless mode. To use this mode STK_TICKLESS_IDLE must be defined to 1 in stk_config....
Definition stk_common.h:51
@ KERNEL_SYNC
Synchronization support (see Event).
Definition stk_common.h:50
bool IsPrivilegedContext()
Check if caller context is Privileged.
Definition cpu.h:17
ARMv7-M/ARMv8-M system fault exception context state capture.
Word BFAR
BusFault Address Register (BFAR).
Word AFSR
Auxiliary Fault Status Register (AFSR).
Word HFSR
HardFault Status Register (HFSR).
hw::ExceptionFrame frame
Saved hardware exception stack frame.
Word MMFAR
Memory Management Fault Address Register (MMFAR).
Word CFSR
Configurable Fault Status Register (CFSR: MemManage, BusFault, UsageFault).
Word CONTROL
Core CONTROL register state snapshot.
bool mmfar_valid
Flag indicating validity of MMFAR address value (derived from CFSR.MMARVALID).
Word EXC_RETURN
Exception return magic value (EXC_RETURN).
bool bfar_valid
Flag indicating validity of BFAR address value (derived from CFSR.BFARVALID).
Concrete implementation of IKernel.
Definition stk.h:102
EAddResult AddTask(ITask *user_task) override
Register task for a soft real-time (SRT) scheduling.
Definition stk.h:1465
IPlatform * GetPlatform() override
Get platform driver instance owned by this kernel.
Definition stk.h:2034
void Initialize(uint32_t resolution_us=PERIODICITY_DEFAULT) override
Initialize kernel.
Definition stk.h:1425
virtual void SetEventOverrider(IEventOverrider *overrider, bool non_secure=false)=0
Set platform event overrider.
Interface for a platform event overrider.
Partial implementation of the user task.
Definition stk_helper.h:98
Thread-safe, type-safe FIFO communication pipe with internal storage.
void Run() override
Entry point of the user task.
SecureHwCommandQueueTask(stk::Word *stack, size_t stack_size)
bool OnException(stk::EHwException exc_id, stk::TId tid, const struct stk::FaultContext *const ctx) override
LedId Id
Definition led.h:32
static void InitAll(bool init_state)
Definition led.h:40
static void SwitchOnExclusive(Id led)
Definition led.h:48
void pico_get_unique_board_id(pico_unique_board_id_t *id_out)
static jmp_buf s_NsExitEnv
#define KERNEL_TYPE
__stk_tz_nsc_entry uint32_t NSC_GetKey(uint8_t key[], uint32_t size)
static void CreateKernel()
__stk_tz_nsc_entry void NSC_GetBoardUID(pico_unique_board_id_t *id_out)
static void InvokeNonSecureState()
static sync::PipeT< HwCommand, 4 > s_HwCmdQueue
static void Configure_SAU(void)
__stk_tz_nsc_entry void NSC_OnExitNs(void)
static void ConfigureSecureState()
__stk_tz_nsc_entry void NSC_bsp_Led_SwitchOnExclusive(bsp::Led::Id led)
static STK_MPU_SHARED_DATA_SECTION stk::sync::PipeT< HwCommand, 4 > s_HwCmdQueue
#define TASK_STACK_SIZE