summaryrefslogtreecommitdiffstats
path: root/src/utils.c
diff options
context:
space:
mode:
authorAlejandro Sirgo Rica <asirgo@soleta.eu>2024-10-25 11:53:22 +0200
committerAlejandro Sirgo Rica <asirgo@soleta.eu>2024-10-25 15:09:31 +0200
commite679925bd0c8608ebe24f34917347ad939c6506d (patch)
tree9076d0ff5d251bc0a0051589796b9f81cb86b11c /src/utils.c
parente960063a137c8fe760a40a73ccd081e457b23952 (diff)
src: add safe_strtoull for safe string to number conversion
Add safe_strtoull to validate the execution of strtoull. Definining the base of the number is required becase partition codes are base 16 but they lack the 0x prefix. Replace uses of atoi and strtoull/strtoul and log the conversion errors.
Diffstat (limited to 'src/utils.c')
-rw-r--r--src/utils.c28
1 files changed, 28 insertions, 0 deletions
diff --git a/src/utils.c b/src/utils.c
index d49a9ac..2607fc6 100644
--- a/src/utils.c
+++ b/src/utils.c
@@ -7,7 +7,12 @@
* (at your option) any later version.
*/
+
#include <ctype.h>
+#include <errno.h>
+#include <assert.h>
+#include <limits.h>
+#include <stdlib.h>
#include "utils.h"
void str_toupper(char *str)
@@ -29,3 +34,26 @@ void str_tolower(char *str)
c++;
}
}
+
+int safe_strtoull(const char *str, uint64_t *out_value, int base, uint64_t max)
+{
+ char *endptr = NULL;
+ uint64_t result;
+ errno = 0;
+
+ assert(str != NULL && out_value != NULL);
+
+ if (str[0] == '-')
+ return -1;
+
+ result = strtoull(str, &endptr, base);
+
+ if (endptr == str ||
+ *endptr != '\0' ||
+ (errno == ERANGE && result == ULLONG_MAX) ||
+ result > max)
+ return -1;
+
+ *out_value = result;
+ return 0;
+}