Alternatives to allocating memory in Mbed TLS (alternative to malloc calloc()/free)

Original link

Alternative ways of allocating memory in Mbed TLS — Mbed TLS documentation

In some cases, such as when there is no operating system on an embedded platform, the heap and calloc()/ free()or is not really available. Mbed TLS still requires some form of dynamic memory allocation to operate the SSL stack. We could assume a maximum size for all structures, but this would consume a lot of memory space. Instead, we chose to have Mbed TLS only use hooks to allocate and deallocate dynamic memory.

Currently you have two options:

  1. Provide your own allocation and deallocation functions.

  2. Use the buffer allocator function in Mbed TLS.

To enable the memory allocation layer, define MBEDTLS_PLATFORM_Cand MBEDTLS_PLATFORM_MEMORYin mbedtls_config.h. See How to configure Mbed TLS .

If the layer is not enabled, the libc standard sum calloc()is free()used.

Internal components

Internally, there are only two function pointers mbedtls_calloc()and mbedtls_free()calls for each dynamic memory allocation or deallocation in Mbed TLS.

extern void * (*mbedtls_calloc)( size_t n, size_t size );
extern void (*mbedtls_free)( void *ptr );

libcThe prototypes and standard calloc()sums of these functions free(). Without any further calls, libcthese pointers are given names by default.

no libc equivalent

If your system does not have libcan equivalent, you will get compile errors like the following calloc()or free()not found.

Defines MBEDTLS_PLATFORM_NO_STD_FUNCTIONSin mbedtls_config.hthe file prevent Mbed TLS from understanding these functions.

Provide your own hooks

If your operating system already provides libcallocator functions, you can set them with:

int mbedtls_platform_set_calloc_free( void * (*calloc_func)( size_t, size_t ),
                                      void (*free_func)( void * ) );

Use the Mbed TLS buffer allocator

If you want Mbed TLS to allocate all the content in the static buffer, you can define it MBEDTLS_MEMORY_BUFFER_ALLOC_Cin mbedtls_config.hthe file.

Before calling any other Mbed TLS functions, enable the buffer allocator as follows:

unsigned char memory_buf[100000];
mbedtls_memory_buffer_alloc_init( memory_buf, sizeof(memory_buf) );

Safety Warning

A buffer allocator is a simple approach to a dynamic memory allocator. No special heap protection mechanisms are implemented.

Use the buffer allocator elsewhere

The buffer allocator itself does not depend on any other part of Mbed TLS. So you can use it in your own code base as well.

Guess you like

Origin blog.csdn.net/yunqian09/article/details/130049103