In several situations, like being without an OS on an embedded platform, there is no real availability of a heap or
free(). mbed TLS still needs some form of dynamic memory allocation to operate the SSL stack. We could just assume maximum sizes for all structures, but that would eat up loads of memory space. Instead we opted for letting mbed TLS only use hooks to allocate and free dynamic memory.
This currently gives you two options:
- Provide your own allocation and freeing functions
- Use our homebrew buffer allocator
In order to enable this memory allocation layer, you should define MBEDTLS_PLATFORM_C and MBEDTLS_PLATFORM_MEMORY in config.h. (Used to be POLARSSL_MEMORY_C in older versions.) See "How do I configure mbed TLS".
If you do not enable the layer, the libc standard
free() are used.
Internally, there are just two function pointers
mbedtls_free() that are called within mbed TLS for each dynamic memory allocation or de-allocation.
extern void * (*mbedtls_calloc)( size_t n, size_t size ); extern void (*mbedtls_free)( void *ptr );
The prototypes for these functions are identical to the libc standard
free(). Without any further calls, the default libc names are assigned to these pointers.
No libc equivalents
If your system does not have a libc equivalent, you will get compile errors as
free() cannot be found.
Defining MBEDTLS_PLATFORM_NO_STD_FUNCTIONS in config.h prevents mbed TLS from ever knowing about those functions.
Providing your own hooks
If your operating system already provides an alternative to the libc allocator functions, you can set them with:
int mbedtls_platform_set_calloc_free( void * (*calloc_func)( size_t, size_t ), void (*free_func)( void * ) );
Using the mbed TLS Buffer Allocator
If you want mbed TLS to allocate everything inside a static buffer, you can enable the Buffer Allocator by defining MBEDTLS_MEMORY_BUFFER_ALLOC_C in config.h.
Then before calling any other mbed TLS functions, enable the Buffer Allocator like this:
unsigned char memory_buf; mbedtls_memory_buffer_alloc_init( memory_buf, sizeof(memory_buf) );
And off you go.
This buffer allocator is a straightforward approach to a dynamic memory allocator. No special heap protection mechanisms have been implemented.
Using the Buffer Allocator elsewhere
The Buffer Allocator itself has no internal dependencies on any of the rest of mbed TLS. So you can use it within your own codebase as well.