-
Notifications
You must be signed in to change notification settings - Fork 149
/
Copy pathmy_getopt.cc
1680 lines (1521 loc) · 55.6 KB
/
my_getopt.cc
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) 2002, 2024, Oracle and/or its affiliates.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License, version 2.0,
as published by the Free Software Foundation.
This program is designed to work with certain software (including
but not limited to OpenSSL) that is licensed under separate terms,
as designated in a particular file or component or in included license
documentation. The authors of MySQL hereby grant you an additional
permission to link the program and your derivative works with the
separately licensed software that they have either included with
the program or referenced in the documentation.
Without limiting anything contained in the foregoing, this file,
which is part of C Driver for MySQL (Connector/C), is also subject to the
Universal FOSS Exception, version 1.0, a copy of which can be found at
http://oss.oracle.com/licenses/universal-foss-exception.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License, version 2.0, for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */
/**
@file mysys/my_getopt.cc
*/
#include <errno.h>
#include <limits.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <algorithm>
#include <array>
#include <bitset>
#include <type_traits>
#include "m_ctype.h"
#include "m_string.h"
#include "my_compiler.h"
#include "my_dbug.h"
#include "my_default.h"
#include "my_getopt.h"
#include "my_inttypes.h"
#include "my_io.h"
#include "my_loglevel.h"
#include "my_macros.h"
#include "mysql/service_mysql_alloc.h"
#include "mysql_version.h" // MYSQL_PERSIST_CONFIG_NAME
#include "mysys/mysys_priv.h"
#include "mysys_err.h"
#include "typelib.h"
typedef void (*init_func_p)(const struct my_option *option, void *variable,
longlong value);
my_error_reporter my_getopt_error_reporter = &my_message_local;
static bool getopt_compare_strings(const char *, const char *, uint);
static longlong getopt_ll(const char *, bool, const my_option *, int *);
static ulonglong getopt_ull(const char *, bool, const my_option *, int *);
static double getopt_double(const char *, bool, const my_option *, int *);
static void init_variables(const struct my_option *, init_func_p);
static void init_one_value(const struct my_option *, void *, longlong);
static void fini_one_value(const struct my_option *, void *, longlong);
static int setval(const struct my_option *, void *, const char *, bool, bool);
static void setval_source(const struct my_option *, void *);
static char *check_struct_option(char *cur_arg, char *key_name);
static bool get_bool_int_argument(const char *argument, bool *error);
/*
The following three variables belong to same group and the number and
order of their arguments must correspond to each other.
*/
static const char *special_opt_prefix[] = {"skip", "disable", "enable",
"maximum", "loose", nullptr};
static const uint special_opt_prefix_lengths[] = {4, 7, 6, 7, 5, 0};
enum enum_special_opt {
OPT_SKIP,
OPT_DISABLE,
OPT_ENABLE,
OPT_MAXIMUM,
OPT_LOOSE
};
char *disabled_my_option = const_cast<char *>("0");
static char enabled_my_option[] = "1";
static char space_char[] = " ";
/*
This is a flag that can be set in client programs. false means that
my_getopt will not print error messages, but the client should do
it by itself
*/
bool my_getopt_print_errors = true;
/*
This is a flag that can be set in client programs. true means that
my_getopt will skip over options it does not know how to handle.
*/
bool my_getopt_skip_unknown = false;
static my_getopt_value getopt_get_addr;
void my_getopt_register_get_addr(my_getopt_value func_addr) {
getopt_get_addr = func_addr;
}
bool is_key_cache_variable_suffix(std::string_view suffix) {
constexpr static std::array<std::string_view, 4> key_cache_components = {
{"key_buffer_size", "key_cache_block_size", "key_cache_division_limit",
"key_cache_age_threshold"}};
for (auto component : key_cache_components) {
if (suffix.size() == component.size() &&
!native_strncasecmp(suffix.data(), component.data(), suffix.size()))
return true;
}
return false;
}
/**
Wrapper around my_handle_options() for interface compatibility.
@param [in,out] argc Command line options (count)
@param [in,out] argv Command line options (values)
@param [in] longopts Descriptor of all valid options
@param [in] get_one_option Optional callback function to process each option,
can be NULL.
@return Error in case of ambiguous or unknown options,
0 on success.
*/
int handle_options(int *argc, char ***argv, const struct my_option *longopts,
my_get_one_option get_one_option) {
return my_handle_options(argc, argv, longopts, get_one_option, nullptr,
false);
}
union ull_dbl {
ulonglong ull;
double dbl;
};
/**
Returns an ulonglong value containing a raw
representation of the given double value.
*/
ulonglong getopt_double2ulonglong(double v) {
union ull_dbl u;
u.dbl = v;
static_assert(sizeof(ulonglong) >= sizeof(double), "");
return u.ull;
}
/**
Returns the double value which corresponds to
the given raw representation.
*/
double getopt_ulonglong2double(ulonglong v) {
union ull_dbl u;
u.ull = v;
return u.dbl;
}
/**
Handle command line options.
Sort options.
Put options first, until special end of options (--),
or until the end of argv. Parse options, check that the given option
matches with one of the options in struct 'my_option'.
Check that option was given an argument if it requires one
Call the optional 'get_one_option()' function once for each option.
Note that handle_options() can be invoked multiple times to
parse a command line in several steps.
In this case, use the global flag @c my_getopt_skip_unknown to indicate
that options unknown in the current step should be preserved in the
command line for later parsing in subsequent steps.
For 'long' options (--a_long_option), @c my_getopt_skip_unknown is
fully supported. Command line parameters such as:
- "--a_long_option"
- "--a_long_option=value"
- "--a_long_option value"
will be preserved as is when the option is not known.
For 'short' options (-S), support for @c my_getopt_skip_unknown
comes with some limitation, because several short options
can also be specified together in the same command line argument,
as in "-XYZ".
The first use case supported is: all short options are declared.
handle_options() will be able to interpret "-XYZ" as one of:
- an unknown X option
- "-X -Y -Z", three short options with no arguments
- "-X -YZ", where Y is a short option with argument Z
- "-XYZ", where X is a short option with argument YZ
based on the full short options specifications.
The second use case supported is: no short option is declared.
handle_options() will reject "-XYZ" as unknown, to be parsed later.
The use case that is explicitly not supported is to provide
only a partial list of short options to handle_options().
This function can not be expected to extract some option Y
in the middle of the string "-XYZ" in these conditions,
without knowing if X will be declared an option later.
Note that this limitation only impacts parsing of several
short options from the same command line argument,
as in "mysqld -anW5".
When each short option is properly separated out in the command line
argument, for example in "mysqld -a -n -w5", the code would actually
work even with partial options specs given at each stage.
@param [in, out] argc command line options (count)
@param [in, out] argv command line options (values)
@param [in] longopts descriptor of all valid options
@param [in] get_one_option optional callback function to process each option,
can be NULL.
@param [in] command_list NULL-terminated list of strings (commands) which
(if set) is looked up for all non-option strings
found while parsing the command line parameters.
The parsing terminates if a match is found. At
exit, argv [out] would contain all the remaining
unparsed options along with the matched command.
@param [in] ignore_unknown_option When set to true, options are continued to
be read even when unknown options are
encountered.
@param [in] boolean_as_int Parse boolean as integer value.
Mimic the logic of parsing booleans at
runtime: Instead of parsing
@code
bool_val = (str_val == '1' || str_val = 'ON') ?
true :
(str_val == '0' || str_val = 'OFF') ?
false :
false;
@endcode
do:
@code
bool_val == (str_val == 'OFF') ?
false :
((str_val == 'ON') ?
true :
atoi(str_val) != 0)
@endcode
@return error in case of ambiguous or unknown options,
0 on success.
*/
int my_handle_options2(int *argc, char ***argv,
const struct my_option *longopts,
my_get_one_option get_one_option,
const char **command_list, bool ignore_unknown_option,
bool boolean_as_int) {
uint argvpos = 0, length;
bool end_of_options = false, must_be_var, set_maximum_value, option_is_loose;
char **pos, **pos_end, *optend, *opt_str, key_name[FN_REFLEN];
char **arg_sep = nullptr, **persist_arg_sep = nullptr;
const struct my_option *optp;
void *value;
bool is_cmdline_arg = true, is_persist_arg = true;
int opt_found;
/* handle_options() assumes arg0 (program name) always exists */
assert(argc && *argc >= 1);
assert(argv && *argv);
(*argc)--; /* Skip the program name */
(*argv)++; /* --- || ---- */
init_variables(longopts, init_one_value);
/*
Search for args_separator, if found, then the first part of the
arguments are loaded from configs
*/
for (pos = *argv, pos_end = pos + *argc; pos != pos_end; pos++) {
if (my_getopt_is_args_separator(*pos)) {
arg_sep = pos;
is_cmdline_arg = false;
break;
}
}
/* search for persist_args_separator */
if (arg_sep) {
for (pos = arg_sep, pos_end = (*argv + *argc); pos != pos_end; pos++) {
if (my_getopt_is_ro_persist_args_separator(*pos)) {
persist_arg_sep = pos;
is_persist_arg = false;
break;
}
}
}
if (arg_sep) {
/*
All options which are between arg_sep and persist_arg_sep are
command line options, thus update the variables_hash with these
options. If persist_arg_sep is NULL then it means there are no
read only persist options, what follows is only command line options.
*/
pos = arg_sep + 1;
while (*pos && pos != persist_arg_sep) {
update_variable_source((const char *)*pos, nullptr);
++pos;
}
}
if (persist_arg_sep) {
/*
All options which are between after persist_arg_sep are
read from persistent file, thus update the variables_hash with
these options with path set to "$datadir/mysqld-auto.cnf".
*/
pos = persist_arg_sep + 1;
char persist_dir[FN_REFLEN] = {0};
fn_format(persist_dir, MYSQL_PERSIST_CONFIG_NAME, datadir_buffer, ".cnf",
MY_UNPACK_FILENAME | MY_SAFE_PATH | MY_RELATIVE_PATH);
while (pos && *pos) {
update_variable_source((const char *)*pos, persist_dir);
++pos;
}
}
for (pos = *argv, pos_end = pos + *argc; pos != pos_end; pos++) {
char **first = pos;
char *cur_arg = *pos;
opt_found = false;
if (!is_cmdline_arg && (my_getopt_is_args_separator(cur_arg))) {
is_cmdline_arg = true;
/* save the separator too if skip unknown options */
if (my_getopt_skip_unknown)
(*argv)[argvpos++] = cur_arg;
else
(*argc)--;
continue;
}
/* skip persist args separator */
if (!is_persist_arg && my_getopt_is_ro_persist_args_separator(cur_arg)) {
is_persist_arg = true;
if (my_getopt_skip_unknown)
(*argv)[argvpos++] = cur_arg;
else
(*argc)--;
continue;
}
if (cur_arg[0] == '-' && cur_arg[1] && !end_of_options) /* must be opt */
{
char *argument = nullptr;
must_be_var = false;
set_maximum_value = false;
option_is_loose = false;
cur_arg++; /* skip '-' */
if (*cur_arg == '-') /* check for long option, */
{
if (!*++cur_arg) /* skip the double dash */
{
/* '--' means end of options, look no further */
end_of_options = true;
(*argc)--;
continue;
}
opt_str = check_struct_option(cur_arg, key_name);
optend = const_cast<char *>(strcend(opt_str, '='));
length = (uint)(optend - opt_str);
if (*optend == '=')
optend++;
else
optend = nullptr;
/*
* For component system variables key_name is the component name and
* opt_str is the variable_name. For structured system variables
* opt_str will have key_cache_**** and key_name is the variable
* instance name And for all other variable key_name will be 0.
*/
if (*key_name) {
std::string tmp_name(opt_str, 0, length);
if (!is_key_cache_variable_suffix(tmp_name.c_str())) {
opt_str = cur_arg;
if (optend)
length = (uint)((optend - opt_str) - 1);
else
length = strlen(opt_str);
}
}
/*
Find first the right option. Return error in case of an ambiguous,
or unknown option
*/
optp = longopts;
if (!(opt_found = findopt(opt_str, length, &optp))) {
/*
Didn't find any matching option. Let's see if someone called
option with a special option prefix
*/
if (!must_be_var) {
if (optend)
must_be_var = true; /* option is followed by an argument */
for (int i = 0; special_opt_prefix[i]; i++) {
if (!getopt_compare_strings(special_opt_prefix[i], opt_str,
special_opt_prefix_lengths[i]) &&
(opt_str[special_opt_prefix_lengths[i]] == '-' ||
opt_str[special_opt_prefix_lengths[i]] == '_')) {
/*
We were called with a special prefix, we can reuse opt_found
*/
opt_str += special_opt_prefix_lengths[i] + 1;
length -= special_opt_prefix_lengths[i] + 1;
if (i == OPT_LOOSE) option_is_loose = true;
if ((opt_found = findopt(opt_str, length, &optp))) {
switch (i) {
case OPT_SKIP:
case OPT_DISABLE:
/*
double negation is actually enable again,
for example: --skip-option=0 -> option = true
*/
optend = (optend && *optend == '0' && !(*(optend + 1)))
? enabled_my_option
: disabled_my_option;
break;
case OPT_ENABLE:
optend = (optend && *optend == '0' && !(*(optend + 1)))
? disabled_my_option
: enabled_my_option;
break;
case OPT_MAXIMUM:
set_maximum_value = true;
must_be_var = true;
break;
}
break; /* break from the inner loop, main loop continues */
}
i = -1; /* restart the loop */
}
}
}
if (!opt_found) {
if (my_getopt_skip_unknown) {
/* Preserve all the components of this unknown option. */
do {
(*argv)[argvpos++] = *first++;
} while (first <= pos);
continue;
}
if (must_be_var) {
if (my_getopt_print_errors)
my_getopt_error_reporter(
option_is_loose ? WARNING_LEVEL : ERROR_LEVEL,
EE_UNKNOWN_VARIABLE, cur_arg);
if (!option_is_loose) return EXIT_UNKNOWN_VARIABLE;
} else {
if (my_getopt_print_errors)
my_getopt_error_reporter(
option_is_loose ? WARNING_LEVEL : ERROR_LEVEL,
EE_UNKNOWN_OPTION, cur_arg);
if (!(option_is_loose || ignore_unknown_option))
return EXIT_UNKNOWN_OPTION;
}
if (option_is_loose || ignore_unknown_option) {
(*argc)--;
continue;
}
}
}
if ((optp->var_type & GET_TYPE_MASK) == GET_DISABLED) {
if (my_getopt_print_errors)
my_message_local(option_is_loose ? WARNING_LEVEL : ERROR_LEVEL,
EE_USING_DISABLED_OPTION, my_progname, opt_str);
if (option_is_loose) {
(*argc)--;
continue;
}
return EXIT_OPTION_DISABLED;
}
{
int error = 0;
value =
optp->var_type & GET_ASK_ADDR
? (*getopt_get_addr)(key_name, strlen(key_name), optp, &error)
: optp->value;
if (error) return error;
}
if (optp->arg_type == NO_ARG) {
/*
Due to historical reasons GET_BOOL var_types still accepts arguments
despite the NO_ARG arg_type attribute. This can seems a bit
unintuitive and care should be taken when refactoring this code.
*/
if (optend && (optp->var_type & GET_TYPE_MASK) != GET_BOOL) {
if (my_getopt_print_errors)
my_getopt_error_reporter(ERROR_LEVEL, EE_OPTION_WITHOUT_ARGUMENT,
my_progname, optp->name);
return EXIT_NO_ARGUMENT_ALLOWED;
}
if ((optp->var_type & GET_TYPE_MASK) == GET_BOOL) {
/*
Set bool to true if no argument or if the user has used
--enable-'option-name'.
*optend was set to '0' if one used --disable-option
*/
(*argc)--;
if (!optend)
*((bool *)value) = true;
else {
bool ret = false;
bool error = false;
ret = boolean_as_int ? get_bool_int_argument(optend, &error)
: get_bool_argument(optend, &error);
if (error) {
my_getopt_error_reporter(WARNING_LEVEL,
EE_OPTION_IGNORED_DUE_TO_INVALID_VALUE,
my_progname, optp->name, optend);
continue;
} else
*((bool *)value) = ret;
}
if (get_one_option &&
get_one_option(
optp->id, optp,
*((bool *)value) ? enabled_my_option : disabled_my_option))
return EXIT_ARGUMENT_INVALID;
/* set variables source */
setval_source(optp, (void *)optp->arg_source);
continue;
}
argument = optend;
} else if (optp->arg_type == REQUIRED_ARG && !optend) {
/*
Check if there are more arguments after this one,
Note: options loaded from config file that requires value
should always be in the form '--option=value'.
*/
if (!is_cmdline_arg || !*++pos) {
if (my_getopt_print_errors)
my_getopt_error_reporter(ERROR_LEVEL, EE_OPTION_REQUIRES_ARGUMENT,
my_progname, optp->name);
return EXIT_ARGUMENT_REQUIRED;
}
argument = *pos;
(*argc)--;
} else
argument = optend;
if (optp->var_type == GET_PASSWORD && is_cmdline_arg && argument)
print_cmdline_password_warning();
} else /* must be short option */
{
for (optend = cur_arg; *optend; optend++) {
opt_found = false;
for (optp = longopts; optp->name; optp++) {
if (optp->id && optp->id == (int)(uchar)*optend) {
/* Option recognized. Find next what to do with it */
opt_found = true;
if ((optp->var_type & GET_TYPE_MASK) == GET_DISABLED) {
if (my_getopt_print_errors)
my_message_local(ERROR_LEVEL, EE_USING_DISABLED_SHORT_OPTION,
my_progname, optp->id);
return EXIT_OPTION_DISABLED;
}
if ((optp->var_type & GET_TYPE_MASK) == GET_BOOL &&
optp->arg_type == NO_ARG) {
*((bool *)optp->value) = true;
if (get_one_option && get_one_option(optp->id, optp, argument))
return EXIT_UNSPECIFIED_ERROR;
continue;
} else if (optp->arg_type == REQUIRED_ARG ||
optp->arg_type == OPT_ARG) {
if (*(optend + 1)) {
/* The rest of the option is option argument */
argument = optend + 1;
/* This is in effect a jump out of the outer loop */
optend = space_char;
if (optp->var_type == GET_PASSWORD && is_cmdline_arg)
print_cmdline_password_warning();
} else {
if (optp->arg_type == OPT_ARG) {
if (optp->var_type == GET_BOOL)
*((bool *)optp->value) = true;
if (get_one_option &&
get_one_option(optp->id, optp, argument))
return EXIT_UNSPECIFIED_ERROR;
continue;
}
/* Check if there are more arguments after this one */
if (!pos[1]) {
if (my_getopt_print_errors)
my_getopt_error_reporter(
ERROR_LEVEL, EE_SHORT_OPTION_REQUIRES_ARGUMENT,
my_progname, optp->id);
return EXIT_ARGUMENT_REQUIRED;
}
argument = *++pos;
(*argc)--;
/* the other loop will break, because *optend + 1 == 0 */
}
}
int error;
if ((error = setval(optp, optp->value, argument,
set_maximum_value, boolean_as_int)))
return error;
if (get_one_option && get_one_option(optp->id, optp, argument))
return EXIT_UNSPECIFIED_ERROR;
break;
}
}
if (!opt_found) {
if (my_getopt_skip_unknown) {
/*
We are currently parsing a single argv[] argument
of the form "-XYZ".
One or the argument found (say Y) is not an option.
Hack the string "-XYZ" to make a "-YZ" substring in it,
and push that to the output as an unrecognized parameter.
*/
assert(optend > *pos);
assert(optend >= cur_arg);
assert(optend <= *pos + strlen(*pos));
assert(*optend);
optend--;
optend[0] = '-'; /* replace 'X' or '-' by '-' */
(*argv)[argvpos++] = optend;
/*
Do not continue to parse at the current "-XYZ" argument,
skip to the next argv[] argument instead.
*/
optend = space_char;
} else {
if (my_getopt_print_errors)
my_getopt_error_reporter(ERROR_LEVEL, EE_UNKNOWN_SHORT_OPTION,
my_progname, *optend);
return EXIT_UNKNOWN_OPTION;
}
}
}
if (opt_found)
(*argc)--; /* option handled (short), decrease argument count */
continue;
}
int error;
if ((error = setval(optp, value, argument, set_maximum_value,
boolean_as_int)))
return error;
if (get_one_option && get_one_option(optp->id, optp, argument))
return EXIT_UNSPECIFIED_ERROR;
(*argc)--; /* option handled (long), decrease argument count */
} else /* non-option found */
{
if (command_list) {
while (*command_list) {
if (!strcmp(*command_list, cur_arg)) {
/* Match found. */
(*argv)[argvpos++] = cur_arg;
/* Copy rest of the un-parsed elements & return. */
while ((++pos) != pos_end) (*argv)[argvpos++] = *pos;
goto done;
}
command_list++;
}
}
(*argv)[argvpos++] = cur_arg;
}
}
done:
/*
Destroy the first, already handled option, so that programs that look
for arguments in 'argv', without checking 'argc', know when to stop.
Items in argv, before the destroyed one, are all non-option -arguments
to the program, yet to be (possibly) handled.
*/
(*argv)[argvpos] = nullptr;
return 0;
}
int my_handle_options(int *argc, char ***argv, const struct my_option *longopts,
my_get_one_option get_one_option,
const char **command_list, bool ignore_unknown_option) {
return my_handle_options2(argc, argv, longopts, get_one_option, command_list,
ignore_unknown_option, false);
}
/**
* This function should be called to print a warning message
* if password string is specified on the command line.
*/
void print_cmdline_password_warning() {
static bool password_warning_announced = false;
if (!password_warning_announced) {
my_message_local(WARNING_LEVEL, EE_USING_PASSWORD_ON_CLI_IS_INSECURE);
password_warning_announced = true;
}
}
/**
@brief Check for struct options
@param[in] cur_arg Current argument under processing from argv
@param[in] key_name variable where to store the possible key name
@details
In case option is a struct option, returns a pointer to the current
argument at the position where the struct option (key_name) ends, the
next character after the dot. In case argument is not a struct option,
returns a pointer to the argument.
key_name will hold the name of the key, or 0 if not found.
@return char*
If struct option Pointer to next character after dot.
If no struct option Pointer to the argument
*/
static char *check_struct_option(char *cur_arg, char *key_name) {
char *dot_pos = const_cast<char *>(
strcend(cur_arg + 1, '.')); /* Skip the first character */
const char *equal_pos = strcend(cur_arg, '=');
const char *space_pos = strcend(cur_arg, ' ');
/*
If the first dot is after an equal sign, then it is part
of a variable value and the option is not a struct option.
Also, if the last character in the string before the ending
NULL, or the character right before equal sign is the first
dot found, the option is not a struct option.
*/
if ((equal_pos > dot_pos) && (space_pos > dot_pos)) {
size_t len = std::min(size_t(dot_pos - cur_arg), size_t(FN_REFLEN - 1));
strmake(key_name, cur_arg, len);
return ++dot_pos;
} else {
key_name[0] = 0;
return cur_arg;
}
}
/**
Parse a boolean command line argument
"ON", "TRUE" and "1" will return true,
other values will return false.
@param argument The value argument
@param [out] error Error indicator
@return boolean value
*/
bool get_bool_argument(const char *argument, bool *error) {
if (!my_strcasecmp(&my_charset_latin1, argument, "true") ||
!my_strcasecmp(&my_charset_latin1, argument, "on") ||
!my_strcasecmp(&my_charset_latin1, argument, "1"))
return true;
if (!my_strcasecmp(&my_charset_latin1, argument, "false") ||
!my_strcasecmp(&my_charset_latin1, argument, "off") ||
!my_strcasecmp(&my_charset_latin1, argument, "0"))
return false;
*error = true;
return false;
}
/**
Parse a boolean command line argument as the SQL interpreter does
"ON" and "TRUE" will return true,
"OFF" and FALSE" will return false;
Non-zero numeric values will return true, zero will return false.
@param argument The value argument
@param [out] error Error indicator
@return boolean value
*/
static bool get_bool_int_argument(const char *argument, bool *error) {
if (!my_strcasecmp(&my_charset_latin1, argument, "true") ||
!my_strcasecmp(&my_charset_latin1, argument, "on"))
return true;
if (!my_strcasecmp(&my_charset_latin1, argument, "false") ||
!my_strcasecmp(&my_charset_latin1, argument, "off"))
return false;
if (!strchr("0123456789+-", argument[0])) {
*error = true;
return false;
}
return atoi(argument) != 0;
}
/**
Will set the source and file name from where this options is set in
my_option struct.
*/
static void setval_source(const struct my_option *opts, void *value) {
set_variable_source(opts->name, value);
}
/*
function: setval
Arguments: opts, argument
Will set the option value to given value
*/
static int setval(const struct my_option *opts, void *value,
const char *argument, bool set_maximum_value,
bool boolean_as_int) {
int err = 0, res = 0;
ulong var_type = opts->var_type & GET_TYPE_MASK;
if (!argument) argument = enabled_my_option;
/*
Thus check applies only to options that have a defined value
storage pointer.
We do it for numeric types only, as empty value is a valid
option for strings (the only way to reset back to default value).
Note: it does not relate to OPT_ARG/REQUIRED_ARG/NO_ARG, since
--param="" is not generally the same as --param.
TODO: Add an option definition flag to signify whether empty value
(i.e. --param="") is an acceptable value or an error and extend
the check to all options.
*/
if (!*argument &&
(var_type == GET_INT || var_type == GET_UINT || var_type == GET_LONG ||
var_type == GET_ULONG || var_type == GET_LL || var_type == GET_ULL ||
var_type == GET_DOUBLE || var_type == GET_ENUM)) {
my_getopt_error_reporter(ERROR_LEVEL, EE_OPTION_WITH_EMPTY_VALUE,
my_progname, opts->name);
return EXIT_ARGUMENT_REQUIRED;
}
if (value) {
if (set_maximum_value && !(value = opts->u_max_value)) {
my_getopt_error_reporter(ERROR_LEVEL,
EE_FAILED_TO_ASSIGN_MAX_VALUE_TO_OPTION,
my_progname, opts->name);
return EXIT_NO_PTR_TO_VARIABLE;
}
bool error = false;
switch (var_type) {
case GET_BOOL: /* If argument differs from 0, enable option, else disable
*/
*((bool *)value) = boolean_as_int
? get_bool_int_argument(argument, &error)
: get_bool_argument(argument, &error);
if (error)
my_getopt_error_reporter(WARNING_LEVEL,
EE_INCORRECT_BOOLEAN_VALUE_FOR_OPTION,
opts->name, argument);
break;
case GET_INT:
*((int *)value) =
(int)getopt_ll(argument, set_maximum_value, opts, &err);
break;
case GET_UINT:
*((uint *)value) =
(uint)getopt_ull(argument, set_maximum_value, opts, &err);
break;
case GET_LONG:
*((long *)value) =
(long)getopt_ll(argument, set_maximum_value, opts, &err);
break;
case GET_ULONG:
*((long *)value) =
(long)getopt_ull(argument, set_maximum_value, opts, &err);
break;
case GET_LL:
*((longlong *)value) =
getopt_ll(argument, set_maximum_value, opts, &err);
break;
case GET_ULL:
*((ulonglong *)value) =
getopt_ull(argument, set_maximum_value, opts, &err);
break;
case GET_DOUBLE:
*((double *)value) =
getopt_double(argument, set_maximum_value, opts, &err);
break;
case GET_STR:
case GET_PASSWORD:
if (argument == enabled_my_option)
break; /* string options don't use this default of "1" */
*static_cast<const char **>(value) = argument;
break;
case GET_STR_ALLOC:
if (argument == enabled_my_option)
break; /* string options don't use this default of "1" */
my_free(*((char **)value));
if (!(*((char **)value) =
my_strdup(key_memory_defaults, argument, MYF(MY_WME)))) {
res = EXIT_OUT_OF_MEMORY;
goto ret;
};
break;
case GET_ENUM: {
int type = find_type(argument, opts->typelib, FIND_TYPE_BASIC);
if (type == 0) {
/*
Accept an integer representation of the enumerated item.
*/
char *endptr;
ulong arg = strtoul(argument, &endptr, 10);
if (*endptr || arg >= opts->typelib->count) {
res = EXIT_ARGUMENT_INVALID;
goto ret;
}
*(ulong *)value = arg;
} else if (type < 0) {
res = EXIT_AMBIGUOUS_OPTION;
goto ret;
} else
*(ulong *)value = type - 1;
} break;
case GET_SET:
*(static_cast<ulonglong *>(value)) =
find_typeset(argument, opts->typelib, &err);
if (err) {
/* Accept an integer representation of the set */
char *endptr;
ulonglong arg = (ulonglong)strtol(argument, &endptr, 10);
if (*endptr || (arg >> 1) >= (1ULL << (opts->typelib->count - 1))) {
res = EXIT_ARGUMENT_INVALID;
goto ret;
};
*static_cast<ulonglong *>(value) = arg;
err = 0;
}
break;
case GET_FLAGSET: {
const char *flag_error;
uint error_len;
*(static_cast<ulonglong *>(value)) = find_set_from_flags(
opts->typelib, opts->typelib->count,
*static_cast<ulonglong *>(value), opts->def_value, argument,
strlen(argument), &flag_error, &error_len);
if (flag_error) {
res = EXIT_ARGUMENT_INVALID;
goto ret;
};
} break;
case GET_NO_ARG: /* get_one_option has taken care of the value already */
default: /* dummy default to avoid compiler warnings */
break;
}
if (err) {
res = EXIT_UNKNOWN_SUFFIX;
goto ret;
};
}
setval_source(opts, (void *)opts->arg_source);
return 0;
ret:
my_getopt_error_reporter(ERROR_LEVEL, EE_FAILED_TO_SET_OPTION_VALUE,
my_progname, argument, opts->name);
return res;
}
/**
Find option
IMPLEMENTATION
Go through all options in the my_option struct. Return true
if an option is found. sets opt_res to the option found, if any.
@param optpat name of option to find (with - or _)
@param length Length of optpat
@param[in,out] opt_res Options
@retval 0 No matching options
@retval 1 Found an option
*/
int findopt(const char *optpat, uint length, const struct my_option **opt_res) {
for (const struct my_option *opt = *opt_res; opt->name; opt++)
if (!getopt_compare_strings(opt->name, optpat, length) &&
!opt->name[length]) {
(*opt_res) = opt;
return 1;
}
return 0;
}
/*