From 3c60e3fa4f4d470085a6f9a8ca6dc78536899cf0 Mon Sep 17 00:00:00 2001
From: Mergen Imeev <imeevma@gmail.com>
Date: Mon, 13 Sep 2021 10:43:25 +0300
Subject: [PATCH] sql: fix possible undefined behavior during cast

This patch fixes possible undefined behavior during the implicit cast of
INTEGER to DOUBLE. The problem is, if the INTEGER is close enough to
2^64, it will be cast to 2^64 when it is cast to DOUBLE. Since we have a
check for loss of precision, this will cause this DOUBLE to be cast to
an INTEGER, which will result in undefined behavior since this DOUBLE is
outside the range of INTEGER.
---
 src/box/sql/mem.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/src/box/sql/mem.c b/src/box/sql/mem.c
index 89b99a183e..99ac4d8e72 100644
--- a/src/box/sql/mem.c
+++ b/src/box/sql/mem.c
@@ -682,7 +682,7 @@ uint_to_double_precise(struct Mem *mem)
 	assert(mem->type == MEM_TYPE_UINT);
 	double d;
 	d = (double)mem->u.u;
-	if (mem->u.u != (uint64_t)d)
+	if (d == (double)UINT64_MAX || mem->u.u != (uint64_t)d)
 		return -1;
 	mem->u.r = d;
 	mem->flags = 0;
-- 
GitLab