[PATCH xbacklight] Subject: exit if conv. from string to double fails

Roberto Ricci rroberto2r at gmail.com
Sun Feb 11 16:12:14 UTC 2018


Signed-off-by: Roberto Ricci <rroberto2r at gmail.com>

atof(3), whose return value is undefined on error, is used to parse
command line arguments, leading to undefined beavior if something else
than a number is specified.
this patch uses strtod(3) and exits on error.
---
 xbacklight.c | 23 +++++++++++++++++------
 1 file changed, 17 insertions(+), 6 deletions(-)

diff --git a/xbacklight.c b/xbacklight.c
index 278043f..7e7eb7d 100644
--- a/xbacklight.c
+++ b/xbacklight.c
@@ -26,6 +26,7 @@
 
 #include <stdio.h>
 #include <stdlib.h>
+#include <errno.h>
 
 #include <xcb/xcb.h>
 #include <xcb/xcb_util.h>
@@ -59,6 +60,16 @@ usage (int exitcode)
     exit (exitcode);
 }
 
+static double
+atof_or_die (char *str)
+{
+    double retval;
+    errno = 0;
+    retval = strtod(str, NULL);
+    if (errno) usage(1);
+    return retval;
+}
+
 static void
 missing_arg (const char *option)
 {
@@ -150,39 +161,39 @@ main (int argc, char **argv)
 	{
 	    if (++i >= argc) missing_arg (argv[i-1]);
 	    op = Set;
-	    value = atof (argv[i]);
+	    value = atof_or_die (argv[i]);
 	    continue;
 	}
 	if (argv[i][0] == '=' && isdigit (argv[i][1]))
 	{
 	    op = Set;
-	    value = atof (argv[i] + 1);
+	    value = atof_or_die (argv[i] + 1);
 	    continue;
 	}
 	if (!strcmp (argv[i], "-inc") || !strcmp (argv[i], "+"))
 	{
 	    if (++i >= argc) missing_arg (argv[i-1]);
 	    op = Inc;
-	    value = atof (argv[i]);
+	    value = atof_or_die (argv[i]);
 	    continue;
 	}
 	if (argv[i][0] == '+' && isdigit (argv[i][1]))
 	{
 	    op = Inc;
-	    value = atof (argv[i] + 1);
+	    value = atof_or_die (argv[i] + 1);
 	    continue;
 	}
 	if (!strcmp (argv[i], "-dec") || !strcmp (argv[i], "-"))
 	{
 	    if (++i >= argc) missing_arg (argv[i-1]);
 	    op = Dec;
-	    value = atof (argv[i]);
+	    value = atof_or_die (argv[i]);
 	    continue;
 	}
 	if (argv[i][0] == '-' && isdigit (argv[i][1]))
 	{
 	    op = Dec;
-	    value = atof (argv[i] + 1);
+	    value = atof_or_die (argv[i] + 1);
 	    continue;
 	}
 	if (!strcmp (argv[i], "-get") || !strcmp (argv[i], "-g"))
-- 
2.16.1



More information about the xorg-devel mailing list