[PATCH] nolibc/stdlib: Improve `getauxval(3)` implementation

From: Charles Mirabile
Date: Tue Jan 16 2024 - 13:13:21 EST


Previously the getauxval function checked for a doubly null entry (i.e.
one whose type and value both were 0) in the auxv array before exiting
the loop.

At least on x86-64, the ABI only specifies that one more long will be
present with value 0 (type AT_NULL) after the pairs of auxv entries.
Whether or not it has a corresponding value is unspecified. This value is
present on linux, but there is no reason to check it as simply seeing an
auxv entry whose type value is AT_NULL should be enough.

This is a matter of taste, but I think processing the data in a structured
way by coercing it into an array of type value pairs, using multiple
return style, and a for loop with a clear exit condition is more readable
than the existing infinite loop with multiple exit points and a return
value variable.

I also added a call to set errno to ENOENT when the entry is not found as
glibc does which allows programs to disambiguate between the case of an
auxv that is not present, and one that is, but with value zero.

Fixes: c61a078015f3 ("nolibc/stdlib: Implement `getauxval(3)` function")
Signed-off-by: Charles Mirabile <cmirabil@xxxxxxxxxx>
---
tools/include/nolibc/stdlib.h | 34 +++++++++++++---------------------
1 file changed, 13 insertions(+), 21 deletions(-)

diff --git a/tools/include/nolibc/stdlib.h b/tools/include/nolibc/stdlib.h
index bacfd35c5156..47be99c5a539 100644
--- a/tools/include/nolibc/stdlib.h
+++ b/tools/include/nolibc/stdlib.h
@@ -104,27 +104,19 @@ char *getenv(const char *name)
static __attribute__((unused))
unsigned long getauxval(unsigned long type)
{
- const unsigned long *auxv = _auxv;
- unsigned long ret;
-
- if (!auxv)
- return 0;
-
- while (1) {
- if (!auxv[0] && !auxv[1]) {
- ret = 0;
- break;
- }
-
- if (auxv[0] == type) {
- ret = auxv[1];
- break;
- }
-
- auxv += 2;
- }
-
- return ret;
+ const struct {
+ unsigned long type, val;
+ } *auxv = (void *)_auxv;
+
+ if (!auxv || !type)
+ goto out;
+
+ for (; auxv->type; ++auxv)
+ if (auxv->type == type)
+ return auxv->val;
+out:
+ SET_ERRNO(ENOENT);
+ return 0;
}

static __attribute__((unused))
--
2.41.0