Skip to content

Commit 080c857

Browse files
ftang1tehcaster
authored andcommitted
mm/slub, kunit: Add testcase for krealloc redzone and zeroing
Danilo Krummrich raised issue about krealloc+GFP_ZERO [1], and Vlastimil suggested to add some test case which can sanity test the kmalloc-redzone and zeroing by utilizing the kmalloc's 'orig_size' debug feature. It covers the grow and shrink case of krealloc() re-using current kmalloc object, and the case of re-allocating a new bigger object. [1]. https://lore.kernel.org/lkml/20240812223707.32049-1-dakr@kernel.org/ Suggested-by: Vlastimil Babka <vbabka@suse.cz> Signed-off-by: Feng Tang <feng.tang@intel.com> Signed-off-by: Vlastimil Babka <vbabka@suse.cz>
1 parent 5474d33 commit 080c857

File tree

1 file changed

+42
-0
lines changed

1 file changed

+42
-0
lines changed

lib/slub_kunit.c

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -192,6 +192,47 @@ static void test_leak_destroy(struct kunit *test)
192192
KUNIT_EXPECT_EQ(test, 2, slab_errors);
193193
}
194194

195+
static void test_krealloc_redzone_zeroing(struct kunit *test)
196+
{
197+
u8 *p;
198+
int i;
199+
struct kmem_cache *s = test_kmem_cache_create("TestSlub_krealloc", 64,
200+
SLAB_KMALLOC|SLAB_STORE_USER|SLAB_RED_ZONE);
201+
202+
p = alloc_hooks(__kmalloc_cache_noprof(s, GFP_KERNEL, 48));
203+
memset(p, 0xff, 48);
204+
205+
kasan_disable_current();
206+
OPTIMIZER_HIDE_VAR(p);
207+
208+
/* Test shrink */
209+
p = krealloc(p, 40, GFP_KERNEL | __GFP_ZERO);
210+
for (i = 40; i < 64; i++)
211+
KUNIT_EXPECT_EQ(test, p[i], SLUB_RED_ACTIVE);
212+
213+
/* Test grow within the same 64B kmalloc object */
214+
p = krealloc(p, 56, GFP_KERNEL | __GFP_ZERO);
215+
for (i = 40; i < 56; i++)
216+
KUNIT_EXPECT_EQ(test, p[i], 0);
217+
for (i = 56; i < 64; i++)
218+
KUNIT_EXPECT_EQ(test, p[i], SLUB_RED_ACTIVE);
219+
220+
validate_slab_cache(s);
221+
KUNIT_EXPECT_EQ(test, 0, slab_errors);
222+
223+
memset(p, 0xff, 56);
224+
/* Test grow with allocating a bigger 128B object */
225+
p = krealloc(p, 112, GFP_KERNEL | __GFP_ZERO);
226+
for (i = 0; i < 56; i++)
227+
KUNIT_EXPECT_EQ(test, p[i], 0xff);
228+
for (i = 56; i < 112; i++)
229+
KUNIT_EXPECT_EQ(test, p[i], 0);
230+
231+
kfree(p);
232+
kasan_enable_current();
233+
kmem_cache_destroy(s);
234+
}
235+
195236
static int test_init(struct kunit *test)
196237
{
197238
slab_errors = 0;
@@ -214,6 +255,7 @@ static struct kunit_case test_cases[] = {
214255
KUNIT_CASE(test_kmalloc_redzone_access),
215256
KUNIT_CASE(test_kfree_rcu),
216257
KUNIT_CASE(test_leak_destroy),
258+
KUNIT_CASE(test_krealloc_redzone_zeroing),
217259
{}
218260
};
219261

0 commit comments

Comments
 (0)