[LTP] [PATCH v16 1/2] lib: New library function tst_get_free_uid
Petr Vorel
pvorel@suse.cz
Thu Oct 22 17:25:42 CEST 2026
Hi Wei,
> +uid_t tst_get_free_uid_(const char *file, const int lineno, uid_t skip);
> +
> +/**
> + * tst_get_free_uid() - Find a UID not assigned to any user.
> + * @skip: UID value to skip (pass 0 to skip none).
> + *
> + * Scans the password database for the first unused UID starting
> + * from 1, skipping @skip. Calls tst_brk(TBROK) if no free UID
> + * is found or a lookup error occurs.
> + *
> + * Return: An unused uid_t value.
> + */
> +#define tst_get_free_uid(skip) tst_get_free_uid_(__FILE__, __LINE__, (skip))
> +
> /*
> * Find unassigned gid. The skip argument can be used to ignore e.g. the main
> * group of a specific user in case it's not listed in the group file. If you
> diff --git a/lib/tst_uid.c b/lib/tst_uid.c
> index b0b087362..47c267bc4 100644
> --- a/lib/tst_uid.c
> +++ b/lib/tst_uid.c
> @@ -5,6 +5,7 @@
> #include <sys/types.h>
> #include <grp.h>
> +#include <pwd.h>
> #include <errno.h>
> #define TST_NO_DEFAULT_MAIN
> @@ -12,6 +13,33 @@
> #include "tst_uid.h"
> #define MAX_GID 32767
> +#define MAX_UID 32767
> +
> +uid_t tst_get_free_uid_(const char *file, const int lineno, uid_t skip)
> +{
> + uid_t ret;
> +
> + for (ret = 1; ret < MAX_UID; ret++) {
> + if (ret == skip)
> + continue;
> +
> + errno = 0;
> + if (getpwuid(ret))
> + continue;
If you don't mind I'd prefer to use the same approach which is on
tst_get_free_gid_(), e.g. set errno first:
errno = 0;
for (ret = 1; ret < MAX_UID; ret++) {
if (ret == skip || getpwuid(ret))
continue;
Reviewed-by: Petr Vorel <pvorel@suse.cz>
Other than that LGTM.
Cc Martin in case he wants to add his ack before I merge.
Kind regards,
Petr
> +
> + if (errno == 0 || errno == ENOENT || errno == ESRCH) {
> + tst_res_(file, lineno, TINFO,
> + "Found unused UID %d", (int)ret);
> + return ret;
> + }
> +
> + tst_brk_(file, lineno, TBROK | TERRNO, "User ID lookup failed");
> + return (uid_t)-1;
> + }
> +
> + tst_brk_(file, lineno, TBROK, "No free user ID found");
> + return (uid_t)-1;
> +}
More information about the ltp
mailing list