From 2834fa26c90b71a4ec2142be02b5a86886e85233 Mon Sep 17 00:00:00 2001 From: manaldush Date: Thu, 4 Sep 2025 13:57:45 +0300 Subject: [PATCH] Fix an undefined behavior for bit shift in citus_stat_tenants.c (#7954) DESCRIPTION: Fixes an undefined behavior that could happen when computing tenant score for citus_stat_tenants Add check for shift size, reset to zero in case of overflow Fixes #7953. --------- Co-authored-by: Onur Tirtir --- src/backend/distributed/stats/stat_tenants.c | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/src/backend/distributed/stats/stat_tenants.c b/src/backend/distributed/stats/stat_tenants.c index 17cd3bf46..7c6c82299 100644 --- a/src/backend/distributed/stats/stat_tenants.c +++ b/src/backend/distributed/stats/stat_tenants.c @@ -49,6 +49,9 @@ ExecutorEnd_hook_type prev_ExecutorEnd = NULL; #define STAT_TENANTS_COLUMNS 9 #define ONE_QUERY_SCORE 1000000000 +/* this doesn't attempt dereferencing given input and is computed in compile-time, so it's safe */ +#define TENANT_STATS_SCORE_FIELD_BIT_LENGTH (sizeof(((TenantStats *) NULL)->score) * 8) + static char AttributeToTenant[MAX_TENANT_ATTRIBUTE_LENGTH] = ""; static CmdType AttributeToCommandType = CMD_UNKNOWN; static int AttributeToColocationGroupId = INVALID_COLOCATION_ID; @@ -605,8 +608,13 @@ ReduceScoreIfNecessary(TenantStats *tenantStats, TimestampTz queryTime) */ if (periodCountAfterLastScoreReduction > 0) { - tenantStats->score >>= periodCountAfterLastScoreReduction; tenantStats->lastScoreReduction = queryTime; + + /* addtional check to avoid undefined behavior */ + tenantStats->score = (periodCountAfterLastScoreReduction < + TENANT_STATS_SCORE_FIELD_BIT_LENGTH) + ? tenantStats->score >> periodCountAfterLastScoreReduction + : 0; } }