VirtualBox

source: vbox/trunk/include/iprt/getopt.h@ 76431

Last change on this file since 76431 was 76431, checked in by vboxsync, 6 years ago

iprt/getopt.h: Include errcore.h for VINF_GETOPT_NOT_OPTION. bugref:9344

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 21.1 KB
Line 
1/** @file
2 * IPRT - Command Line Parsing.
3 */
4
5/*
6 * Copyright (C) 2007-2017 Oracle Corporation
7 *
8 * This file is part of VirtualBox Open Source Edition (OSE), as
9 * available from http://www.virtualbox.org. This file is free software;
10 * you can redistribute it and/or modify it under the terms of the GNU
11 * General Public License (GPL) as published by the Free Software
12 * Foundation, in version 2 as it comes in the "COPYING" file of the
13 * VirtualBox OSE distribution. VirtualBox OSE is distributed in the
14 * hope that it will be useful, but WITHOUT ANY WARRANTY of any kind.
15 *
16 * The contents of this file may alternatively be used under the terms
17 * of the Common Development and Distribution License Version 1.0
18 * (CDDL) only, as it comes in the "COPYING.CDDL" file of the
19 * VirtualBox OSE distribution, in which case the provisions of the
20 * CDDL are applicable instead of those of the GPL.
21 *
22 * You may elect to license modified versions of this file under the
23 * terms and conditions of either the GPL or the CDDL or both.
24 */
25
26#ifndef ___iprt_getopt_h
27#define ___iprt_getopt_h
28
29
30#include <iprt/cdefs.h>
31#include <iprt/types.h>
32#include <iprt/errcore.h> /* for VINF_GETOPT_NOT_OPTION */
33
34RT_C_DECLS_BEGIN
35
36/** @defgroup grp_rt_getopt RTGetOpt - Command Line Parsing
37 * @ingroup grp_rt
38 * @{
39 */
40
41/** @name Values for RTGETOPTDEF::fFlags and the fFlags parameter of
42 * RTGetOptFetchValue.
43 *
44 * @remarks When neither of the RTGETOPT_FLAG_HEX, RTGETOPT_FLAG_OCT and RTGETOPT_FLAG_DEC
45 * flags are specified with a integer value format, RTGetOpt will default to
46 * decimal but recognize the 0x prefix when present. RTGetOpt will not look for
47 * for the octal prefix (0).
48 * @{ */
49/** Requires no extra argument.
50 * (Can be assumed to be 0 for ever.) */
51#define RTGETOPT_REQ_NOTHING 0
52/** A value is required or error will be returned. */
53#define RTGETOPT_REQ_STRING 1
54/** The value must be a valid signed 8-bit integer or an error will be returned. */
55#define RTGETOPT_REQ_INT8 2
56/** The value must be a valid unsigned 8-bit integer or an error will be returned. */
57#define RTGETOPT_REQ_UINT8 3
58/** The value must be a valid signed 16-bit integer or an error will be returned. */
59#define RTGETOPT_REQ_INT16 4
60/** The value must be a valid unsigned 16-bit integer or an error will be returned. */
61#define RTGETOPT_REQ_UINT16 5
62/** The value must be a valid signed 32-bit integer or an error will be returned. */
63#define RTGETOPT_REQ_INT32 6
64/** The value must be a valid unsigned 32-bit integer or an error will be returned. */
65#define RTGETOPT_REQ_UINT32 7
66/** The value must be a valid signed 64-bit integer or an error will be returned. */
67#define RTGETOPT_REQ_INT64 8
68/** The value must be a valid unsigned 64-bit integer or an error will be returned. */
69#define RTGETOPT_REQ_UINT64 9
70/** The value must be a valid IPv4 address.
71 * (Not a name, but 4 values in the 0..255 range with dots separating them). */
72#define RTGETOPT_REQ_IPV4ADDR 10
73/** The value must be a valid IPv4 CIDR.
74 * As with RTGETOPT_REQ_IPV4ADDR, no name.
75 */
76#define RTGETOPT_REQ_IPV4CIDR 11
77#if 0
78/* take placers */
79/** The value must be a valid IPv6 addr
80 * @todo: Add types and parsing routines in (iprt/net.h)
81 */
82#define RTGETOPT_REQ_IPV6ADDR 12
83/** The value must be a valid IPv6 CIDR
84 * @todo: Add types and parsing routines in (iprt/net.h)
85 */
86#define RTGETOPT_REQ_IPV6CIDR 13
87#endif
88/** The value must be a valid ethernet MAC address. */
89#define RTGETOPT_REQ_MACADDR 14
90/** The value must be a valid UUID. */
91#define RTGETOPT_REQ_UUID 15
92/** The value must be a string with value as "on" or "off". */
93#define RTGETOPT_REQ_BOOL_ONOFF 16
94/** Boolean option accepting a wide range of typical ways of
95 * expression true and false. */
96#define RTGETOPT_REQ_BOOL 17
97/** The value must two unsigned 32-bit integer values separated by a colon,
98 * slash, pipe or space(s). */
99#define RTGETOPT_REQ_UINT32_PAIR 18
100/** The value must two unsigned 64-bit integer values separated by a colon,
101 * slash, pipe or space(s). */
102#define RTGETOPT_REQ_UINT64_PAIR 19
103/** The value must at least unsigned 32-bit integer value, optionally
104 * followed by a second separated by a colon, slash, pipe or space(s). */
105#define RTGETOPT_REQ_UINT32_OPTIONAL_PAIR 20
106/** The value must at least unsigned 64-bit integer value, optionally
107 * followed by a second separated by a colon, slash, pipe or space(s). */
108#define RTGETOPT_REQ_UINT64_OPTIONAL_PAIR 21
109/** The mask of the valid required types. */
110#define RTGETOPT_REQ_MASK 31
111/** Treat the value as hexadecimal - only applicable with the RTGETOPT_REQ_*INT*. */
112#define RTGETOPT_FLAG_HEX RT_BIT(16)
113/** Treat the value as octal - only applicable with the RTGETOPT_REQ_*INT*. */
114#define RTGETOPT_FLAG_OCT RT_BIT(17)
115/** Treat the value as decimal - only applicable with the RTGETOPT_REQ_*INT*. */
116#define RTGETOPT_FLAG_DEC RT_BIT(18)
117/** The index value is attached to the argument - only valid for long arguments. */
118#define RTGETOPT_FLAG_INDEX RT_BIT(19)
119/** Treat the long option as case insensitive. */
120#define RTGETOPT_FLAG_ICASE RT_BIT(20)
121/** Mask of valid bits - for validation. */
122#define RTGETOPT_VALID_MASK ( RTGETOPT_REQ_MASK \
123 | RTGETOPT_FLAG_HEX \
124 | RTGETOPT_FLAG_OCT \
125 | RTGETOPT_FLAG_DEC \
126 | RTGETOPT_FLAG_INDEX \
127 | RTGETOPT_FLAG_ICASE)
128/** @} */
129
130/**
131 * An option definition.
132 */
133typedef struct RTGETOPTDEF
134{
135 /** The long option.
136 * This is optional */
137 const char *pszLong;
138 /** The short option character.
139 * This doesn't have to be a character, it may also be a \#define or enum value if
140 * there isn't any short version of this option. Must be greater than 0. */
141 int iShort;
142 /** The flags (RTGETOPT_*). */
143 unsigned fFlags;
144} RTGETOPTDEF;
145/** Pointer to an option definition. */
146typedef RTGETOPTDEF *PRTGETOPTDEF;
147/** Pointer to an const option definition. */
148typedef const RTGETOPTDEF *PCRTGETOPTDEF;
149
150/**
151 * Option argument union.
152 *
153 * What ends up here depends on argument format in the option definition.
154 *
155 * @remarks Integers will bet put in the \a i and \a u members and sign/zero extended
156 * according to the signedness indicated by the \a fFlags. So, you can choose
157 * use which ever of the integer members for accessing the value regardless
158 * of restrictions indicated in the \a fFlags.
159 */
160typedef union RTGETOPTUNION
161{
162 /** Pointer to the definition on failure or when the option doesn't take an argument.
163 * This can be NULL for some errors. */
164 PCRTGETOPTDEF pDef;
165 /** A RTGETOPT_REQ_STRING option argument. */
166 const char *psz;
167
168 /** A RTGETOPT_REQ_INT8 option argument. */
169 int8_t i8;
170 /** A RTGETOPT_REQ_UINT8 option argument . */
171 uint8_t u8;
172 /** A RTGETOPT_REQ_INT16 option argument. */
173 int16_t i16;
174 /** A RTGETOPT_REQ_UINT16 option argument . */
175 uint16_t u16;
176 /** A RTGETOPT_REQ_INT16 option argument. */
177 int32_t i32;
178 /** A RTGETOPT_REQ_UINT32 option argument . */
179 uint32_t u32;
180 /** A RTGETOPT_REQ_INT64 option argument. */
181 int64_t i64;
182 /** A RTGETOPT_REQ_UINT64 option argument. */
183 uint64_t u64;
184#ifdef ___iprt_net_h
185 /** A RTGETOPT_REQ_IPV4ADDR option argument. */
186 RTNETADDRIPV4 IPv4Addr;
187 /** A RTGETOPT_REQ_IPV4CIDR option argument. */
188 struct
189 {
190 RTNETADDRIPV4 IPv4Network;
191 RTNETADDRIPV4 IPv4Netmask;
192 } CidrIPv4;
193#endif
194 /** A RTGETOPT_REQ_MACADDR option argument. */
195 RTMAC MacAddr;
196 /** A RTGETOPT_REQ_UUID option argument. */
197 RTUUID Uuid;
198 /** A boolean flag. */
199 bool f;
200 /** A RTGETOPT_REQ_UINT32_PAIR or RTGETOPT_REQ_UINT32_OPTIONAL_PAIR option
201 * argument. */
202 struct
203 {
204 uint32_t uFirst;
205 uint32_t uSecond; /**< Set to UINT32_MAX if optional and not present. */
206 } PairU32;
207 /** A RTGETOPT_REQ_UINT64_COLON_PAIR option argument. */
208 struct
209 {
210 uint64_t uFirst;
211 uint64_t uSecond; /**< Set to UINT64_MAX if optional and not present. */
212 } PairU64;
213} RTGETOPTUNION;
214/** Pointer to an option argument union. */
215typedef RTGETOPTUNION *PRTGETOPTUNION;
216/** Pointer to a const option argument union. */
217typedef RTGETOPTUNION const *PCRTGETOPTUNION;
218
219
220/**
221 * RTGetOpt state.
222 */
223typedef struct RTGETOPTSTATE
224{
225 /** The next argument. */
226 int iNext;
227 /** Argument array. */
228 char **argv;
229 /** Number of items in argv. */
230 int argc;
231 /** Option definition array. */
232 PCRTGETOPTDEF paOptions;
233 /** Number of items in paOptions. */
234 size_t cOptions;
235 /** The next short option.
236 * (For parsing ls -latrT4 kind of option lists.) */
237 const char *pszNextShort;
238 /** The option definition which matched. NULL otherwise. */
239 PCRTGETOPTDEF pDef;
240 /** The index of an index option, otherwise UINT32_MAX. */
241 uint32_t uIndex;
242 /** The flags passed to RTGetOptInit. */
243 uint32_t fFlags;
244 /** Number of non-options that we're skipping during a sorted get. The value
245 * INT32_MAX is used to indicate that there are no more options. This is used
246 * to implement '--'. */
247 int32_t cNonOptions;
248
249 /* More members may be added later for dealing with new features. */
250} RTGETOPTSTATE;
251/** Pointer to RTGetOpt state. */
252typedef RTGETOPTSTATE *PRTGETOPTSTATE;
253
254
255/**
256 * Initialize the RTGetOpt state.
257 *
258 * The passed in argument vector may be sorted if fFlags indicates that this is
259 * desired (to be implemented).
260 *
261 * @returns VINF_SUCCESS, VERR_INVALID_PARAMETER or VERR_INVALID_POINTER.
262 * @param pState The state.
263 *
264 * @param argc Argument count, to be copied from what comes in with
265 * main().
266 * @param argv Argument array, to be copied from what comes in with
267 * main(). This may end up being modified by the
268 * option/argument sorting.
269 * @param paOptions Array of RTGETOPTDEF structures, which must specify what
270 * options are understood by the program.
271 * @param cOptions Number of array items passed in with paOptions.
272 * @param iFirst The argument to start with (in argv).
273 * @param fFlags The flags, see RTGETOPTINIT_FLAGS_XXX.
274 */
275RTDECL(int) RTGetOptInit(PRTGETOPTSTATE pState, int argc, char **argv,
276 PCRTGETOPTDEF paOptions, size_t cOptions,
277 int iFirst, uint32_t fFlags);
278
279/** @name RTGetOptInit flags.
280 * @{ */
281/** Sort the arguments so that options comes first, then non-options. */
282#define RTGETOPTINIT_FLAGS_OPTS_FIRST RT_BIT_32(0)
283/** Prevent add the standard version and help options:
284 * - "--help", "-h" and "-?" returns 'h'.
285 * - "--version" and "-V" return 'V'.
286 */
287#define RTGETOPTINIT_FLAGS_NO_STD_OPTS RT_BIT_32(1)
288/** @} */
289
290/**
291 * Command line argument parser, handling both long and short options and checking
292 * argument formats, if desired.
293 *
294 * This is to be called in a loop until it returns 0 (meaning that all options
295 * were parsed) or a negative value (meaning that an error occurred). How non-option
296 * arguments are dealt with depends on the flags passed to RTGetOptInit. The default
297 * (fFlags = 0) is to return VINF_GETOPT_NOT_OPTION with pValueUnion->psz pointing to
298 * the argument string.
299 *
300 * For example, for a program which takes the following options:
301 *
302 * --optwithstring (or -s) and a string argument;
303 * --optwithint (or -i) and a 32-bit signed integer argument;
304 * --verbose (or -v) with no arguments,
305 *
306 * code would look something like this:
307 *
308 * @code
309int main(int argc, char **argv)
310{
311 int rc = RTR3Init();
312 if (RT_FAILURE(rc))
313 return RTMsgInitFailure(rc);
314
315 static const RTGETOPTDEF s_aOptions[] =
316 {
317 { "--optwithstring", 's', RTGETOPT_REQ_STRING },
318 { "--optwithint", 'i', RTGETOPT_REQ_INT32 },
319 { "--verbose", 'v', 0 },
320 };
321
322 int ch;
323 RTGETOPTUNION ValueUnion;
324 RTGETOPTSTATE GetState;
325 RTGetOptInit(&GetState, argc, argv, s_aOptions, RT_ELEMENTS(s_aOptions), 1, 0);
326 while ((ch = RTGetOpt(&GetState, &ValueUnion)))
327 {
328 // for options that require an argument, ValueUnion has received the value
329 switch (ch)
330 {
331 case 's': // --optwithstring or -s
332 // string argument, copy ValueUnion.psz
333 break;
334
335 case 'i': // --optwithint or -i
336 // integer argument, copy ValueUnion.i32
337 break;
338
339 case 'v': // --verbose or -v
340 g_fOptVerbose = true;
341 break;
342
343 case VINF_GETOPT_NOT_OPTION:
344 // handle non-option argument in ValueUnion.psz.
345 break;
346
347 default:
348 return RTGetOptPrintError(ch, &ValueUnion);
349 }
350 }
351
352 return RTEXITCODE_SUCCESS;
353}
354 @endcode
355 *
356 * @returns 0 when done parsing.
357 * @returns the iShort value of the option. pState->pDef points to the option
358 * definition which matched.
359 * @returns IPRT error status on parse error.
360 * @returns VINF_GETOPT_NOT_OPTION when encountering a non-option argument and
361 * RTGETOPT_FLAG_SORT was not specified. pValueUnion->psz points to the
362 * argument string.
363 * @returns VERR_GETOPT_UNKNOWN_OPTION when encountering an unknown option.
364 * pValueUnion->psz points to the option string.
365 * @returns VERR_GETOPT_REQUIRED_ARGUMENT_MISSING and pValueUnion->pDef if
366 * a required argument (aka value) was missing for an option.
367 * @returns VERR_GETOPT_INVALID_ARGUMENT_FORMAT and pValueUnion->pDef if
368 * argument (aka value) conversion failed.
369 *
370 * @param pState The state previously initialized with RTGetOptInit.
371 * @param pValueUnion Union with value; in the event of an error, psz member
372 * points to erroneous parameter; otherwise, for options
373 * that require an argument, this contains the value of
374 * that argument, depending on the type that is required.
375 */
376RTDECL(int) RTGetOpt(PRTGETOPTSTATE pState, PRTGETOPTUNION pValueUnion);
377
378/**
379 * Fetch a value.
380 *
381 * Used to retrive a value argument in a manner similar to what RTGetOpt does
382 * (@a fFlags -> @a pValueUnion). This can be used when handling
383 * VINF_GETOPT_NOT_OPTION, but is equally useful for decoding options that
384 * takes more than one value.
385 *
386 * @returns VINF_SUCCESS on success.
387 * @returns IPRT error status on parse error.
388 * @returns VERR_INVALID_PARAMETER if the flags are wrong.
389 * @returns VERR_GETOPT_UNKNOWN_OPTION when pState->pDef is null.
390 * @returns VERR_GETOPT_REQUIRED_ARGUMENT_MISSING if there are no more
391 * available arguments. pValueUnion->pDef is NULL.
392 * @returns VERR_GETOPT_INVALID_ARGUMENT_FORMAT and pValueUnion->pDef is
393 * unchanged if value conversion failed.
394 *
395 * @param pState The state previously initialized with RTGetOptInit.
396 * @param pValueUnion Union with value; in the event of an error, psz member
397 * points to erroneous parameter; otherwise, for options
398 * that require an argument, this contains the value of
399 * that argument, depending on the type that is required.
400 * @param fFlags What to get, that is RTGETOPT_REQ_XXX.
401 */
402RTDECL(int) RTGetOptFetchValue(PRTGETOPTSTATE pState, PRTGETOPTUNION pValueUnion, uint32_t fFlags);
403
404/**
405 * Gets the pointer to the argv entry of the current non-option argument.
406 *
407 * This function ASSUMES the previous RTGetOpt() call returned
408 * VINF_GETOPT_NOT_OPTION and require RTGETOPTINIT_FLAGS_OPTS_FIRST to be
409 * specified to RTGetOptInit().
410 *
411 * @returns Pointer to the argv entry of the current non-option. NULL if
412 * (detectable) precondition isn't fullfilled (asserted)
413 * @param pState The state previously initialized with RTGetOptInit.
414 */
415RTDECL(char **) RTGetOptNonOptionArrayPtr(PRTGETOPTSTATE pState);
416
417/**
418 * Print error messages for a RTGetOpt default case.
419 *
420 * Uses RTMsgError.
421 *
422 * @returns Suitable exit code.
423 *
424 * @param ch The RTGetOpt return value.
425 * @param pValueUnion The value union returned by RTGetOpt.
426 */
427RTDECL(RTEXITCODE) RTGetOptPrintError(int ch, PCRTGETOPTUNION pValueUnion);
428
429/**
430 * Formats error messages for a RTGetOpt default case.
431 *
432 * @returns On success, positive count of formatted character excluding the
433 * terminator. On buffer overflow, negative number giving the required
434 * buffer size (including terminator char). (RTStrPrintf2 style.)
435 *
436 * @param pszBuf The buffer to format into.
437 * @param cbBuf The size of the buffer @a pszBuf points to.
438 * @param ch The RTGetOpt return value.
439 * @param pValueUnion The value union returned by RTGetOpt.
440 */
441RTDECL(ssize_t) RTGetOptFormatError(char *pszBuf, size_t cbBuf, int ch, PCRTGETOPTUNION pValueUnion);
442
443/**
444 * Parses the @a pszCmdLine string into an argv array.
445 *
446 * This is useful for converting a response file or similar to an argument
447 * vector that can be used with RTGetOptInit().
448 *
449 * This function aims at following the bourne shell string quoting rules.
450 *
451 * @returns IPRT status code.
452 *
453 * @param ppapszArgv Where to return the argument vector. This must be
454 * freed by calling RTGetOptArgvFreeEx or
455 * RTGetOptArgvFree.
456 * @param pcArgs Where to return the argument count.
457 * @param pszCmdLine The string to parse.
458 * @param fFlags A combination of the RTGETOPTARGV_CNV_XXX flags,
459 * except RTGETOPTARGV_CNV_UNQUOTED is not supported.
460 * @param pszSeparators String containing the argument separators. If NULL,
461 * then space, tab, line feed (\\n) and return (\\r)
462 * are used.
463 */
464RTDECL(int) RTGetOptArgvFromString(char ***ppapszArgv, int *pcArgs, const char *pszCmdLine, uint32_t fFlags,
465 const char *pszSeparators);
466
467/**
468 * Frees and argument vector returned by RTGetOptStringToArgv.
469 *
470 * @param papszArgv Argument vector. NULL is fine.
471 */
472RTDECL(void) RTGetOptArgvFree(char **papszArgv);
473
474/**
475 * Frees and argument vector returned by RTGetOptStringToArgv, taking
476 * RTGETOPTARGV_CNV_MODIFY_INPUT into account.
477 *
478 * @param papszArgv Argument vector. NULL is fine.
479 * @param fFlags The flags passed to RTGetOptStringToArgv.
480 */
481RTDECL(void) RTGetOptArgvFreeEx(char **papszArgv, uint32_t fFlags);
482
483/**
484 * Turns an argv array into a command line string.
485 *
486 * This is useful for calling CreateProcess on Windows, but can also be used for
487 * displaying an argv array.
488 *
489 * This function aims at following the bourn shell string quoting rules.
490 *
491 * @returns IPRT status code.
492 *
493 * @param ppszCmdLine Where to return the command line string. This must
494 * be freed by calling RTStrFree.
495 * @param papszArgv The argument vector to convert.
496 * @param fFlags A combination of the RTGETOPTARGV_CNV_XXX flags.
497 */
498RTDECL(int) RTGetOptArgvToString(char **ppszCmdLine, const char * const *papszArgv, uint32_t fFlags);
499
500/** @name RTGetOptArgvToString, RTGetOptArgvToUtf16String and
501 * RTGetOptArgvFromString flags
502 * @{ */
503/** Quote strings according to the Microsoft CRT rules. */
504#define RTGETOPTARGV_CNV_QUOTE_MS_CRT UINT32_C(0x00000000)
505/** Quote strings according to the Unix Bourne Shell. */
506#define RTGETOPTARGV_CNV_QUOTE_BOURNE_SH UINT32_C(0x00000001)
507/** Don't quote any strings at all. */
508#define RTGETOPTARGV_CNV_UNQUOTED UINT32_C(0x00000002)
509/** Mask for the quoting style. */
510#define RTGETOPTARGV_CNV_QUOTE_MASK UINT32_C(0x00000003)
511/** Allow RTGetOptArgvFromString to modifying the command line input string.
512 * @note Must use RTGetOptArgvFreeEx to free. */
513#define RTGETOPTARGV_CNV_MODIFY_INPUT UINT32_C(0x00000004)
514/** Valid bits. */
515#define RTGETOPTARGV_CNV_VALID_MASK UINT32_C(0x00000007)
516/** @} */
517
518/**
519 * Convenience wrapper around RTGetOpArgvToString and RTStrToUtf16.
520 *
521 * @returns IPRT status code.
522 *
523 * @param ppwszCmdLine Where to return the command line string. This must
524 * be freed by calling RTUtf16Free.
525 * @param papszArgv The argument vector to convert.
526 * @param fFlags A combination of the RTGETOPTARGV_CNV_XXX flags.
527 */
528RTDECL(int) RTGetOptArgvToUtf16String(PRTUTF16 *ppwszCmdLine, const char * const *papszArgv, uint32_t fFlags);
529
530/** @} */
531
532RT_C_DECLS_END
533
534#endif
535
Note: See TracBrowser for help on using the repository browser.

© 2024 Oracle Support Privacy / Do Not Sell My Info Terms of Use Trademark Policy Automated Access Etiquette