[Libguestfs] [PATCH 1/3] mllib: Fix parsing of integers on the command line and use correct int type.

Richard W.M. Jones rjones at redhat.com
Fri Jul 15 21:37:27 UTC 2016


Currently input such as "1ABC" or "1.1" is parsed (as 1).  If there is
trailing data on the command line, refuse to accept it.

In addition this parses the integer into a C 'long', which is as close
as we can get to the OCaml idea of a native int.  This prevents the
gross rounding error from the earlier code if the integer parameter
was larger than 32 bits (on a 64 bit platform), but is still not
completely free of rounding problems because the OCaml type is 31 or
63 bits.

Probably we should have explicit 'int32' and 'int64' types in the
OCaml code, instead of using (native) 'int'.
---
 mllib/getopt-c.c | 9 ++++++---
 1 file changed, 6 insertions(+), 3 deletions(-)

diff --git a/mllib/getopt-c.c b/mllib/getopt-c.c
index 1f129a7..afb8793 100644
--- a/mllib/getopt-c.c
+++ b/mllib/getopt-c.c
@@ -247,7 +247,8 @@ guestfs_int_mllib_getopt_parse (value argsv, value specsv, value anon_funv, valu
     actionv = Field (specv, 1);
 
     switch (Tag_val (actionv)) {
-    int num;
+    long num;
+    int nchars;
 
     case 0:  /* Unit of (unit -> unit) */
       v = Field (actionv, 0);
@@ -274,7 +275,8 @@ guestfs_int_mllib_getopt_parse (value argsv, value specsv, value anon_funv, valu
       break;
 
     case 5:  /* Int of string * (int -> unit) */
-      if (sscanf (optarg, "%d", &num) != 1) {
+      if (sscanf (optarg, "%ld%n", &num, &nchars) < 1
+          || optarg[nchars] != '\0') {
         fprintf (stderr, _("'%s' is not a numeric value.\n"),
                  guestfs_int_program_name);
         show_error (EXIT_FAILURE);
@@ -284,7 +286,8 @@ guestfs_int_mllib_getopt_parse (value argsv, value specsv, value anon_funv, valu
       break;
 
     case 6:  /* Set_int of string * int ref */
-      if (sscanf (optarg, "%d", &num) != 1) {
+      if (sscanf (optarg, "%ld%n", &num, &nchars) < 1
+          || optarg[nchars] != '\0') {
         fprintf (stderr, _("'%s' is not a numeric value.\n"),
                  guestfs_int_program_name);
         show_error (EXIT_FAILURE);
-- 
2.7.4




More information about the Libguestfs mailing list