VirtualBox

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

Last change on this file since 96407 was 96407, checked in by vboxsync, 2 years ago

scm copyright and license note update

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