Use getopt_long() to handle command line arguments.
Introduce ext_err for common exit with errors.

Signed-off-by: Fouad Hilly <fouad.hi...@cloud.com>
---
 tools/misc/xen-ucode.c | 49 +++++++++++++++++++++++++++++++++---------
 1 file changed, 39 insertions(+), 10 deletions(-)

diff --git a/tools/misc/xen-ucode.c b/tools/misc/xen-ucode.c
index 1edcebfb9f9c..9bde991c5df5 100644
--- a/tools/misc/xen-ucode.c
+++ b/tools/misc/xen-ucode.c
@@ -11,6 +11,7 @@
 #include <sys/stat.h>
 #include <fcntl.h>
 #include <xenctrl.h>
+#include <getopt.h>
 
 static xc_interface *xch;
 
@@ -20,7 +21,10 @@ static const char   amd_id[] = "AuthenticAMD";
 static void usage(const char *name)
 {
     printf("%s: Xen microcode updating tool\n"
-            "Usage: %s [<microcode file> | show-cpu-info]\n"
+            "Usage: %s [<microcode file> | --show-cpu-info]\n"
+            "\n"
+            "  -h, --help            display this help and exit\n"
+            "  -s, --show-cpu-info   show CPU information and exit\n"
             "\n"
             , name, name);
 }
@@ -82,9 +86,16 @@ static void show_curr_cpu(FILE *f)
 int main(int argc, char *argv[])
 {
     int fd, ret;
-    char *filename, *buf;
+    char *filename = NULL, *buf;
     size_t len;
     struct stat st;
+    int opt;
+
+    const static struct option options[] = {
+        {"help", no_argument, NULL, 'h'},
+        {"show-cpu-info", no_argument, NULL, 's'},
+        {NULL, no_argument, NULL, 0}
+    };
 
     xch = xc_interface_open(NULL, NULL, 0);
     if ( xch == NULL )
@@ -94,20 +105,33 @@ int main(int argc, char *argv[])
         exit(1);
     }
 
-    if ( argc < 2 )
+    if ( argc != 2 )
+        goto ext_err;
+
+    while ( (opt = getopt_long(argc, argv, "hs:", options, NULL)) != -1 )
     {
-        usage(argv[0]);
-        show_curr_cpu(stderr);
-        exit(2);
+        switch (opt)
+        {
+            case 'h':
+                usage(argv[0]);
+                exit(EXIT_SUCCESS);
+            case 's':
+                if ( argc > 2 )
+                    goto ext_err;
+                show_curr_cpu(stdout);
+                exit(EXIT_SUCCESS);
+            default:
+                goto ext_err;
+        }
     }
 
-    if ( !strcmp(argv[1], "show-cpu-info") )
+    filename = argv[1];
+    if ( filename == NULL )
     {
-        show_curr_cpu(stdout);
-        return 0;
+        printf("File name error\n");
+        goto ext_err;
     }
 
-    filename = argv[1];
     fd = open(filename, O_RDONLY);
     if ( fd < 0 )
     {
@@ -149,4 +173,9 @@ int main(int argc, char *argv[])
     close(fd);
 
     return 0;
+
+ext_err:
+    usage(argv[0]);
+    show_curr_cpu(stderr);
+    exit(STDERR_FILENO);
 }
-- 
2.42.0


Reply via email to