1 /* 2 * Copyright (c) 2015-2019, ARM Limited and Contributors. All rights reserved. 3 * 4 * SPDX-License-Identifier: BSD-3-Clause 5 */ 6 7 #include <assert.h> 8 #include <stddef.h> 9 10 /* mbed TLS headers */ 11 #include <mbedtls/memory_buffer_alloc.h> 12 #include <mbedtls/platform.h> 13 14 #include <common/debug.h> 15 #include <drivers/auth/mbedtls/mbedtls_common.h> 16 #include <drivers/auth/mbedtls/mbedtls_config.h> 17 #include <plat/common/platform.h> 18 19 #pragma weak plat_get_mbedtls_heap 20 21 static void cleanup(void) 22 { 23 ERROR("EXIT from BL2\n"); 24 panic(); 25 } 26 27 /* 28 * mbed TLS initialization function 29 */ 30 void mbedtls_init(void) 31 { 32 static int ready; 33 void *heap_addr; 34 size_t heap_size = 0; 35 int err; 36 37 if (!ready) { 38 if (atexit(cleanup)) 39 panic(); 40 41 err = plat_get_mbedtls_heap(&heap_addr, &heap_size); 42 43 /* Ensure heap setup is proper */ 44 if (err < 0) { 45 ERROR("Mbed TLS failed to get a heap\n"); 46 panic(); 47 } 48 assert(heap_size >= TF_MBEDTLS_HEAP_SIZE); 49 50 /* Initialize the mbed TLS heap */ 51 mbedtls_memory_buffer_alloc_init(heap_addr, heap_size); 52 53 #ifdef MBEDTLS_PLATFORM_SNPRINTF_ALT 54 mbedtls_platform_set_snprintf(snprintf); 55 #endif 56 ready = 1; 57 } 58 } 59 60 /* 61 * The following default implementation of the function simply returns the 62 * by default allocated heap. 63 */ 64 int plat_get_mbedtls_heap(void **heap_addr, size_t *heap_size) 65 { 66 static unsigned char heap[TF_MBEDTLS_HEAP_SIZE]; 67 68 assert(heap_addr != NULL); 69 assert(heap_size != NULL); 70 71 *heap_addr = heap; 72 *heap_size = sizeof(heap); 73 return 0; 74 } 75