xref: /rk3399_ARM-atf/plat/renesas/common/rcar_stack_protector.c (revision 76d5d32fcf7e8859721e0d63a1ecc6b674a4ae0e)
1 /*
2  * Copyright (c) 2021-2025, Renesas Electronics Corporation. All rights reserved.
3  *
4  * SPDX-License-Identifier: BSD-3-Clause
5  */
6 
7 #include <stdint.h>
8 
9 #include <arch_helpers.h>
10 #include <common/debug.h>
11 
12 #define RANDOM_CANARY_VALUE	((u_register_t)0xDFF5FC8A720E205EULL)
13 
14 u_register_t plat_get_stack_protector_canary(void)
15 {
16 	uintptr_t val1 = (uintptr_t)__builtin_return_address(0U);
17 	uintptr_t val2 = (uintptr_t)__builtin_frame_address(0U);
18 	u_register_t cnt;
19 	u_register_t seed;
20 	u_register_t mul;
21 	u_register_t ret;
22 
23 	cnt = read_cntpct_el0();
24 	seed = (cnt ^ RANDOM_CANARY_VALUE) & ULONG_MAX;
25 	ret = seed;
26 
27 	INFO("seed value: 0x%16lx    cnt: 0x%16lx\n", seed, cnt);
28 
29 	if ((ULONG_MAX / val1) > seed) {
30 		mul = (u_register_t)(val1 * seed);
31 		if ((ULONG_MAX - mul) > val2) {
32 			ret = mul + val2;
33 		}
34 	}
35 
36 	INFO("canary value: 0x%lx    cnt: 0x%16lx\n", ret, read_cntpct_el0());
37 
38 	return ret;
39 }
40