From bd68950c352b5c9350fe8be22f5dc5d9f1ce2707 Mon Sep 17 00:00:00 2001 From: Bartosz Golaszewski Date: Sat, 3 Aug 2019 18:14:32 +0200 Subject: [PATCH] tests: mockup: validate the chip index where applicable In functions that take the chip index as argument: let's verify that its value is valid i.e. it refers to an existing chip to avoid potential segfaults. While we're at it: delegate the validation of arguments in mockup getter helpers to a separate routine. Signed-off-by: Bartosz Golaszewski --- tests/mockup/gpio-mockup.c | 35 ++++++++++++++++++++--------------- 1 file changed, 20 insertions(+), 15 deletions(-) diff --git a/tests/mockup/gpio-mockup.c b/tests/mockup/gpio-mockup.c index 56920b7..608a764 100644 --- a/tests/mockup/gpio-mockup.c +++ b/tests/mockup/gpio-mockup.c @@ -375,34 +375,43 @@ EXPORT int gpio_mockup_remove(struct gpio_mockup *ctx) return 0; } -EXPORT const char * -gpio_mockup_chip_name(struct gpio_mockup *ctx, unsigned int idx) +static bool index_valid(struct gpio_mockup *ctx, unsigned int idx) { if (!ctx->chips) { errno = ENODEV; - return NULL; + return false; + } + + if (idx >= ctx->num_chips) { + errno = EINVAL; + return false; } + return true; +} + +EXPORT const char * +gpio_mockup_chip_name(struct gpio_mockup *ctx, unsigned int idx) +{ + if (!index_valid(ctx, idx)) + return NULL; + return ctx->chips[idx]->name; } EXPORT const char * gpio_mockup_chip_path(struct gpio_mockup *ctx, unsigned int idx) { - if (!ctx->chips) { - errno = ENODEV; + if (!index_valid(ctx, idx)) return NULL; - } return ctx->chips[idx]->path; } EXPORT int gpio_mockup_chip_num(struct gpio_mockup *ctx, unsigned int idx) { - if (!ctx->chips) { - errno = ENODEV; + if (!index_valid(ctx, idx)) return -1; - } return ctx->chips[idx]->num; } @@ -432,10 +441,8 @@ EXPORT int gpio_mockup_get_value(struct gpio_mockup *ctx, char buf; int fd; - if (!ctx->chips) { - errno = ENODEV; + if (!index_valid(ctx, chip_idx)) return -1; - } fd = debugfs_open(ctx->chips[chip_idx]->num, line_offset, O_RDONLY); if (fd < 0) @@ -465,10 +472,8 @@ EXPORT int gpio_mockup_set_pull(struct gpio_mockup *ctx, ssize_t wr; int fd; - if (!ctx->chips) { - errno = ENODEV; + if (!index_valid(ctx, chip_idx)) return -1; - } fd = debugfs_open(ctx->chips[chip_idx]->num, line_offset, O_WRONLY); if (fd < 0) -- 2.30.2