1 /*
2  * Copyright (c) 2021-2023, 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 
plat_get_stack_protector_canary(void)14 u_register_t plat_get_stack_protector_canary(void)
15 {
16 	u_register_t cnt;
17 	u_register_t seed;
18 	u_register_t mul;
19 	u_register_t ret;
20 	uintptr_t val1 = (uintptr_t)__builtin_return_address(0U);
21 	uintptr_t val2 = (uintptr_t)__builtin_frame_address(0U);
22 
23 	cnt = read_cntpct_el0();
24 	seed = (cnt ^ RANDOM_CANARY_VALUE) & ULONG_MAX;
25 	ret = seed;
26 
27 	if ((ULONG_MAX/val1) > seed) {
28 		mul = (u_register_t)(val1 * seed);
29 		if ((mul < ULONG_MAX) &&
30 				((ULONG_MAX - (u_register_t)mul) > val2)) {
31 			ret = mul + val2;
32 		}
33 	}
34 
35 	return ret;
36 }
37