Cppcheck
cppcheck.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 cppcheckH
21 #define cppcheckH
22 //---------------------------------------------------------------------------
23 
24 #include "analyzerinfo.h"
25 #include "check.h"
26 #include "color.h"
27 #include "config.h"
28 #include "errorlogger.h"
29 #include "settings.h"
30 
31 #include <cstddef>
32 #include <fstream>
33 #include <functional>
34 #include <list>
35 #include <map>
36 #include <memory>
37 #include <set>
38 #include <string>
39 #include <unordered_set>
40 #include <vector>
41 
42 class TokenList;
43 enum class SHOWTIME_MODES;
44 struct FileSettings;
46 class Tokenizer;
47 class FileWithDetails;
48 
49 namespace simplecpp { class TokenList; }
50 
51 /// @addtogroup Core
52 /// @{
53 
54 /**
55  * @brief This is the base class which will use other classes to do
56  * static code analysis for C and C++ code to find possible
57  * errors or places that could be improved.
58  * Usage: See check() for more info.
59  */
61 public:
62  using ExecuteCmdFn = std::function<int (std::string,std::vector<std::string>,std::string,std::string&)>;
63 
64  /**
65  * @brief Constructor.
66  */
67  CppCheck(ErrorLogger &errorLogger,
68  bool useGlobalSuppressions,
69  ExecuteCmdFn executeCommand);
70 
71  /**
72  * @brief Destructor.
73  */
74  ~CppCheck() override;
75 
76  /**
77  * @brief This starts the actual checking. Note that you must call
78  * parseFromArgs() or settings() and addFile() before calling this.
79  * @return amount of errors found or 0 if none were found.
80  */
81 
82  /**
83  * @brief Check the file.
84  * This function checks one given file for errors.
85  * @param path Path to the file to check.
86  * @return amount of errors found or 0 if none were found.
87  * @note You must set settings before calling this function (by calling
88  * settings()).
89  */
90  unsigned int check(const std::string &path);
91  unsigned int check(const FileSettings &fs);
92 
93  /**
94  * @brief Check the file.
95  * This function checks one "virtual" file. The file is not read from
96  * the disk but the content is given in @p content. In errors the @p path
97  * is used as a filename.
98  * @param path Path to the file to check.
99  * @param content File content as a string.
100  * @return amount of errors found or 0 if none were found.
101  * @note You must set settings before calling this function (by calling
102  * settings()).
103  */
104  unsigned int check(const std::string &path, const std::string &content);
105 
106  /**
107  * @brief Get reference to current settings.
108  * @return a reference to current settings
109  */
110  Settings &settings();
111 
112  /**
113  * @brief Returns current version number as a string.
114  * @return version, e.g. "1.38"
115  */
116  static const char * version();
117 
118  /**
119  * @brief Returns extra version info as a string.
120  * This is for returning extra version info, like Git commit id, build
121  * time/date etc.
122  * @return extra version info, e.g. "04d42151" (Git commit id).
123  */
124  static const char * extraVersion();
125 
126  /**
127  * @brief Call all "getErrorMessages" in all registered Check classes.
128  * Also print out XML header and footer.
129  */
130  static void getErrorMessages(ErrorLogger &errorlogger);
131 
132  void tooManyConfigsError(const std::string &file, const int numberOfConfigurations);
133  void purgedConfigurationMessage(const std::string &file, const std::string& configuration);
134 
135  /** Analyse whole program, run this after all TUs has been scanned.
136  * This is deprecated and the plan is to remove this when
137  * .analyzeinfo is good enough.
138  * Return true if an error is reported.
139  */
140  bool analyseWholeProgram();
141 
142  /** Analyze all files using clang-tidy */
143  void analyseClangTidy(const FileSettings &fileSettings);
144 
145  /** analyse whole program use .analyzeinfo files */
146  unsigned int analyseWholeProgram(const std::string &buildDir, const std::list<FileWithDetails> &files, const std::list<FileSettings>& fileSettings);
147 
148  /** Remove *.ctu-info files */
149  void removeCtuInfoFiles(const std::list<FileWithDetails>& files, const std::list<FileSettings>& fileSettings); // cppcheck-suppress functionConst // has side effects
150 
151  static void resetTimerResults();
152  static void printTimerResults(SHOWTIME_MODES mode);
153 
154  bool isPremiumCodingStandardId(const std::string& id) const;
155 
156  std::string getAddonMessage(const std::string& id, const std::string& text) const;
157 
158  /**
159  * @brief Get dumpfile <rawtokens> contents, this is only public for testing purposes
160  */
161  std::string getDumpFileContentsRawTokens(const std::vector<std::string>& files, const simplecpp::TokenList& tokens1) const;
162 
163 private:
164 #ifdef HAVE_RULES
165  /** Are there "simple" rules */
166  bool hasRule(const std::string &tokenlist) const;
167 #endif
168 
169  /** @brief There has been an internal error => Report information message */
170  void internalError(const std::string &filename, const std::string &msg);
171 
172  /**
173  * @brief Check a file using stream
174  * @param filename file name
175  * @param cfgname cfg name
176  * @param fileStream stream the file content can be read from
177  * @return number of errors found
178  */
179  unsigned int checkFile(const std::string& filename, const std::string &cfgname, std::istream* fileStream = nullptr);
180 
181  /**
182  * @brief Check normal tokens
183  * @param tokenizer tokenizer instance
184  */
185  void checkNormalTokens(const Tokenizer &tokenizer);
186 
187  /**
188  * Execute addons
189  */
190  void executeAddons(const std::vector<std::string>& files, const std::string& file0);
191  void executeAddons(const std::string &dumpFile, const std::string& file0);
192 
193  /**
194  * Execute addons
195  */
196  void executeAddonsWholeProgram(const std::list<FileWithDetails> &files);
197 
198 #ifdef HAVE_RULES
199  /**
200  * @brief Execute rules, if any
201  * @param tokenlist token list to use (define / normal / raw)
202  * @param list token list
203  */
204  void executeRules(const std::string &tokenlist, const TokenList &list);
205 #endif
206 
207  unsigned int checkClang(const std::string &path);
208 
209  /**
210  * @brief Errors and warnings are directed here.
211  *
212  * @param msg Errors messages are normally in format
213  * "[filepath:line number] Message", e.g.
214  * "[main.cpp:4] Uninitialized member variable"
215  */
216  void reportErr(const ErrorMessage &msg) override;
217 
218  /**
219  * @brief Information about progress is directed here.
220  *
221  * @param outmsg Message to show, e.g. "Checking main.cpp..."
222  */
223  void reportOut(const std::string &outmsg, Color c = Color::Reset) override;
224 
225  // TODO: store hashes instead of the full messages
226  std::unordered_set<std::string> mErrorList;
228 
229  void reportProgress(const std::string &filename, const char stage[], const std::size_t value) override;
230 
232 
233  /** @brief Current preprocessor configuration */
234  std::string mCurrentConfig;
235 
236  using Location = std::pair<std::string, int>;
237  std::map<Location, std::set<std::string>> mLocationMacros; // What macros are used on a location?
238 
239  unsigned int mExitCode{};
240 
242 
243  /** Are there too many configs? */
244  bool mTooManyConfigs{};
245 
246  /** File info used for whole program analysis */
247  std::list<Check::FileInfo*> mFileInfo;
248 
250 
251  /** Callback for executing a shell command (exe, args, output) */
253 
254  std::ofstream mPlistFile;
255 
256  std::unique_ptr<CheckUnusedFunctions> mUnusedFunctionsCheck;
257 };
258 
259 /// @}
260 //---------------------------------------------------------------------------
261 #endif // cppcheckH
Analyzer information.
Definition: analyzerinfo.h:50
Check for functions never called.
This is the base class which will use other classes to do static code analysis for C and C++ code to ...
Definition: cppcheck.h:60
ErrorLogger & mErrorLogger
Definition: cppcheck.h:231
std::unordered_set< std::string > mErrorList
Definition: cppcheck.h:226
std::unique_ptr< CheckUnusedFunctions > mUnusedFunctionsCheck
Definition: cppcheck.h:256
AnalyzerInformation mAnalyzerInformation
Definition: cppcheck.h:249
Settings mSettings
Definition: cppcheck.h:227
std::string getAddonMessage(const std::string &id, const std::string &text) const
std::list< Check::FileInfo * > mFileInfo
File info used for whole program analysis.
Definition: cppcheck.h:247
std::function< int(std::string, std::vector< std::string >, std::string, std::string &)> ExecuteCmdFn
Definition: cppcheck.h:62
std::pair< std::string, int > Location
Definition: cppcheck.h:236
bool mUseGlobalSuppressions
Definition: cppcheck.h:241
std::string mCurrentConfig
Current preprocessor configuration.
Definition: cppcheck.h:234
std::ofstream mPlistFile
Definition: cppcheck.h:254
std::map< Location, std::set< std::string > > mLocationMacros
Definition: cppcheck.h:237
ExecuteCmdFn mExecuteCommand
Callback for executing a shell command (exe, args, output)
Definition: cppcheck.h:252
This is an interface, which the class responsible of error logging should implement.
Definition: errorlogger.h:214
virtual void reportErr(const ErrorMessage &msg)=0
Information about found errors and warnings is directed here.
virtual void reportOut(const std::string &outmsg, Color c=Color::Reset)=0
Information about progress is directed here.
virtual void reportProgress(const std::string &filename, const char stage[], const std::size_t value)
Report progress to client.
Definition: errorlogger.h:241
Wrapper for error messages, provided by reportErr()
Definition: errorlogger.h:48
This is just a container for general settings so that we don't need to pass individual values to func...
Definition: settings.h:95
The main purpose is to tokenize the source code.
Definition: tokenize.h:46
Color
Definition: color.h:27
#define CPPCHECKLIB
Definition: config.h:35
File settings.
Definition: filesettings.h:57
SHOWTIME_MODES
Definition: timer.h:30