libselinux/backport-libselinux-use-DJB2a-string-hash-function.patch
fly_fzc 1adbdc5f45 backport upstream patches
(cherry picked from commit 0327677f388cddd541515ad3c502b705258fbffc)
2023-12-07 09:35:09 +08:00

54 lines
1.6 KiB
Diff

From f1178a13dc8bc9e750cf59de1db8fc48867f9293 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Christian=20G=C3=B6ttsche?= <cgzones@googlemail.com>
Date: Wed, 16 Aug 2023 14:38:44 +0200
Subject: [PATCH] libselinux: use DJB2a string hash function
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
The hash table implementation uses `& (SIDTAB_SIZE - 1)` to truncate
generated hashes to the number of buckets. This operation is equal to
`% SIDTAB_SIZE` if and only if the size is a power of two (which seems
to be always the case). One property of the binary and with a power of
two (and probably a small one <=2048) is all higher bits are discarded.
Thus a hash function is needed with a good avalanche effect, which the
current one is not.
Signed-off-by: Christian Göttsche <cgzones@googlemail.com>
Acked-by: James Carter <jwcart2@gmail.com>
---
libselinux/src/avc_sidtab.c | 17 +++++++----------
1 file changed, 7 insertions(+), 10 deletions(-)
diff --git a/src/avc_sidtab.c b/src/avc_sidtab.c
index f179d855..e396a938 100644
--- a/src/avc_sidtab.c
+++ b/src/avc_sidtab.c
@@ -15,16 +15,13 @@
static inline unsigned sidtab_hash(const char * key)
{
- const char *p;
- unsigned int size;
- unsigned int val;
-
- val = 0;
- size = strlen(key);
- for (p = key; (unsigned int)(p - key) < size; p++)
- val =
- (val << 4 | (val >> (8 * sizeof(unsigned int) - 4))) ^ (*p);
- return val & (SIDTAB_SIZE - 1);
+ unsigned int hash = 5381;
+ unsigned char c;
+
+ while ((c = *(unsigned const char *)key++))
+ hash = ((hash << 5) + hash) ^ c;
+
+ return hash & (SIDTAB_SIZE - 1);
}
int sidtab_init(struct sidtab *s)
--
2.27.0