diff --git a/wolfcrypt/src/memory.c b/wolfcrypt/src/memory.c index 470b09cf9..3d38265cf 100644 --- a/wolfcrypt/src/memory.c +++ b/wolfcrypt/src/memory.c @@ -389,10 +389,19 @@ int wolfSSL_StaticBufferSz(byte* buffer, word32 sz, int flag) /* creating only IO buffers from memory passed in, max TLS is 16k */ if (flag & WOLFMEM_IO_POOL || flag & WOLFMEM_IO_POOL_FIXED) { - ava = sz % (memSz + padSz + WOLFMEM_IO_SZ); + if (ava < (memSz + padSz + WOLFMEM_IO_SZ)) { + return 0; /* not enough room for even one bucket */ + } + + ava = ava % (memSz + padSz + WOLFMEM_IO_SZ); } else { int i, k; + + if (ava < (bucketSz[0] + padSz + memSz)) { + return 0; /* not enough room for even one bucket */ + } + while ((ava >= (bucketSz[0] + padSz + memSz)) && (ava > 0)) { /* start at largest and move to smaller buckets */ for (i = (WOLFMEM_MAX_BUCKETS - 1); i >= 0; i--) { diff --git a/wolfcrypt/test/test.c b/wolfcrypt/test/test.c index 3c0b57400..f5bc9a686 100644 --- a/wolfcrypt/test/test.c +++ b/wolfcrypt/test/test.c @@ -4327,6 +4327,9 @@ int memory_test(void) word32 size[] = { WOLFMEM_BUCKETS }; word32 dist[] = { WOLFMEM_DIST }; byte buffer[30000]; /* make large enough to involve many bucket sizes */ + int pad = -(int)((wolfssl_word)&(buffer[0])) & (WOLFSSL_STATIC_ALIGN - 1); + /* pad to account for if head of buffer is not at set memory + * alignment when tests are ran */ /* check macro settings */ if (sizeof(size)/sizeof(word32) != WOLFMEM_MAX_BUCKETS) { @@ -4351,7 +4354,7 @@ int memory_test(void) } /* check that padding size returned is possible */ - if (wolfSSL_MemoryPaddingSz() <= WOLFSSL_STATIC_ALIGN) { + if (wolfSSL_MemoryPaddingSz() < WOLFSSL_STATIC_ALIGN) { return -101; /* no room for wc_Memory struct */ } @@ -4364,8 +4367,8 @@ int memory_test(void) } /* check function to return optimum buffer size (rounded down) */ - if ((ret = wolfSSL_StaticBufferSz(buffer, sizeof(buffer), WOLFMEM_GENERAL)) - % WOLFSSL_STATIC_ALIGN != 0) { + ret = wolfSSL_StaticBufferSz(buffer, sizeof(buffer), WOLFMEM_GENERAL); + if ((ret - pad) % WOLFSSL_STATIC_ALIGN != 0) { return -104; /* not aligned! */ } @@ -4382,21 +4385,22 @@ int memory_test(void) } ret = wolfSSL_MemoryPaddingSz(); + ret += pad; /* add space that is going to be needed if buffer not aligned */ if (wolfSSL_StaticBufferSz(buffer, size[0] + ret + 1, WOLFMEM_GENERAL) != (ret + (int)size[0])) { return -108; /* did not round down to nearest bucket value */ } ret = wolfSSL_StaticBufferSz(buffer, sizeof(buffer), WOLFMEM_IO_POOL); - if (ret < 0) { + if ((ret - pad) < 0) { return -109; } - if ((ret % (WOLFMEM_IO_SZ + wolfSSL_MemoryPaddingSz())) != 0) { + if (((ret - pad) % (WOLFMEM_IO_SZ + wolfSSL_MemoryPaddingSz())) != 0) { return -110; /* not even chunks of memory for IO size */ } - if ((ret % WOLFSSL_STATIC_ALIGN) != 0) { + if (((ret - pad) % WOLFSSL_STATIC_ALIGN) != 0) { return -111; /* memory not aligned */ }