Skip to content

Commit 9dd5134

Browse files
committed
kunit/overflow: Adjust for __counted_by with DEFINE_RAW_FLEX()
When a flexible array structure has a __counted_by annotation, its use with DEFINE_RAW_FLEX() will result in the count being zero-initialized. This is expected since one doesn't want to use RAW with a counted_by struct. Adjust the tests to check for the condition and for compiler support. Reported-by: Christian Schrefl <chrisi.schrefl@gmail.com> Closes: https://lore.kernel.org/all/0bfc6b38-8bc5-4971-b6fb-dc642a73fbfe@gmail.com/ Suggested-by: Nathan Chancellor <nathan@kernel.org> Reviewed-by: Nathan Chancellor <nathan@kernel.org> Link: https://lore.kernel.org/r/20240610182301.work.272-kees@kernel.org Tested-by: Christian Schrefl <chrisi.schrefl@gmail.com> Reviewed-by: Christian Schrefl <chrisi.schrefl@gmail.com> Signed-off-by: Kees Cook <kees@kernel.org>
1 parent f7d3b1f commit 9dd5134

1 file changed

Lines changed: 17 additions & 3 deletions

File tree

lib/overflow_kunit.c

Lines changed: 17 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1178,14 +1178,28 @@ struct foo {
11781178
s16 array[] __counted_by(counter);
11791179
};
11801180

1181+
struct bar {
1182+
int a;
1183+
u32 counter;
1184+
s16 array[];
1185+
};
1186+
11811187
static void DEFINE_FLEX_test(struct kunit *test)
11821188
{
1183-
DEFINE_RAW_FLEX(struct foo, two, array, 2);
1189+
/* Using _RAW_ on a __counted_by struct will initialize "counter" to zero */
1190+
DEFINE_RAW_FLEX(struct foo, two_but_zero, array, 2);
1191+
#if __has_attribute(__counted_by__)
1192+
int expected_raw_size = sizeof(struct foo);
1193+
#else
1194+
int expected_raw_size = sizeof(struct foo) + 2 * sizeof(s16);
1195+
#endif
1196+
/* Without annotation, it will always be on-stack size. */
1197+
DEFINE_RAW_FLEX(struct bar, two, array, 2);
11841198
DEFINE_FLEX(struct foo, eight, array, counter, 8);
11851199
DEFINE_FLEX(struct foo, empty, array, counter, 0);
11861200

1187-
KUNIT_EXPECT_EQ(test, __struct_size(two),
1188-
sizeof(struct foo) + sizeof(s16) + sizeof(s16));
1201+
KUNIT_EXPECT_EQ(test, __struct_size(two_but_zero), expected_raw_size);
1202+
KUNIT_EXPECT_EQ(test, __struct_size(two), sizeof(struct bar) + 2 * sizeof(s16));
11891203
KUNIT_EXPECT_EQ(test, __struct_size(eight), 24);
11901204
KUNIT_EXPECT_EQ(test, __struct_size(empty), sizeof(struct foo));
11911205
}

0 commit comments

Comments
 (0)