From 7ff7394d9e4e9189c30fd018235e6b1728c6f2d0 Mon Sep 17 00:00:00 2001 From: Zbigniew Jędrzejewski-Szmek Date: Fri, 11 Oct 2013 19:33:13 -0400 Subject: Never call qsort on potentially NULL arrays This extends 62678ded 'efi: never call qsort on potentially NULL arrays' to all other places where qsort is used and it is not obvious that the count is non-zero. --- src/shared/cgroup-show.c | 2 ++ src/shared/conf-files.c | 2 +- src/shared/efivars.c | 3 +-- src/shared/fileio.c | 1 + src/shared/util.h | 12 ++++++++++++ 5 files changed, 17 insertions(+), 3 deletions(-) (limited to 'src/shared') diff --git a/src/shared/cgroup-show.c b/src/shared/cgroup-show.c index e971f36190..cc44ab4ea9 100644 --- a/src/shared/cgroup-show.c +++ b/src/shared/cgroup-show.c @@ -44,6 +44,8 @@ static void show_pid_array(int pids[], unsigned n_pids, const char *prefix, unsi unsigned i, m, pid_width; pid_t biggest = 0; + assert(n_pids > 0); + /* Filter duplicates */ m = 0; for (i = 0; i < n_pids; i++) { diff --git a/src/shared/conf-files.c b/src/shared/conf-files.c index 6d99739353..ed4070c662 100644 --- a/src/shared/conf-files.c +++ b/src/shared/conf-files.c @@ -127,7 +127,7 @@ static int conf_files_list_strv_internal(char ***strv, const char *suffix, const return -ENOMEM; } - qsort(files, hashmap_size(fh), sizeof(char *), base_cmp); + qsort_safe(files, hashmap_size(fh), sizeof(char *), base_cmp); *strv = files; hashmap_free(fh); diff --git a/src/shared/efivars.c b/src/shared/efivars.c index c015b16857..f3eb6a6e5d 100644 --- a/src/shared/efivars.c +++ b/src/shared/efivars.c @@ -384,8 +384,7 @@ int efi_get_boot_options(uint16_t **options) { list[count ++] = id; } - if (list) - qsort(list, count, sizeof(uint16_t), cmp_uint16); + qsort_safe(list, count, sizeof(uint16_t), cmp_uint16); *options = list; return count; diff --git a/src/shared/fileio.c b/src/shared/fileio.c index 603a1c7b38..733b320388 100644 --- a/src/shared/fileio.c +++ b/src/shared/fileio.c @@ -662,6 +662,7 @@ int get_status_field(const char *filename, const char *pattern, char **field) { int r; assert(filename); + assert(pattern); assert(field); r = read_full_file(filename, &status, NULL); diff --git a/src/shared/util.h b/src/shared/util.h index 26af5b30af..09e556d011 100644 --- a/src/shared/util.h +++ b/src/shared/util.h @@ -772,3 +772,15 @@ bool id128_is_valid(const char *s) _pure_; void parse_user_at_host(char *arg, char **user, char **host); int split_pair(const char *s, const char *sep, char **l, char **r); + +/** + * Normal qsort requires base to be nonnull. Here were require + * that only if nmemb > 0. + */ +static inline void qsort_safe(void *base, size_t nmemb, size_t size, + int (*compar)(const void *, const void *)) { + if (nmemb) { + assert(base); + qsort(base, nmemb, size, compar); + } +} -- cgit v1.2.3-54-g00ecf