[LTP] [PATCH 1/2] lib/safe_macros: Add SAFE_STRTOF

Zhao Gongyi zhaogongyi@huawei.com
Wed Nov 30 03:19:00 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         | 26 ++++++++++++++++++++++++++
 3 files changed, 32 insertions(+)

diff --git a/include/safe_macros_fn.h b/include/safe_macros_fn.h
index 114d8fd43..546db4ad8 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);
+
 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..9ff98e7db 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) \
+	safe_strtof(__FILE__, __LINE__, NULL, (str))
+
 #define SAFE_SYSCONF(name) \
 	safe_sysconf(__FILE__, __LINE__, NULL, name)

diff --git a/lib/safe_macros.c b/lib/safe_macros.c
index d8816631f..954f1d40a 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,31 @@ 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 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 (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