-
Notifications
You must be signed in to change notification settings - Fork 2.1k
/
Copy pathCHIPArgParser.cpp
1713 lines (1520 loc) · 63.6 KB
/
CHIPArgParser.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
*
* Copyright (c) 2020 Project CHIP Authors
* Copyright (c) 2017 Nest Labs, Inc.
* All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* @file
* Support functions for parsing command-line arguments.
*
*/
#include "CHIPArgParser.hpp"
#if CHIP_CONFIG_ENABLE_ARG_PARSER
#include <climits>
#include <ctype.h>
#include <errno.h>
#include <getopt.h>
#include <inttypes.h>
#include <lib/support/SafeInt.h>
#include <limits.h>
#include <stdarg.h>
#include <stdint.h>
#include <string.h>
#include <strings.h>
#include <unistd.h>
#include <lib/support/CHIPMem.h>
#include <lib/support/CHIPMemString.h>
#include <lib/support/EnforceFormat.h>
#include <lib/support/logging/Constants.h>
/*
* TODO: Revisit these if and when fabric ID and node ID support has
* been integrated into the stack.
*/
#ifndef CHIP_ARG_PARSER_PARSE_FABRIC_ID
#define CHIP_ARG_PARSER_PARSE_FABRIC_ID 0
#endif // CHIP_ARG_PARSER_PARSE_FABRIC_ID
namespace chip {
namespace ArgParser {
using namespace chip;
static char * MakeShortOptions(OptionSet ** optSets);
static struct option * MakeLongOptions(OptionSet ** optSets);
static int32_t SplitArgs(char * argStr, char **& argList, char * initialArg = nullptr);
static bool GetNextArg(char *& parsePoint);
static size_t CountOptionSets(OptionSet * optSets[]);
static size_t CountAllOptions(OptionSet * optSets[]);
static void FindOptionByIndex(OptionSet ** optSets, int optIndex, OptionSet *& optSet, OptionDef *& optDef);
static void FindOptionById(OptionSet ** optSets, int optId, OptionSet *& optSet, OptionDef *& optDef);
static const char ** MakeUniqueHelpGroupNamesList(OptionSet * optSets[]);
static void PutStringWithNewLine(FILE * s, const char * str);
static void PutStringWithBlankLine(FILE * s, const char * str);
#if CHIP_CONFIG_ENABLE_ARG_PARSER_VALIDITY_CHECKS
static bool SanityCheckOptions(OptionSet * optSets[]);
#endif // CHIP_CONFIG_ENABLE_ARG_PARSER_VALIDITY_CHECKS
static inline bool IsShortOptionChar(int ch)
{
return isgraph(ch);
}
#ifdef CONFIG_NON_POSIX_GETOPT_LONG
static inline bool IsNotAnOption(char * const argv[], int element, int character)
{
char c = argv[element][character];
return c == 0 || c == ' ' || c == '\t' || c == '\n' || c == '\r' || optarg == argv[element] + character;
}
static inline bool IsShortOption(char * const argv[], int element)
{
return argv[element][1] != '-';
}
static inline int NextElementWithOptions(char * const argv[], int element)
{
do
{
element++;
} while (argv[element] && argv[element][0] != '-');
return element;
}
static inline int FirstCharacter(char * const argv[], int element)
{
if (!argv[element])
return 0;
return argv[element][1] == '-' ? 2 : 1;
}
#endif // CONFIG_NON_POSIX_GETOPT_LONG
/**
* @brief
* The list of OptionSets passed to the currently active ParseArgs() call.
*
* @details
* This value will be NULL when no call to ParseArgs() is in progress.
*/
OptionSet ** gActiveOptionSets = nullptr;
/**
* @brief
* Pointer to function used to print errors that occur during argument parsing.
*
* @details
* Applications should call PrintArgError() to report errors in their option and
* non-option argument handling functions, rather than printing directly to
* stdout/stderr.
*
* Defaults to a pointer to the `DefaultPrintArgError()` function.
*/
void (*PrintArgError)(const char * msg, ...) = DefaultPrintArgError;
/**
* @fn bool ParseArgs(const char *progName, int argc, char * const argv[], OptionSet *optSets[],
* NonOptionArgHandlerFunct nonOptArgHandler, bool ignoreUnknown)
*
* @brief
* Parse a set of command line-style arguments, calling handling functions to process each
* option and non-option argument.
*
* @param[in] progName The name of the program or context in which the arguments are
* being parsed. This string will be used to prefix error
* messages and warnings.
* @param[in] argc The number of arguments to be parsed, plus 1.
* @param[in] argv An array of argument strings to be parsed. The array length must
* be 1 greater than the value specified for argc, and
* argv[argc] must be set to NULL. Argument parsing begins with the
* *second* array element (argv[1]); element 0 is ignored.
* `argv` may have its elements permuted as a side effect of this
* function. Non-options will be moved to the end of argv.
* @param[in] optSets A list of pointers to `OptionSet` structures that define the legal
* options. The supplied list must be terminated with a NULL.
* @param[in] nonOptArgHandler A pointer to a function that will be called once option parsing
* is complete with any remaining non-option arguments . The function
* is called regardless of whether any arguments remain. If a NULL
* is passed `ParseArgs()` will report an error if any non-option
* arguments are present.
* @param[in] ignoreUnknown If true, silently ignore any unrecognized options.
*
* @return `true` if all options and non-option arguments were parsed
* successfully; `false` if an option was unrecognized or if one of
* the handler functions failed (i.e. returned false).
*
*
* @details
* ParseArgs() takes a list of arguments (`argv`) and parses them according to a set of supplied
* option definitions. The function supports both long (--opt) and short (-o) options and implements
* the same option syntax as the GNU getopt_long(3) function.
*
* Option definitions are passed to ParseArgs() as an array of OptionSet structures (`optSets`).
* Each OptionSet contains an array of option definitions and a handler function. ParseArgs()
* processes option arguments in the given order, calling the respective handler function for
* each recognized option. Once all options have been parsed, a separate non-option handler
* function (`nonOptArgHandler`) is called once to process any remaining arguments.
*
*
* ## OPTION SETS
*
* An OptionSet contains a set of option definitions along with a pointer to a handler function
* that will be called when one of the associated options is encountered. Option sets also
* contain help text describing the syntax and purpose of each option (see OPTION HELP below).
* Option sets are designed to allow the creation of re-usable collections of related options.
* This simplifies the effort needed to maintain multiple applications that accept similar options
* (e.g. test applications).
*
* There are two patterns for defining OptionSets--one can either initialize an instance of the
* OptionSet struct itself, e.g. as a static global, or subclass OptionSetBase and provide a
* constructor. The latter uses a pure virtual `HandleOption()` function to delegate option
* handling to the subclass.
*
* Lists of OptionSets are passed to the ParseArgs() function as a NULL-terminated array of pointers.
* E.g.:
*
* static OptionSet gToolOptions =
* {
* HandleOption, // handler function
* gToolOptionDefs, // array of option definitions
* "GENERAL OPTIONS", // help group
* gToolOptionHelp // option help text
* };
*
* static OptionSet *gOptionSets[] =
* {
* &gToolOptions,
* &gNetworkOptions,
* &gTestingOptions,
* &gHelpOptions,
* NULL
* };
*
* int main(int argc, char *argv[])
* {
* if (!ParseArgs("test-app", argc, argv, gOptionSets))
* {
* ...
* }
* }
*
*
* ## OPTION DEFINITIONS
*
* Options are defined using the `OptionDef` structure. Option definitions are organized as an array
* of OptionDef elements, where each element contains: the name of the option, a integer id that is
* used to identify the option, and whether the option expects/allows an argument. The end of the
* option array is signaled by a NULL Name field. E.g.:
*
* enum
* {
* kOpt_Listen = 1000,
* kOpt_Length,
* kOpt_Count,
* };
*
* static OptionDef gToolOptionDefs[] =
* {
* // NAME REQUIRES/ALLOWS ARG? ID/SHORT OPTION CHAR
* // ============================================================
* { "listen", kNoArgument, kOpt_Listen },
* { "length", kArgumentRequired, kOpt_Length },
* { "count", kArgumentRequired, kOpt_Count },
* { "num", kArgumentRequired, kOpt_Count }, // alias for --count
* { "debug", kArgumentOptional, 'd' },
* { "help", kNoArgument, 'h' },
* { NULL }
* };
*
*
* ## OPTION IDS
*
* Option ids identify options to the code that handles them (the OptionHandler function). Option ids
* are relative to the OptionSet in which they appear, and thus may be reused across different
* OptionSets (however see SHORT OPTIONS below). Common convention is to start numbering option ids
* at 1000, however any number > 128 can be used. Alias options can be created by using the same
* option id with different option names.
*
*
* ## SHORT OPTIONS
*
* Unlike getopt_long(3), ParseArgs() does not take a separate string specifying the list of short
* option characters. Rather, any option whose id value falls in the range of graphical ASCII
* characters will allow that character to be used as a short option.
*
* ParseArgs() requires that short option characters be unique across *all* OptionSets. Because of
* this, the use of short options is discouraged for any OptionSets that are shared across programs
* due to the significant chance for collisions. Short options characters may be reused within a
* single OptionSet to allow for the creation of alias long option names.
*
*
* ## OPTION HELP
*
* Each OptionSet contains an `OptionHelp` string that describes the purpose and syntax of the
* associated options. These strings are used by the `PrintOptionHelp()` function to generate
* option usage information.
*
* By convention, option help strings consist of a syntax example following by a textual
* description of the option. If the option has a short version, or an alias name, it is given
* before primary long name. For consistency, syntax lines are indented with 2 spaces, while
* description lines are indented with 7 spaces. A single blank line follows each option
* description, including the last one.
*
* E.g.:
*
* static const char *const gToolOptionHelp =
* " --listen\n"
* " Listen and respond to requests sent from another node.\n"
* "\n"
* " --length <num>\n"
* " Send requests with the specified number of bytes in the payload.\n"
* "\n"
* " --num, --count <num>\n"
* " Send the specified number of requests and exit.\n"
* "\n"
* " -d, --debug [<level>]\n"
* " Set debug logging to the given level. (Default: 1)\n"
* "\n"
* " -h, --help\n"
* " Print help information.\n"
* "\n";
*
*
* ## OPTION HELP GROUPS
*
* OptionSets contain a `HelpGroupName` string which is used to group options together in the
* help output. The `PrintOptionHelp()` function uses the HelpGroupName as a section title in
* the generated usage output. If multiple OptionSets have the same HelpGroupName,
* PrintOptionHelp() will print the option help for the different OptionSets together under
* a common section title.
*
*
* ## NON-POSIX IMPLEMENTATIONS OF getopt_long
*
* Some platforms have a version of getopt_long that behaves differently from the POSIX
* version. Define CONFIG_NON_POSIX_GETOPT_LONG if the platform's implementation of getopt_long
* differs from POSIX in the following ways (as is the case for ESP32 and OpenIoT):
* (a) Sets optopt to '?' when encountering an unknown short option, instead of setting it
* to the actual value of the character it encountered.
* (b) Treats an unknown long option like a series of short options.
* (c) Does not always permute argv to put the nonoptions at the end.
*
*/
bool ParseArgs(const char * progName, int argc, char * const argv[], OptionSet * optSets[],
NonOptionArgHandlerFunct nonOptArgHandler, bool ignoreUnknown)
{
bool res = false;
char optName[64];
char * optArg;
char * shortOpts = nullptr;
struct option * longOpts = nullptr;
OptionSet * curOptSet;
OptionDef * curOpt;
bool handlerRes;
int optIndex = -1;
#ifdef CONFIG_NON_POSIX_GETOPT_LONG
// The element and character being looked at during the current iteration's call to getopt_long.
int currentElement = 0;
int currentCharacter;
// The value of optind after the last time getopt_long was called.
int prevOptIndex = 1;
// All the nonoptions we have found so far will be in range [firstNonoption, lastNonoptionPlus1).
int firstNonoption = 1;
int lastNonoptionPlus1 = 1;
// Temporary variables used When finding a new set of nonoptions.
int firstNonoptionNew;
int lastNonoptionPlus1New;
// Temporary variables used when moving already-found nonoptions later in the array so that they
// will be contiguous with the new non-options that were just found.
// Index the nonoption is being moved to.
int moveNonoptionToHere;
// Initial index of the nonoption being moved.
int nonoptionToMove;
// Index of the next pair of elements to swap in argv (indexToSwap and indexToSwap+1).
int indexToSwap;
// Temporary variable for swapping elements of argv.
char * tempSwap;
// Permutable version of argv. Needed to move the nonoptions to the end.
char ** permutableArgv = const_cast<char **>(argv);
#endif // CONFIG_NON_POSIX_GETOPT_LONG
// The getopt() functions do not support recursion, so exit immediately with an
// error if called recursively.
if (gActiveOptionSets != nullptr)
{
PrintArgError("INTERNAL ERROR: ParseArgs() called recursively\n", progName);
return false;
}
// The C standard mandates that argv[argc] == NULL and certain versions of getopt() require this
// to function properly. So fail if this is not true.
if (argv[argc] != nullptr)
{
PrintArgError("INTERNAL ERROR: argv[argc] != NULL\n", progName);
return false;
}
// Set gActiveOptionSets to the current option set list.
gActiveOptionSets = optSets;
#if CHIP_CONFIG_ENABLE_ARG_PARSER_VALIDITY_CHECKS
if (!SanityCheckOptions(optSets))
goto done;
#endif
// Generate a short options string in the format expected by getopt_long().
shortOpts = MakeShortOptions(optSets);
if (shortOpts == nullptr)
{
PrintArgError("%s: Memory allocation failure\n", progName);
goto done;
}
// Generate a list of long option structures in the format expected by getopt_long().
longOpts = MakeLongOptions(optSets);
if (longOpts == nullptr)
{
PrintArgError("%s: Memory allocation failure\n", progName);
goto done;
}
#ifdef CONFIG_NON_POSIX_GETOPT_LONG
// This non-POSIX getopt_long will sometimes permute argv, but not in all the cases that the POSIX version would and not always
// at the same times. This makes it hard to predict when it will permute, which can sometimes break the manual permutation that
// we're trying to do in here. To avoid this we do an initial pass through the full argv and let getopt_long get all its
// permuting out of the way so that we know argv will remain stable once we begin to parse it for real.
optind = 0;
while (getopt_long(argc, argv, shortOpts, longOpts, &optIndex) != -1)
{
}
#endif // CONFIG_NON_POSIX_GETOPT_LONG
// Force getopt() to reset its internal state.
optind = 0;
// Process any option arguments...
while (true)
{
int id;
optIndex = -1;
// Attempt to match the current option argument (argv[optind]) against the defined long and short options.
optarg = nullptr;
optopt = 0;
#ifdef CONFIG_NON_POSIX_GETOPT_LONG
// Advance to the next element/character that getopt_long will be processing.
// If currentElement has been initialized and currentElement is currently a short option (or short option group).
if (currentElement > 0 && IsShortOption(argv, currentElement))
{
// If the next character is null or whitespace or the start of the most recent optarg.
if (IsNotAnOption(argv, currentElement, currentCharacter + 1))
{
// Move currentElement to the next element that starts with '-'
currentElement = NextElementWithOptions(argv, currentElement);
// Set currentCharacter to the first character after the hyphens.
currentCharacter = FirstCharacter(argv, currentElement);
}
else // The next character is another option.
currentCharacter++;
}
else // currentElement is currently uninitialized or a long option.
{
// Move currentElement to the next element that starts with '-'
currentElement = NextElementWithOptions(argv, currentElement);
// Set currentCharacter to the first character after the hyphens.
currentCharacter = FirstCharacter(argv, currentElement);
}
#endif // CONFIG_NON_POSIX_GETOPT_LONG
id = getopt_long(argc, argv, shortOpts, longOpts, &optIndex);
#ifdef CONFIG_NON_POSIX_GETOPT_LONG
// The POSIX implementation does the sorting as it goes, gradually permuting argv to put the nonoptions towards the end.
// This code attempts to simulate that outcome, the one difference being that the POSIX version will move nonoptions after
// the next time getopt_long is called, whereas this code will only move nonoptions when it either encounters additional
// nonoptions or it reaches the end. The final result (at the time the nonoption handler is called) is the same, but the
// elements of argv during the execution of this loop may not always match what they would be with the POSIX version. It is
// only guaranteed to match at the end.
// The elements that just now got processed by getopt_long are [prevOptIndex, optind] if the new option is the non-final
// character of an option group (e.g. 'a' or 'b' in "-abc"), or [prevOptIndex, optind) if it's the final character of an
// option group or not a group at all. Walk through those elements knowing that all elements we encounter before reaching
// the option must be nonoptions. Store the range of those nonoptions in firstNonoptionNew and lastNonoptionPlus1New. If
// this is the final iteration (getopt_long returned -1) then prevOptIndex == optind == argc, which means firstNonoptionNe
// == lastNonoptionPlus1New == argc, the following for loop will be skipped, and all the nonoptions we had already found
// will get moved to the end of argv.
firstNonoptionNew = prevOptIndex;
lastNonoptionPlus1New = prevOptIndex;
for (nonoptionToMove = prevOptIndex; nonoptionToMove <= optind; nonoptionToMove++)
{
// Note that this loop INCLUDES nonoptionToMove=optind since the option that just got processed might be part of a group
// of short options all sharing a single '-', in which case optind is going to land on that same element several times
// in a row before it moves past it.
if (argv[nonoptionToMove] && argv[nonoptionToMove][0] == '-')
{
lastNonoptionPlus1New = nonoptionToMove;
break;
}
}
// Only move the already-found nonoptions if we just now found new nonoptions or we have reached the end.
if (firstNonoptionNew < lastNonoptionPlus1New || id == -1)
{
// Move the old set of nonoptions we had already found so that they abut the new set of nonoptions we just now found,
// thus giving us a single contiguous block of nonoptions.
moveNonoptionToHere = firstNonoptionNew - 1;
for (nonoptionToMove = lastNonoptionPlus1 - 1; nonoptionToMove >= firstNonoption; nonoptionToMove--)
{
// Move element nonoptionToMove (the last nonoption we haven't moved yet) into the slot moveNonoptionToHere.
for (indexToSwap = nonoptionToMove; indexToSwap < moveNonoptionToHere; indexToSwap++)
{
// Swap element indexToSwap with element indexToSwap + 1.
tempSwap = permutableArgv[indexToSwap];
permutableArgv[indexToSwap] = permutableArgv[indexToSwap + 1];
permutableArgv[indexToSwap + 1] = tempSwap;
}
// Decrement moveNonoptionToHere so the next nonoption we move will go into the slot before it.
moveNonoptionToHere--;
}
// Update the range of nonoptions so that it encompasses the merged set.
firstNonoption = firstNonoptionNew - (lastNonoptionPlus1 - firstNonoption);
lastNonoptionPlus1 = lastNonoptionPlus1New;
}
// Store the value of optind so we'll know which elements getopt_long processes the next time it is called.
prevOptIndex = optind;
#endif // CONFIG_NON_POSIX_GETOPT_LONG
// Stop if there are no more options.
if (id == -1)
break;
// If the current option is unrecognized, fail with an error message unless ignoreUnknown == true.
if (id == '?')
{
if (ignoreUnknown)
continue;
if (optopt != 0)
{
#ifdef CONFIG_NON_POSIX_GETOPT_LONG
if (IsShortOption(argv, currentElement))
{
// On this platform an unknown short option sets optopt to '?' instead of the actual option character, so fetch
// the character from argv.
if (optopt == '?')
optopt = argv[currentElement][currentCharacter];
PrintArgError("%s: Unknown option: -%c\n", progName, optopt);
}
else // Long option
{
// On this platform an unknown long option is treated like a group of short options, so skip past the rest of
// this element.
optind++;
PrintArgError("%s: Unknown option: %s\n", progName, argv[currentElement]);
}
#else
PrintArgError("%s: Unknown option: -%c\n", progName, optopt);
#endif // CONFIG_NON_POSIX_GETOPT_LONG
}
else // optopt == 0 only happens for long options, so optind has already advanced.
PrintArgError("%s: Unknown option: %s\n", progName, argv[optind - 1]);
goto done;
}
// If the option was recognized, but it is lacking an argument, fail with
// an error message.
if (id == ':')
{
// NOTE: with the way getopt_long() works, it is impossible to tell whether the option that
// was missing an argument was a long option or a short option.
#ifdef CONFIG_NON_POSIX_GETOPT_LONG
PrintArgError("%s: Missing argument for %s option\n", progName, argv[currentElement]);
#else
PrintArgError("%s: Missing argument for %s option\n", progName, argv[optind - 1]);
#endif // CONFIG_NON_POSIX_GETOPT_LONG
goto done;
}
// If a long option was matched...
if (optIndex != -1)
{
// Locate the option set and definition using the index value returned by getopt_long().
FindOptionByIndex(optSets, optIndex, curOptSet, curOpt);
// Form a string containing the name of the option as it appears on the command line.
snprintf(optName, sizeof(optName), "--%s", curOpt->Name);
}
// Otherwise a short option was matched...
else
{
// Locate the option set and definition using the option id.
FindOptionById(optSets, id, curOptSet, curOpt);
// Form a string containing the name of the short option as it would appears on the
// command line if given by itself.
snprintf(optName, sizeof(optName), "-%c", id);
}
// Prevent handlers from inadvertently using the getopt global optarg.
optArg = optarg;
optarg = nullptr;
// Call the option handler function defined for the matching option set.
// Exit immediately if the option handler failed.
handlerRes = curOptSet->OptionHandler(progName, curOptSet, id, optName, optArg);
if (!handlerRes)
goto done;
}
// If supplied, call the non-option argument handler with the remaining arguments (if any).
if (nonOptArgHandler != nullptr)
{
#ifdef CONFIG_NON_POSIX_GETOPT_LONG
// On a POSIX implementation, on the final iteration when getopt_long returns -1 indicating it has nothing left to do,
// optind would be set to the location of the first nonoption (all of which by now would have been moved to the end of
// argv). On some non-POSIX implementations this is not true -- it simply sets optind to the location of argv's terminal
// NULL (i.e. optind == argc). So we have to alter optind here to simulate the POSIX behavior.
optind = firstNonoption;
#endif // CONFIG_NON_POSIX_GETOPT_LONG
if (!nonOptArgHandler(progName, argc - optind, argv + optind))
goto done;
}
// otherwise, if there are additional arguments, fail with an error.
else if (optind < argc)
{
PrintArgError("%s: Unexpected argument: %s\n", progName, argv[optind]);
goto done;
}
res = true;
done:
if (shortOpts != nullptr)
chip::Platform::MemoryFree(shortOpts);
if (longOpts != nullptr)
chip::Platform::MemoryFree(longOpts);
gActiveOptionSets = nullptr;
return res;
}
bool ParseArgs(const char * progName, int argc, char * const argv[], OptionSet * optSets[],
NonOptionArgHandlerFunct nonOptArgHandler)
{
return ParseArgs(progName, argc, argv, optSets, nonOptArgHandler, false);
}
bool ParseArgs(const char * progName, int argc, char * const argv[], OptionSet * optSets[])
{
return ParseArgs(progName, argc, argv, optSets, nullptr, false);
}
/**
* @brief
* Parse a set of arguments from a given string.
*
* @param[in] progName The name of the program or context in which the arguments are
* being parsed. This string will be used to prefix error
* messages and warnings.
* @param[in] argStr A string containing options and arguments to be parsed.
* @param[in] optSets A list of pointers to `OptionSet` structures that define the legal
* options. The supplied list must be terminated with a NULL.
* @param[in] nonOptArgHandler A pointer to a function that will be called once option parsing
* is complete with any remaining non-option arguments . The function
* is called regardless of whether any arguments remain. If a NULL
* is passed `ParseArgs()` will report an error if any non-option
* arguments are present.
* @param[in] ignoreUnknown If true, silently ignore any unrecognized options.
*
* @return `true` if all options and non-option arguments were parsed
* successfully; `false` if an option was unrecognized, if one of
* the handler functions failed (i.e. returned false) or if an
* internal error occurred.
*
* @details
* ParseArgsFromString() splits a given string (`argStr`) into a set of arguments and parses the
* arguments using the ParseArgs() function.
*
* The syntax of the input strings is similar to unix shell command syntax, but with a simplified
* quoting scheme. Specifically:
*
* - Arguments are delimited by whitespace, unless the whitespace is quoted or escaped.
*
* - A backslash escapes the following character, causing it to be treated as a normal character.
* The backslash itself is stripped.
*
* - Single or double quotes begin/end quoted substrings. Within a substring, the only special
* characters are backslash, which escapes the next character, and the corresponding end quote.
* The begin/end quote characters are stripped.
*
* E.g.:
*
* --listen --count 10 --sw-version '1.0 (DEVELOPMENT)' "--hostname=nest.com"
*
*/
bool ParseArgsFromString(const char * progName, const char * argStr, OptionSet * optSets[],
NonOptionArgHandlerFunct nonOptArgHandler, bool ignoreUnknown)
{
char ** argv = nullptr;
int argc;
bool res;
chip::Platform::ScopedMemoryString argStrCopy(argStr, strlen(argStr));
if (!argStrCopy)
{
PrintArgError("%s: Memory allocation failure\n", progName);
return false;
}
argc = SplitArgs(argStrCopy.Get(), argv, const_cast<char *>(progName));
if (argc < 0)
{
PrintArgError("%s: Memory allocation failure\n", progName);
return false;
}
res = ParseArgs(progName, argc, argv, optSets, nonOptArgHandler, ignoreUnknown);
chip::Platform::MemoryFree(argv);
return res;
}
bool ParseArgsFromString(const char * progName, const char * argStr, OptionSet * optSets[],
NonOptionArgHandlerFunct nonOptArgHandler)
{
return ParseArgsFromString(progName, argStr, optSets, nonOptArgHandler, false);
}
bool ParseArgsFromString(const char * progName, const char * argStr, OptionSet * optSets[])
{
return ParseArgsFromString(progName, argStr, optSets, nullptr, false);
}
/**
* @brief
* Parse a set of arguments from a named environment variable
*
* @param[in] progName The name of the program or context in which the arguments are
* being parsed. This string will be used to prefix error
* messages and warnings.
* @param[in] varName The name of the environment variable.
* @param[in] optSets A list of pointers to `OptionSet` structures that define the legal
* options. The supplied list must be terminated with a NULL.
* @param[in] nonOptArgHandler A pointer to a function that will be called once option parsing
* is complete with any remaining non-option arguments . The function
* is called regardless of whether any arguments remain. If a NULL
* is passed `ParseArgs()` will report an error if any non-option
* arguments are present.
* @param[in] ignoreUnknown If true, silently ignore any unrecognized options.
*
* @return `true` if all options and non-option arguments were parsed
* successfully, or if the specified environment variable is not set;
* `false` if an option was unrecognized, if one of the handler
* functions failed (i.e. returned false) or if an internal error
* occurred.
*
* @details
* ParseArgsFromEnvVar() reads a named environment variable and passes the value to `ParseArgsFromString()`
* for parsing. If the environment variable is not set, the function does nothing.
*/
bool ParseArgsFromEnvVar(const char * progName, const char * varName, OptionSet * optSets[],
NonOptionArgHandlerFunct nonOptArgHandler, bool ignoreUnknown)
{
const char * argStr = getenv(varName);
if (argStr == nullptr)
return true;
return ParseArgsFromString(progName, argStr, optSets, nonOptArgHandler, ignoreUnknown);
}
bool ParseArgsFromEnvVar(const char * progName, const char * varName, OptionSet * optSets[])
{
return ParseArgsFromEnvVar(progName, varName, optSets, nullptr, false);
}
bool ParseArgsFromEnvVar(const char * progName, const char * varName, OptionSet * optSets[],
NonOptionArgHandlerFunct nonOptArgHandler)
{
return ParseArgsFromEnvVar(progName, varName, optSets, nonOptArgHandler, false);
}
/**
* @brief
* Print the help text for a specified list of options to a stream.
*
* @param[in] optSets A list of pointers to `OptionSet` structures that contain the
* help text to print.
* @param[in] s The FILE stream to which the help text should be printed.
*
*/
void PrintOptionHelp(OptionSet * optSets[], FILE * s)
{
// Get a list of the unique help group names for the given option sets.
const char ** helpGroupNames = MakeUniqueHelpGroupNamesList(optSets);
if (helpGroupNames == nullptr)
{
PrintArgError("Memory allocation failure\n");
return;
}
// For each help group...
for (size_t nameIndex = 0; helpGroupNames[nameIndex] != nullptr; nameIndex++)
{
// Print the group name.
PutStringWithBlankLine(s, helpGroupNames[nameIndex]);
// Print the option help text for all options that have the same group name.
for (size_t optSetIndex = 0; optSets[optSetIndex] != nullptr; optSetIndex++)
if (strcasecmp(helpGroupNames[nameIndex], optSets[optSetIndex]->HelpGroupName) == 0)
{
PutStringWithBlankLine(s, optSets[optSetIndex]->OptionHelp);
}
}
chip::Platform::MemoryFree(helpGroupNames);
}
/**
* @brief
* Print an error message associated with argument parsing.
*
* @param[in] msg The message to be printed.
*
* @details
* Default function used to print error messages that arise due to the parsing
* of arguments.
*
* Applications should call through the PrintArgError function pointer, rather
* than calling this function directly.
*/
void ENFORCE_FORMAT(1, 2) DefaultPrintArgError(const char * msg, ...)
{
va_list ap;
va_start(ap, msg);
vfprintf(stderr, msg, ap);
va_end(ap);
}
/**
* Parse a string as a boolean value.
*
* This function accepts the following input values (case-insensitive):
* "true", "yes", "t", "y", "1", "false", "no", "f", "n", "0".
*
* @param[in] str A pointer to a NULL-terminated C string representing
* the value to parse.
* @param[out] output A reference to storage for a bool to which the parsed
* value will be stored on success.
*
* @return true on success; otherwise, false on failure.
*/
bool ParseBoolean(const char * str, bool & output)
{
if (strcasecmp(str, "true") == 0 || strcasecmp(str, "yes") == 0 ||
((str[0] == '1' || str[0] == 't' || str[0] == 'T' || str[0] == 'y' || str[0] == 'Y') && str[1] == 0))
{
output = true;
return true;
}
if (strcasecmp(str, "false") == 0 || strcasecmp(str, "no") == 0 ||
((str[0] == '0' || str[0] == 'f' || str[0] == 'F' || str[0] == 'n' || str[0] == 'N') && str[1] == 0))
{
output = false;
return true;
}
return false;
}
/**
* Parse and attempt to convert a string to a 64-bit unsigned integer,
* applying the appropriate interpretation based on the base parameter.
*
* @param[in] str A pointer to a NULL-terminated C string representing
* the integer to parse.
* @param[out] output A reference to storage for a 64-bit unsigned integer
* to which the parsed value will be stored on success.
* @param[in] base The base according to which the string should be
* interpreted and parsed. If 0 or 16, the string may
* be hexadecimal and prefixed with "0x". Otherwise, a 0
* is implied as 10 unless a leading 0 is encountered in
* which 8 is implied.
*
* @return true on success; otherwise, false on failure.
*/
bool ParseInt(const char * str, uint64_t & output, int base)
{
char * parseEnd;
errno = 0;
output = strtoull(str, &parseEnd, base);
return parseEnd > str && *parseEnd == 0 && (output != ULLONG_MAX || errno == 0);
}
/**
* Parse and attempt to convert a string to a 32-bit unsigned integer,
* applying the appropriate interpretation based on the base parameter.
*
* @param[in] str A pointer to a NULL-terminated C string representing
* the integer to parse.
* @param[out] output A reference to storage for a 32-bit unsigned integer
* to which the parsed value will be stored on success.
* @param[in] base The base according to which the string should be
* interpreted and parsed. If 0 or 16, the string may
* be hexadecimal and prefixed with "0x". Otherwise, a 0
* is implied as 10 unless a leading 0 is encountered in
* which 8 is implied.
*
* @return true on success; otherwise, false on failure.
*/
bool ParseInt(const char * str, uint32_t & output, int base)
{
char * parseEnd;
unsigned long v;
errno = 0;
v = strtoul(str, &parseEnd, base);
if (!CanCastTo<uint32_t>(v))
{
return false;
}
output = static_cast<uint32_t>(v);
return parseEnd > str && *parseEnd == 0 && (v != ULONG_MAX || errno == 0);
}
/**
* Parse and attempt to convert a string to a 32-bit signed integer,
* applying the appropriate interpretation based on the base parameter.
*
* @param[in] str A pointer to a NULL-terminated C string representing
* the integer to parse.
* @param[out] output A reference to storage for a 32-bit signed integer
* to which the parsed value will be stored on success.
* @param[in] base The base according to which the string should be
* interpreted and parsed. If 0 or 16, the string may
* be hexadecimal and prefixed with "0x". Otherwise, a 0
* is implied as 10 unless a leading 0 is encountered in
* which 8 is implied.
*
* @return true on success; otherwise, false on failure.
*/
bool ParseInt(const char * str, int32_t & output, int base)
{
char * parseEnd;
long v;
errno = 0;
v = strtol(str, &parseEnd, base);
if (!CanCastTo<int32_t>(v))
{
return false;
}
output = static_cast<int32_t>(v);
return parseEnd > str && *parseEnd == 0 && ((v != LONG_MIN && v != LONG_MAX) || errno == 0);
}
/**
* Parse and attempt to convert a string to a 16-bit unsigned integer,
* applying the appropriate interpretation based on the base parameter.
*
* @param[in] str A pointer to a NULL-terminated C string representing
* the integer to parse.
* @param[out] output A reference to storage for a 16-bit unsigned integer
* to which the parsed value will be stored on success.
* @param[in] base The base according to which the string should be
* interpreted and parsed. If 0 or 16, the string may
* be hexadecimal and prefixed with "0x". Otherwise, a 0
* is implied as 10 unless a leading 0 is encountered in
* which 8 is implied.
*
* @return true on success; otherwise, false on failure.
*/
bool ParseInt(const char * str, uint16_t & output, int base)
{
uint32_t v;
if (!ParseInt(str, v, base) || !CanCastTo<uint16_t>(v))
{
return false;
}
output = static_cast<uint16_t>(v);
return true;
}
/**
* Parse and attempt to convert a string to a 8-bit unsigned integer,
* applying the appropriate interpretation based on the base parameter.
*
* @param[in] str A pointer to a NULL-terminated C string representing
* the integer to parse.
* @param[out] output A reference to storage for a 8-bit unsigned integer
* to which the parsed value will be stored on success.
* @param[in] base The base according to which the string should be
* interpreted and parsed. If 0 or 16, the string may
* be hexadecimal and prefixed with "0x". Otherwise, a 0
* is implied as 10 unless a leading 0 is encountered in
* which 8 is implied.
*
* @return true on success; otherwise, false on failure.
*/
bool ParseInt(const char * str, uint8_t & output, int base)
{
uint32_t v;
if (!ParseInt(str, v, base) || !CanCastTo<uint8_t>(v))
{
return false;