Debian Codegraph @

lib/util/shhopt.c

raw
1 /*------------------------------------------------------------------------
2 | FILE shhopt.c
3 |
4 | DESCRIPTION Functions for parsing command line arguments. Values
5 | of miscellaneous types may be stored in variables,
6 | or passed to functions as specified.
7 |
8 | REQUIREMENTS Some systems lack the ANSI C -function strtoul. If your
9 | system is one of those, you'll need to write one yourself,
10 | or get the GNU liberty-library (from prep.ai.mit.edu).
11 |
12 | WRITTEN BY Sverre H. Huseby <[email protected]>
13 +----------------------------------------------------------------------*/
14
15 /*************************************************************************
16 This is based on work by Sverre H. Huseby <[email protected]>.
17 These functions are backward compatible with the 'shhopt'
18 distributed by Huseby.
19
20 See the file README.shhopt for copy licensing information.
21 *************************************************************************/
22
23 #include <stdio.h>
24 #include <stdlib.h>
25 #include <stdarg.h>
26 #include <string.h>
27 #include <ctype.h>
28 #include <limits.h>
29 #include <errno.h>
30 #include <assert.h>
31
32 #include "mallocvar.h"
33 #include "nstring.h"
34 #include "token.h"
35 #include "shhopt.h"
36
37
38
39 static void optFatalFunc(const char *, ...);
40 static void (*optFatal)(const char *format, ...) = optFatalFunc;
41
42
43
44 static void
45 optFatalFunc(const char * const format, ...) {
46 /*----------------------------------------------------------------------------
47 FUNCTION Show given message and abort the program.
48
49 INPUT Arguments used as with printf().
50
51 RETURNS Never returns. The program is aborted.
52 -----------------------------------------------------------------------------*/
53 va_list ap;
54
55 fflush(stdout);
56 va_start(ap, format);
57 vfprintf(stderr, format, ap);
58 va_end(ap);
59 fprintf(stderr, "\n");
60 exit(99);
61 }
62
63
64
65 static int
66 optStructCount(const optEntry * const opt) {
67 /*--------------------------------------------------------------------------
68 FUNCTION Get number of options in a optStruct.
69
70 INPUT opt array of possible options.
71
72 RETURNS Number of options in the given array.
73
74 DESCRIPTION Count elements in an optStruct-array. The structure must
75 be ended using an element of type OPT_END.
76 ----------------------------------------------------------------------------*/
77 int ret = 0;
78
79 while (opt[ret].type != OPT_END && ret < 500)
80 ++ret;
81 return ret;
82 }
83
84
85
86 enum Shortlong {SL_SHORT, SL_LONG};
87
88 static void
89 optMatch(optEntry const opt[],
90 const char * const targetOpt,
91 enum Shortlong const shortLong,
92 bool * const foundP,
93 unsigned int * const optIndexP) {
94 /*------------------------------------------------------------------------
95 FUNCTION Find a matching option.
96
97 INPUT opt array of valid option names.
98 targetOpt option string to match, without `-' or `--'.
99 e.g. "verbose" or "height=5"
100 shortLong whether to match short option or long
101
102 RETURNS *foundP there is a matching option class the table
103 *optIndexP index in the option class table
104 meaningless if *foundP is false
105
106 DESCRIPTION Short options are matched from the first character in
107 the given string.
108
109 Where multiple entries in opt[] match, return the first.
110 --------------------------------------------------------------------------*/
111 unsigned int const optCt = optStructCount(opt);
112
113 unsigned int q;
114 unsigned int matchlen;
115 bool found;
116 unsigned int optIndex;
117
118 if (shortLong == SL_LONG) {
119 const char * const equalPos = strchr(targetOpt, '=');
120 if (equalPos)
121 matchlen = equalPos - &targetOpt[0];
122 else
123 matchlen = strlen(targetOpt);
124 } else
125 matchlen = 0;
126
127 for (q = 0, found = false; q < optCt && !found; ++q) {
128 switch (shortLong) {
129 case SL_LONG: {
130 if (opt[q].longName) {
131 if (strneq(targetOpt, opt[q].longName, matchlen)) {
132 found = true;
133 optIndex = q;
134 }
135 }
136 }
137 case SL_SHORT: {
138 if (opt[q].shortName) {
139 if (targetOpt[0] == opt[q].shortName) {
140 found = true;
141 optIndex = q;
142 }
143 }
144 }
145 }
146 }
147 *foundP = found;
148 *optIndexP = optIndex;
149 }
150
151
152
153 static char *
154 optString(optEntry const opte,
155 int const lng) {
156 /*--------------------------------------------------------------------------
157 FUNCTION Return a (static) string with the option name.
158
159 INPUT opt the option to stringify.
160 lng is it a long option?
161
162 RETURNS Pointer to static string.
163 --------------------------------------------------------------------------*/
164 static char ret[31];
165
166 if (lng) {
167 strcpy(ret, "--");
168 strncpy(ret + 2, opte.longName, 28);
169 } else {
170 ret[0] = '-';
171 ret[1] = opte.shortName;
172 ret[2] = '\0';
173 }
174 return ret;
175 }
176
177
178
179 static optEntry
180 optStructToEntry(optStruct const opt) {
181 /*----------------------------------------------------------------------------
182 Return the information in 'opt' (an optStruct type) as an optEntry type.
183 optEntry is newer and has an additional field.
184 -----------------------------------------------------------------------------*/
185 optEntry opte;
186
187 opte.shortName = opt.shortName;
188 opte.longName = opt.longName;
189 opte.type = opt.type;
190 opte.arg = opt.arg;
191 opte.specified = NULL;
192 opte.flags = opt.flags;
193
194 return opte;
195 }
196
197
198
199 static optEntry *
200 optStructTblToEntryTbl(const optStruct * const optStructTable) {
201 /*----------------------------------------------------------------------------
202 Return a table of optEntry types containing the information in the
203 input table of optStruct types.
204
205 Return it in newly malloc'ed storage.
206 -----------------------------------------------------------------------------*/
207 int count;
208 /* Number of entries in input table, including OPT_END marker */
209 int i;
210
211 optEntry *optEntryTable; /* malloc'ed array */
212
213 /* Count the entries in optStructTable[] */
214 for (i = 0; optStructTable[i].type != OPT_END && i < 500; i++);
215 count = i+1;
216
217 optEntryTable = (optEntry *) malloc(count * sizeof(optEntry));
218 if (optEntryTable) {
219 int i;
220 for (i = 0; i < count; i++)
221 optEntryTable[i] = optStructToEntry(optStructTable[i]);
222 }
223 return(optEntryTable);
224 }
225
226
227
228
229 static int
230 optNeedsArgument(const optEntry opt) {
231 /*--------------------------------------------------------------------------
232 FUNCTION Check if an option requires an argument.
233
234 INPUT opt the option to check.
235
236 RETURNS Boolean value.
237 ---------------------------------------------------------------------------*/
238 return opt.type == OPT_STRING
239 || opt.type == OPT_INT
240 || opt.type == OPT_UINT
241 || opt.type == OPT_LONG
242 || opt.type == OPT_ULONG
243 || opt.type == OPT_FLOAT
244 || opt.type == OPT_NAMELIST
245 || opt.type == OPT_STRINGLIST
246 ;
247 }
248
249
250
251 static void
252 argvRemove(int * const argcP,
253 const char ** const argv,
254 unsigned int const n) {
255 /*------------------------------------------------------------------------
256 INPUT argc pointer to number of options.
257 argv array of option-/argument-strings.
258 n index of option to remove.
259
260 OUTPUT argc new argument count.
261 argv array with given argument removed.
262 --------------------------------------------------------------------------*/
263 if (n < *argcP) {
264 unsigned int i;
265
266 for (i = n; i++ < *argcP; )
267 argv[i - 1] = argv[i];
268
269 --*argcP;
270 }
271 }
272
273
274
275 static void
276 getToken(const char * const tokenStart,
277 char const delimiter,
278 const char ** const tokenP,
279 const char ** const nextP) {
280 /*----------------------------------------------------------------------------
281 Find the token starting at 'tokenStart' up to but not including
282 the first 'delimiter' character or end of string. Return it in newly
283 malloced memory as *tokenP, NUL-terminated.
284
285 Make *nextP point just past the token, i.e. to the delimiter or
286 end of string NUL character.
287
288 Note that if the string is empty, or starts with the delimiter,
289 we return an empty string and *nextP == tokenStart, i.e. *nextP
290 doesn't necessarily advance.
291 -----------------------------------------------------------------------------*/
292 const char * error;
293
294 pm_gettoken(tokenStart, delimiter, tokenP, nextP, &error);
295
296 if (error)
297 optFatal("error parsing a token: %s", error);
298 }
299
300
301
302 static void
303 parseNameList(const char * const listText,
304 struct optNameValue ** const listP) {
305
306 unsigned int const maxOptionCount = 100;
307
308 const char * cursor;
309 unsigned int optionCount;
310 struct optNameValue * list;
311
312 MALLOCARRAY_NOFAIL(list, maxOptionCount+1);
313
314 cursor = &listText[0]; /* initial value */
315
316 optionCount = 0; /* initial value */
317
318 while (optionCount < maxOptionCount && *cursor != '\0') {
319 const char * next;
320 struct optNameValue pair;
321
322 getToken(cursor, '=', &pair.name, &next);
323
324 cursor = next;
325
326 if (*cursor == '\0')
327 optFatal("name=value option value ends prematurely. An equal "
328 "sign was expected following name '%s'", pair.name);
329
330 assert(*cursor == '=');
331 ++cursor;
332
333 getToken(cursor, ',', &pair.value, &next);
334
335 cursor = next;
336
337 list[optionCount++] = pair;
338
339 if (*cursor != '\0') {
340 assert(*cursor == ',');
341 ++cursor;
342 }
343 }
344 list[optionCount].name = NULL;
345 list[optionCount].value = NULL;
346
347 *listP = list;
348 }
349
350
351
352 static void
353 parseStringList(const char * const listText,
354 const char *** const listP) {
355
356 unsigned int const maxStringCount = 100;
357
358 const char * cursor;
359 unsigned int stringCount;
360 const char ** list;
361
362 MALLOCARRAY_NOFAIL(list, maxStringCount+1);
363
364 cursor = &listText[0]; /* initial value */
365
366 stringCount = 0; /* initial value */
367
368 while (stringCount < maxStringCount && *cursor != '\0') {
369 const char * next;
370
371 getToken(cursor, ',', &list[stringCount++], &next);
372
373 cursor = next;
374
375 if (*cursor != '\0') {
376 assert(*cursor == ',');
377 ++cursor;
378 }
379 }
380 list[stringCount] = NULL;
381
382 *listP = list;
383 }
384
385
386
387 static void
388 optExecute(optEntry const opt,
389 const char * const arg,
390 int const lng) {
391 /*--------------------------------------------------------------------------
392 FUNCTION Perform the action of an option.
393
394 INPUT opt element in array of defined options that
395 applies to this option
396 arg argument to option, if it applies.
397 lng was the option given as a long option?
398
399 RETURNS Nothing. Aborts in case of error.
400 ----------------------------------------------------------------------------*/
401 if (opt.specified)
402 *opt.specified = 1;
403
404 switch (opt.type) {
405 case OPT_FLAG:
406 if (opt.arg)
407 *((int *) opt.arg) = 1;
408 break;
409
410 case OPT_STRING:
411 if (opt.arg)
412 *((const char **) opt.arg) = arg;
413 break;
414
415 case OPT_INT:
416 case OPT_LONG: {
417 long tmp;
418 char *e;
419
420 if (arg == NULL)
421 optFatal("internal error: optExecute() called with NULL argument "
422 "'%s'", optString(opt, lng));
423 tmp = strtol(arg, &e, 10);
424 if (*e)
425 optFatal("invalid number `%s'", arg);
426 if (errno == ERANGE
427 || (opt.type == OPT_INT && (tmp > INT_MAX || tmp < INT_MIN)))
428 optFatal("number `%s' to `%s' out of range",
429 arg, optString(opt, lng));
430 if (opt.type == OPT_INT) {
431 *((int *) opt.arg) = (int) tmp;
432 } else /* OPT_LONG */ {
433 if (opt.arg)
434 *((long *) opt.arg) = tmp;
435 }
436 } break;
437
438 case OPT_UINT:
439 case OPT_ULONG: {
440 unsigned long tmp;
441 char * tailPtr;
442
443 if (arg == NULL)
444 optFatal("internal error: optExecute() called with NULL argument "
445 "'%s'", optString(opt, lng));
446
447 if (arg[0] == '-' || arg[1] == '+')
448 optFatal("unsigned number '%s' has a sign ('%c')",
449 arg, arg[0]);
450 tmp = strtoul(arg, &tailPtr, 10);
451 if (*tailPtr)
452 optFatal("invalid number `%s'", arg);
453 if (errno == ERANGE
454 || (opt.type == OPT_UINT && tmp > UINT_MAX))
455 optFatal("number `%s' to `%s' out of range",
456 arg, optString(opt, lng));
457 if (opt.type == OPT_UINT) {
458 if (opt.arg)
459 *((unsigned *) opt.arg) = (unsigned) tmp;
460 } else /* OPT_ULONG */ {
461 if (opt.arg)
462 *((unsigned long *) opt.arg) = tmp;
463 }
464 } break;
465 case OPT_FLOAT: {
466 float tmp;
467 char *e;
468
469 if (arg == NULL)
470 optFatal("internal error: optExecute() called with NULL argument "
471 "'%s'", optString(opt, lng));
472 tmp = strtod(arg, &e);
473 if (*e)
474 optFatal("invalid floating point number `%s'", arg);
475 if (errno == ERANGE)
476 optFatal("floating point number `%s' to `%s' out of range",
477 arg, optString(opt, lng));
478 if (opt.arg)
479 *((float *) opt.arg) = tmp;
480 } break;
481 case OPT_NAMELIST: {
482 if (arg == NULL)
483 optFatal("internal error: optExecute() called with NULL argument "
484 "'%s'", optString(opt, lng));
485
486 if (opt.arg)
487 parseNameList(arg, (struct optNameValue **)opt.arg);
488
489 } break;
490 case OPT_STRINGLIST: {
491 if (arg == NULL)
492 optFatal("internal error: optExecute() called with NULL argument "
493 "'%s'", optString(opt, lng));
494
495 if (opt.arg)
496 parseStringList(arg, (const char ***)opt.arg);
497
498 } break;
499 default:
500 break;
501 }
502 }
503
504
505
506 void
507 pm_optSetFatalFunc(void (*f)(const char *, ...)) {
508 /*--------------------------------------------------------------------------
509 | FUNCTION Set function used to display error message and exit.
510 |
511 | INPUT f function accepting printf()'like parameters,
512 | that _must_ abort the program.
513 ----------------------------------------------------------------------------*/
514 optFatal = f;
515 }
516
517
518
519 void
520 pm_optParseOptions(int * const argcP,
521 char ** const argv,
522 optStruct * const opt,
523 int const allowNegNum) {
524 /*------------------------------------------------------------------------
525 FUNCTION Parse commandline options.
526
527 INPUT argc Pointer to number of options.
528 argv Array of option-/argument-strings.
529 opt Array of possible options.
530 allowNegNum
531 a negative number is not to be taken as
532 an option.
533
534 OUTPUT argc new argument count.
535 argv array with arguments removed.
536
537 RETURNS Nothing. Aborts in case of error.
538
539 DESCRIPTION This function checks each option in the argv-array
540 against strings in the opt-array, and `executes' any
541 matching action. Any arguments to the options are
542 extracted and stored in the variables or passed to
543 functions pointed to by entries in opt.
544
545 Options and arguments used are removed from the argv-
546 array, and argc is decreased accordingly.
547
548 Any error leads to program abortion.
549 ----------------------------------------------------------------------------*/
550 int ai; /* argv index. */
551 int optarg; /* argv index of option argument, or -1 if none. */
552 int done;
553 char * arg; /* Pointer to argument to an option. */
554 char * o; /* pointer to an option character */
555 char * p;
556
557 optEntry * optTable; /* malloc'ed array */
558
559 optTable = optStructTblToEntryTbl(opt);
560 if (optTable == NULL)
561 optFatal("Memory allocation failed (trying to allocate space for "
562 "new-format option table)");
563
564 /*
565 * Loop through all arguments.
566 */
567 for (ai = 0; ai < *argcP; ) {
568 /*
569 * "--" indicates that the rest of the argv-array does not
570 * contain options.
571 */
572 if (streq(argv[ai], "--")) {
573 argvRemove(argcP, (const char **)argv, ai);
574 break;
575 }
576
577 if (allowNegNum && argv[ai][0] == '-' && ISDIGIT(argv[ai][1])) {
578 ++ai;
579 continue;
580 } else if (strneq(argv[ai], "--", 2)) {
581 bool found;
582 unsigned int mi;
583 /* long option */
584 /* find matching option */
585 optMatch(optTable, argv[ai] + 2, SL_LONG, &found, &mi);
586 if (!found)
587 optFatal("unrecognized option `%s'", argv[ai]);
588
589 /* possibly locate the argument to this option. */
590 arg = NULL;
591 if ((p = strchr(argv[ai], '=')) != NULL)
592 arg = p + 1;
593
594 /* does this option take an argument? */
595 optarg = -1;
596 if (optNeedsArgument(optTable[mi])) {
597 /* option needs an argument. find it. */
598 if (!arg) {
599 if ((optarg = ai + 1) == *argcP)
600 optFatal("option `%s' requires an argument",
601 optString(optTable[mi], 1));
602 arg = argv[optarg];
603 }
604 } else {
605 if (arg)
606 optFatal("option `%s' doesn't allow an argument",
607 optString(optTable[mi], 1));
608 }
609 optExecute(optTable[mi], arg, 1);
610 /* remove option and any argument from the argv-array. */
611 if (optarg >= 0)
612 argvRemove(argcP, (const char **)argv, ai);
613 argvRemove(argcP, (const char **)argv, ai);
614 } else if (*argv[ai] == '-') {
615 /* A dash by itself is not considered an option. */
616 if (argv[ai][1] == '\0') {
617 ++ai;
618 continue;
619 }
620 /* Short option(s) following */
621 o = argv[ai] + 1;
622 done = 0;
623 optarg = -1;
624 while (*o && !done) {
625 bool found;
626 unsigned int mi;
627 /* find matching option */
628 optMatch(optTable, o, SL_SHORT, &found, &mi);
629 if (!found)
630 optFatal("unrecognized option `-%c'", *o);
631
632 /* does this option take an argument? */
633 optarg = -1;
634 arg = NULL;
635 if (optNeedsArgument(optTable[mi])) {
636 /* option needs an argument. find it. */
637 arg = o + 1;
638 if (!*arg) {
639 if ((optarg = ai + 1) == *argcP)
640 optFatal("option `%s' requires an argument",
641 optString(optTable[mi], 0));
642 arg = argv[optarg];
643 }
644 done = 1;
645 }
646 /* perform the action of this option. */
647 optExecute(optTable[mi], arg, 0);
648 ++o;
649 }
650 /* remove option and any argument from the argv-array. */
651 if (optarg >= 0)
652 argvRemove(argcP, (const char **)argv, ai);
653 argvRemove(argcP, (const char **)argv, ai);
654 } else {
655 /* a non-option argument */
656 ++ai;
657 }
658 }
659 free(optTable);
660 }
661
662
663 static void
664 parseShortOptionToken(const char ** const argv,
665 int const argc,
666 int const ai,
667 const optEntry * const optTable,
668 unsigned int * const tokensConsumedP) {
669 /*----------------------------------------------------------------------------
670 Parse a cluster of short options, e.g. -walne .
671
672 The last option in the cluster might take an argument, and we parse
673 that as well. e.g. -cf myfile or -cfmyfile .
674
675 argv[] and argc describe the whole program argument set. 'ai' is the
676 index of the argument that is the short option cluster.
677 -----------------------------------------------------------------------------*/
678 const char * optP; /* A short option character */
679 const char * arg; /* The argument of the short option */
680 bool processedArg;
681 /* We processed an argument to one of the one-character options.
682 This necessarily means there are no more options in this token
683 to process.
684 */
685
686 *tokensConsumedP = 1; /* initial assumption */
687
688 for (optP = argv[ai] + 1, processedArg = false;
689 *optP && !processedArg; ) {
690
691 bool found;
692 unsigned int mi; /* index into option table */
693 /* find matching option */
694 optMatch(optTable, optP, SL_SHORT, &found, &mi);
695 if (!found)
696 optFatal("unrecognized option `-%c'", *optP);
697
698 /* does this option take an argument? */
699 if (optNeedsArgument(optTable[mi])) {
700 /* option needs an argument. find it. */
701 arg = optP + 1;
702 if (!*arg) {
703 if (ai + 1 >= argc)
704 optFatal("option `%s' requires an argument",
705 optString(optTable[mi], 0));
706 arg = argv[ai+1];
707 ++*tokensConsumedP;
708 }
709 processedArg = 1;
710 } else
711 arg = NULL;
712 /* perform the action of this option. */
713 optExecute(optTable[mi], arg, 0);
714 ++optP;
715 }
716 }
717
718
719
720 static void
721 fatalUnrecognizedLongOption(const char * const optionName,
722 optEntry const optTable[]) {
723
724 unsigned int const optCt = optStructCount(optTable);
725
726 unsigned int q;
727
728 char optList[1024];
729
730 optList[0] = '\0'; /* initial value */
731
732 for (q = 0;
733 q < optCt && strlen(optList) + 1 <= sizeof(optList);
734 ++q) {
735
736 const optEntry * const optEntryP = &optTable[q];
737 const char * entry;
738
739 if (optEntryP->longName)
740 pm_asprintf(&entry, "-%s ", optEntryP->longName);
741 else
742 pm_asprintf(&entry, "-%c ", optEntryP->shortName);
743
744 strncat(optList, entry, sizeof(optList) - strlen(optList) - 1);
745
746 pm_strfree(entry);
747
748 if (strlen(optList) + 1 == sizeof(optList)) {
749 /* Buffer is full. Overwrite end of list with ellipsis */
750 strcpy(&optList[sizeof(optList) - 4], "...");
751 }
752 }
753 optFatal("unrecognized option '%s'. Recognized options are: %s",
754 optionName, optList);
755 }
756
757
758
759 static void
760 parseLongOption(const char ** const argv,
761 int const argc,
762 int const ai,
763 int const namepos,
764 const optEntry * const optTable,
765 unsigned int * const tokensConsumedP) {
766 /*----------------------------------------------------------------------------
767 Parse a long option, e.g. -verbose or --verbose.
768
769 The option might take an argument, and we parse
770 that as well. e.g. -file=myfile or -file myfile .
771
772 argv[] and argc describe the whole program argument set. 'ai' is the
773 index of the argument that is the long option.
774 -----------------------------------------------------------------------------*/
775 char * equalsArg;
776 /* The argument of an option, included in the same token, after a
777 "=". NULL if no "=" in the token.
778 */
779 const char * arg; /* The argument of an option; NULL if none */
780 bool found;
781 unsigned int mi; /* index into option table */
782
783 /* The current token is an option, and its name starts at
784 Index 'namepos' in the argument.
785 */
786 *tokensConsumedP = 1; /* initial assumption */
787 /* find matching option */
788 optMatch(optTable, &argv[ai][namepos], SL_LONG, &found, &mi);
789 if (!found)
790 fatalUnrecognizedLongOption(argv[ai], optTable);
791
792 /* possibly locate the argument to this option. */
793 {
794 char * p;
795 if ((p = strchr(argv[ai], '=')) != NULL)
796 equalsArg = p + 1;
797 else
798 equalsArg = NULL;
799 }
800 /* does this option take an argument? */
801 if (optNeedsArgument(optTable[mi])) {
802 /* option needs an argument. find it. */
803 if (equalsArg)
804 arg = equalsArg;
805 else {
806 if (ai + 1 == argc)
807 optFatal("option `%s' requires an argument",
808 optString(optTable[mi], 1));
809 arg = argv[ai+1];
810 ++*tokensConsumedP;
811 }
812 } else {
813 if (equalsArg)
814 optFatal("option `%s' doesn't allow an argument, but you "
815 "have specified it in the form name=value",
816 optString(optTable[mi], 1));
817 else
818 arg = NULL;
819 }
820 /* perform the action of this option. */
821 optExecute(optTable[mi], arg, 1);
822 }
823
824
825
826 void
827 pm_optParseOptions2(int * const argcP,
828 char ** const argv,
829 optStruct2 const opt,
830 unsigned long const flags) {
831 /*----------------------------------------------------------------------------
832 This does the same thing as pm_optParseOptions3(), except that there is no
833 "specified" return value.
834
835 This function exists for backward compatibility.
836 -----------------------------------------------------------------------------*/
837 optStruct3 opt3;
838
839 opt3.short_allowed = opt.short_allowed;
840 opt3.allowNegNum = opt.allowNegNum;
841 opt3.opt_table = optStructTblToEntryTbl(opt.opt_table);
842
843 if (opt3.opt_table == NULL)
844 optFatal("Memory allocation failed (trying to allocate space for "
845 "new-format option table)");
846
847 pm_optParseOptions3(argcP, argv, opt3, sizeof(opt3), flags);
848
849 free(opt3.opt_table);
850 }
851
852
853
854
855 static void
856 zeroSpecified(const optEntry * const optTable) {
857 /*----------------------------------------------------------------------------
858 Set all the "number of times specified" return values identified in the
859 option table opttable[] to zero.
860 -----------------------------------------------------------------------------*/
861 unsigned int i;
862
863 for (i = 0; optTable[i].type != OPT_END; ++i) {
864 if (optTable[i].specified)
865 *(optTable[i].specified) = 0;
866 }
867 }
868
869
870
871 void
872 pm_optParseOptions3(int * const argcP,
873 char ** const argv,
874 optStruct3 const opt,
875 unsigned int const optStructSz,
876 unsigned long const flags) {
877 /*----------------------------------------------------------------------------
878 Same as 'pm_optParseOptions4', except argv has type char ** instead of const
879 char **. This function does not modify the argv[] strings; it exists for
880 backward compatibility with programs that pass an argv of type char ** .
881 -----------------------------------------------------------------------------*/
882 pm_optParseOptions4(argcP, (const char **)argv, opt, optStructSz, flags);
883 }
884
885
886
887 void
888 pm_optParseOptions4(int * const argcP,
889 const char ** const argv,
890 optStruct3 const opt,
891 unsigned int const optStructSize,
892 unsigned long const flags) {
893 /*---------------------------------------------------------------------------
894 FUNCTION Parse commandline options.
895
896 INPUT argc Pointer to number of options.
897 argv Array of option-/argument-strings.
898 opt Structure describing option syntax.
899 optStructSize
900 Size of "opt" (since the caller may be older
901 than this function, it may be using a structure
902 with fewer fields than exist today. We use this
903 parameter to handle those older callers).
904 flags Result is undefined if not zero.
905 For future expansion.
906
907 OUTPUT argc new argument count.
908 argv array with arguments removed.
909
910 Areas pointed to by pointers in 'opt' get updated with
911 option values and counts.
912
913 RETURNS Nothing. Aborts in case of error.
914
915 DESCRIPTION This function checks each option in the argv-array
916 against strings in the opt-array, and `executes' any
917 matching action. Any arguments to the options are
918 extracted and stored in the variables or passed to
919 functions pointed to by entries in opt.
920
921 This differs from pm_optParseOptions in that it accepts
922 long options with just one hyphen and doesn't accept
923 any short options. It also has accommodations for
924 future expansion.
925
926 Options and arguments used are removed from the argv-
927 array, and argc is decreased accordingly.
928
929 Any error leads to program abortion.
930 ----------------------------------------------------------------------------*/
931 unsigned int ai; /* argv index. */
932 unsigned int tokensConsumed;
933 bool noMoreOptions;
934 /* We've encountered the "no more options" token */
935
936 zeroSpecified(opt.opt_table);
937
938 for (ai = 0, noMoreOptions = false; ai < *argcP; ) {
939 if (noMoreOptions)
940 /* Can't be an option -- there aren't any more */
941 ++ai;
942 else if (argv[ai][0] != '-')
943 /* Can't be an option -- doesn't start with a dash */
944 ++ai;
945 else {
946 /* It starts with a dash -- could be an option */
947 if (argv[ai][1] == '\0') {
948 /* A dash by itself is not considered an option. */
949 ++ai;
950 tokensConsumed = 0;
951 } else if (opt.allowNegNum && ISDIGIT(argv[ai][1])) {
952 /* It's a negative number parameter, not an option */
953 ++ai;
954 tokensConsumed = 0;
955 } else if (argv[ai][1] == '-') {
956 /* It starts with -- */
957 if (argv[ai][2] == '\0') {
958 /* The entire thing is "--". That means no more options */
959 tokensConsumed = 1;
960 noMoreOptions = true;
961 } else
962 /* It's an option that starts with "--" */
963 parseLongOption(argv, *argcP, ai, 2,
964 opt.opt_table, &tokensConsumed);
965 } else {
966 if (opt.short_allowed) {
967 /* It's a cluster of (one or more) short options */
968 parseShortOptionToken(argv, *argcP, ai,
969 opt.opt_table, &tokensConsumed);
970 } else {
971 /* It's a long option that starts with "-" */
972 parseLongOption(argv, *argcP, ai, 1,
973 opt.opt_table, &tokensConsumed);
974 }
975
976 }
977 /* remove option and any argument from the argv-array. */
978 {
979 unsigned int i;
980 for (i = 0; i < tokensConsumed; ++i)
981 argvRemove(argcP, argv, ai);
982 }
983 }
984 }
985 }
986
987
988
989 void
990 pm_optDestroyNameValueList(struct optNameValue * const list) {
991
992 unsigned int i;
993
994 for (i = 0; list[i].name; ++i) {
995 pm_strfree(list[i].name);
996 pm_strfree(list[i].value);
997 }
998
999 free(list);
1000 }
1001
1002