java-topology/defects/memcached/patch/0001-slabs-clsid-binary-search.patch

40 lines
1.5 KiB
Diff

# UNDF: UNDF-2026-000000348
From HEAD Mon Sep 17 00:00:00 2001
Subject: [PATCH] slabs: replace linear scan in slabs_clsid with binary search
CWE-407: slabs_clsid() walks the slabclass[] array linearly to find the
smallest class that fits a requested size. slabclass[] is sorted ascending
by size (guaranteed by slabs_init), so binary search applies.
With up to 63 slab classes (MAX_NUMBER_OF_SLAB_CLASSES-1) linear search
performs up to 63 comparisons; binary search performs at most 6 (⌈log₂63⌉).
slabs_clsid is called on every item allocation (do_item_alloc, do_item_alloc_chunk,
item_store_check) making it a hot path at high write throughput.
--- a/slabs.c
+++ b/slabs.c
@@ -77,12 +77,19 @@ unsigned int slabs_size(const int clsid) {
unsigned int slabs_clsid(const size_t size) {
- int res = POWER_SMALLEST;
-
if (size == 0 || size > settings.item_size_max)
return 0;
- while (size > slabclass[res].size)
- if (res++ == power_largest) /* won't fit in the biggest slab */
- return power_largest;
- return res;
+
+ /* CWE-407 fix: binary search over sorted slabclass[POWER_SMALLEST..power_largest].
+ * slabs_init guarantees strictly increasing .size values. */
+ int lo = POWER_SMALLEST, hi = power_largest;
+ while (lo < hi) {
+ int mid = lo + (hi - lo) / 2;
+ if (slabclass[mid].size < size)
+ lo = mid + 1;
+ else
+ hi = mid;
+ }
+ /* lo == hi == smallest class whose size >= requested size */
+ return lo;
}