[LTP] [PATCH v3 1/3] lib/safe_macros: Add SAFE_STRTOF
Zhao Gongyi
zhaogongyi@huawei.com
Mon Dec 5 07:54:30 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 | 33 +++++++++++++++++++++++++++++++++
3 files changed, 39 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..0fb5580ac 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,38 @@ 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) {
+ tst_brkm_(file, lineno, TBROK | TERRNO, cleanup_fn,
+ "strtof(%s) failed", str);
+ return rval;
+ }
+
+ if (endptr == str || (*endptr != '\0' && *endptr != '\n')) {
+ tst_brkm_(file, lineno, TBROK, cleanup_fn,
+ "Invalid value: '%s'", str);
+ return 0;
+ }
+
+ 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;
+ }
+
+ 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