Repository navigation
Expand file tree
/
Copy pathcmdlineparser.cpp
More file actions
1891 lines (1777 loc) · 80.2 KB
/
Copy pathcmdlineparser.cpp
File metadata and controls
1891 lines (1777 loc) · 80.2 KB
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
/*
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2026 Cppcheck team.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* 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 for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "cmdlineparser.h"
#include "addoninfo.h"
#include "check.h"
#include "checks.h"
#include "checkers.h"
#include "color.h"
#include "config.h"
#include "cppcheck.h"
#include "errorlogger.h"
#include "errortypes.h"
#include "filelister.h"
#include "filesettings.h"
#include "importproject.h"
#include "library.h"
#include "path.h"
#include "pathmatch.h"
#include "platform.h"
#include "settings.h"
#include "standards.h"
#include "suppressions.h"
#include "utils.h"
#include "frontend.h"
#include <rfl/Rename.hpp>
#include <rfl/cli.hpp>
#include <algorithm>
#include <cassert>
#include <cstdio>
#include <cstdlib> // EXIT_FAILURE
#include <cstring>
#include <fstream>
#include <iostream>
#include <iterator>
#include <list>
#include <optional>
#include <set>
#include <sstream>
#include <string>
#include <string_view>
#include <unordered_set>
#include <utility>
#include <vector>
#ifdef HAVE_RULES
#include "regex.h"
#include "rule.h"
// xml is used for rules
#include "xml.h"
#include <memory>
#endif
static bool addFilesToList(const std::string& fileList, std::vector<std::string>& pathNames)
{
std::istream *files;
std::ifstream infile;
if (fileList == "-") { // read from stdin
files = &std::cin;
} else {
infile.open(fileList);
if (!infile.is_open())
return false;
files = &infile;
}
std::string fileName;
while (std::getline(*files, fileName)) { // next line
if (!fileName.empty()) {
pathNames.emplace_back(std::move(fileName));
}
}
return true;
}
static bool addIncludePathsToList(const std::string& fileList, std::list<std::string>& pathNames)
{
std::ifstream files(fileList);
if (files) {
std::string pathName;
while (std::getline(files, pathName)) { // next line
if (!pathName.empty()) {
pathName = Path::removeQuotationMarks(std::move(pathName));
pathName = Path::fromNativeSeparators(std::move(pathName));
// If path doesn't end with / or \, add it
if (!endsWith(pathName, '/'))
pathName += '/';
pathNames.emplace_back(std::move(pathName));
}
}
return true;
}
return false;
}
static bool addPathsToSet(const std::string& fileName, std::set<std::string>& set)
{
std::list<std::string> templist;
if (!addIncludePathsToList(fileName, templist))
return false;
set.insert(templist.cbegin(), templist.cend());
return true;
}
namespace {
using rfl::cli::Arg;
using rfl::cli::Flag;
using rfl::cli::OptGroup;
using namespace rfl::cli::attr;
// Presets.hpp (GnuStyle/GnuLastWins/PosixStrict) all bundle SeparateOptionValues,
// which would override RequireEquals; cppcheck rejects `--opt val` without `=`.
using CppcheckCliProcessors = rfl::Processors<
rfl::DefaultIfMissing,
rfl::NoExtraFields,
rfl::cli::PureFlags,
rfl::cli::LastValueWins,
rfl::cli::RequireEquals,
rfl::cli::ListDelimiter<"">>;
struct PremiumArgs {
Arg<std::vector<std::string>, ValueName<"option">,
Desc<"Cppcheck Premium option (autosar, cert-c, cert-c++, misra-c-2012/2023/2025, misra-c++-2008/2023, bughunting, metrics, safety, safety-off; append :all for coding standards).">>
premium{};
Arg<std::optional<std::string>, ValueName<"BITS">,
Desc<"Integer precision to use in Cert C INT35-C analysis.">>
premium_cert_c_int_precision{};
Arg<std::optional<std::string>, ValueName<"path">,
Desc<"Provide Cppcheck Premium license file path.">>
premium_license_file{};
};
struct CppcheckArgs {
Arg<std::vector<std::string>, ValueName<"addon">,
Desc<"Execute addon, e.g. --addon=misra. If options must be provided a json configuration is needed.">>
addon{};
Arg<std::optional<std::string>, ValueName<"python interpreter">,
Desc<"Python interpreter for addons (default tries \"python3\", then \"python\").">>
addon_python{};
Flag<Hidden, Negatable<>> analyze_all_vs_configs{false};
Flag<Short<"CC">,
Desc<"Do not remove comments during preprocessing (requires -E).">>
keep_comments{false};
Arg<std::optional<std::string>, ValueName<"dir">,
Desc<"Cppcheck work folder for whole program analysis and cached results.">>
cppcheck_build_dir{};
Flag<Desc<"Check cppcheck configuration. Normal code analysis is disabled.">>
check_config{false};
Flag<Hidden, Negatable<>> check_headers{false};
Arg<std::optional<std::string>, ValueName<"level">, DefaultHint<"normal">,
Desc<"Configure valueflow analysis depth: reduced, normal, or exhaustive.">>
check_level{};
Flag<Desc<"Show information messages when library files have incomplete info.">>
check_library{false};
Flag<Hidden, Negatable<>> check_unused_templates{false};
Arg<std::optional<std::string>, Hidden> check_version{};
Arg<std::optional<std::string>, ValueName<"file">,
Desc<"Write a report of all active checkers to the given file.">>
checkers_report{};
Arg<std::optional<std::string>, Hidden> checks_max_time{};
Arg<std::optional<std::string>, Implicit<"clang">, ValueName<"path">,
Deprecated<"Use Clang parser instead of the builtin Cppcheck parser (will be removed in Cppcheck 2.27).">>
clang{};
Arg<std::optional<std::string>, Implicit<"clang-tidy">, Hidden> clang_tidy{};
Arg<std::vector<std::string>, ValueName<"dir">,
Desc<"Path prefix to exclude from configuration checking in headers.">>
config_exclude{};
Arg<std::vector<std::string>, ValueName<"file">,
Desc<"A file containing a list of config-excludes.">>
config_excludes_file{};
Flag<Hidden, Negatable<>> cpp_header_probe{false};
Flag<Hidden, Alias<"debug-normal">> debug{false};
Flag<Hidden> debug_analyzerinfo{false};
Flag<Hidden> debug_ast{false};
Flag<Hidden> debug_clang_output{false};
Flag<Hidden> debug_ignore{false};
Flag<Hidden> debug_ipc{false};
Arg<std::optional<std::string>, Implicit<"all">, Hidden> debug_lookup{};
Flag<Hidden> debug_simplified{false};
Flag<Hidden> debug_symdb{false};
Flag<Hidden> debug_template{false};
Flag<Hidden> debug_valueflow{false};
Flag<Hidden> debug_warnings{false};
Arg<std::vector<std::string>, ValueName<"severity">,
Desc<"Disable checks with the given severity (see --enable).">>
disable{};
Flag<Hidden> doc{false};
Flag<Desc<"Dump xml data (.dump) for each translation unit.">>
dump{false};
Arg<std::vector<std::string>, Short<"D">, ValueName<"ID">,
Desc<"Define preprocessor symbol (e.g. -DDEBUG=1 -D__cplusplus).">>
define{};
Flag<Short<"E">,
Desc<"Print preprocessor output on stdout and don't do any further processing.">>
preprocess_only{false};
Flag<Hidden> emit_duplicates{false};
Arg<std::vector<std::string>, ValueName<"severity">,
Desc<"Enable additional checks (comma-separated: warning, performance, portability, information, style, unusedFunction, missingInclude, all).">>
enable{};
Arg<std::optional<std::string>, ValueName<"n">, DefaultHint<"0">,
Desc<"Exit code returned if errors are found.">>
error_exitcode{};
Flag<Desc<"Print a list of all error messages in XML format.">>
errorlist{false};
Arg<std::optional<std::string>, Implicit<"stdout">, Hidden> exception_handling{};
Arg<std::optional<std::string>, Hidden> executor{};
Arg<std::vector<std::string>, ValueName<"spec">,
Desc<"Error ID which should not result in a non-zero exitcode.">>
exitcode_suppress{};
Arg<std::vector<std::string>, ValueName<"file">,
Desc<"File of error IDs that should not cause a non-zero exitcode.">>
exitcode_suppressions{};
Arg<std::vector<std::string>, ValueName<"str">,
Desc<"Analyze only files matching filter ('-' reads from stdin, '+' uses CLI files as filters).">>
file_filter{};
Arg<std::vector<std::string>, ValueName<"file">,
Desc<"Text file listing files to check, one per line ('-' reads from stdin).">>
file_list{};
Flag<Hidden> filesdir{false};
Flag<Short<"f">,
Desc<"Force checking of all configurations in files (overrides --max-configs).">>
force{false};
Flag<Desc<"Treat char type as signed.">> fsigned_char{false};
Flag<Desc<"Treat char type as unsigned.">> funsigned_char{false};
Flag<Short<"h">, Desc<"Print this help.">> help{false};
Arg<std::vector<std::string>, Short<"I">, ValueName<"dir">,
Desc<"Directory to search for include files.">>
include_dir{};
Arg<std::vector<std::string>, ValueName<"file">,
Desc<"Text file listing include directories, one per line.">>
includes_file{};
Arg<std::vector<std::string>, ValueName<"file">,
Desc<"Force inclusion of a file before the checked file.">>
include{};
Arg<std::vector<std::string>, Short<"i">, ValueName<"str">,
Desc<"Ignore files or directories matching glob pattern.">>
ignore{};
Flag<Desc<"Allow reporting inconclusive analysis results.">>
inconclusive{false};
Flag<Desc<"Enable inline suppressions (e.g. '// cppcheck-suppress warningId').">>
inline_suppr{false};
Arg<std::optional<std::string>, Short<"j">, ValueName<"jobs">,
Desc<"Start <jobs> threads to do the checking simultaneously.">>
jobs{};
Arg<std::optional<std::string>, Short<"l">, ValueName<"load">,
Desc<"Do not start new threads if load average is at least <load>.">>
load_average{};
Arg<std::optional<std::string>, Short<"x">, ValueName<"language">,
Desc<"Force checking all files as the given language (c or c++).">>
language{};
Arg<std::vector<std::string>, ValueName<"cfg">,
Desc<"Load library configuration file <cfg> (std.cfg is loaded automatically).">>
library{};
Arg<std::optional<std::string>, ValueName<"limit">, DefaultHint<"12">,
Desc<"Maximum number of #ifdef configurations to check in a file (overrides --force).">>
max_configs{};
Arg<std::optional<std::string>, ValueName<"N">, DefaultHint<"2">,
Desc<"Max depth in whole program analysis.">>
max_ctu_depth{};
Arg<std::optional<std::string>, Hidden> max_template_recursion{};
Flag<Hidden> no_cppcheck_build_dir{false};
Arg<std::optional<std::string>, ValueName<"file">,
Desc<"Write results to file rather than standard error.">>
output_file{};
Arg<std::optional<std::string>, ValueName<"format">,
Desc<"Output format: text, sarif, xml (deprecated), xmlv2, or xmlv3.">>
output_format{};
Arg<std::optional<std::string>, Hidden> performance_valueflow_max_time{};
Arg<std::optional<std::string>, Hidden> performance_valueflow_max_if_count{};
Arg<std::optional<std::string>, Hidden> performance_valueflow_max_iterations{};
Arg<std::optional<std::string>, ValueName<"type|file">,
Desc<"Platform-specific types and sizes (unix32, unix64, win32A, win32W, win64, avr8, elbrus-e1cp, pic8, pic8-enhanced, pic16, mips32, native, unspecified, or XML file).">>
platform{};
Arg<std::optional<std::string>, ValueName<"path">,
Desc<"Generate Clang-plist output files in folder.">>
plist_output{};
OptGroup<"Premium", PremiumArgs> premium_opts{};
Arg<std::vector<std::string>, ValueName<"file">,
Desc<"Run Cppcheck on project (*.sln, *.slnx, *.vcxproj, compile_commands.json, *.bpr).">>
project{};
Arg<std::optional<std::string>, ValueName<"config">,
Desc<"Limit Visual Studio project configuration (e.g. 'Release|Win32').">>
project_configuration{};
Flag<Short<"q">,
Desc<"Do not show progress reports (not mutually exclusive with --verbose).">>
quiet{false};
Arg<std::vector<std::string>, Short<"rp">, Implicit<"">, ValueName<"paths">,
Desc<"Use relative paths in output (separate multiple base paths by ';').">>
relative_paths{};
Arg<std::optional<std::string>, Implicit<"10">,
Desc<"Report progress messages while checking a file (single job only).">>
report_progress{};
Arg<std::optional<std::string>, ValueName<"type">,
Desc<"Add guideline/classification fields: normal, autosar, cert-c-2016, cert-cpp-2016, misra-c-2012, misra-c-2023, misra-c-2025, misra-cpp-2008, misra-cpp-2023.">>
report_type{};
Arg<std::vector<std::string>, ValueName<"rule">,
Desc<"Match regular expression.">>
rule{};
Arg<std::vector<std::string>, ValueName<"file">,
Desc<"Use given rule XML file.">>
rule_file{};
Flag<Negatable<>, Desc<"Enable safety-certified checking mode.">>
safety{false};
Arg<std::optional<std::string>, ValueName<"mode">, DefaultHint<"none">,
Desc<"Show timing information: none, file, file-total, summary, top5_file, top5_summary.">>
showtime{};
Arg<std::vector<std::string>, ValueName<"id">,
Desc<"Set language standard: c89, c99, c11, c++03, c++11, c++14, c++17, c++20.">>
std{};
Arg<std::vector<std::string>, ValueName<"spec">,
Desc<"Suppress warnings matching [error id]:[filename]:[line].">>
suppress{};
Arg<std::vector<std::string>, ValueName<"file">,
Desc<"Suppress warnings listed in the given file.">>
suppressions_list{};
Arg<std::vector<std::string>, ValueName<"file">,
Desc<"Suppress warnings listed in an XML file.">>
suppress_xml{};
rfl::Rename<"template",
Arg<std::optional<std::string>, ValueName<"'<text>'">,
Desc<"Format error messages (pre-defined: gcc, cppcheck1, vs, edit, simple).">>>
template_format{};
Arg<std::optional<std::string>, ValueName<"'<text>'">,
Desc<"Format error message location.">>
template_location{};
Arg<std::optional<std::string>, Hidden> template_max_time{};
Arg<std::optional<std::string>, Hidden> typedef_max_time{};
Arg<std::vector<std::string>, Short<"U">, ValueName<"ID">,
Desc<"Undefine preprocessor symbol (e.g. -UDEBUG).">>
undefine{};
Arg<std::optional<std::string>, Hidden> valueflow_max_iterations{};
Flag<Short<"v">,
Desc<"Output more detailed error information (not mutually exclusive with --quiet).">>
verbose{false};
Flag<Desc<"Print out version number.">>
version{false};
Flag<Desc<"Write results in xml format to error stream (stderr).">>
xml{false};
Arg<std::optional<std::string>, Hidden> xml_version{};
Arg<std::vector<std::string>, Positional> files{};
};
template<typename T>
bool parseNumberValue(CmdLineLogger& logger, const std::string& optPrefix, const std::string& val, T& num, bool mustBePositive = false)
{
T tmp;
std::string err;
if (!strToInt(val, tmp, &err)) {
logger.printError("argument to '" + optPrefix + "' is not valid - " + err + ".");
return false;
}
if (mustBePositive && tmp < 0) {
logger.printError("argument to '" + optPrefix + "' needs to be a positive integer.");
return false;
}
num = tmp;
return true;
}
std::string findRawArg(int argc, const char* const argv[], const std::string_view prefix)
{
for (int i = 1; i < argc; ++i) {
const std::string_view a(argv[i]);
if (a == prefix || (a.size() > prefix.size() && a.starts_with(prefix) && a[prefix.size()] == '='))
return std::string(a);
}
return std::string(prefix);
}
void reportCliParseError(CmdLineLogger& logger, const std::string& err, int argc, const char* const argv[], bool isPremium)
{
constexpr std::string_view missingPrefix = "Missing value for option '";
constexpr std::string_view unknownLongPrefix = "Unknown option '";
constexpr std::string_view unknownShortPrefix = "Unknown short argument: ";
if (err.starts_with(missingPrefix)) {
const std::size_t endQuote = err.find('\'', missingPrefix.size());
if (endQuote != std::string::npos) {
const std::string opt = err.substr(missingPrefix.size(), endQuote - missingPrefix.size());
if (opt == "-x") {
logger.printError("no language given to '-x' option.");
return;
}
if (opt.size() == 2 && opt[0] == '-') {
logger.printError("argument to '" + opt + "' is missing.");
return;
}
logger.printError("unrecognized command line option: \"" + findRawArg(argc, argv, opt) + "\".");
return;
}
}
if (err.starts_with(unknownLongPrefix)) {
const std::size_t endQuote = err.find('\'', unknownLongPrefix.size());
if (endQuote != std::string::npos) {
const std::string opt = err.substr(unknownLongPrefix.size(), endQuote - unknownLongPrefix.size());
if (isPremium && opt.starts_with("--premium-")) {
logger.printError("invalid --premium option '" + opt.substr(10) + "'.");
return;
}
logger.printError("unrecognized command line option: \"" + findRawArg(argc, argv, opt) + "\".");
return;
}
}
if (err.starts_with(unknownShortPrefix)) {
const std::size_t inPos = err.find(" (in '");
if (inPos != std::string::npos) {
const std::size_t start = inPos + 6;
const std::size_t endQuote = err.find('\'', start);
if (endQuote != std::string::npos) {
logger.printError("unrecognized command line option: \"" + err.substr(start, endQuote - start) + "\".");
return;
}
}
const std::size_t dotPos = err.find('.', unknownShortPrefix.size());
const std::string opt = err.substr(unknownShortPrefix.size(),
dotPos == std::string::npos ? std::string::npos : dotPos - unknownShortPrefix.size());
logger.printError("unrecognized command line option: \"" + findRawArg(argc, argv, opt) + "\".");
return;
}
logger.printError(err);
}
class XMLErrorMessagesLogger : public ErrorLogger
{
void reportOut(const std::string & outmsg, Color /*c*/ = Color::Reset) override
{
std::cout << outmsg << std::endl;
}
void reportErr(const ErrorMessage &msg) override
{
reportOut(msg.toXML());
}
void reportMetric(const std::string &metric) override
{
/* Not used here */
(void) metric;
}
void reportProgress(const std::string & /*filename*/, const char /*stage*/[], const std::size_t /*value*/) override
{}
};
}
CmdLineParser::CmdLineParser(CmdLineLogger &logger, Settings &settings, Suppressions &suppressions)
: mLogger(logger)
, mSettings(settings)
, mSuppressions(suppressions)
{}
bool CmdLineParser::fillSettingsFromArgs(int argc, const char* const argv[])
{
const Result result = parseFromArgs(argc, argv);
switch (result) {
case Result::Success:
break;
case Result::Exit:
Settings::terminate();
return true;
case Result::Fail:
return false;
}
// Libraries must be loaded before FileLister is executed to ensure markup files will be
// listed properly.
if (!loadLibraries(mSettings))
return false;
if (!loadAddons(mSettings))
return false;
// Check that all include paths exist
{
for (auto iter = mSettings.includePaths.cbegin();
iter != mSettings.includePaths.cend();
) {
const std::string path(Path::toNativeSeparators(*iter));
if (Path::isDirectory(path))
++iter;
else {
// TODO: this bypasses the template format and other settings
// If the include path is not found, warn user and remove the non-existing path from the list.
if (mSettings.severity.isEnabled(Severity::information))
std::cout << "(information) Couldn't find path given by -I '" << path << '\'' << std::endl;
iter = mSettings.includePaths.erase(iter);
}
}
}
// Output a warning for the user if he tries to exclude headers
const std::vector<std::string>& ignored = mIgnoredPaths;
const bool warn = std::any_of(ignored.cbegin(), ignored.cend(), [](const std::string& i) {
return Path::isHeader(i);
});
if (warn) {
mLogger.printMessage("filename exclusion does not apply to header (.h and .hpp) files.");
mLogger.printMessage("Please use --suppress for ignoring results from the header files.");
}
const std::vector<std::string>& pathnamesRef = mPathNames;
const std::list<FileSettings>& fileSettingsRef = mFileSettings;
// the inputs can only be used exclusively - CmdLineParser should already handle this
assert(!(!pathnamesRef.empty() && !fileSettingsRef.empty()));
if (!fileSettingsRef.empty()) {
std::list<FileSettings> fileSettings;
if (!mSettings.fileFilters.empty()) {
// filter only for the selected filenames from all project files
PathMatch filtermatcher(mSettings.fileFilters, Path::getCurrentPath());
std::copy_if(fileSettingsRef.cbegin(), fileSettingsRef.cend(), std::back_inserter(fileSettings), [&](const FileSettings &fs) {
return filtermatcher.match(fs.filename());
});
if (fileSettings.empty()) {
for (const std::string& f: mSettings.fileFilters)
mLogger.printError("could not find any files matching the filter:" + f);
return false;
}
}
else {
fileSettings = fileSettingsRef;
}
// TODO: de-duplicate
mFileSettings.clear();
frontend::applyLang(fileSettings, mSettings, mEnforcedLang);
// sort the markup last
std::copy_if(fileSettings.cbegin(), fileSettings.cend(), std::back_inserter(mFileSettings), [&](const FileSettings &fs) {
return !mSettings.library.markupFile(fs.filename()) || !mSettings.library.processMarkupAfterCode(fs.filename());
});
std::copy_if(fileSettings.cbegin(), fileSettings.cend(), std::back_inserter(mFileSettings), [&](const FileSettings &fs) {
return mSettings.library.markupFile(fs.filename()) && mSettings.library.processMarkupAfterCode(fs.filename());
});
if (mFileSettings.empty()) {
mLogger.printError("could not find or open any of the paths given.");
return false;
}
}
if (!pathnamesRef.empty()) {
std::list<FileWithDetails> filesResolved;
// Execute recursiveAddFiles() to each given file parameter
// TODO: verbose log which files were ignored?
const PathMatch matcher(ignored, Path::getCurrentPath());
for (const std::string &pathname : pathnamesRef) {
const std::string err = FileLister::recursiveAddFiles(filesResolved, Path::toNativeSeparators(pathname), mSettings.library.markupExtensions(), matcher, mSettings.debugignore);
if (!err.empty()) {
// TODO: bail out?
mLogger.printMessage(err);
}
}
if (filesResolved.empty()) {
mLogger.printError("could not find or open any of the paths given.");
// TODO: PathMatch should provide the information if files were ignored
if (!ignored.empty())
mLogger.printMessage("Maybe all paths were ignored?");
return false;
}
std::list<FileWithDetails> files;
if (!mSettings.fileFilters.empty()) {
files = filterFiles(mSettings.fileFilters, filesResolved);
if (files.empty()) {
for (const std::string& f: mSettings.fileFilters)
mLogger.printError("could not find any files matching the filter:" + f);
return false;
}
}
else {
files = std::move(filesResolved);
}
// de-duplicate files
{
auto it = files.begin();
while (it != files.end()) {
const std::string& absname = it->abspath();
// TODO: log if duplicated files were dropped
files.erase(std::remove_if(std::next(it), files.end(), [&](const FileWithDetails& entry) {
return entry.abspath() == absname;
}), files.end());
++it;
}
}
frontend::applyLang(files, mSettings, mEnforcedLang);
// sort the markup last
std::copy_if(files.cbegin(), files.cend(), std::inserter(mFiles, mFiles.end()), [&](const FileWithDetails& entry) {
return !mSettings.library.markupFile(entry.path()) || !mSettings.library.processMarkupAfterCode(entry.path());
});
std::copy_if(files.cbegin(), files.cend(), std::inserter(mFiles, mFiles.end()), [&](const FileWithDetails& entry) {
return mSettings.library.markupFile(entry.path()) && mSettings.library.processMarkupAfterCode(entry.path());
});
if (mFiles.empty()) {
mLogger.printError("could not find or open any of the paths given.");
return false;
}
}
return true;
}
// TODO: normalize/simplify/native all path parameters
// TODO: error out on all missing given files/paths
CmdLineParser::Result CmdLineParser::parseFromArgs(int argc, const char* const argv[])
{
mSettings.exename = Path::getCurrentExecutablePath(argv[0]);
bool xmlOptionProvided = false;
bool outputFormatOptionProvided = false;
// default to --check-level=normal from CLI for now
mSettings.setCheckLevel(Settings::CheckLevel::normal);
// read --debug-lookup early so the option is available for the cppcheck.cfg loading
for (int i = 1; i < argc; i++) {
if (std::strcmp(argv[i], "--debug-lookup") == 0)
mSettings.debuglookup = true;
else if (std::strncmp(argv[i], "--debug-lookup=", 15) == 0) {
const std::string lookup = argv[i] + 15;
if (lookup == "all")
mSettings.debuglookup = true;
else if (lookup == "addon")
mSettings.debuglookupAddon = true;
else if (lookup == "config")
mSettings.debuglookupConfig = true;
else if (lookup == "library")
mSettings.debuglookupLibrary = true;
else if (lookup == "platform")
mSettings.debuglookupPlatform = true;
else {
mLogger.printError("unknown lookup '" + lookup + "'");
return Result::Fail;
}
}
}
if (!loadCppcheckCfg())
return Result::Fail;
if (argc <= 1) {
printHelp();
return Result::Exit;
}
// check for exclusive options (take precedence over invalid other options)
for (int i = 1; i < argc; i++) {
if (std::strcmp(argv[i], "--doc") == 0) {
std::ostringstream doc;
for (const Check * const c : CheckInstances::get()) {
const std::string& name(c->name());
const std::string info(c->classInfo());
if (!name.empty() && !info.empty())
doc << "## " << name << " ##\n"
<< info << "\n";
}
mLogger.printRaw(doc.str());
return Result::Exit;
}
if (std::strcmp(argv[i], "--errorlist") == 0) {
{
XMLErrorMessagesLogger xmlLogger;
std::cout << ErrorMessage::getXMLHeader(mSettings.cppcheckCfgProductName, 2);
CppCheck::getErrorMessages(xmlLogger);
std::cout << ErrorMessage::getXMLFooter(2) << std::endl;
}
return Result::Exit;
}
if (std::strcmp(argv[i], "-h") == 0 || std::strcmp(argv[i], "--help") == 0) {
printHelp();
return Result::Exit;
}
if (std::strcmp(argv[i], "--filesdir") == 0) {
#ifdef FILESDIR
mLogger.printRaw(FILESDIR);
#endif
return Result::Exit;
}
if (std::strcmp(argv[i], "--version") == 0) {
mLogger.printRaw(getVersion());
return Result::Exit;
}
}
// Parse all options and positional files via reflect-cpp CLI.
auto parsed = rfl::cli::read_detailed<CppcheckArgs, CppcheckCliProcessors>(argc, argv);
if (!parsed) {
reportCliParseError(mLogger, parsed.error().what(), argc, argv, mSettings.premium);
return Result::Fail;
}
const auto& occurrences = parsed->occurrences;
bool debug = false;
bool inputAsFilter = false; // set by: --file-filter=+
ImportProject::Type projectType = ImportProject::Type::NONE;
ImportProject project;
std::string vsConfig;
std::string platform;
char defaultSign = '\0';
std::vector<std::string> lookupPaths{
Path::getCurrentPath(), // TODO: do we want to look in CWD?
Path::getPathFromFilename(mSettings.exename),
};
bool executorAuto = true;
for (const auto& [opt, val] : occurrences) {
if (opt == "define") {
std::string define = val;
if (define.find('=') == std::string::npos)
define += "=1";
if (!mSettings.userDefines.empty())
mSettings.userDefines += ";";
mSettings.userDefines += define;
}
else if (opt == "preprocess-only") {
mSettings.preprocessOnly = true;
mSettings.quiet = true;
}
else if (opt == "keep-comments") {
mSettings.keepComments = true;
}
else if (opt == "include-dir") {
std::string path = Path::fromNativeSeparators(Path::removeQuotationMarks(val));
if (!endsWith(path, '/'))
path += '/';
mSettings.includePaths.emplace_back(std::move(path));
}
else if (opt == "undefine") {
mSettings.userUndefs.insert(val);
}
else if (opt == "addon") {
mSettings.addons.emplace(val);
}
else if (opt == "addon-python") {
mSettings.addonPython = val;
}
else if (opt == "analyze-all-vs-configs") {
mSettings.analyzeAllVsConfigs = (val != "false");
mAnalyzeAllVsConfigsSetOnCmdLine = true;
}
else if (opt == "check-config") {
mSettings.checkConfiguration = true;
}
else if (opt == "check-headers") {
mSettings.checkHeaders = (val != "false");
}
else if (opt == "check-level") {
Settings::CheckLevel level = Settings::CheckLevel::normal;
if (val == "reduced")
level = Settings::CheckLevel::reduced;
else if (val == "normal")
level = Settings::CheckLevel::normal;
else if (val == "exhaustive")
level = Settings::CheckLevel::exhaustive;
else {
mLogger.printError("unknown '--check-level' value '" + val + "'.");
return Result::Fail;
}
mSettings.setCheckLevel(level);
}
else if (opt == "check-library") {
mSettings.checkLibrary = true;
}
else if (opt == "check-unused-templates") {
mSettings.checkUnusedTemplates = (val != "false");
}
else if (opt == "check-version") {
if (!loadCppcheckCfg())
return Result::Fail;
if (getVersion() != val) {
mLogger.printError("--check-version check failed. Aborting.");
return Result::Fail;
}
}
else if (opt == "checkers-report") {
mSettings.checkersReportFilename = val;
}
else if (opt == "checks-max-time") {
if (!parseNumberValue(mLogger, "--checks-max-time=", val, mSettings.checksMaxTime, true))
return Result::Fail;
}
else if (opt == "clang") {
mSettings.clang = true;
mSettings.clangExecutable = val;
}
else if (opt == "clang-tidy") {
mSettings.clangTidy = true;
mSettings.clangTidyExecutable = val;
}
else if (opt == "config-exclude") {
mSettings.configExcludePaths.insert(Path::fromNativeSeparators(val));
}
else if (opt == "config-excludes-file") {
if (!addPathsToSet(val, mSettings.configExcludePaths)) {
mLogger.printError("unable to open config excludes file at '" + val + "'");
return Result::Fail;
}
}
else if (opt == "cppcheck-build-dir") {
std::string path = Path::fromNativeSeparators(val);
if (path.empty()) {
mLogger.printError("no path has been specified for --cppcheck-build-dir");
return Result::Fail;
}
if (endsWith(path, '/'))
path.pop_back();
mSettings.buildDir = std::move(path);
}
else if (opt == "cpp-header-probe") {
mSettings.cppHeaderProbe = (val != "false");
}
else if (opt == "debug-analyzerinfo") {
mSettings.debugainfo = true;
}
else if (opt == "debug-ast") {
mSettings.debugast = true;
}
else if (opt == "debug-clang-output") {
mSettings.debugClangOutput = true;
}
else if (opt == "debug-ignore") {
mSettings.debugignore = true;
}
else if (opt == "debug-ipc") {
mSettings.debugipc = true;
}
else if (opt == "debug") {
debug = true;
}
else if (opt == "debug-lookup") {
continue; // already handled above
}
else if (opt == "debug-simplified") {
mSettings.debugSimplified = true;
}
else if (opt == "debug-symdb") {
mSettings.debugsymdb = true;
}
else if (opt == "debug-template") {
mSettings.debugtemplate = true;
}
else if (opt == "debug-valueflow") {
mSettings.debugvalueflow = true;
}
else if (opt == "debug-warnings") {
mSettings.debugwarnings = true;
}
else if (opt == "disable") {
const std::string errmsg = mSettings.removeEnabled(val);
if (!errmsg.empty()) {
mLogger.printError(errmsg);
return Result::Fail;
}
}
else if (opt == "dump") {
mSettings.dump = true;
}
else if (opt == "emit-duplicates") {
mSettings.emitDuplicates = true;
}
else if (opt == "enable") {
const std::string errmsg = mSettings.addEnabled(val);
if (!errmsg.empty()) {
mLogger.printError(errmsg);
return Result::Fail;
}
// when "style" is enabled, also enable "warning", "performance" and "portability"
if (val.find("style") != std::string::npos) {
mSettings.addEnabled("warning");
mSettings.addEnabled("performance");
mSettings.addEnabled("portability");
}
}
else if (opt == "error-exitcode") {
if (!parseNumberValue(mLogger, "--error-exitcode=", val, mSettings.exitCode))
return Result::Fail;
}
else if (opt == "exception-handling") {
#if defined(USE_WINDOWS_SEH) || defined(USE_UNIX_SIGNAL_HANDLING)
if (val != "stderr" && val != "stdout") {
mLogger.printError("invalid '--exception-handling' argument");
return Result::Fail;
}
mSettings.exceptionHandling = true;
mSettings.exceptionOutput = (val == "stderr") ? stderr : stdout;
#else
mLogger.printError("Option --exception-handling is not supported since Cppcheck has not been built with any exception handling enabled.");
return Result::Fail;
#endif
}
else if (opt == "executor") {
if (val == "auto") {
executorAuto = true;
mSettings.executor = Settings::defaultExecutor();
}
else if (val == "thread") {
#if defined(HAS_THREADING_MODEL_THREAD)
executorAuto = false;
mSettings.executor = Settings::ExecutorType::Thread;
#else
mLogger.printError("executor type 'thread' cannot be used as Cppcheck has not been built with a respective threading model.");
return Result::Fail;
#endif
}
else if (val == "process") {
#if defined(HAS_THREADING_MODEL_FORK)
executorAuto = false;
mSettings.executor = Settings::ExecutorType::Process;
#else
mLogger.printError("executor type 'process' cannot be used as Cppcheck has not been built with a respective threading model.");
return Result::Fail;
#endif
}
else {
mLogger.printError("unknown executor: '" + val + "'.");
return Result::Fail;
}
}
else if (opt == "exitcode-suppress") {
const std::string errmsg(mSuppressions.nofail.addSuppressionLine(val));
if (!errmsg.empty()) {
mLogger.printError(errmsg);
return Result::Fail;
}
}
else if (opt == "exitcode-suppressions") {
std::ifstream f(val);
if (!f.is_open()) {
mLogger.printError("couldn't open the file: \"" + val + "\".");
return Result::Fail;
}
const std::string errmsg(mSuppressions.nofail.parseFile(f));
if (!errmsg.empty()) {
mLogger.printError(errmsg);
return Result::Fail;
}
}
else if (opt == "file-filter") {
if (val == "-") {
if (!addFilesToList(val, mSettings.fileFilters)) {
mLogger.printError("Failed: --file-filter=-");
return Result::Fail;
}
} else if (val == "+") {
inputAsFilter = true;
} else {
mSettings.fileFilters.emplace_back(val);
}
}
else if (opt == "file-list") {
if (!addFilesToList(val, mPathNames)) {
mLogger.printError("couldn't open the file: \"" + val + "\".");
return Result::Fail;
}
}
else if (opt == "force") {
mSettings.force = true;
mSettings.maxConfigsOption = Settings::maxConfigsNotAssigned;
}
else if (opt == "fsigned-char") {
defaultSign = 's';
}