|
| 1 | +// Route OpenSSL allocations through the raw memory allocators. |
| 2 | +// Shared by the _ssl and _hashlib modules. |
| 3 | + |
| 4 | +#ifndef Py_OPENSSL_MEM_H |
| 5 | +#define Py_OPENSSL_MEM_H |
| 6 | + |
| 7 | +#include "Python.h" |
| 8 | + |
| 9 | +#include <openssl/crypto.h> // CRYPTO_set_mem_functions() |
| 10 | + |
| 11 | +// LibreSSL stubs out CRYPTO_set_mem_functions() and BoringSSL lacks it. |
| 12 | +// AWS-LC has it, but unlike OpenSSL it does not refuse to install hooks |
| 13 | +// after the first allocation, so earlier size-prefixed allocations would |
| 14 | +// be freed with the wrong allocator. |
| 15 | +#if !defined(LIBRESSL_VERSION_NUMBER) && !defined(OPENSSL_IS_BORINGSSL) \ |
| 16 | + && !defined(OPENSSL_IS_AWSLC) |
| 17 | +# define _Py_OPENSSL_CAN_SET_MEM_FUNCTIONS |
| 18 | +#endif |
| 19 | + |
| 20 | +#ifdef _Py_OPENSSL_CAN_SET_MEM_FUNCTIONS |
| 21 | + |
| 22 | +static void * |
| 23 | +_PyOpenSSL_Malloc(size_t size, const char *Py_UNUSED(file), |
| 24 | + int Py_UNUSED(line)) |
| 25 | +{ |
| 26 | + return PyMem_RawMalloc(size); |
| 27 | +} |
| 28 | + |
| 29 | +static void * |
| 30 | +_PyOpenSSL_Realloc(void *ptr, size_t size, const char *Py_UNUSED(file), |
| 31 | + int Py_UNUSED(line)) |
| 32 | +{ |
| 33 | + return PyMem_RawRealloc(ptr, size); |
| 34 | +} |
| 35 | + |
| 36 | +static void |
| 37 | +_PyOpenSSL_Free(void *ptr, const char *Py_UNUSED(file), |
| 38 | + int Py_UNUSED(line)) |
| 39 | +{ |
| 40 | + PyMem_RawFree(ptr); |
| 41 | +} |
| 42 | + |
| 43 | +#endif // _Py_OPENSSL_CAN_SET_MEM_FUNCTIONS |
| 44 | + |
| 45 | +static void |
| 46 | +_PyOpenSSL_SetupMemFunctions(void) |
| 47 | +{ |
| 48 | +#ifdef _Py_OPENSSL_CAN_SET_MEM_FUNCTIONS |
| 49 | + // Fails if OpenSSL has already allocated memory (e.g. another |
| 50 | + // libcrypto user in the process); it then keeps its current allocator. |
| 51 | + (void)CRYPTO_set_mem_functions(_PyOpenSSL_Malloc, _PyOpenSSL_Realloc, |
| 52 | + _PyOpenSSL_Free); |
| 53 | +#endif |
| 54 | +} |
| 55 | + |
| 56 | +#endif // !Py_OPENSSL_MEM_H |
0 commit comments