Cppcheck
settings.h
Go to the documentation of this file.
1 /*
2  * Cppcheck - A tool for static C/C++ code analysis
3  * Copyright (C) 2007-2024 Cppcheck team.
4  *
5  * This program is free software: you can redistribute it and/or modify
6  * it under the terms of the GNU General Public License as published by
7  * the Free Software Foundation, either version 3 of the License, or
8  * (at your option) any later version.
9  *
10  * This program is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13  * GNU General Public License for more details.
14  *
15  * You should have received a copy of the GNU General Public License
16  * along with this program. If not, see <http://www.gnu.org/licenses/>.
17  */
18 
19 //---------------------------------------------------------------------------
20 #ifndef settingsH
21 #define settingsH
22 //---------------------------------------------------------------------------
23 
24 #include "addoninfo.h"
25 #include "config.h"
26 #include "errortypes.h"
27 #include "library.h"
28 #include "platform.h"
29 #include "standards.h"
30 #include "suppressions.h"
31 
32 #include <algorithm>
33 #include <atomic>
34 #include <cstddef>
35 #include <cstdint>
36 #include <functional>
37 #include <list>
38 #include <map>
39 #include <set>
40 #include <string>
41 #include <tuple>
42 #include <vector>
43 #include <unordered_set>
44 
45 enum class SHOWTIME_MODES;
46 namespace ValueFlow {
47  class Value;
48 }
49 
50 /// @addtogroup Core
51 /// @{
52 
53 template<typename T>
55  uint32_t mFlags = 0;
56 public:
57  uint32_t intValue() const {
58  return mFlags;
59  }
60  void clear() {
61  mFlags = 0;
62  }
63  void fill() {
64  mFlags = 0xFFFFFFFF;
65  }
66  bool isEnabled(T flag) const {
67  return (mFlags & (1U << (uint32_t)flag)) != 0;
68  }
69  void enable(T flag) {
70  mFlags |= (1U << (uint32_t)flag);
71  }
73  mFlags |= group.intValue();
74  }
75  void disable(T flag) {
76  mFlags &= ~(1U << (uint32_t)flag);
77  }
79  mFlags &= ~(group.intValue());
80  }
81  void setEnabled(T flag, bool enabled) {
82  if (enabled)
83  enable(flag);
84  else
85  disable(flag);
86  }
87 };
88 
89 
90 /**
91  * @brief This is just a container for general settings so that we don't need
92  * to pass individual values to functions or constructors now or in the
93  * future when we might have even more detailed settings.
94  */
96 private:
97 
98  /** @brief terminate checking */
99  static std::atomic<bool> mTerminated;
100 
101 public:
102  Settings();
103 
104  static std::string loadCppcheckCfg(Settings& settings, Suppressions& suppressions);
105 
106  static std::pair<std::string, std::string> getNameAndVersion(const std::string& productName);
107 
108  /** @brief addons, either filename of python/json file or json data */
109  std::unordered_set<std::string> addons;
110 
111  /** @brief the loaded addons infos */
112  std::vector<AddonInfo> addonInfos;
113 
114  /** @brief Path to the python interpreter to be used to run addons. */
115  std::string addonPython;
116 
117  /** @brief Paths used as base for conversion to relative paths. */
118  std::vector<std::string> basePaths;
119 
120  /** @brief --cppcheck-build-dir. Always uses / as path separator. No trailing path separator. */
121  std::string buildDir;
122 
123  /** @brief check all configurations (false if -D or --max-configs is used */
124  bool checkAllConfigurations = true;
125 
126  /** Is the 'configuration checking' wanted? */
127  bool checkConfiguration{};
128 
129  /**
130  * Check code in the headers, this is on by default but can
131  * be turned off to save CPU */
132  bool checkHeaders = true;
133 
134  /** Check for incomplete info in library files? */
135  bool checkLibrary{};
136 
137  /** @brief The maximum time in seconds for the checks of a single file */
138  int checksMaxTime{};
139 
140  /** @brief --checkers-report=<filename> : Generate report of executed checkers */
142 
143  /** @brief check unknown function return values */
144  std::set<std::string> checkUnknownFunctionReturn;
145 
146  /** Check unused/uninstantiated templates */
147  bool checkUnusedTemplates = true;
148 
149  /** Use Clang */
150  bool clang{};
151 
152  /** Custom Clang executable */
153  std::string clangExecutable = "clang";
154 
155  /** Use clang-tidy */
156  bool clangTidy{};
157 
158  /** Internal: Clear the simplecpp non-existing include cache */
159  bool clearIncludeCache{};
160 
161  /** @brief include paths excluded from checking the configuration */
162  std::set<std::string> configExcludePaths;
163 
164  /** cppcheck.cfg: Custom product name */
166 
167  /** cppcheck.cfg: About text */
168  std::string cppcheckCfgAbout;
169 
170  /** @brief Are we running from DACA script? */
171  bool daca{};
172 
173  /** @brief Is --debug-normal given? */
174  bool debugnormal{};
175 
176  /** @brief Is --debug-simplified given? */
177  bool debugSimplified{};
178 
179  /** @brief Is --debug-template given? */
180  bool debugtemplate{};
181 
182  /** @brief Is --debug-warnings given? */
183  bool debugwarnings{};
184 
185  /** @brief Is --dump given? */
186  bool dump{};
187  std::string dumpFile;
188 
189  /** @brief Name of the language that is enforced. Empty per default. */
190  Standards::Language enforcedLang{};
191 
192 #if defined(USE_WINDOWS_SEH) || defined(USE_UNIX_SIGNAL_HANDLING)
193  /** @brief Is --exception-handling given */
194  bool exceptionHandling{};
195 #endif
196 
197  enum class ExecutorType
198  {
199 #ifdef HAS_THREADING_MODEL_THREAD
200  Thread,
201 #endif
202 #ifdef HAS_THREADING_MODEL_FORK
203  Process
204 #endif
205  };
206 
208 
209  // argv[0]
210  std::string exename;
211 
212  /** @brief If errors are found, this value is returned from main().
213  Default value is 0. */
214  int exitCode{};
215 
216  /** @brief List of --file-filter for analyzing special files */
217  std::vector<std::string> fileFilters;
218 
219  /** @brief Force checking the files with "too many" configurations (--force). */
220  bool force{};
221 
222  /** @brief List of include paths, e.g. "my/includes/" which should be used
223  for finding include files inside source files. (-I) */
224  std::list<std::string> includePaths;
225 
226  /** @brief Is --inline-suppr given? */
227  bool inlineSuppressions{};
228 
229  /** @brief How many processes/threads should do checking at the same
230  time. Default is 1. (-j N) */
231  unsigned int jobs = 1;
232 
233  /** @brief --library= */
234  std::list<std::string> libraries;
235 
236  /** Library */
238 
239  /** @brief Load average value */
240  int loadAverage{};
241 
242  /** @brief Maximum number of configurations to check before bailing.
243  Default is 12. (--max-configs=N) */
244  int maxConfigs = 12;
245 
246  /** @brief --max-ctu-depth */
247  int maxCtuDepth = 2;
248 
249  /** @brief max template recursion */
250  int maxTemplateRecursion = 100;
251 
252  /** @brief write results (--output-file=&lt;file&gt;) */
253  std::string outputFile;
254 
256 
257  /** @brief Experimental: --performance-valueflow-max-time=T */
258  int performanceValueFlowMaxTime = -1;
259 
260  /** @brief --performance-valueflow-max-if-count=C */
261  int performanceValueFlowMaxIfCount = -1;
262 
263  /** @brief max number of sets of arguments to pass to subfuncions in valueflow */
264  int performanceValueFlowMaxSubFunctionArgs = 256;
265 
266  /** @brief pid of cppcheck. Intention is that this is set in the main process. */
267  int pid;
268 
269  /** @brief plist output (--plist-output=&lt;dir&gt;) */
270  std::string plistOutput;
271 
272  /** @brief Extra arguments for Cppcheck Premium addon */
273  std::string premiumArgs;
274 
275  /** Is checker id enabled by premiumArgs */
276  bool isPremiumEnabled(const char id[]) const;
277 
278  /** @brief Using -E for debugging purposes */
279  bool preprocessOnly{};
280 
281  /** @brief Is --quiet given? */
282  bool quiet{};
283 
284  /** @brief Use relative paths in output. */
285  bool relativePaths{};
286 
287  /** @brief --report-progress */
288  int reportProgress{-1};
289 
290 #ifdef HAVE_RULES
291  /** Rule */
292  struct CPPCHECKLIB Rule {
293  std::string tokenlist = "normal"; // use normal tokenlist
294  std::string pattern;
295  std::string id = "rule"; // default id
296  std::string summary;
297  Severity severity = Severity::style; // default severity
298  };
299 
300  /**
301  * @brief Extra rules
302  */
303  std::list<Rule> rules;
304 #endif
305 
306  /**
307  * @brief Safety certified behavior
308  * Show checkers report when Cppcheck finishes
309  * Make cppcheck checking more strict about critical errors
310  * - returns nonzero if there is critical errors
311  * - a critical error id is not suppressed (by mistake?) with glob pattern
312  */
313  bool safety = false;
314 
315  /** Do not only check how interface is used. Also check that interface is safe. */
317 
318  static const char XmlRootName[];
319  static const char XmlClasses[];
320  static const char XmlExternalFunctions[];
321  static const char XmlInternalFunctions[];
322  static const char XmlExternalVariables[];
323 
324  void clear() {
325  classes = externalFunctions = internalFunctions = externalVariables = false;
326  }
327 
328  /**
329  * Public interface of classes
330  * - public function parameters can have any value
331  * - public functions can be called in any order
332  * - public variables can have any value
333  */
334  bool classes{};
335 
336  /**
337  * External functions
338  * - external functions can be called in any order
339  * - function parameters can have any values
340  */
341  bool externalFunctions{};
342 
343  /**
344  * Experimental: assume that internal functions can be used in any way
345  * This is only available in the GUI.
346  */
347  bool internalFunctions{};
348 
349  /**
350  * Global variables that can be modified outside the TU.
351  * - Such variable can have "any" value
352  */
353  bool externalVariables{};
354  };
355 
357 
361 
362  /** @brief show timing information (--showtime=file|summary|top5) */
363  SHOWTIME_MODES showtime{};
364 
365  /** Struct contains standards settings */
367 
368  /** @brief suppressions */
370 
371  /** @brief The output format in which the errors are printed in text mode,
372  e.g. "{severity} {file}:{line} {message} {id}" */
373  std::string templateFormat;
374 
375  /** @brief The output format in which the error locations are printed in
376  * text mode, e.g. "{file}:{line} {info}" */
377  std::string templateLocation;
378 
379  /** @brief The maximum time in seconds for the template instantiation */
380  std::size_t templateMaxTime{};
381 
382  /** @brief The maximum time in seconds for the typedef simplification */
383  std::size_t typedefMaxTime{};
384 
385  /** @brief defines given by the user */
386  std::string userDefines;
387 
388  /** @brief undefines given by the user */
389  std::set<std::string> userUndefs;
390 
391  /** @brief forced includes given by the user */
392  std::list<std::string> userIncludes;
393 
394  /** @brief the maximum iterations of valueflow (--valueflow-max-iterations=T) */
395  std::size_t valueFlowMaxIterations = 4;
396 
397  /** @brief Is --verbose given? */
398  bool verbose{};
399 
400  /** @brief write XML results (--xml) */
401  bool xml{};
402 
403  /** @brief XML version (--xml-version=..) */
404  int xml_version = 2;
405 
406  /**
407  * @brief return true if a included file is to be excluded in Preprocessor::getConfigs
408  * @return true for the file to be excluded.
409  */
410  bool configurationExcluded(const std::string &file) const {
411  return std::any_of(configExcludePaths.begin(), configExcludePaths.end(), [&file](const std::string& path) {
412  return file.length() >= path.length() && file.compare(0, path.length(), path) == 0;
413  });
414  }
415 
416  /**
417  * @brief Enable extra checks by id. See isEnabled()
418  * @param str single id or list of id values to be enabled
419  * or empty string to enable all. e.g. "style,possibleError"
420  * @return error message. empty upon success
421  */
422  std::string addEnabled(const std::string &str);
423 
424  /**
425  * @brief Disable extra checks by id
426  * @param str single id or list of id values to be enabled
427  * or empty string to enable all. e.g. "style,possibleError"
428  * @return error message. empty upon success
429  */
430  std::string removeEnabled(const std::string &str);
431 
432  /**
433  * @brief Returns true if given value can be shown
434  * @return true if the value can be shown
435  */
436  bool isEnabled(const ValueFlow::Value *value, bool inconclusiveCheck=false) const;
437 
438  /** Is library specified? */
439  bool hasLib(const std::string &lib) const {
440  return std::find(libraries.cbegin(), libraries.cend(), lib) != libraries.cend();
441  }
442 
443  /** @brief Request termination of checking */
444  static void terminate(bool t = true) {
446  }
447 
448  /** @brief termination requested? */
449  static bool terminated() {
450  return Settings::mTerminated;
451  }
452 
453  std::set<std::string> summaryReturn;
454 
455  void loadSummaries();
456 
457  bool useSingleJob() const {
458  return jobs == 1;
459  }
460 
461  enum class CheckLevel {
462  normal,
463  exhaustive
464  };
465  CheckLevel checkLevel = CheckLevel::exhaustive;
466 
467  void setCheckLevel(CheckLevel level);
468 
469  using ExecuteCmdFn = std::function<int (std::string,std::vector<std::string>,std::string,std::string&)>;
470  void setMisraRuleTexts(const ExecuteCmdFn& executeCommand);
471  void setMisraRuleTexts(const std::string& data);
472  std::string getMisraRuleText(const std::string& id, const std::string& text) const;
473 
474  static ExecutorType defaultExecutor();
475 
476 private:
477  static std::string parseEnabled(const std::string &str, std::tuple<SimpleEnableGroup<Severity>, SimpleEnableGroup<Checks>> &groups);
478  std::string applyEnabled(const std::string &str, bool enable);
479  std::map<std::string, std::string> mMisraRuleTexts;
480 };
481 
482 /// @}
483 //---------------------------------------------------------------------------
484 #endif // settingsH
Library definitions handling.
Definition: library.h:52
Platform settings.
Definition: platform.h:43
This is just a container for general settings so that we don't need to pass individual values to func...
Definition: settings.h:95
std::set< std::string > userUndefs
undefines given by the user
Definition: settings.h:389
static void terminate(bool t=true)
Request termination of checking.
Definition: settings.h:444
static std::atomic< bool > mTerminated
terminate checking
Definition: settings.h:99
bool hasLib(const std::string &lib) const
Is library specified?
Definition: settings.h:439
int pid
pid of cppcheck.
Definition: settings.h:267
std::set< std::string > configExcludePaths
include paths excluded from checking the configuration
Definition: settings.h:162
std::map< std::string, std::string > mMisraRuleTexts
Definition: settings.h:479
std::vector< std::string > basePaths
Paths used as base for conversion to relative paths.
Definition: settings.h:118
bool configurationExcluded(const std::string &file) const
return true if a included file is to be excluded in Preprocessor::getConfigs
Definition: settings.h:410
Suppressions supprs
suppressions
Definition: settings.h:369
std::string plistOutput
plist output (–plist-output=<dir>)
Definition: settings.h:270
std::string templateFormat
The output format in which the errors are printed in text mode, e.g.
Definition: settings.h:373
ExecutorType
Definition: settings.h:198
std::string exename
Definition: settings.h:210
SimpleEnableGroup< Checks > checks
Definition: settings.h:360
std::function< int(std::string, std::vector< std::string >, std::string, std::string &)> ExecuteCmdFn
Definition: settings.h:469
static bool terminated()
termination requested?
Definition: settings.h:449
std::unordered_set< std::string > addons
addons, either filename of python/json file or json data
Definition: settings.h:109
Library library
Library.
Definition: settings.h:237
SafeChecks safeChecks
Definition: settings.h:356
std::string buildDir
–cppcheck-build-dir.
Definition: settings.h:121
std::string templateLocation
The output format in which the error locations are printed in text mode, e.g.
Definition: settings.h:377
std::string cppcheckCfgProductName
cppcheck.cfg: Custom product name
Definition: settings.h:165
std::string userDefines
defines given by the user
Definition: settings.h:386
std::vector< AddonInfo > addonInfos
the loaded addons infos
Definition: settings.h:112
std::string premiumArgs
Extra arguments for Cppcheck Premium addon.
Definition: settings.h:273
std::set< std::string > summaryReturn
Definition: settings.h:453
Platform platform
Definition: settings.h:255
std::string cppcheckCfgAbout
cppcheck.cfg: About text
Definition: settings.h:168
std::string outputFile
write results (–output-file=<file>)
Definition: settings.h:253
bool useSingleJob() const
Definition: settings.h:457
ExecutorType executor
Definition: settings.h:207
std::set< std::string > checkUnknownFunctionReturn
check unknown function return values
Definition: settings.h:144
std::list< std::string > libraries
–library=
Definition: settings.h:234
std::list< std::string > includePaths
List of include paths, e.g.
Definition: settings.h:224
std::string dumpFile
Definition: settings.h:187
SimpleEnableGroup< Certainty > certainty
Definition: settings.h:359
std::list< std::string > userIncludes
forced includes given by the user
Definition: settings.h:392
SimpleEnableGroup< Severity > severity
Definition: settings.h:358
std::string checkersReportFilename
–checkers-report=<filename> : Generate report of executed checkers
Definition: settings.h:141
std::vector< std::string > fileFilters
List of –file-filter for analyzing special files.
Definition: settings.h:217
std::string addonPython
Path to the python interpreter to be used to run addons.
Definition: settings.h:115
Standards standards
Struct contains standards settings.
Definition: settings.h:366
bool isEnabled(T flag) const
Definition: settings.h:66
void setEnabled(T flag, bool enabled)
Definition: settings.h:81
uint32_t intValue() const
Definition: settings.h:57
void enable(SimpleEnableGroup< T > group)
Definition: settings.h:72
void disable(T flag)
Definition: settings.h:75
void disable(SimpleEnableGroup< T > group)
Definition: settings.h:78
uint32_t mFlags
Definition: settings.h:55
void enable(T flag)
Definition: settings.h:69
#define WARN_UNUSED
Definition: config.h:110
#define CPPCHECKLIB
Definition: config.h:35
Severity
enum class for severity.
Definition: errortypes.h:63
@ style
Style warning.
int maxCtuDepth
Definition: ctu.cpp:58
Do not only check how interface is used.
Definition: settings.h:316
This is just a container for standards settings.
Definition: standards.h:36
SHOWTIME_MODES
Definition: timer.h:30