39b26daee94650bc0dd64bd02725c5f861186e3c
[sliver-openvswitch.git] / lib / command-line.c
1 /*
2  * Copyright (c) 2008, 2009, 2010, 2011, 2013 Nicira, Inc.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at:
7  *
8  *     http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 #include <config.h>
18 #include "command-line.h"
19 #include <getopt.h>
20 #include <limits.h>
21 #include <stdlib.h>
22 #include "ovs-thread.h"
23 #include "util.h"
24 #include "vlog.h"
25
26 VLOG_DEFINE_THIS_MODULE(command_line);
27
28 /* Given the GNU-style long options in 'options', returns a string that may be
29  * passed to getopt() with the corresponding short options.  The caller is
30  * responsible for freeing the string. */
31 char *
32 long_options_to_short_options(const struct option options[])
33 {
34     char short_options[UCHAR_MAX * 3 + 1];
35     char *p = short_options;
36
37     for (; options->name; options++) {
38         const struct option *o = options;
39         if (o->flag == NULL && o->val > 0 && o->val <= UCHAR_MAX) {
40             *p++ = o->val;
41             if (o->has_arg == required_argument) {
42                 *p++ = ':';
43             } else if (o->has_arg == optional_argument) {
44                 *p++ = ':';
45                 *p++ = ':';
46             }
47         }
48     }
49     *p = '\0';
50
51     return xstrdup(short_options);
52 }
53
54 /* Runs the command designated by argv[0] within the command table specified by
55  * 'commands', which must be terminated by a command whose 'name' member is a
56  * null pointer.
57  *
58  * Command-line options should be stripped off, so that a typical invocation
59  * looks like "run_command(argc - optind, argv + optind, my_commands);". */
60 void
61 run_command(int argc, char *argv[], const struct command commands[])
62 {
63     const struct command *p;
64
65     if (argc < 1) {
66         ovs_fatal(0, "missing command name; use --help for help");
67     }
68
69     for (p = commands; p->name != NULL; p++) {
70         if (!strcmp(p->name, argv[0])) {
71             int n_arg = argc - 1;
72             if (n_arg < p->min_args) {
73                 VLOG_FATAL( "'%s' command requires at least %d arguments",
74                             p->name, p->min_args);
75             } else if (n_arg > p->max_args) {
76                 VLOG_FATAL("'%s' command takes at most %d arguments",
77                            p->name, p->max_args);
78             } else {
79                 p->handler(argc, argv);
80                 if (ferror(stdout)) {
81                     VLOG_FATAL("write to stdout failed");
82                 }
83                 if (ferror(stderr)) {
84                     VLOG_FATAL("write to stderr failed");
85                 }
86                 return;
87             }
88         }
89     }
90
91     VLOG_FATAL("unknown command '%s'; use --help for help", argv[0]);
92 }
93 \f
94 /* Process title. */
95
96 #ifdef LINUX_DATAPATH
97 static char *argv_start;       /* Start of command-line arguments in memory. */
98 static size_t argv_size;       /* Number of bytes of command-line arguments. */
99 static char *saved_proctitle;  /* Saved command-line arguments. */
100 static pthread_mutex_t proctitle_mutex = PTHREAD_MUTEX_INITIALIZER;
101
102 /* Prepares the process so that proctitle_set() can later succeed.
103  *
104  * This modifies the argv[] array so that it no longer points into the memory
105  * that it originally does.  Later, proctitle_set() might overwrite that
106  * memory.  That means that this function should be called before anything else
107  * that accesses the process's argv[] array.  Ideally, it should be called
108  * before anything else, period, at the very beginning of program
109  * execution.  */
110 void
111 proctitle_init(int argc, char **argv)
112 {
113     int i;
114
115     assert_single_threaded();
116     if (!argc || !argv[0]) {
117         /* This situation should never occur, but... */
118         return;
119     }
120
121     /* Specialized version of first loop iteration below. */
122     argv_start = argv[0];
123     argv_size = strlen(argv[0]) + 1;
124     argv[0] = xstrdup(argv[0]);
125
126     for (i = 1; i < argc; i++) {
127         size_t size = strlen(argv[i]) + 1;
128
129         /* Add (argv[i], strlen(argv[i])+1) to (argv_start, argv_size). */
130         if (argv[i] + size == argv_start) {
131             /* Arguments grow downward in memory. */
132             argv_start -= size;
133             argv_size += size;
134         } else if (argv[i] == argv_start + argv_size) {
135             /* Arguments grow upward in memory. */
136             argv_size += size;
137         } else {
138             /* Arguments not contiguous.  (Is this really Linux?) */
139         }
140
141         /* Copy out the old argument so we can reuse the space. */
142         argv[i] = xstrdup(argv[i]);
143     }
144 }
145
146 /* Changes the name of the process, as shown by "ps", to the program name
147  * followed by 'format', which is formatted as if by printf(). */
148 void
149 proctitle_set(const char *format, ...)
150 {
151     va_list args;
152     int n;
153
154     if (!argv_start || argv_size < 8) {
155         return;
156     }
157
158     xpthread_mutex_lock(&proctitle_mutex);
159     if (!saved_proctitle) {
160         saved_proctitle = xmemdup(argv_start, argv_size);
161     }
162
163     va_start(args, format);
164     n = snprintf(argv_start, argv_size, "%s: ", program_name);
165     if (n < argv_size) {
166         n += vsnprintf(argv_start + n, argv_size - n, format, args);
167     }
168     if (n >= argv_size) {
169         /* The name is too long, so add an ellipsis at the end. */
170         strcpy(&argv_start[argv_size - 4], "...");
171     } else {
172         /* Fill the extra space with null bytes, so that trailing bytes don't
173          * show up in the command line. */
174         memset(&argv_start[n], '\0', argv_size - n);
175     }
176     va_end(args);
177     xpthread_mutex_unlock(&proctitle_mutex);
178 }
179
180 /* Restores the process's original command line, as seen by "ps". */
181 void
182 proctitle_restore(void)
183 {
184     xpthread_mutex_lock(&proctitle_mutex);
185     if (saved_proctitle) {
186         memcpy(argv_start, saved_proctitle, argv_size);
187         free(saved_proctitle);
188         saved_proctitle = NULL;
189     }
190     xpthread_mutex_unlock(&proctitle_mutex);
191 }
192 #else  /* !LINUX_DATAPATH*/
193 /* Stubs that don't do anything on non-Linux systems. */
194
195 void
196 proctitle_init(int argc OVS_UNUSED, char **argv OVS_UNUSED)
197 {
198 }
199
200 #if !(defined(__FreeBSD__) || defined(__NetBSD__))
201 /* On these platforms we #define this to setproctitle. */
202 void
203 proctitle_set(const char *format OVS_UNUSED, ...)
204 {
205 }
206 #endif
207
208 void
209 proctitle_restore(void)
210 {
211 }
212 #endif  /* !LINUX_DATAPATH */