Updated gnulib and added hash-pjw-bare
[gnutls.git] / src / libopts / autoopts.c
blob1eff7002fa2c59eedad7745923cfedc34ad9bebb
2 /**
3 * \file autoopts.c
5 * Time-stamp: "2012-03-04 19:44:56 bkorb"
7 * This file contains all of the routines that must be linked into
8 * an executable to use the generated option processing. The optional
9 * routines are in separately compiled modules so that they will not
10 * necessarily be linked in.
12 * This file is part of AutoOpts, a companion to AutoGen.
13 * AutoOpts is free software.
14 * AutoOpts is Copyright (c) 1992-2012 by Bruce Korb - all rights reserved
16 * AutoOpts is available under any one of two licenses. The license
17 * in use must be one of these two and the choice is under the control
18 * of the user of the license.
20 * The GNU Lesser General Public License, version 3 or later
21 * See the files "COPYING.lgplv3" and "COPYING.gplv3"
23 * The Modified Berkeley Software Distribution License
24 * See the file "COPYING.mbsd"
26 * These files have the following md5sums:
28 * 43b91e8ca915626ed3818ffb1b71248b pkg/libopts/COPYING.gplv3
29 * 06a1a2e4760c90ea5e1dad8dfaac4d39 pkg/libopts/COPYING.lgplv3
30 * 66a5cedaf62c4b2637025f049f9b826f pkg/libopts/COPYING.mbsd
33 #ifndef PKGDATADIR
34 # define PKGDATADIR ""
35 #endif
37 static char const zNil[] = "";
38 static arg_types_t argTypes = { NULL };
39 static char line_fmt_buf[32];
40 static bool displayEnum = false;
41 static char const pkgdatadir_default[] = PKGDATADIR;
42 static char const * program_pkgdatadir = pkgdatadir_default;
43 static tOptionLoadMode option_load_mode = OPTION_LOAD_UNCOOKED;
44 static tePagerState pagerState = PAGER_STATE_INITIAL;
46 FILE * option_usage_fp = NULL;
48 /* = = = START-STATIC-FORWARD = = = */
49 static tSuccess
50 next_opt_arg_must(tOptions * pOpts, tOptState* pOptState);
52 static tSuccess
53 next_opt_arg_may(tOptions * pOpts, tOptState * pOptState);
55 static tSuccess
56 next_opt_arg_none(tOptions * pOpts, tOptState* pOptState);
58 static tSuccess
59 next_opt(tOptions * pOpts, tOptState * pOptState);
61 static tSuccess
62 doPresets(tOptions * pOpts);
63 /* = = = END-STATIC-FORWARD = = = */
65 LOCAL void *
66 ao_malloc(size_t sz)
68 void * res = malloc(sz);
69 if (res == NULL) {
70 fprintf(stderr, zAO_Alloc, (int)sz);
71 exit(EXIT_FAILURE);
73 return res;
75 #undef malloc
76 #define malloc(_s) ao_malloc(_s)
78 LOCAL void *
79 ao_realloc(void *p, size_t sz)
81 void * res = (p == NULL) ? malloc(sz) : realloc(p, sz);
82 if (res == NULL) {
83 fprintf(stderr, zAO_Realloc, (int)sz, p);
84 exit(EXIT_FAILURE);
86 return res;
88 #undef realloc
89 #define realloc(_p,_s) ao_realloc(_p,_s)
91 LOCAL char *
92 ao_strdup(char const *str)
94 char * res = strdup(str);
95 if (res == NULL) {
96 fprintf(stderr, zAO_Strdup, (int)strlen(str));
97 exit(EXIT_FAILURE);
99 return res;
101 #undef strdup
102 #define strdup(_p) ao_strdup(_p)
104 #ifndef HAVE_PATHFIND
105 # include "compat/pathfind.c"
106 #endif
108 #ifndef HAVE_SNPRINTF
109 # include "compat/snprintf.c"
110 #endif
112 #ifndef HAVE_STRDUP
113 # include "compat/strdup.c"
114 #endif
116 #ifndef HAVE_STRCHR
117 # include "compat/strchr.c"
118 #endif
121 * handle_opt
123 * This routine handles equivalencing, sets the option state flags and
124 * invokes the handler procedure, if any.
126 LOCAL tSuccess
127 handle_opt(tOptions * pOpts, tOptState* pOptState)
130 * Save a copy of the option procedure pointer.
131 * If this is an equivalence class option, we still want this proc.
133 tOptDesc* pOD = pOptState->pOD;
134 tOptProc* pOP = pOD->pOptProc;
135 if (pOD->fOptState & OPTST_ALLOC_ARG)
136 AGFREE(pOD->optArg.argString);
138 pOD->optArg.argString = pOptState->pzOptArg;
141 * IF we are presetting options, then we will ignore any un-presettable
142 * options. They are the ones either marked as such.
144 if ( ((pOpts->fOptSet & OPTPROC_PRESETTING) != 0)
145 && ((pOD->fOptState & OPTST_NO_INIT) != 0)
147 return PROBLEM;
150 * IF this is an equivalence class option,
151 * THEN
152 * Save the option value that got us to this option
153 * entry. (It may not be pOD->optChar[0], if this is an
154 * equivalence entry.)
155 * set the pointer to the equivalence class base
157 if (pOD->optEquivIndex != NO_EQUIVALENT) {
158 tOptDesc* p = pOpts->pOptDesc + pOD->optEquivIndex;
161 * IF the current option state has not been defined (set on the
162 * command line), THEN we will allow continued resetting of
163 * the value. Once "defined", then it must not change.
165 if ((pOD->fOptState & OPTST_DEFINED) != 0) {
167 * The equivalenced-to option has been found on the command
168 * line before. Make sure new occurrences are the same type.
170 * IF this option has been previously equivalenced and
171 * it was not the same equivalenced-to option,
172 * THEN we have a usage problem.
174 if (p->optActualIndex != pOD->optIndex) {
175 fprintf(stderr, (char*)zMultiEquiv, p->pz_Name, pOD->pz_Name,
176 (pOpts->pOptDesc + p->optActualIndex)->pz_Name);
177 return FAILURE;
179 } else {
181 * Set the equivalenced-to actual option index to no-equivalent
182 * so that we set all the entries below. This option may either
183 * never have been selected before, or else it was selected by
184 * some sort of "presetting" mechanism.
186 p->optActualIndex = NO_EQUIVALENT;
189 if (p->optActualIndex != pOD->optIndex) {
191 * First time through, copy over the state
192 * and add in the equivalence flag
194 p->optActualValue = pOD->optValue;
195 p->optActualIndex = pOD->optIndex;
196 pOptState->flags |= OPTST_EQUIVALENCE;
200 * Copy the most recent option argument. set membership state
201 * is kept in ``p->optCookie''. Do not overwrite.
203 p->optArg.argString = pOD->optArg.argString;
204 pOD = p;
206 } else {
207 pOD->optActualValue = pOD->optValue;
208 pOD->optActualIndex = pOD->optIndex;
211 pOD->fOptState &= OPTST_PERSISTENT_MASK;
212 pOD->fOptState |= (pOptState->flags & ~OPTST_PERSISTENT_MASK);
215 * Keep track of count only for DEFINED (command line) options.
216 * IF we have too many, build up an error message and bail.
218 if ( (pOD->fOptState & OPTST_DEFINED)
219 && (++pOD->optOccCt > pOD->optMaxCt) ) {
221 if ((pOpts->fOptSet & OPTPROC_ERRSTOP) != 0) {
222 char const * pzEqv =
223 (pOD->optEquivIndex != NO_EQUIVALENT) ? zEquiv : zNil;
225 fputs(zErrOnly, stderr);
227 if (pOD->optMaxCt > 1)
228 fprintf(stderr, zAtMost, pOD->optMaxCt, pOD->pz_Name, pzEqv);
229 else
230 fprintf(stderr, zOnlyOne, pOD->pz_Name, pzEqv);
233 return FAILURE;
237 * If provided a procedure to call, call it
239 if (pOP != NULL)
240 (*pOP)(pOpts, pOD);
242 return SUCCESS;
245 static tSuccess
246 next_opt_arg_must(tOptions * pOpts, tOptState* pOptState)
249 * An option argument is required. Long options can either have
250 * a separate command line argument, or an argument attached by
251 * the '=' character. Figure out which.
253 switch (pOptState->optType) {
254 case TOPT_SHORT:
256 * See if an arg string follows the flag character
258 if (*++(pOpts->pzCurOpt) == NUL)
259 pOpts->pzCurOpt = pOpts->origArgVect[ pOpts->curOptIdx++ ];
260 pOptState->pzOptArg = pOpts->pzCurOpt;
261 break;
263 case TOPT_LONG:
265 * See if an arg string has already been assigned (glued on
266 * with an `=' character)
268 if (pOptState->pzOptArg == NULL)
269 pOptState->pzOptArg = pOpts->origArgVect[ pOpts->curOptIdx++ ];
270 break;
272 default:
273 #ifdef DEBUG
274 fputs("AutoOpts lib error: option type not selected\n", stderr);
275 exit(EXIT_FAILURE);
276 #endif
278 case TOPT_DEFAULT:
280 * The option was selected by default. The current token is
281 * the option argument.
283 break;
287 * Make sure we did not overflow the argument list.
289 if (pOpts->curOptIdx > pOpts->origArgCt) {
290 fprintf(stderr, zMisArg, pOpts->pzProgPath, pOptState->pOD->pz_Name);
291 return FAILURE;
294 pOpts->pzCurOpt = NULL; /* next time advance to next arg */
295 return SUCCESS;
299 * Process an optional option argument. For short options, it looks at the
300 * character after the option character, or it consumes the next full argument.
301 * For long options, it looks for an '=' character attachment to the long
302 * option name before deciding to take the next command line argument.
304 * @param pOpts the option descriptor
305 * @param pOptState a structure for managing the current processing state
306 * @returns SUCCESS or does not return
308 static tSuccess
309 next_opt_arg_may(tOptions * pOpts, tOptState * pOptState)
312 * An option argument is optional.
314 switch (pOptState->optType) {
315 case TOPT_SHORT:
316 if (*++pOpts->pzCurOpt != NUL)
317 pOptState->pzOptArg = pOpts->pzCurOpt;
318 else {
319 char* pzLA = pOpts->origArgVect[ pOpts->curOptIdx ];
322 * BECAUSE it is optional, we must make sure
323 * we did not find another flag and that there
324 * is such an argument.
326 if ((pzLA == NULL) || (*pzLA == '-'))
327 pOptState->pzOptArg = NULL;
328 else {
329 pOpts->curOptIdx++; /* argument found */
330 pOptState->pzOptArg = pzLA;
333 break;
335 case TOPT_LONG:
337 * Look for an argument if we don't already have one (glued on
338 * with a `=' character) *AND* we are not in named argument mode
340 if ( (pOptState->pzOptArg == NULL)
341 && (! NAMED_OPTS(pOpts))) {
342 char* pzLA = pOpts->origArgVect[ pOpts->curOptIdx ];
345 * BECAUSE it is optional, we must make sure
346 * we did not find another flag and that there
347 * is such an argument.
349 if ((pzLA == NULL) || (*pzLA == '-'))
350 pOptState->pzOptArg = NULL;
351 else {
352 pOpts->curOptIdx++; /* argument found */
353 pOptState->pzOptArg = pzLA;
356 break;
358 default:
359 case TOPT_DEFAULT:
360 fputs(zAO_Woops, stderr );
361 exit(EX_SOFTWARE);
365 * After an option with an optional argument, we will
366 * *always* start with the next option because if there
367 * were any characters following the option name/flag,
368 * they would be interpreted as the argument.
370 pOpts->pzCurOpt = NULL;
371 return SUCCESS;
375 static tSuccess
376 next_opt_arg_none(tOptions * pOpts, tOptState* pOptState)
379 * No option argument. Make sure next time around we find
380 * the correct option flag character for short options
382 if (pOptState->optType == TOPT_SHORT)
383 (pOpts->pzCurOpt)++;
386 * It is a long option. Make sure there was no ``=xxx'' argument
388 else if (pOptState->pzOptArg != NULL) {
389 fprintf(stderr, zNoArg, pOpts->pzProgPath, pOptState->pOD->pz_Name);
390 return FAILURE;
394 * It is a long option. Advance to next command line argument.
396 else
397 pOpts->pzCurOpt = NULL;
398 return SUCCESS;
402 * Find the option descriptor and option argument (if any) for the
403 * next command line argument. DO NOT modify the descriptor. Put
404 * all the state in the state argument so that the option can be skipped
405 * without consequence (side effect).
407 * @param pOpts the program option descriptor
408 * @param pOptState the state of the next found option
410 static tSuccess
411 next_opt(tOptions * pOpts, tOptState * pOptState)
414 tSuccess res = find_opt(pOpts, pOptState);
415 if (! SUCCESSFUL(res))
416 return res;
419 if ( ((pOptState->flags & OPTST_DEFINED) != 0)
420 && ((pOptState->pOD->fOptState & OPTST_NO_COMMAND) != 0)) {
421 fprintf(stderr, zNotCmdOpt, pOptState->pOD->pz_Name);
422 return FAILURE;
425 return get_opt_arg(pOpts, pOptState);
429 /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
431 * DO PRESETS
433 * The next several routines do the immediate action pass on the command
434 * line options, then the environment variables, then the config files in
435 * reverse order. Once done with that, the order is reversed and all
436 * the config files and environment variables are processed again, this
437 * time only processing the non-immediate action options. doPresets()
438 * will then return for optionProcess() to do the final pass on the command
439 * line arguments.
443 * scan the command line for immediate action options.
444 * This is only called the first time through.
445 * While this procedure is active, the OPTPROC_IMMEDIATE is true.
447 * @param pOpts program options descriptor
448 * @returns SUCCESS or FAILURE
450 LOCAL tSuccess
451 immediate_opts(tOptions * pOpts)
453 tSuccess res;
455 pOpts->fOptSet |= OPTPROC_IMMEDIATE;
456 pOpts->curOptIdx = 1; /* start by skipping program name */
457 pOpts->pzCurOpt = NULL;
460 * Examine all the options from the start. We process any options that
461 * are marked for immediate processing.
463 for (;;) {
464 tOptState opt_st = OPTSTATE_INITIALIZER(PRESET);
466 res = next_opt(pOpts, &opt_st);
467 switch (res) {
468 case FAILURE: goto failed_option;
469 case PROBLEM: res = SUCCESS; goto leave;
470 case SUCCESS: break;
474 * IF this is an immediate-attribute option, then do it.
476 if (! DO_IMMEDIATELY(opt_st.flags))
477 continue;
479 if (! SUCCESSFUL(handle_opt(pOpts, &opt_st)))
480 break;
481 } failed_option:;
483 if ((pOpts->fOptSet & OPTPROC_ERRSTOP) != 0)
484 (*pOpts->pUsageProc)(pOpts, EXIT_FAILURE);
486 leave:
488 pOpts->fOptSet &= ~OPTPROC_IMMEDIATE;
489 return res;
493 * Process all the options from our current position onward. (This allows
494 * interspersed options and arguments for the few non-standard programs that
495 * require it.) Thus, do not rewind option indexes because some programs
496 * choose to re-invoke after a non-option.
498 * @param pOpts program options descriptor
499 * @returns SUCCESS or FAILURE
501 LOCAL tSuccess
502 regular_opts(tOptions * pOpts)
504 /* assert: pOpts->fOptSet & OPTPROC_IMMEDIATE == 0 */
505 for (;;) {
506 tOptState opt_st = OPTSTATE_INITIALIZER(DEFINED);
508 switch (next_opt(pOpts, &opt_st)) {
509 case FAILURE: goto failed_option;
510 case PROBLEM: return SUCCESS; /* no more args */
511 case SUCCESS: break;
515 * IF this is an immediate action option,
516 * THEN skip it (unless we are supposed to do it a second time).
518 if (! DO_NORMALLY(opt_st.flags)) {
519 if (! DO_SECOND_TIME(opt_st.flags))
520 continue;
521 opt_st.pOD->optOccCt--; /* don't count this repetition */
524 if (! SUCCESSFUL(handle_opt(pOpts, &opt_st)))
525 break;
526 } failed_option:;
528 if ((pOpts->fOptSet & OPTPROC_ERRSTOP) != 0)
529 (*pOpts->pUsageProc)(pOpts, EXIT_FAILURE);
531 return FAILURE;
536 * check for preset values from a config files or envrionment variables
538 static tSuccess
539 doPresets(tOptions * pOpts)
541 tOptDesc * pOD = NULL;
543 if (! SUCCESSFUL(immediate_opts(pOpts)))
544 return FAILURE;
547 * IF this option set has a --save-opts option, then it also
548 * has a --load-opts option. See if a command line option has disabled
549 * option presetting.
551 if ( (pOpts->specOptIdx.save_opts != NO_EQUIVALENT)
552 && (pOpts->specOptIdx.save_opts != 0)) {
553 pOD = pOpts->pOptDesc + pOpts->specOptIdx.save_opts + 1;
554 if (DISABLED_OPT(pOD))
555 return SUCCESS;
559 * Until we return from this procedure, disable non-presettable opts
561 pOpts->fOptSet |= OPTPROC_PRESETTING;
563 * IF there are no config files,
564 * THEN do any environment presets and leave.
566 if (pOpts->papzHomeList == NULL) {
567 env_presets(pOpts, ENV_ALL);
569 else {
570 env_presets(pOpts, ENV_IMM);
573 * Check to see if environment variables have disabled presetting.
575 if ((pOD != NULL) && ! DISABLED_OPT(pOD))
576 intern_file_load(pOpts);
579 * ${PROGRAM_LOAD_OPTS} value of "no" cannot disable other environment
580 * variable options. Only the loading of .rc files.
582 env_presets(pOpts, ENV_NON_IMM);
584 pOpts->fOptSet &= ~OPTPROC_PRESETTING;
586 return SUCCESS;
589 /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
591 * THESE ROUTINES ARE CALLABLE FROM THE GENERATED OPTION PROCESSING CODE
593 /*=--subblock=arg=arg_type,arg_name,arg_desc =*/
594 /*=*
595 * library: opts
596 * header: your-opts.h
598 * lib_description:
600 * These are the routines that libopts users may call directly from their
601 * code. There are several other routines that can be called by code
602 * generated by the libopts option templates, but they are not to be
603 * called from any other user code. The @file{options.h} header is
604 * fairly clear about this, too.
607 /*=export_func optionProcess
609 * what: this is the main option processing routine
611 * arg: + tOptions* + pOpts + program options descriptor +
612 * arg: + int + argc + program arg count +
613 * arg: + char** + argv + program arg vector +
615 * ret_type: int
616 * ret_desc: the count of the arguments processed
618 * doc:
620 * This is the main entry point for processing options. It is intended
621 * that this procedure be called once at the beginning of the execution of
622 * a program. Depending on options selected earlier, it is sometimes
623 * necessary to stop and restart option processing, or to select completely
624 * different sets of options. This can be done easily, but you generally
625 * do not want to do this.
627 * The number of arguments processed always includes the program name.
628 * If one of the arguments is "--", then it is counted and the processing
629 * stops. If an error was encountered and errors are to be tolerated, then
630 * the returned value is the index of the argument causing the error.
631 * A hyphen by itself ("-") will also cause processing to stop and will
632 * @emph{not} be counted among the processed arguments. A hyphen by itself
633 * is treated as an operand. Encountering an operand stops option
634 * processing.
636 * err: Errors will cause diagnostics to be printed. @code{exit(3)} may
637 * or may not be called. It depends upon whether or not the options
638 * were generated with the "allow-errors" attribute, or if the
639 * ERRSKIP_OPTERR or ERRSTOP_OPTERR macros were invoked.
642 optionProcess(tOptions * pOpts, int argCt, char ** argVect)
644 if (! SUCCESSFUL(validate_struct(pOpts, argVect[0])))
645 exit(EX_SOFTWARE);
648 * Establish the real program name, the program full path,
649 * and do all the presetting the first time thru only.
651 if ((pOpts->fOptSet & OPTPROC_INITDONE) == 0) {
652 pOpts->origArgCt = (unsigned int)argCt;
653 pOpts->origArgVect = argVect;
654 pOpts->fOptSet |= OPTPROC_INITDONE;
655 if (HAS_pzPkgDataDir(pOpts))
656 program_pkgdatadir = pOpts->pzPkgDataDir;
658 if (! SUCCESSFUL(doPresets(pOpts)))
659 return 0;
662 * IF option name conversion was suppressed but it is not suppressed
663 * for the command line, then it's time to translate option names.
664 * Usage text will not get retranslated.
666 if ( ((pOpts->fOptSet & OPTPROC_TRANSLATE) != 0)
667 && (pOpts->pTransProc != NULL)
668 && ((pOpts->fOptSet & OPTPROC_NO_XLAT_MASK)
669 == OPTPROC_NXLAT_OPT_CFG) ) {
671 pOpts->fOptSet &= ~OPTPROC_NXLAT_OPT_CFG;
672 (*pOpts->pTransProc)();
675 if ((pOpts->fOptSet & OPTPROC_REORDER) != 0)
676 optionSort(pOpts);
678 pOpts->curOptIdx = 1;
679 pOpts->pzCurOpt = NULL;
683 * IF we are (re)starting,
684 * THEN reset option location
686 else if (pOpts->curOptIdx <= 0) {
687 pOpts->curOptIdx = 1;
688 pOpts->pzCurOpt = NULL;
691 if (! SUCCESSFUL(regular_opts(pOpts)))
692 return pOpts->origArgCt;
695 * IF there were no errors
696 * AND we have RC/INI files
697 * AND there is a request to save the files
698 * THEN do that now before testing for conflicts.
699 * (conflicts are ignored in preset options)
701 if ( (pOpts->specOptIdx.save_opts != NO_EQUIVALENT)
702 && (pOpts->specOptIdx.save_opts != 0)) {
703 tOptDesc* pOD = pOpts->pOptDesc + pOpts->specOptIdx.save_opts;
705 if (SELECTED_OPT(pOD)) {
706 optionSaveFile(pOpts);
707 exit(EXIT_SUCCESS);
712 * IF we are checking for errors,
713 * THEN look for too few occurrences of required options
715 if ((pOpts->fOptSet & OPTPROC_ERRSTOP) != 0) {
716 if (! is_consistent(pOpts))
717 (*pOpts->pUsageProc)(pOpts, EXIT_FAILURE);
720 return pOpts->curOptIdx;
724 * Local Variables:
725 * mode: C
726 * c-file-style: "stroustrup"
727 * indent-tabs-mode: nil
728 * End:
729 * end of autoopts/autoopts.c */