[LTP] [PATCH v2 1/2] lib/safe_macros: Add SAFE_STRTOF
Zhao Gongyi
zhaogongyi@huawei.com
Thu Dec 1 03:51:40 CET 2022
Add a new macro SAFE_STRTOF, which is a safe mode of strtof().
Signed-off-by: Zhao Gongyi <zhaogongyi@huawei.com>
---
include/safe_macros_fn.h | 3 +++
include/tst_safe_macros.h | 3 +++
lib/safe_macros.c | 34 ++++++++++++++++++++++++++++++++++
3 files changed, 40 insertions(+)
diff --git a/include/safe_macros_fn.h b/include/safe_macros_fn.h
index 114d8fd43..d256091b7 100644
--- a/include/safe_macros_fn.h
+++ b/include/safe_macros_fn.h
@@ -133,6 +133,9 @@ unsigned long safe_strtoul(const char *file, const int lineno,
void (cleanup_fn)(void),
char *str, unsigned long min, unsigned long max);
+float safe_strtof(const char *file, const int lineno,
+ void (cleanup_fn)(void), char *str, float min, float max);
+
long safe_sysconf(const char *file, const int lineno,
void (cleanup_fn)(void), int name);
diff --git a/include/tst_safe_macros.h b/include/tst_safe_macros.h
index ab00dd14a..0cf3d7878 100644
--- a/include/tst_safe_macros.h
+++ b/include/tst_safe_macros.h
@@ -186,6 +186,9 @@ int safe_getgroups(const char *file, const int lineno, int size, gid_t list[]);
#define SAFE_STRTOUL(str, min, max) \
safe_strtoul(__FILE__, __LINE__, NULL, (str), (min), (max))
+#define SAFE_STRTOF(str, min, max) \
+ safe_strtof(__FILE__, __LINE__, NULL, (str), (min), (max))
+
#define SAFE_SYSCONF(name) \
safe_sysconf(__FILE__, __LINE__, NULL, name)
diff --git a/lib/safe_macros.c b/lib/safe_macros.c
index d8816631f..d00336748 100644
--- a/lib/safe_macros.c
+++ b/lib/safe_macros.c
@@ -21,6 +21,7 @@
#include <stdlib.h>
#include <unistd.h>
#include <malloc.h>
+#include <math.h>
#include "test.h"
#include "safe_macros.h"
@@ -629,6 +630,39 @@ unsigned long safe_strtoul(const char *file, const int lineno,
return rval;
}
+float safe_strtof(const char *file, const int lineno,
+ void (cleanup_fn) (void), char *str,
+ float min, float max)
+{
+ float rval;
+ char *endptr;
+
+ errno = 0;
+ rval = strtof(str, &endptr);
+
+ if ((errno == ERANGE) || (rval == 0)
+ || (rval == HUGE_VAL) || (rval == -HUGE_VAL)) {
+ tst_brkm_(file, lineno, TBROK | TERRNO, cleanup_fn,
+ "strtof(%s) failed", str);
+ return rval;
+ }
+
+ if (rval > max || rval < min) {
+ tst_brkm_(file, lineno, TBROK, cleanup_fn,
+ "strtof(%s): %f is out of range %f - %f",
+ str, rval, min, max);
+ return 0;
+ }
+
+ if (endptr == str || (*endptr != '\0' && *endptr != '\n')) {
+ tst_brkm_(file, lineno, TBROK, cleanup_fn,
+ "Invalid value: '%s'", str);
+ return 0;
+ }
+
+ return rval;
+}
+
long safe_sysconf(const char *file, const int lineno,
void (cleanup_fn) (void), int name)
{
--
2.17.1
More information about the ltp
mailing list