From 9c7c709b3ebcea84d4fc933fc49dd67f8e4aa3b6 Mon Sep 17 00:00:00 2001 From: Leonid Yuriev Date: Wed, 12 May 2021 17:44:18 +0300 Subject: [PATCH] mdbx: avoid underflow during monotime/16dot16 conversion. --- src/osal.c | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) diff --git a/src/osal.c b/src/osal.c index a030f681..16bccf61 100644 --- a/src/osal.c +++ b/src/osal.c @@ -1908,7 +1908,8 @@ mdbx_osal_16dot16_to_monotime(uint32_t seconds_16dot16) { #else const uint64_t ratio = UINT64_C(1000000000); #endif - return (ratio * seconds_16dot16 + 32768) >> 16; + const uint64_t ret = (ratio * seconds_16dot16 + 32768) >> 16; + return likely(ret || seconds_16dot16 == 0) ? ret : /* fix underflow */ 1; } MDBX_INTERNAL_FUNC uint32_t mdbx_osal_monotime_to_16dot16(uint64_t monotime) { @@ -1920,13 +1921,15 @@ MDBX_INTERNAL_FUNC uint32_t mdbx_osal_monotime_to_16dot16(uint64_t monotime) { if (monotime > limit) return UINT32_MAX; } + const uint32_t ret = #if defined(_WIN32) || defined(_WIN64) - return (uint32_t)((monotime << 16) / performance_frequency.QuadPart); + (uint32_t)((monotime << 16) / performance_frequency.QuadPart); #elif defined(__APPLE__) || defined(__MACH__) - return (uint32_t)((monotime << 16) / ratio_16dot16_to_monotine); + (uint32_t)((monotime << 16) / ratio_16dot16_to_monotine); #else - return (uint32_t)(monotime * 128 / 1953125); + (uint32_t)(monotime * 128 / 1953125); #endif + return likely(ret || monotime == 0) ? ret : /* fix underflow */ 1; } MDBX_INTERNAL_FUNC uint64_t mdbx_osal_monotime(void) {