Visitar URL original
Check for JSON error when parsing addon .json files + fixes (#2374) · napcode/cppcheck@c990d10 · GitHub
Skip to content

Commit c990d10

Browse files
authored
Check for JSON error when parsing addon .json files + fixes (cppcheck-opensource#2374)
* cppcheck.cpp: Check for JSON error when parsing addon .json files This fixes that errors in JSON files given via `--addon=*.json` are silently ignored and maybe only a part of the JSON file is used. Now the error message which picojson can return is checked and a corresponding error message is returned again by getAddonInfo(). * naming.json: Fix missing comma * CLI: Fix naming violations detected by addon naming.py via naming.json * Addon naming: Add argument for validating names of constants * LIB: Rename functions/variables so they are valid, loosen naming rules * GUI: Fix naming violations
1 parent feeb27f commit c990d10

24 files changed

Lines changed: 168 additions & 147 deletions

‎addons/naming.py‎

Lines changed: 16 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -21,12 +21,16 @@ def validate_regex(expr):
2121

2222

2323
RE_VARNAME = None
24+
RE_CONSTNAME = None
2425
RE_PRIVATE_MEMBER_VARIABLE = None
2526
RE_FUNCTIONNAME = None
2627
for arg in sys.argv[1:]:
2728
if arg[:6] == '--var=':
2829
RE_VARNAME = arg[6:]
2930
validate_regex(RE_VARNAME)
31+
elif arg.startswith('--const='):
32+
RE_CONSTNAME = arg[arg.find('=')+1:]
33+
validate_regex(RE_CONSTNAME)
3034
elif arg.startswith('--private-member-variable='):
3135
RE_PRIVATE_MEMBER_VARIABLE = arg[arg.find('=')+1:]
3236
validate_regex(RE_PRIVATE_MEMBER_VARIABLE)
@@ -49,11 +53,22 @@ def reportError(token, severity, msg, errorId):
4953
print('Checking ' + arg + ', config "' + cfg.name + '"...')
5054
if RE_VARNAME:
5155
for var in cfg.variables:
52-
if var.nameToken:
56+
if var.access == 'Private':
57+
continue
58+
if var.nameToken and not var.isConst:
5359
res = re.match(RE_VARNAME, var.nameToken.str)
5460
if not res:
5561
reportError(var.typeStartToken, 'style', 'Variable ' +
5662
var.nameToken.str + ' violates naming convention', 'varname')
63+
if RE_CONSTNAME:
64+
for var in cfg.variables:
65+
if var.access == 'Private':
66+
continue
67+
if var.nameToken and var.isConst:
68+
res = re.match(RE_CONSTNAME, var.nameToken.str)
69+
if not res:
70+
reportError(var.typeStartToken, 'style', 'Constant ' +
71+
var.nameToken.str + ' violates naming convention', 'constname')
5772
if RE_PRIVATE_MEMBER_VARIABLE:
5873
for var in cfg.variables:
5974
if (var.access is None) or var.access != 'Private':

‎cli/cmdlineparser.cpp‎

Lines changed: 25 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -44,53 +44,53 @@
4444
#include <tinyxml2.h>
4545
#endif
4646

47-
static void addFilesToList(const std::string& FileList, std::vector<std::string>& PathNames)
47+
static void addFilesToList(const std::string& fileList, std::vector<std::string>& pathNames)
4848
{
4949
// To keep things initially simple, if the file can't be opened, just be silent and move on.
50-
std::istream *Files;
51-
std::ifstream Infile;
52-
if (FileList == "-") { // read from stdin
53-
Files = &std::cin;
50+
std::istream *files;
51+
std::ifstream infile;
52+
if (fileList == "-") { // read from stdin
53+
files = &std::cin;
5454
} else {
55-
Infile.open(FileList);
56-
Files = &Infile;
55+
infile.open(fileList);
56+
files = &infile;
5757
}
58-
if (Files && *Files) {
59-
std::string FileName;
60-
while (std::getline(*Files, FileName)) { // next line
61-
if (!FileName.empty()) {
62-
PathNames.push_back(FileName);
58+
if (files && *files) {
59+
std::string fileName;
60+
while (std::getline(*files, fileName)) { // next line
61+
if (!fileName.empty()) {
62+
pathNames.push_back(fileName);
6363
}
6464
}
6565
}
6666
}
6767

68-
static bool addIncludePathsToList(const std::string& FileList, std::list<std::string>* PathNames)
68+
static bool addIncludePathsToList(const std::string& fileList, std::list<std::string>* pathNames)
6969
{
70-
std::ifstream Files(FileList);
71-
if (Files) {
72-
std::string PathName;
73-
while (std::getline(Files, PathName)) { // next line
74-
if (!PathName.empty()) {
75-
PathName = Path::removeQuotationMarks(PathName);
76-
PathName = Path::fromNativeSeparators(PathName);
70+
std::ifstream files(fileList);
71+
if (files) {
72+
std::string pathName;
73+
while (std::getline(files, pathName)) { // next line
74+
if (!pathName.empty()) {
75+
pathName = Path::removeQuotationMarks(pathName);
76+
pathName = Path::fromNativeSeparators(pathName);
7777

7878
// If path doesn't end with / or \, add it
79-
if (!endsWith(PathName, '/'))
80-
PathName += '/';
79+
if (!endsWith(pathName, '/'))
80+
pathName += '/';
8181

82-
PathNames->push_back(PathName);
82+
pathNames->push_back(pathName);
8383
}
8484
}
8585
return true;
8686
}
8787
return false;
8888
}
8989

90-
static bool addPathsToSet(const std::string& FileName, std::set<std::string>* set)
90+
static bool addPathsToSet(const std::string& fileName, std::set<std::string>* set)
9191
{
9292
std::list<std::string> templist;
93-
if (!addIncludePathsToList(FileName, &templist))
93+
if (!addIncludePathsToList(fileName, &templist))
9494
return false;
9595
set->insert(templist.begin(), templist.end());
9696
return true;

‎cli/cppcheckexecutor.cpp‎

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -208,7 +208,7 @@ void CppCheckExecutor::setSettings(const Settings &settings)
208208
* \return size of array
209209
* */
210210
template<typename T, int size>
211-
std::size_t GetArrayLength(const T(&)[size])
211+
std::size_t getArrayLength(const T(&)[size])
212212
{
213213
return size;
214214
}
@@ -228,7 +228,7 @@ static void print_stacktrace(FILE* output, bool demangling, int maxdepth, bool l
228228
#define ADDRESSDISPLAYLENGTH ((sizeof(long)==8)?12:8)
229229
const int fd = fileno(output);
230230
void *callstackArray[32]= {nullptr}; // the less resources the better...
231-
const int currentdepth = backtrace(callstackArray, (int)GetArrayLength(callstackArray));
231+
const int currentdepth = backtrace(callstackArray, (int)getArrayLength(callstackArray));
232232
const int offset=2; // some entries on top are within our own exception handling code or libc
233233
if (maxdepth<0)
234234
maxdepth=currentdepth-offset;
@@ -256,7 +256,7 @@ static void print_stacktrace(FILE* output, bool demangling, int maxdepth, bool l
256256
char input_buffer[1024]= {0};
257257
strncpy(input_buffer, firstBracketName+1, plus-firstBracketName-1);
258258
char output_buffer[2048]= {0};
259-
size_t length = GetArrayLength(output_buffer);
259+
size_t length = getArrayLength(output_buffer);
260260
int status=0;
261261
// We're violating the specification - passing stack address instead of malloc'ed heap.
262262
// Benefit is that no further heap is required, while there is sufficient stack...
@@ -539,7 +539,7 @@ static void CppcheckSignalHandler(int signo, siginfo_t * info, void * context)
539539
namespace {
540540
const ULONG maxnamelength = 512;
541541
struct IMAGEHLP_SYMBOL64_EXT : public IMAGEHLP_SYMBOL64 {
542-
TCHAR NameExt[maxnamelength]; // actually no need to worry about character encoding here
542+
TCHAR nameExt[maxnamelength]; // actually no need to worry about character encoding here
543543
};
544544
typedef BOOL (WINAPI *fpStackWalk64)(DWORD, HANDLE, HANDLE, LPSTACKFRAME64, PVOID, PREAD_PROCESS_MEMORY_ROUTINE64, PFUNCTION_TABLE_ACCESS_ROUTINE64, PGET_MODULE_BASE_ROUTINE64, PTRANSLATE_ADDRESS_ROUTINE64);
545545
fpStackWalk64 pStackWalk64;
@@ -574,7 +574,7 @@ namespace {
574574
}
575575

576576

577-
void PrintCallstack(FILE* outputFile, PEXCEPTION_POINTERS ex)
577+
void printCallstack(FILE* outputFile, PEXCEPTION_POINTERS ex)
578578
{
579579
if (!loadDbgHelp())
580580
return;
@@ -628,7 +628,7 @@ namespace {
628628
break;
629629
pSymGetSymFromAddr64(hProcess, (ULONG64)stack.AddrPC.Offset, &displacement, &symbol);
630630
TCHAR undname[maxnamelength]= {0};
631-
pUnDecorateSymbolName((const TCHAR*)symbol.Name, (PTSTR)undname, (DWORD)GetArrayLength(undname), UNDNAME_COMPLETE);
631+
pUnDecorateSymbolName((const TCHAR*)symbol.Name, (PTSTR)undname, (DWORD)getArrayLength(undname), UNDNAME_COMPLETE);
632632
if (beyond_main>=0)
633633
++beyond_main;
634634
if (_tcscmp(undname, _T("main"))==0)
@@ -751,7 +751,7 @@ namespace {
751751
break;
752752
}
753753
fputc('\n', outputFile);
754-
PrintCallstack(outputFile, ex);
754+
printCallstack(outputFile, ex);
755755
fflush(outputFile);
756756
return EXCEPTION_EXECUTE_HANDLER;
757757
}

‎cli/filelister.cpp‎

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -40,7 +40,7 @@
4040
// When compiling Unicode targets WinAPI automatically uses *W Unicode versions
4141
// of called functions. Thus, we explicitly call *A versions of the functions.
4242

43-
static BOOL MyIsDirectory(const std::string& path)
43+
static BOOL myIsDirectory(const std::string& path)
4444
{
4545
#ifdef __BORLANDC__
4646
return (GetFileAttributes(path.c_str()) & FILE_ATTRIBUTE_DIRECTORY);
@@ -50,13 +50,13 @@ static BOOL MyIsDirectory(const std::string& path)
5050
#endif
5151
}
5252

53-
static HANDLE MyFindFirstFile(const std::string& path, LPWIN32_FIND_DATAA findData)
53+
static HANDLE myFindFirstFile(const std::string& path, LPWIN32_FIND_DATAA findData)
5454
{
5555
HANDLE hFind = FindFirstFileA(path.c_str(), findData);
5656
return hFind;
5757
}
5858

59-
static BOOL MyFileExists(const std::string& path)
59+
static BOOL myFileExists(const std::string& path)
6060
{
6161
#ifdef __BORLANDC__
6262
DWORD fa = GetFileAttributes(path.c_str());
@@ -86,7 +86,7 @@ void FileLister::addFiles(std::map<std::string, std::size_t> &files, const std::
8686
std::string searchPattern = cleanedPath;
8787

8888
// The user wants to check all files in a dir
89-
const bool checkAllFilesInDir = (MyIsDirectory(cleanedPath) != FALSE);
89+
const bool checkAllFilesInDir = (myIsDirectory(cleanedPath) != FALSE);
9090

9191
if (checkAllFilesInDir) {
9292
const char c = cleanedPath.back();
@@ -111,7 +111,7 @@ void FileLister::addFiles(std::map<std::string, std::size_t> &files, const std::
111111
}
112112

113113
WIN32_FIND_DATAA ffd;
114-
HANDLE hFind = MyFindFirstFile(searchPattern, &ffd);
114+
HANDLE hFind = myFindFirstFile(searchPattern, &ffd);
115115
if (INVALID_HANDLE_VALUE == hFind)
116116
return;
117117

@@ -152,12 +152,12 @@ void FileLister::addFiles(std::map<std::string, std::size_t> &files, const std::
152152

153153
bool FileLister::isDirectory(const std::string &path)
154154
{
155-
return (MyIsDirectory(path) != FALSE);
155+
return (myIsDirectory(path) != FALSE);
156156
}
157157

158158
bool FileLister::fileExists(const std::string &path)
159159
{
160-
return (MyFileExists(path) != FALSE);
160+
return (myFileExists(path) != FALSE);
161161
}
162162

163163

‎gui/checkthread.cpp‎

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -122,12 +122,12 @@ void CheckThread::runAddonsAndTools(const ImportProject::FileSettings *fileSetti
122122
continue;
123123

124124
QStringList args;
125-
for (std::list<std::string>::const_iterator I = fileSettings->includePaths.begin(); I != fileSettings->includePaths.end(); ++I)
126-
args << ("-I" + QString::fromStdString(*I));
125+
for (std::list<std::string>::const_iterator incIt = fileSettings->includePaths.begin(); incIt != fileSettings->includePaths.end(); ++incIt)
126+
args << ("-I" + QString::fromStdString(*incIt));
127127
for (std::list<std::string>::const_iterator i = fileSettings->systemIncludePaths.begin(); i != fileSettings->systemIncludePaths.end(); ++i)
128128
args << "-isystem" << QString::fromStdString(*i);
129-
foreach (QString D, QString::fromStdString(fileSettings->defines).split(";")) {
130-
args << ("-D" + D);
129+
foreach (QString def, QString::fromStdString(fileSettings->defines).split(";")) {
130+
args << ("-D" + def);
131131
}
132132
foreach (const std::string& U, fileSettings->undefs) {
133133
args << QString::fromStdString("-U" + U);

‎lib/checkfunctions.cpp‎

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -415,16 +415,16 @@ void CheckFunctions::checkLibraryMatchFunctions()
415415
if (!mSettings->checkLibrary || !mSettings->isEnabled(Settings::INFORMATION))
416416
return;
417417

418-
bool New = false;
418+
bool insideNew = false;
419419
for (const Token *tok = mTokenizer->tokens(); tok; tok = tok->next()) {
420420
if (!tok->scope() || !tok->scope()->isExecutable())
421421
continue;
422422

423423
if (tok->str() == "new")
424-
New = true;
424+
insideNew = true;
425425
else if (tok->str() == ";")
426-
New = false;
427-
else if (New)
426+
insideNew = false;
427+
else if (insideNew)
428428
continue;
429429

430430
if (!Token::Match(tok, "%name% (") || Token::Match(tok, "asm|sizeof|catch"))

‎lib/checkleakautovar.cpp‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -637,7 +637,7 @@ void CheckLeakAutoVar::checkScope(const Token * const startToken,
637637
if (allocation.status == VarInfo::NOALLOC && Token::simpleMatch(tok, ") ; }")) {
638638
const std::string &functionName(tok->link()->previous()->str());
639639
bool unknown = false;
640-
if (mTokenizer->IsScopeNoReturn(tok->tokAt(2), &unknown)) {
640+
if (mTokenizer->isScopeNoReturn(tok->tokAt(2), &unknown)) {
641641
if (!unknown)
642642
varInfo->clear();
643643
else if (!mSettings->library.isLeakIgnore(functionName) && !mSettings->library.isUse(functionName))

‎lib/checkmemoryleak.cpp‎

Lines changed: 13 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -559,7 +559,7 @@ void CheckMemoryLeakInFunction::checkReallocUsage()
559559
if (Token::simpleMatch(tokEndRealloc->next(), "; if (") &&
560560
notvar(tokEndRealloc->tokAt(3)->astOperand2(), tok->varId())) {
561561
const Token* tokEndBrace = tokEndRealloc->linkAt(3)->linkAt(1);
562-
if (tokEndBrace && mTokenizer->IsScopeNoReturn(tokEndBrace))
562+
if (tokEndBrace && mTokenizer->isScopeNoReturn(tokEndBrace))
563563
continue;
564564
}
565565

@@ -606,8 +606,8 @@ void CheckMemoryLeakInClass::variable(const Scope *scope, const Token *tokVarnam
606606
const std::string& classname = scope->className;
607607

608608
// Check if member variable has been allocated and deallocated..
609-
CheckMemoryLeak::AllocType Alloc = CheckMemoryLeak::No;
610-
CheckMemoryLeak::AllocType Dealloc = CheckMemoryLeak::No;
609+
CheckMemoryLeak::AllocType memberAlloc = CheckMemoryLeak::No;
610+
CheckMemoryLeak::AllocType memberDealloc = CheckMemoryLeak::No;
611611

612612
bool allocInConstructor = false;
613613
bool deallocInDestructor = false;
@@ -619,7 +619,7 @@ void CheckMemoryLeakInClass::variable(const Scope *scope, const Token *tokVarnam
619619
if (!func.hasBody()) {
620620
if (destructor) { // implementation for destructor is not seen => assume it deallocates all variables properly
621621
deallocInDestructor = true;
622-
Dealloc = CheckMemoryLeak::Many;
622+
memberDealloc = CheckMemoryLeak::Many;
623623
}
624624
continue;
625625
}
@@ -652,16 +652,16 @@ void CheckMemoryLeakInClass::variable(const Scope *scope, const Token *tokVarnam
652652
if (constructor)
653653
allocInConstructor = true;
654654

655-
if (Alloc != No && Alloc != alloc)
655+
if (memberAlloc != No && memberAlloc != alloc)
656656
alloc = CheckMemoryLeak::Many;
657657

658-
if (alloc != CheckMemoryLeak::Many && Dealloc != CheckMemoryLeak::No && Dealloc != CheckMemoryLeak::Many && Dealloc != alloc) {
658+
if (alloc != CheckMemoryLeak::Many && memberDealloc != CheckMemoryLeak::No && memberDealloc != CheckMemoryLeak::Many && memberDealloc != alloc) {
659659
std::list<const Token *> callstack;
660660
callstack.push_back(tok);
661661
mismatchAllocDealloc(callstack, classname + "::" + varname);
662662
}
663663

664-
Alloc = alloc;
664+
memberAlloc = alloc;
665665
}
666666
}
667667

@@ -679,16 +679,16 @@ void CheckMemoryLeakInClass::variable(const Scope *scope, const Token *tokVarnam
679679
deallocInDestructor = true;
680680

681681
// several types of allocation/deallocation?
682-
if (Dealloc != CheckMemoryLeak::No && Dealloc != dealloc)
682+
if (memberDealloc != CheckMemoryLeak::No && memberDealloc != dealloc)
683683
dealloc = CheckMemoryLeak::Many;
684684

685-
if (dealloc != CheckMemoryLeak::Many && Alloc != CheckMemoryLeak::No && Alloc != Many && Alloc != dealloc) {
685+
if (dealloc != CheckMemoryLeak::Many && memberAlloc != CheckMemoryLeak::No && memberAlloc != Many && memberAlloc != dealloc) {
686686
std::list<const Token *> callstack;
687687
callstack.push_back(tok);
688688
mismatchAllocDealloc(callstack, classname + "::" + varname);
689689
}
690690

691-
Dealloc = dealloc;
691+
memberDealloc = dealloc;
692692
}
693693

694694
// Function call .. possible deallocation
@@ -702,9 +702,9 @@ void CheckMemoryLeakInClass::variable(const Scope *scope, const Token *tokVarnam
702702
}
703703

704704
if (allocInConstructor && !deallocInDestructor) {
705-
unsafeClassError(tokVarname, classname, classname + "::" + varname /*, Alloc*/);
706-
} else if (Alloc != CheckMemoryLeak::No && Dealloc == CheckMemoryLeak::No) {
707-
unsafeClassError(tokVarname, classname, classname + "::" + varname /*, Alloc*/);
705+
unsafeClassError(tokVarname, classname, classname + "::" + varname /*, memberAlloc*/);
706+
} else if (memberAlloc != CheckMemoryLeak::No && memberDealloc == CheckMemoryLeak::No) {
707+
unsafeClassError(tokVarname, classname, classname + "::" + varname /*, memberAlloc*/);
708708
}
709709
}
710710

‎lib/checkother.cpp‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -247,13 +247,13 @@ void CheckOther::checkSuspiciousSemicolon()
247247
if (Token::simpleMatch(scope.bodyStart, "{ ; } {") &&
248248
scope.bodyStart->previous()->linenr() == scope.bodyStart->tokAt(2)->linenr()
249249
&& scope.bodyStart->linenr()+1 >= scope.bodyStart->tokAt(3)->linenr()) {
250-
SuspiciousSemicolonError(scope.classDef);
250+
suspiciousSemicolonError(scope.classDef);
251251
}
252252
}
253253
}
254254
}
255255

256-
void CheckOther::SuspiciousSemicolonError(const Token* tok)
256+
void CheckOther::suspiciousSemicolonError(const Token* tok)
257257
{
258258
reportError(tok, Severity::warning, "suspiciousSemicolon",
259259
"Suspicious use of ; at the end of '" + (tok ? tok->str() : std::string()) + "' statement.", CWE398, true);

0 commit comments

Comments
 (0)