kunit: introduce kunit_kmalloc_array/kunit_kcalloc() helpers

Add in:
* kunit_kmalloc_array() and wire up kunit_kmalloc() to be a special
case of it.
* kunit_kcalloc() for symmetry with kunit_kzalloc()

This should using KUnit more natural by making it more similar to the
existing *alloc() APIs.

And while we shouldn't necessarily be writing unit tests where overflow
should be a concern, it can't hurt to be safe.

Signed-off-by: Daniel Latypov <dlatypov@google.com>
Reviewed-by: David Gow <davidgow@google.com>
Reviewed-by: Brendan Higgins <brendanhiggins@google.com>
Signed-off-by: Shuah Khan <skhan@linuxfoundation.org>
This commit is contained in:
Daniel Latypov 2021-05-03 13:58:34 -07:00 committed by Shuah Khan
parent 8a5124c0f3
commit 7122debb43
2 changed files with 45 additions and 15 deletions

View file

@ -572,41 +572,43 @@ int kunit_destroy_resource(struct kunit *test, kunit_resource_match_t match,
}
EXPORT_SYMBOL_GPL(kunit_destroy_resource);
struct kunit_kmalloc_params {
struct kunit_kmalloc_array_params {
size_t n;
size_t size;
gfp_t gfp;
};
static int kunit_kmalloc_init(struct kunit_resource *res, void *context)
static int kunit_kmalloc_array_init(struct kunit_resource *res, void *context)
{
struct kunit_kmalloc_params *params = context;
struct kunit_kmalloc_array_params *params = context;
res->data = kmalloc(params->size, params->gfp);
res->data = kmalloc_array(params->n, params->size, params->gfp);
if (!res->data)
return -ENOMEM;
return 0;
}
static void kunit_kmalloc_free(struct kunit_resource *res)
static void kunit_kmalloc_array_free(struct kunit_resource *res)
{
kfree(res->data);
}
void *kunit_kmalloc(struct kunit *test, size_t size, gfp_t gfp)
void *kunit_kmalloc_array(struct kunit *test, size_t n, size_t size, gfp_t gfp)
{
struct kunit_kmalloc_params params = {
struct kunit_kmalloc_array_params params = {
.size = size,
.n = n,
.gfp = gfp
};
return kunit_alloc_resource(test,
kunit_kmalloc_init,
kunit_kmalloc_free,
kunit_kmalloc_array_init,
kunit_kmalloc_array_free,
gfp,
&params);
}
EXPORT_SYMBOL_GPL(kunit_kmalloc);
EXPORT_SYMBOL_GPL(kunit_kmalloc_array);
void kunit_kfree(struct kunit *test, const void *ptr)
{