Parcourir la source

cmSystemTools: Fix StringToULong to reject negative numbers

Fixes: #19161
Brad King il y a 6 ans
Parent
commit
f0948499f6
2 fichiers modifiés avec 23 ajouts et 0 suppressions
  1. 6 0
      Source/cmSystemTools.cxx
  2. 17 0
      Tests/CMakeLib/testSystemTools.cxx

+ 6 - 0
Source/cmSystemTools.cxx

@@ -3023,6 +3023,12 @@ bool cmSystemTools::StringToULong(const char* str, unsigned long* value)
 {
   errno = 0;
   char* endp;
+  while (isspace(*str)) {
+    ++str;
+  }
+  if (*str == '-') {
+    return false;
+  }
   *value = strtoul(str, &endp, 10);
   return (*endp == '\0') && (endp != str) && (errno == 0);
 }

+ 17 - 0
Tests/CMakeLib/testSystemTools.cxx

@@ -93,5 +93,22 @@ int testSystemTools(int /*unused*/, char* /*unused*/ [])
   if (!failed) {
     cmPassed("cmSystemTools::strverscmp working");
   }
+
+  // ----------------------------------------------------------------------
+  // Test cmSystemTools::StringToULong
+  {
+    unsigned long value;
+    cmAssert(cmSystemTools::StringToULong("1", &value) && value == 1,
+             "StringToULong parses a decimal integer.");
+    cmAssert(cmSystemTools::StringToULong(" 1", &value) && value == 1,
+             "StringToULong parses a decimal integer after whitespace.");
+    cmAssert(!cmSystemTools::StringToULong("-1", &value),
+             "StringToULong rejects a negative number.");
+    cmAssert(!cmSystemTools::StringToULong(" -1", &value),
+             "StringToULong rejects a negative number after whitespace.");
+    cmAssert(!cmSystemTools::StringToULong("1x", &value),
+             "StringToULong rejects trailing content.");
+  }
+
   return failed;
 }