usage: SAFE_STRTOL(cleanup_fn, string, min, max);
when no specific range required, min could be LONG_MIN and max could be
LONG_MAX;

return: converted long int type value.

Signed-off-by: Caspar Zhang <[email protected]>
---
 include/safe_macros.h |    5 +++++
 lib/safe_macros.c     |   24 +++++++++++++++++++++++-
 2 files changed, 28 insertions(+), 1 deletions(-)

diff --git a/include/safe_macros.h b/include/safe_macros.h
index 12f03ef..fbfe6cd 100644
--- a/include/safe_macros.h
+++ b/include/safe_macros.h
@@ -146,5 +146,10 @@ int safe_truncate(const char *file, const int lineno,
 #define SAFE_TRUNCATE(cleanup_fn, fd, length) \
 	safe_truncate(__FILE__, __LINE__, cleanup_fn, (path), (length))
 
+long safe_strtol(const char *file, const int lineno,
+	    void (cleanup_fn)(void), char *str, long min, long max);
+#define SAFE_STRTOL(cleanup_fn, str, min, max) \
+	safe_strtol(__FILE__, __LINE__, cleanup_fn, (str), (min), (max))
+
 #endif
 #endif
diff --git a/lib/safe_macros.c b/lib/safe_macros.c
index 569952d..c6280c6 100644
--- a/lib/safe_macros.c
+++ b/lib/safe_macros.c
@@ -4,6 +4,7 @@
 #include <sys/stat.h>
 #include <fcntl.h>
 #include <libgen.h>
+#include <limits.h>
 #include <pwd.h>
 #include <stdarg.h>
 #include <stdlib.h>
@@ -315,7 +316,7 @@ int safe_ftruncate(const char *file, const int lineno,
 	    void (cleanup_fn)(void), int fd, off_t length)
 {
 	int rval;
-	
+
 	rval = ftruncate(fd, length);
 	if (rval == -1) {
 		tst_brkm(TBROK|TERRNO, cleanup_fn, "ftruncate failed at %s:%d",
@@ -338,3 +339,24 @@ int safe_truncate(const char *file, const int lineno,
 
 	return rval;
 }
+
+long safe_strtol(const char *file, const int lineno,
+	    void (cleanup_fn)(void), char *str, long min, long max)
+{
+	int rval;
+	char *endptr;
+
+	rval = strtol(str, &endptr, 10);
+	if ((errno == ERANGE && (rval == LONG_MAX || rval == LONG_MIN))
+		    || (errno != 0 && rval == 0))
+		tst_brkm(TBROK|TERRNO, cleanup_fn, "strtol failed at %s:%d",
+			 file, lineno);
+	if (rval >= max || rval <= min)
+		tst_brkm(TBROK, cleanup_fn,
+			 "converted value out of range: %ld - %ld",
+			 min, max);
+	if (endptr == str || (*endptr != '\0' && *endptr != '\n'))
+		tst_brkm(TBROK, cleanup_fn, "Invalid value: %s", str);
+
+	return rval;
+}
------------------------------------------------------------------------------
Virtualization & Cloud Management Using Capacity Planning
Cloud computing makes use of virtualization - but cloud computing 
also focuses on allowing computing to be delivered as a service.
http://www.accelacomm.com/jaw/sfnl/114/51521223/
_______________________________________________
Ltp-list mailing list
[email protected]
https://lists.sourceforge.net/lists/listinfo/ltp-list

Reply via email to