Cppcheck
library.cpp
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 #include "library.h"
20 
21 #include "astutils.h"
22 #include "errortypes.h"
23 #include "mathlib.h"
24 #include "path.h"
25 #include "symboldatabase.h"
26 #include "token.h"
27 #include "tokenlist.h"
28 #include "utils.h"
29 #include "valueflow.h"
30 #include "vfvalue.h"
31 
32 #include <algorithm>
33 #include <cctype>
34 #include <climits>
35 #include <cstring>
36 #include <list>
37 #include <memory>
38 #include <sstream>
39 #include <stack>
40 #include <stdexcept>
41 #include <string>
42 
43 #include "xml.h"
44 
45 static std::vector<std::string> getnames(const char *names)
46 {
47  std::vector<std::string> ret;
48  while (const char *p = std::strchr(names,',')) {
49  ret.emplace_back(names, p-names);
50  names = p + 1;
51  }
52  ret.emplace_back(names);
53  return ret;
54 }
55 
56 static void gettokenlistfromvalid(const std::string& valid, bool cpp, TokenList& tokenList)
57 {
58  std::istringstream istr(valid + ',');
59  tokenList.createTokens(istr, cpp ? Standards::Language::CPP : Standards::Language::C); // TODO: check result?
60  for (Token *tok = tokenList.front(); tok; tok = tok->next()) {
61  if (Token::Match(tok,"- %num%")) {
62  tok->str("-" + tok->strAt(1));
63  tok->deleteNext();
64  }
65  }
66 }
67 
68 Library::Error Library::load(const char exename[], const char path[])
69 {
70  if (std::strchr(path,',') != nullptr) {
71  std::string p(path);
72  for (;;) {
73  const std::string::size_type pos = p.find(',');
74  if (pos == std::string::npos)
75  break;
76  const Error &e = load(exename, p.substr(0,pos).c_str());
77  if (e.errorcode != ErrorCode::OK)
78  return e;
79  p = p.substr(pos+1);
80  }
81  if (!p.empty())
82  return load(exename, p.c_str());
83  return Error();
84  }
85 
86  std::string absolute_path;
87  // open file..
88  tinyxml2::XMLDocument doc;
89  tinyxml2::XMLError error = doc.LoadFile(path);
90  if (error == tinyxml2::XML_ERROR_FILE_READ_ERROR && Path::getFilenameExtension(path).empty())
91  // Reading file failed, try again...
92  error = tinyxml2::XML_ERROR_FILE_NOT_FOUND;
93  if (error == tinyxml2::XML_ERROR_FILE_NOT_FOUND) {
94  // failed to open file.. is there no extension?
95  std::string fullfilename(path);
96  if (Path::getFilenameExtension(fullfilename).empty()) {
97  fullfilename += ".cfg";
98  error = doc.LoadFile(fullfilename.c_str());
99  if (error != tinyxml2::XML_ERROR_FILE_NOT_FOUND)
100  absolute_path = Path::getAbsoluteFilePath(fullfilename);
101  }
102 
103  std::list<std::string> cfgfolders;
104 #ifdef FILESDIR
105  cfgfolders.emplace_back(FILESDIR "/cfg");
106 #endif
107  if (exename) {
109  cfgfolders.push_back(exepath + "cfg");
110  cfgfolders.push_back(exepath + "../cfg");
111  cfgfolders.push_back(exepath);
112  }
113 
114  while (error == tinyxml2::XML_ERROR_FILE_NOT_FOUND && !cfgfolders.empty()) {
115  const std::string cfgfolder(cfgfolders.back());
116  cfgfolders.pop_back();
117  const char *sep = (!cfgfolder.empty() && endsWith(cfgfolder,'/') ? "" : "/");
118  const std::string filename(cfgfolder + sep + fullfilename);
119  error = doc.LoadFile(filename.c_str());
120  if (error != tinyxml2::XML_ERROR_FILE_NOT_FOUND)
121  absolute_path = Path::getAbsoluteFilePath(filename);
122  }
123  } else
124  absolute_path = Path::getAbsoluteFilePath(path);
125 
126  if (error == tinyxml2::XML_SUCCESS) {
127  if (mFiles.find(absolute_path) == mFiles.end()) {
128  Error err = load(doc);
129  if (err.errorcode == ErrorCode::OK)
130  mFiles.insert(absolute_path);
131  return err;
132  }
133 
134  return Error(ErrorCode::OK); // ignore duplicates
135  }
136 
137  if (error == tinyxml2::XML_ERROR_FILE_NOT_FOUND)
139 
140  doc.PrintError();
141  return Error(ErrorCode::BAD_XML);
142 }
143 
145 {
146  if (yieldName == "at_index")
148  if (yieldName == "item")
149  return Container::Yield::ITEM;
150  if (yieldName == "buffer")
152  if (yieldName == "buffer-nt")
154  if (yieldName == "start-iterator")
156  if (yieldName == "end-iterator")
158  if (yieldName == "iterator")
160  if (yieldName == "size")
161  return Container::Yield::SIZE;
162  if (yieldName == "empty")
165 }
167 {
168  if (actionName == "resize")
170  if (actionName == "clear")
172  if (actionName == "push")
174  if (actionName == "pop")
175  return Container::Action::POP;
176  if (actionName == "find")
178  if (actionName == "find-const")
180  if (actionName == "insert")
182  if (actionName == "erase")
184  if (actionName == "change-content")
186  if (actionName == "change-internal")
188  if (actionName == "change")
191 }
192 
193 Library::Error Library::load(const tinyxml2::XMLDocument &doc)
194 {
195  const tinyxml2::XMLElement * const rootnode = doc.FirstChildElement();
196 
197  if (rootnode == nullptr) {
198  doc.PrintError();
199  return Error(ErrorCode::BAD_XML);
200  }
201 
202  if (strcmp(rootnode->Name(),"def") != 0)
203  return Error(ErrorCode::UNSUPPORTED_FORMAT, rootnode->Name());
204 
205  const int format = rootnode->IntAttribute("format", 1); // Assume format version 1 if nothing else is specified (very old .cfg files had no 'format' attribute)
206 
207  if (format > 2 || format <= 0)
209 
210  std::set<std::string> unknown_elements;
211 
212  for (const tinyxml2::XMLElement *node = rootnode->FirstChildElement(); node; node = node->NextSiblingElement()) {
213  const std::string nodename = node->Name();
214  if (nodename == "memory" || nodename == "resource") {
215  // get allocationId to use..
216  int allocationId = 0;
217  for (const tinyxml2::XMLElement *memorynode = node->FirstChildElement(); memorynode; memorynode = memorynode->NextSiblingElement()) {
218  if (strcmp(memorynode->Name(),"dealloc")==0) {
219  const auto names = getnames(memorynode->GetText());
220  for (const auto& n : names) {
221  const std::map<std::string, AllocFunc>::const_iterator it = mDealloc.find(n);
222  if (it != mDealloc.end()) {
223  allocationId = it->second.groupId;
224  break;
225  }
226  }
227  if (allocationId != 0)
228  break;
229  }
230  }
231  if (allocationId == 0) {
232  if (nodename == "memory")
233  while (!ismemory(++mAllocId));
234  else
235  while (!isresource(++mAllocId));
236  allocationId = mAllocId;
237  }
238 
239  // add alloc/dealloc/use functions..
240  for (const tinyxml2::XMLElement *memorynode = node->FirstChildElement(); memorynode; memorynode = memorynode->NextSiblingElement()) {
241  const std::string memorynodename = memorynode->Name();
242  const auto names = getnames(memorynode->GetText());
243  if (memorynodename == "alloc" || memorynodename == "realloc") {
244  AllocFunc temp = {0};
245  temp.groupId = allocationId;
246 
247  temp.initData = memorynode->BoolAttribute("init", true);
248  temp.arg = memorynode->IntAttribute("arg", -1);
249 
250  const char *bufferSize = memorynode->Attribute("buffer-size");
251  if (!bufferSize)
253  else {
254  if (std::strncmp(bufferSize, "malloc", 6) == 0)
256  else if (std::strncmp(bufferSize, "calloc", 6) == 0)
258  else if (std::strncmp(bufferSize, "strdup", 6) == 0)
260  else
261  return Error(ErrorCode::BAD_ATTRIBUTE_VALUE, bufferSize);
262  temp.bufferSizeArg1 = 1;
263  temp.bufferSizeArg2 = 2;
264  if (bufferSize[6] == 0) {
265  // use default values
266  } else if (bufferSize[6] == ':' && bufferSize[7] >= '1' && bufferSize[7] <= '5') {
267  temp.bufferSizeArg1 = bufferSize[7] - '0';
268  if (bufferSize[8] == ',' && bufferSize[9] >= '1' && bufferSize[9] <= '5')
269  temp.bufferSizeArg2 = bufferSize[9] - '0';
270  } else
271  return Error(ErrorCode::BAD_ATTRIBUTE_VALUE, bufferSize);
272  }
273 
274  if (memorynodename == "realloc")
275  temp.reallocArg = memorynode->IntAttribute("realloc-arg", 1);
276 
277  auto& map = (memorynodename == "realloc") ? mRealloc : mAlloc;
278  for (const auto& n : names)
279  map[n] = temp;
280  } else if (memorynodename == "dealloc") {
281  AllocFunc temp = {0};
282  temp.groupId = allocationId;
283  temp.arg = memorynode->IntAttribute("arg", 1);
284  for (const auto& n : names)
285  mDealloc[n] = temp;
286  } else if (memorynodename == "use")
287  for (const auto& n : names)
288  functions[n].use = true;
289  else
290  unknown_elements.insert(memorynodename);
291  }
292  }
293 
294  else if (nodename == "define") {
295  const char *name = node->Attribute("name");
296  if (name == nullptr)
297  return Error(ErrorCode::MISSING_ATTRIBUTE, "name");
298  const char *value = node->Attribute("value");
299  if (value == nullptr)
300  return Error(ErrorCode::MISSING_ATTRIBUTE, "value");
301  auto result = defines.insert(std::string(name) + " " + value);
302  if (!result.second)
303  return Error(ErrorCode::DUPLICATE_DEFINE, name);
304  }
305 
306  else if (nodename == "function") {
307  const char *name = node->Attribute("name");
308  if (name == nullptr)
309  return Error(ErrorCode::MISSING_ATTRIBUTE, "name");
310  for (const std::string &s : getnames(name)) {
311  const Error &err = loadFunction(node, s, unknown_elements);
312  if (err.errorcode != ErrorCode::OK)
313  return err;
314  }
315  }
316 
317  else if (nodename == "reflection") {
318  for (const tinyxml2::XMLElement *reflectionnode = node->FirstChildElement(); reflectionnode; reflectionnode = reflectionnode->NextSiblingElement()) {
319  if (strcmp(reflectionnode->Name(), "call") != 0) {
320  unknown_elements.insert(reflectionnode->Name());
321  continue;
322  }
323 
324  const char * const argString = reflectionnode->Attribute("arg");
325  if (!argString)
326  return Error(ErrorCode::MISSING_ATTRIBUTE, "arg");
327 
328  mReflection[reflectionnode->GetText()] = strToInt<int>(argString);
329  }
330  }
331 
332  else if (nodename == "markup") {
333  const char * const extension = node->Attribute("ext");
334  if (!extension)
335  return Error(ErrorCode::MISSING_ATTRIBUTE, "ext");
336  mMarkupExtensions.insert(extension);
337 
338  mReportErrors[extension] = (node->Attribute("reporterrors", "true") != nullptr);
339  mProcessAfterCode[extension] = (node->Attribute("aftercode", "true") != nullptr);
340 
341  for (const tinyxml2::XMLElement *markupnode = node->FirstChildElement(); markupnode; markupnode = markupnode->NextSiblingElement()) {
342  const std::string markupnodename = markupnode->Name();
343  if (markupnodename == "keywords") {
344  for (const tinyxml2::XMLElement *librarynode = markupnode->FirstChildElement(); librarynode; librarynode = librarynode->NextSiblingElement()) {
345  if (strcmp(librarynode->Name(), "keyword") == 0) {
346  const char* nodeName = librarynode->Attribute("name");
347  if (nodeName == nullptr)
348  return Error(ErrorCode::MISSING_ATTRIBUTE, "name");
349  mKeywords[extension].insert(nodeName);
350  } else
351  unknown_elements.insert(librarynode->Name());
352  }
353  }
354 
355  else if (markupnodename == "exported") {
356  for (const tinyxml2::XMLElement *exporter = markupnode->FirstChildElement(); exporter; exporter = exporter->NextSiblingElement()) {
357  if (strcmp(exporter->Name(), "exporter") != 0) {
358  unknown_elements.insert(exporter->Name());
359  continue;
360  }
361 
362  const char * const prefix = exporter->Attribute("prefix");
363  if (!prefix)
364  return Error(ErrorCode::MISSING_ATTRIBUTE, "prefix");
365 
366  for (const tinyxml2::XMLElement *e = exporter->FirstChildElement(); e; e = e->NextSiblingElement()) {
367  const std::string ename = e->Name();
368  if (ename == "prefix")
369  mExporters[prefix].addPrefix(e->GetText());
370  else if (ename == "suffix")
371  mExporters[prefix].addSuffix(e->GetText());
372  else
373  unknown_elements.insert(ename);
374  }
375  }
376  }
377 
378  else if (markupnodename == "imported") {
379  for (const tinyxml2::XMLElement *librarynode = markupnode->FirstChildElement(); librarynode; librarynode = librarynode->NextSiblingElement()) {
380  if (strcmp(librarynode->Name(), "importer") == 0)
381  mImporters[extension].insert(librarynode->GetText());
382  else
383  unknown_elements.insert(librarynode->Name());
384  }
385  }
386 
387  else if (markupnodename == "codeblocks") {
388  for (const tinyxml2::XMLElement *blocknode = markupnode->FirstChildElement(); blocknode; blocknode = blocknode->NextSiblingElement()) {
389  const std::string blocknodename = blocknode->Name();
390  if (blocknodename == "block") {
391  const char * blockName = blocknode->Attribute("name");
392  if (blockName)
393  mExecutableBlocks[extension].addBlock(blockName);
394  } else if (blocknodename == "structure") {
395  const char * start = blocknode->Attribute("start");
396  if (start)
397  mExecutableBlocks[extension].setStart(start);
398  const char * end = blocknode->Attribute("end");
399  if (end)
400  mExecutableBlocks[extension].setEnd(end);
401  const char * offset = blocknode->Attribute("offset");
402  if (offset) {
403  // cppcheck-suppress templateInstantiation - TODO: fix this - see #11631
404  mExecutableBlocks[extension].setOffset(strToInt<int>(offset));
405  }
406  }
407 
408  else
409  unknown_elements.insert(blocknodename);
410  }
411  }
412 
413  else
414  unknown_elements.insert(markupnodename);
415  }
416  }
417 
418  else if (nodename == "container") {
419  const char* const id = node->Attribute("id");
420  if (!id)
421  return Error(ErrorCode::MISSING_ATTRIBUTE, "id");
422 
423  Container& container = containers[id];
424 
425  const char* const inherits = node->Attribute("inherits");
426  if (inherits) {
427  const std::unordered_map<std::string, Container>::const_iterator i = containers.find(inherits);
428  if (i != containers.end())
429  container = i->second; // Take values from parent and overwrite them if necessary
430  else
431  return Error(ErrorCode::BAD_ATTRIBUTE_VALUE, inherits);
432  }
433 
434  const char* const startPattern = node->Attribute("startPattern");
435  if (startPattern) {
436  container.startPattern = startPattern;
437  container.startPattern2 = startPattern;
438  if (!endsWith(container.startPattern, '<'))
439  container.startPattern2 += " !!::";
440  }
441  const char* const endPattern = node->Attribute("endPattern");
442  if (endPattern)
443  container.endPattern = endPattern;
444  const char* const itEndPattern = node->Attribute("itEndPattern");
445  if (itEndPattern)
446  container.itEndPattern = itEndPattern;
447  const char* const opLessAllowed = node->Attribute("opLessAllowed");
448  if (opLessAllowed)
449  container.opLessAllowed = strcmp(opLessAllowed, "true") == 0;
450  const char* const hasInitializerListConstructor = node->Attribute("hasInitializerListConstructor");
451  if (hasInitializerListConstructor)
452  container.hasInitializerListConstructor = strcmp(hasInitializerListConstructor, "true") == 0;
453  const char* const view = node->Attribute("view");
454  if (view)
455  container.view = strcmp(view, "true") == 0;
456 
457  for (const tinyxml2::XMLElement *containerNode = node->FirstChildElement(); containerNode; containerNode = containerNode->NextSiblingElement()) {
458  const std::string containerNodeName = containerNode->Name();
459  if (containerNodeName == "size" || containerNodeName == "access" || containerNodeName == "other") {
460  for (const tinyxml2::XMLElement *functionNode = containerNode->FirstChildElement(); functionNode; functionNode = functionNode->NextSiblingElement()) {
461  if (strcmp(functionNode->Name(), "function") != 0) {
462  unknown_elements.insert(functionNode->Name());
463  continue;
464  }
465 
466  const char* const functionName = functionNode->Attribute("name");
467  if (!functionName)
468  return Error(ErrorCode::MISSING_ATTRIBUTE, "name");
469 
470  const char* const action_ptr = functionNode->Attribute("action");
472  if (action_ptr) {
473  std::string actionName = action_ptr;
474  action = Container::actionFrom(actionName);
475  if (action == Container::Action::NO_ACTION)
476  return Error(ErrorCode::BAD_ATTRIBUTE_VALUE, actionName);
477  }
478 
479  const char* const yield_ptr = functionNode->Attribute("yields");
481  if (yield_ptr) {
482  std::string yieldName = yield_ptr;
483  yield = Container::yieldFrom(yieldName);
484  if (yield == Container::Yield::NO_YIELD)
485  return Error(ErrorCode::BAD_ATTRIBUTE_VALUE, yieldName);
486  }
487 
488  const char* const returnType = functionNode->Attribute("returnType");
489  if (returnType)
490  container.functions[functionName].returnType = returnType;
491 
492  container.functions[functionName].action = action;
493  container.functions[functionName].yield = yield;
494  }
495 
496  if (containerNodeName == "size") {
497  const char* const templateArg = containerNode->Attribute("templateParameter");
498  if (templateArg)
499  container.size_templateArgNo = strToInt<int>(templateArg);
500  } else if (containerNodeName == "access") {
501  const char* const indexArg = containerNode->Attribute("indexOperator");
502  if (indexArg)
503  container.arrayLike_indexOp = strcmp(indexArg, "array-like") == 0;
504  }
505  } else if (containerNodeName == "type") {
506  const char* const templateArg = containerNode->Attribute("templateParameter");
507  if (templateArg)
508  container.type_templateArgNo = strToInt<int>(templateArg);
509 
510  const char* const string = containerNode->Attribute("string");
511  if (string)
512  container.stdStringLike = strcmp(string, "std-like") == 0;
513  const char* const associative = containerNode->Attribute("associative");
514  if (associative)
515  container.stdAssociativeLike = strcmp(associative, "std-like") == 0;
516  const char* const unstable = containerNode->Attribute("unstable");
517  if (unstable) {
518  std::string unstableType = unstable;
519  if (unstableType.find("erase") != std::string::npos)
520  container.unstableErase = true;
521  if (unstableType.find("insert") != std::string::npos)
522  container.unstableInsert = true;
523  }
524  } else if (containerNodeName == "rangeItemRecordType") {
525  for (const tinyxml2::XMLElement* memberNode = node->FirstChildElement(); memberNode; memberNode = memberNode->NextSiblingElement()) {
526  const char *memberName = memberNode->Attribute("name");
527  const char *memberTemplateParameter = memberNode->Attribute("templateParameter");
529  member.name = memberName ? memberName : "";
530  member.templateParameter = memberTemplateParameter ? strToInt<int>(memberTemplateParameter) : -1;
531  container.rangeItemRecordType.emplace_back(std::move(member));
532  }
533  } else
534  unknown_elements.insert(containerNodeName);
535  }
536  }
537 
538  else if (nodename == "smart-pointer") {
539  const char *className = node->Attribute("class-name");
540  if (!className)
541  return Error(ErrorCode::MISSING_ATTRIBUTE, "class-name");
542  SmartPointer& smartPointer = smartPointers[className];
543  smartPointer.name = className;
544  for (const tinyxml2::XMLElement* smartPointerNode = node->FirstChildElement(); smartPointerNode;
545  smartPointerNode = smartPointerNode->NextSiblingElement()) {
546  const std::string smartPointerNodeName = smartPointerNode->Name();
547  if (smartPointerNodeName == "unique")
548  smartPointer.unique = true;
549  }
550  }
551 
552  else if (nodename == "type-checks") {
553  for (const tinyxml2::XMLElement *checkNode = node->FirstChildElement(); checkNode; checkNode = checkNode->NextSiblingElement()) {
554  const std::string &checkName = checkNode->Name();
555  for (const tinyxml2::XMLElement *checkTypeNode = checkNode->FirstChildElement(); checkTypeNode; checkTypeNode = checkTypeNode->NextSiblingElement()) {
556  const std::string checkTypeName = checkTypeNode->Name();
557  const char *typeName = checkTypeNode->GetText();
558  if (!typeName)
559  continue;
560  if (checkTypeName == "check")
561  mTypeChecks[std::pair<std::string,std::string>(checkName, typeName)] = TypeCheck::check;
562  else if (checkTypeName == "suppress")
563  mTypeChecks[std::pair<std::string,std::string>(checkName, typeName)] = TypeCheck::suppress;
564  else if (checkTypeName == "checkFiniteLifetime")
565  mTypeChecks[std::pair<std::string,std::string>(checkName, typeName)] = TypeCheck::checkFiniteLifetime;
566  }
567  }
568  }
569 
570  else if (nodename == "podtype") {
571  const char * const name = node->Attribute("name");
572  if (!name)
573  return Error(ErrorCode::MISSING_ATTRIBUTE, "name");
574  PodType podType = {0};
575  podType.stdtype = PodType::Type::NO;
576  const char * const stdtype = node->Attribute("stdtype");
577  if (stdtype) {
578  if (std::strcmp(stdtype, "bool") == 0)
579  podType.stdtype = PodType::Type::BOOL;
580  else if (std::strcmp(stdtype, "char") == 0)
581  podType.stdtype = PodType::Type::CHAR;
582  else if (std::strcmp(stdtype, "short") == 0)
583  podType.stdtype = PodType::Type::SHORT;
584  else if (std::strcmp(stdtype, "int") == 0)
585  podType.stdtype = PodType::Type::INT;
586  else if (std::strcmp(stdtype, "long") == 0)
587  podType.stdtype = PodType::Type::LONG;
588  else if (std::strcmp(stdtype, "long long") == 0)
590  }
591  const char * const size = node->Attribute("size");
592  if (size)
593  podType.size = strToInt<unsigned int>(size);
594  const char * const sign = node->Attribute("sign");
595  if (sign)
596  podType.sign = *sign;
597  for (const std::string &s : getnames(name))
598  mPodTypes[s] = podType;
599  }
600 
601  else if (nodename == "platformtype") {
602  const char * const type_name = node->Attribute("name");
603  if (type_name == nullptr)
604  return Error(ErrorCode::MISSING_ATTRIBUTE, "name");
605  const char *value = node->Attribute("value");
606  if (value == nullptr)
607  return Error(ErrorCode::MISSING_ATTRIBUTE, "value");
608  PlatformType type;
609  type.mType = value;
610  std::set<std::string> platform;
611  for (const tinyxml2::XMLElement *typenode = node->FirstChildElement(); typenode; typenode = typenode->NextSiblingElement()) {
612  const std::string typenodename = typenode->Name();
613  if (typenodename == "platform") {
614  const char * const type_attribute = typenode->Attribute("type");
615  if (type_attribute == nullptr)
616  return Error(ErrorCode::MISSING_ATTRIBUTE, "type");
617  platform.insert(type_attribute);
618  } else if (typenodename == "signed")
619  type.mSigned = true;
620  else if (typenodename == "unsigned")
621  type.mUnsigned = true;
622  else if (typenodename == "long")
623  type.mLong = true;
624  else if (typenodename == "pointer")
625  type.mPointer= true;
626  else if (typenodename == "ptr_ptr")
627  type.mPtrPtr = true;
628  else if (typenodename == "const_ptr")
629  type.mConstPtr = true;
630  else
631  unknown_elements.insert(typenodename);
632  }
633  if (platform.empty()) {
634  const PlatformType * const type_ptr = platform_type(type_name, emptyString);
635  if (type_ptr) {
636  if (*type_ptr == type)
637  return Error(ErrorCode::DUPLICATE_PLATFORM_TYPE, type_name);
638  return Error(ErrorCode::PLATFORM_TYPE_REDEFINED, type_name);
639  }
640  mPlatformTypes[type_name] = std::move(type);
641  } else {
642  for (const std::string &p : platform) {
643  const PlatformType * const type_ptr = platform_type(type_name, p);
644  if (type_ptr) {
645  if (*type_ptr == type)
646  return Error(ErrorCode::DUPLICATE_PLATFORM_TYPE, type_name);
647  return Error(ErrorCode::PLATFORM_TYPE_REDEFINED, type_name);
648  }
649  mPlatforms[p].mPlatformTypes[type_name] = type;
650  }
651  }
652  }
653 
654  else if (nodename == "entrypoint") {
655  const char * const type_name = node->Attribute("name");
656  if (type_name == nullptr)
657  return Error(ErrorCode::MISSING_ATTRIBUTE, "name");
658  mEntrypoints.emplace(type_name);
659  }
660 
661  else
662  unknown_elements.insert(nodename);
663  }
664  if (!unknown_elements.empty()) {
665  std::string str;
666  for (std::set<std::string>::const_iterator i = unknown_elements.cbegin(); i != unknown_elements.cend();) {
667  str += *i;
668  if (++i != unknown_elements.end())
669  str += ", ";
670  }
671  return Error(ErrorCode::UNKNOWN_ELEMENT, str);
672  }
673  return Error(ErrorCode::OK);
674 }
675 
676 Library::Error Library::loadFunction(const tinyxml2::XMLElement * const node, const std::string &name, std::set<std::string> &unknown_elements)
677 {
678  if (name.empty())
679  return Error(ErrorCode::OK);
680 
681  // TODO: write debug warning if we modify an existing entry
682  Function& func = functions[name];
683 
684  for (const tinyxml2::XMLElement *functionnode = node->FirstChildElement(); functionnode; functionnode = functionnode->NextSiblingElement()) {
685  const std::string functionnodename = functionnode->Name();
686  if (functionnodename == "noreturn") {
687  const char * const text = functionnode->GetText();
688  if (strcmp(text, "false") == 0)
690  else if (strcmp(text, "maybe") == 0)
692  else
693  mNoReturn[name] = FalseTrueMaybe::True; // Safe
694  } else if (functionnodename == "pure")
695  func.ispure = true;
696  else if (functionnodename == "const") {
697  func.ispure = true;
698  func.isconst = true; // a constant function is pure
699  } else if (functionnodename == "leak-ignore")
700  func.leakignore = true;
701  else if (functionnodename == "not-overlapping-data") {
702  NonOverlappingData nonOverlappingData;
703  nonOverlappingData.ptr1Arg = functionnode->IntAttribute("ptr1-arg", -1);
704  nonOverlappingData.ptr2Arg = functionnode->IntAttribute("ptr2-arg", -1);
705  nonOverlappingData.sizeArg = functionnode->IntAttribute("size-arg", -1);
706  nonOverlappingData.strlenArg = functionnode->IntAttribute("strlen-arg", -1);
707  nonOverlappingData.countArg = functionnode->IntAttribute("count-arg", -1);
708  mNonOverlappingData[name] = nonOverlappingData;
709  } else if (functionnodename == "use-retval") {
711  if (const char *type = functionnode->Attribute("type"))
712  if (std::strcmp(type, "error-code") == 0)
714  } else if (functionnodename == "returnValue") {
715  if (const char *expr = functionnode->GetText())
716  mReturnValue[name] = expr;
717  if (const char *type = functionnode->Attribute("type"))
718  mReturnValueType[name] = type;
719  if (const char *container = functionnode->Attribute("container"))
720  mReturnValueContainer[name] = strToInt<int>(container);
721  // cppcheck-suppress shadowFunction - TODO: fix this
722  if (const char *unknownReturnValues = functionnode->Attribute("unknownValues")) {
723  if (std::strcmp(unknownReturnValues, "all") == 0) {
724  std::vector<MathLib::bigint> values{LLONG_MIN, LLONG_MAX};
725  mUnknownReturnValues[name] = std::move(values);
726  }
727  }
728  } else if (functionnodename == "arg") {
729  const char* argNrString = functionnode->Attribute("nr");
730  if (!argNrString)
731  return Error(ErrorCode::MISSING_ATTRIBUTE, "nr");
732  const bool bAnyArg = strcmp(argNrString, "any") == 0;
733  const bool bVariadicArg = strcmp(argNrString, "variadic") == 0;
734  const int nr = (bAnyArg || bVariadicArg) ? -1 : strToInt<int>(argNrString);
735  ArgumentChecks &ac = func.argumentChecks[nr];
736  ac.optional = functionnode->Attribute("default") != nullptr;
737  ac.variadic = bVariadicArg;
738  const char * const argDirection = functionnode->Attribute("direction");
739  if (argDirection) {
740  const size_t argDirLen = strlen(argDirection);
741  if (!strncmp(argDirection, "in", argDirLen)) {
743  } else if (!strncmp(argDirection, "out", argDirLen)) {
745  } else if (!strncmp(argDirection, "inout", argDirLen)) {
747  }
748  }
749  for (const tinyxml2::XMLElement *argnode = functionnode->FirstChildElement(); argnode; argnode = argnode->NextSiblingElement()) {
750  const std::string argnodename = argnode->Name();
751  int indirect = 0;
752  const char * const indirectStr = argnode->Attribute("indirect");
753  if (indirectStr)
754  indirect = strToInt<int>(indirectStr);
755  if (argnodename == "not-bool")
756  ac.notbool = true;
757  else if (argnodename == "not-null")
758  ac.notnull = true;
759  else if (argnodename == "not-uninit")
760  ac.notuninit = indirect;
761  else if (argnodename == "formatstr")
762  ac.formatstr = true;
763  else if (argnodename == "strz")
764  ac.strz = true;
765  else if (argnodename == "valid") {
766  // Validate the validation expression
767  const char *p = argnode->GetText();
769  return Error(ErrorCode::BAD_ATTRIBUTE_VALUE, (!p ? "\"\"" : p));
770  // Set validation expression
771  ac.valid = p;
772  }
773  else if (argnodename == "minsize") {
774  const char *typeattr = argnode->Attribute("type");
775  if (!typeattr)
776  return Error(ErrorCode::MISSING_ATTRIBUTE, "type");
777 
779  if (strcmp(typeattr,"strlen")==0)
781  else if (strcmp(typeattr,"argvalue")==0)
783  else if (strcmp(typeattr,"sizeof")==0)
785  else if (strcmp(typeattr,"mul")==0)
787  else if (strcmp(typeattr,"value")==0)
789  else
790  return Error(ErrorCode::BAD_ATTRIBUTE_VALUE, typeattr);
791 
793  const char *valueattr = argnode->Attribute("value");
794  if (!valueattr)
795  return Error(ErrorCode::MISSING_ATTRIBUTE, "value");
796  long long minsizevalue = 0;
797  try {
798  minsizevalue = strToInt<long long>(valueattr);
799  } catch (const std::runtime_error&) {
800  return Error(ErrorCode::BAD_ATTRIBUTE_VALUE, valueattr);
801  }
802  if (minsizevalue <= 0)
803  return Error(ErrorCode::BAD_ATTRIBUTE_VALUE, valueattr);
804  ac.minsizes.emplace_back(type, 0);
805  ac.minsizes.back().value = minsizevalue;
806  } else {
807  const char *argattr = argnode->Attribute("arg");
808  if (!argattr)
809  return Error(ErrorCode::MISSING_ATTRIBUTE, "arg");
810  if (strlen(argattr) != 1 || argattr[0]<'0' || argattr[0]>'9')
811  return Error(ErrorCode::BAD_ATTRIBUTE_VALUE, argattr);
812 
813  ac.minsizes.reserve(type == ArgumentChecks::MinSize::Type::MUL ? 2 : 1);
814  ac.minsizes.emplace_back(type, argattr[0] - '0');
816  const char *arg2attr = argnode->Attribute("arg2");
817  if (!arg2attr)
818  return Error(ErrorCode::MISSING_ATTRIBUTE, "arg2");
819  if (strlen(arg2attr) != 1 || arg2attr[0]<'0' || arg2attr[0]>'9')
820  return Error(ErrorCode::BAD_ATTRIBUTE_VALUE, arg2attr);
821  ac.minsizes.back().arg2 = arg2attr[0] - '0';
822  }
823  }
824  const char* baseTypeAttr = argnode->Attribute("baseType"); // used by VALUE, ARGVALUE
825  if (baseTypeAttr)
826  ac.minsizes.back().baseType = baseTypeAttr;
827  }
828 
829  else if (argnodename == "iterator") {
830  ac.iteratorInfo.it = true;
831  const char* str = argnode->Attribute("type");
832  ac.iteratorInfo.first = (str && std::strcmp(str, "first") == 0);
833  ac.iteratorInfo.last = (str && std::strcmp(str, "last") == 0);
834  ac.iteratorInfo.container = argnode->IntAttribute("container", 0);
835  }
836 
837  else
838  unknown_elements.insert(argnodename);
839  }
840  if (ac.notuninit == 0)
841  ac.notuninit = ac.notnull ? 1 : 0;
842  } else if (functionnodename == "ignorefunction") {
843  func.ignore = true;
844  } else if (functionnodename == "formatstr") {
845  func.formatstr = true;
846  const tinyxml2::XMLAttribute* scan = functionnode->FindAttribute("scan");
847  const tinyxml2::XMLAttribute* secure = functionnode->FindAttribute("secure");
848  func.formatstr_scan = scan && scan->BoolValue();
849  func.formatstr_secure = secure && secure->BoolValue();
850  } else if (functionnodename == "warn") {
851  WarnInfo wi;
852  const char* const severity = functionnode->Attribute("severity");
853  if (severity == nullptr)
854  return Error(ErrorCode::MISSING_ATTRIBUTE, "severity");
855  wi.severity = severityFromString(severity);
856 
857  const char* const cstd = functionnode->Attribute("cstd");
858  if (cstd) {
859  if (!wi.standards.setC(cstd))
861  } else
863 
864  const char* const cppstd = functionnode->Attribute("cppstd");
865  if (cppstd) {
866  if (!wi.standards.setCPP(cppstd))
867  return Error(ErrorCode::BAD_ATTRIBUTE_VALUE, cppstd);
868  } else
870 
871  const char* const reason = functionnode->Attribute("reason");
872  const char* const alternatives = functionnode->Attribute("alternatives");
873  if (reason && alternatives) {
874  // Construct message
875  wi.message = std::string(reason) + " function '" + name + "' called. It is recommended to use ";
876  std::vector<std::string> alt = getnames(alternatives);
877  for (std::size_t i = 0; i < alt.size(); ++i) {
878  wi.message += "'" + alt[i] + "'";
879  if (i == alt.size() - 1)
880  wi.message += " instead.";
881  else if (i == alt.size() - 2)
882  wi.message += " or ";
883  else
884  wi.message += ", ";
885  }
886  } else {
887  const char * const message = functionnode->GetText();
888  if (!message)
889  return Error(ErrorCode::MISSING_ATTRIBUTE, "\"reason\" and \"alternatives\" or some text.");
890 
891  wi.message = message;
892  }
893 
894  functionwarn[name] = std::move(wi);
895  } else if (functionnodename == "container") {
896  const char* const action_ptr = functionnode->Attribute("action");
898  if (action_ptr) {
899  std::string actionName = action_ptr;
900  action = Container::actionFrom(actionName);
901  if (action == Container::Action::NO_ACTION)
902  return Error(ErrorCode::BAD_ATTRIBUTE_VALUE, actionName);
903  }
904  func.containerAction = action;
905 
906  const char* const yield_ptr = functionnode->Attribute("yields");
908  if (yield_ptr) {
909  std::string yieldName = yield_ptr;
910  yield = Container::yieldFrom(yieldName);
911  if (yield == Container::Yield::NO_YIELD)
912  return Error(ErrorCode::BAD_ATTRIBUTE_VALUE, yieldName);
913  }
914  func.containerYield = yield;
915 
916  const char* const returnType = functionnode->Attribute("returnType");
917  if (returnType)
918  func.returnType = returnType;
919  } else
920  unknown_elements.insert(functionnodename);
921  }
922  return Error(ErrorCode::OK);
923 }
924 
925 bool Library::isIntArgValid(const Token *ftok, int argnr, const MathLib::bigint argvalue) const
926 {
927  const ArgumentChecks *ac = getarg(ftok, argnr);
928  if (!ac || ac->valid.empty())
929  return true;
930  if (ac->valid.find('.') != std::string::npos)
931  return isFloatArgValid(ftok, argnr, argvalue);
932  TokenList tokenList(nullptr);
933  gettokenlistfromvalid(ac->valid, ftok->isCpp(), tokenList);
934  for (const Token *tok = tokenList.front(); tok; tok = tok->next()) {
935  if (tok->isNumber() && argvalue == MathLib::toBigNumber(tok->str()))
936  return true;
937  if (Token::Match(tok, "%num% : %num%") && argvalue >= MathLib::toBigNumber(tok->str()) && argvalue <= MathLib::toBigNumber(tok->strAt(2)))
938  return true;
939  if (Token::Match(tok, "%num% : ,") && argvalue >= MathLib::toBigNumber(tok->str()))
940  return true;
941  if ((!tok->previous() || tok->previous()->str() == ",") && Token::Match(tok,": %num%") && argvalue <= MathLib::toBigNumber(tok->strAt(1)))
942  return true;
943  }
944  return false;
945 }
946 
947 bool Library::isFloatArgValid(const Token *ftok, int argnr, double argvalue) const
948 {
949  const ArgumentChecks *ac = getarg(ftok, argnr);
950  if (!ac || ac->valid.empty())
951  return true;
952  TokenList tokenList(nullptr);
953  gettokenlistfromvalid(ac->valid, ftok->isCpp(), tokenList);
954  for (const Token *tok = tokenList.front(); tok; tok = tok->next()) {
955  if (Token::Match(tok, "%num% : %num%") && argvalue >= MathLib::toDoubleNumber(tok->str()) && argvalue <= MathLib::toDoubleNumber(tok->strAt(2)))
956  return true;
957  if (Token::Match(tok, "%num% : ,") && argvalue >= MathLib::toDoubleNumber(tok->str()))
958  return true;
959  if ((!tok->previous() || tok->previous()->str() == ",") && Token::Match(tok,": %num%") && argvalue <= MathLib::toDoubleNumber(tok->strAt(1)))
960  return true;
961  if (Token::Match(tok, "%num%") && MathLib::isFloat(tok->str()) && MathLib::isEqual(tok->str(), MathLib::toString(argvalue)))
962  return true;
963  if (Token::Match(tok, "! %num%") && MathLib::isFloat(tok->next()->str()))
964  return MathLib::isNotEqual(tok->next()->str(), MathLib::toString(argvalue));
965  }
966  return false;
967 }
968 
969 std::string Library::getFunctionName(const Token *ftok, bool &error) const
970 {
971  if (!ftok) {
972  error = true;
973  return "";
974  }
975  if (ftok->isName()) {
976  if (Token::simpleMatch(ftok->astParent(), "::"))
977  return ftok->str();
978  for (const Scope *scope = ftok->scope(); scope; scope = scope->nestedIn) {
979  if (!scope->isClassOrStruct())
980  continue;
981  const std::vector<Type::BaseInfo> &derivedFrom = scope->definedType->derivedFrom;
982  for (const Type::BaseInfo & baseInfo : derivedFrom) {
983  std::string name;
984  const Token* tok = baseInfo.nameTok; // baseInfo.name still contains template parameters, but is missing namespaces
985  if (tok->str() == "::")
986  tok = tok->next();
987  while (Token::Match(tok, "%name%|::")) {
988  name += tok->str();
989  tok = tok->next();
990  }
991  name += "::" + ftok->str();
992  if (functions.find(name) != functions.end() && matchArguments(ftok, name))
993  return name;
994  }
995  }
996  return ftok->str();
997  }
998  if (ftok->str() == "::") {
999  if (!ftok->astOperand2())
1000  return getFunctionName(ftok->astOperand1(), error);
1001  return getFunctionName(ftok->astOperand1(),error) + "::" + getFunctionName(ftok->astOperand2(),error);
1002  }
1003  if (ftok->str() == "." && ftok->astOperand1()) {
1004  const std::string type = astCanonicalType(ftok->astOperand1(), ftok->originalName() == "->");
1005  if (type.empty()) {
1006  error = true;
1007  return "";
1008  }
1009 
1010  return type + "::" + getFunctionName(ftok->astOperand2(),error);
1011  }
1012  error = true;
1013  return "";
1014 }
1015 
1016 std::string Library::getFunctionName(const Token *ftok) const
1017 {
1018  if (!Token::Match(ftok, "%name% )| (") && (ftok->strAt(-1) != "&" || ftok->previous()->astOperand2()))
1019  return "";
1020 
1021  // Lookup function name using AST..
1022  if (ftok->astParent()) {
1023  bool error = false;
1024  const Token * tok = ftok->astParent()->isUnaryOp("&") ? ftok->astParent()->astOperand1() : ftok->next()->astOperand1();
1025  std::string ret = getFunctionName(tok, error);
1026  if (error)
1027  return {};
1028  if (startsWith(ret, "::"))
1029  ret.erase(0, 2);
1030  return ret;
1031  }
1032 
1033  // Lookup function name without using AST..
1034  if (Token::simpleMatch(ftok->previous(), "."))
1035  return "";
1036  if (!Token::Match(ftok->tokAt(-2), "%name% ::"))
1037  return ftok->str();
1038  std::string ret(ftok->str());
1039  ftok = ftok->tokAt(-2);
1040  while (Token::Match(ftok, "%name% ::")) {
1041  ret = ftok->str() + "::" + ret;
1042  ftok = ftok->tokAt(-2);
1043  }
1044  return ret;
1045 }
1046 
1047 bool Library::isnullargbad(const Token *ftok, int argnr) const
1048 {
1049  const ArgumentChecks *arg = getarg(ftok, argnr);
1050  if (!arg) {
1051  // scan format string argument should not be null
1052  const std::string funcname = getFunctionName(ftok);
1053  const std::unordered_map<std::string, Function>::const_iterator it = functions.find(funcname);
1054  if (it != functions.cend() && it->second.formatstr && it->second.formatstr_scan)
1055  return true;
1056  }
1057  return arg && arg->notnull;
1058 }
1059 
1060 bool Library::isuninitargbad(const Token *ftok, int argnr, int indirect, bool *hasIndirect) const
1061 {
1062  const ArgumentChecks *arg = getarg(ftok, argnr);
1063  if (!arg) {
1064  // non-scan format string argument should not be uninitialized
1065  const std::string funcname = getFunctionName(ftok);
1066  const std::unordered_map<std::string, Function>::const_iterator it = functions.find(funcname);
1067  if (it != functions.cend() && it->second.formatstr && !it->second.formatstr_scan)
1068  return true;
1069  }
1070  if (hasIndirect && arg && arg->notuninit >= 1)
1071  *hasIndirect = true;
1072  return arg && arg->notuninit >= indirect;
1073 }
1074 
1075 
1076 /** get allocation info for function */
1078 {
1079  while (Token::simpleMatch(tok, "::"))
1080  tok = tok->astOperand2() ? tok->astOperand2() : tok->astOperand1();
1081  const std::string funcname = getFunctionName(tok);
1082  return isNotLibraryFunction(tok) && functions.find(funcname) != functions.end() ? nullptr : getAllocDealloc(mAlloc, funcname);
1083 }
1084 
1085 /** get deallocation info for function */
1087 {
1088  while (Token::simpleMatch(tok, "::"))
1089  tok = tok->astOperand2() ? tok->astOperand2() : tok->astOperand1();
1090  const std::string funcname = getFunctionName(tok);
1091  return isNotLibraryFunction(tok) && functions.find(funcname) != functions.end() ? nullptr : getAllocDealloc(mDealloc, funcname);
1092 }
1093 
1094 /** get reallocation info for function */
1096 {
1097  while (Token::simpleMatch(tok, "::"))
1098  tok = tok->astOperand2() ? tok->astOperand2() : tok->astOperand1();
1099  const std::string funcname = getFunctionName(tok);
1100  return isNotLibraryFunction(tok) && functions.find(funcname) != functions.end() ? nullptr : getAllocDealloc(mRealloc, funcname);
1101 }
1102 
1103 /** get allocation id for function */
1104 int Library::getAllocId(const Token *tok, int arg) const
1105 {
1106  const Library::AllocFunc* af = getAllocFuncInfo(tok);
1107  return (af && af->arg == arg) ? af->groupId : 0;
1108 }
1109 
1110 /** get deallocation id for function */
1111 int Library::getDeallocId(const Token *tok, int arg) const
1112 {
1113  const Library::AllocFunc* af = getDeallocFuncInfo(tok);
1114  return (af && af->arg == arg) ? af->groupId : 0;
1115 }
1116 
1117 /** get reallocation id for function */
1118 int Library::getReallocId(const Token *tok, int arg) const
1119 {
1120  const Library::AllocFunc* af = getReallocFuncInfo(tok);
1121  return (af && af->arg == arg) ? af->groupId : 0;
1122 }
1123 
1124 
1125 const Library::ArgumentChecks * Library::getarg(const Token *ftok, int argnr) const
1126 {
1127  if (isNotLibraryFunction(ftok))
1128  return nullptr;
1129  const std::unordered_map<std::string, Function>::const_iterator it1 = functions.find(getFunctionName(ftok));
1130  if (it1 == functions.cend())
1131  return nullptr;
1132  const std::map<int,ArgumentChecks>::const_iterator it2 = it1->second.argumentChecks.find(argnr);
1133  if (it2 != it1->second.argumentChecks.cend())
1134  return &it2->second;
1135  const std::map<int,ArgumentChecks>::const_iterator it3 = it1->second.argumentChecks.find(-1);
1136  if (it3 != it1->second.argumentChecks.cend())
1137  return &it3->second;
1138  return nullptr;
1139 }
1140 
1141 bool Library::isScopeNoReturn(const Token *end, std::string *unknownFunc) const
1142 {
1143  if (unknownFunc)
1144  unknownFunc->clear();
1145 
1146  if (Token::Match(end->tokAt(-2), "!!{ ; }")) {
1147  const Token *lastTop = end->tokAt(-2)->astTop();
1148  if (Token::simpleMatch(lastTop, "<<") &&
1149  Token::simpleMatch(lastTop->astOperand1(), "(") &&
1150  Token::Match(lastTop->astOperand1()->previous(), "%name% ("))
1151  return isnoreturn(lastTop->astOperand1()->previous());
1152  }
1153 
1154  if (!Token::simpleMatch(end->tokAt(-2), ") ; }"))
1155  return false;
1156 
1157  const Token *funcname = end->linkAt(-2)->previous();
1158  const Token *start = funcname;
1159  if (Token::Match(funcname->tokAt(-3),"( * %name% )")) {
1160  funcname = funcname->previous();
1161  start = funcname->tokAt(-3);
1162  } else if (funcname->isName()) {
1163  while (Token::Match(start, "%name%|.|::"))
1164  start = start->previous();
1165  } else {
1166  return false;
1167  }
1168  if (Token::Match(start,"[;{}]") && Token::Match(funcname, "%name% )| (")) {
1169  if (funcname->isKeyword())
1170  return false;
1171  if (funcname->str() == "exit")
1172  return true;
1173  if (!isnotnoreturn(funcname)) {
1174  if (unknownFunc && !isnoreturn(funcname))
1175  *unknownFunc = funcname->str();
1176  return true;
1177  }
1178  }
1179  return false;
1180 }
1181 
1182 const Library::Container* Library::detectContainerInternal(const Token* const typeStart, DetectContainer detect, bool* isIterator, bool withoutStd) const
1183 {
1184  const Token* firstLinkedTok = nullptr;
1185  for (const Token* tok = typeStart; tok && !tok->varId(); tok = tok->next()) {
1186  if (!tok->link())
1187  continue;
1188 
1189  firstLinkedTok = tok;
1190  break;
1191  }
1192 
1193  for (const std::pair<const std::string, Library::Container> & c : containers) {
1194  const Container& container = c.second;
1195  if (container.startPattern.empty())
1196  continue;
1197 
1198  const int offset = (withoutStd && startsWith(container.startPattern2, "std :: ")) ? 7 : 0;
1199 
1200  // If endPattern is undefined, it will always match, but itEndPattern has to be defined.
1201  if (detect != IteratorOnly && container.endPattern.empty()) {
1202  if (!Token::Match(typeStart, container.startPattern2.c_str() + offset))
1203  continue;
1204 
1205  if (isIterator)
1206  *isIterator = false;
1207  return &container;
1208  }
1209 
1210  if (!firstLinkedTok)
1211  continue;
1212 
1213  const bool matchedStartPattern = Token::Match(typeStart, container.startPattern2.c_str() + offset);
1214  if (!matchedStartPattern)
1215  continue;
1216 
1217  if (detect != ContainerOnly && Token::Match(firstLinkedTok->link(), container.itEndPattern.c_str())) {
1218  if (isIterator)
1219  *isIterator = true;
1220  return &container;
1221  }
1222  if (detect != IteratorOnly && Token::Match(firstLinkedTok->link(), container.endPattern.c_str())) {
1223  if (isIterator)
1224  *isIterator = false;
1225  return &container;
1226  }
1227  }
1228  return nullptr;
1229 }
1230 
1231 const Library::Container* Library::detectContainer(const Token* typeStart) const
1232 {
1233  return detectContainerInternal(typeStart, ContainerOnly);
1234 }
1235 
1236 const Library::Container* Library::detectIterator(const Token* typeStart) const
1237 {
1238  return detectContainerInternal(typeStart, IteratorOnly);
1239 }
1240 
1241 const Library::Container* Library::detectContainerOrIterator(const Token* typeStart, bool* isIterator, bool withoutStd) const
1242 {
1243  bool res;
1244  const Library::Container* c = detectContainerInternal(typeStart, Both, &res, withoutStd);
1245  if (c && isIterator)
1246  *isIterator = res;
1247  return c;
1248 }
1249 
1250 bool Library::isContainerYield(const Token * const cond, Library::Container::Yield y, const std::string& fallback)
1251 {
1252  if (!cond)
1253  return false;
1254  if (cond->str() == "(") {
1255  const Token* tok = cond->astOperand1();
1256  if (tok && tok->str() == ".") {
1257  if (tok->astOperand1() && tok->astOperand1()->valueType()) {
1258  if (const Library::Container *container = tok->astOperand1()->valueType()->container) {
1259  return tok->astOperand2() && y == container->getYield(tok->astOperand2()->str());
1260  }
1261  } else if (!fallback.empty()) {
1262  return Token::simpleMatch(cond, "( )") && cond->previous()->str() == fallback;
1263  }
1264  }
1265  }
1266  return false;
1267 }
1268 
1270 {
1271  if (Token::simpleMatch(cond, "(")) {
1272  const Token* tok = cond->astOperand1();
1273  if (tok && tok->str() == ".") {
1274  if (tok->astOperand1() && tok->astOperand1()->valueType()) {
1275  if (const Library::Container *container = tok->astOperand1()->valueType()->container) {
1276  if (tok->astOperand2())
1277  return container->getYield(tok->astOperand2()->str());
1278  }
1279  }
1280  }
1281  }
1283 }
1284 
1285 // returns true if ftok is not a library function
1286 bool Library::isNotLibraryFunction(const Token *ftok) const
1287 {
1288  if (ftok->isKeyword() || ftok->isStandardType())
1289  return true;
1290 
1291  if (ftok->function() && ftok->function()->nestedIn && ftok->function()->nestedIn->type != Scope::eGlobal)
1292  return true;
1293 
1294  // variables are not library functions.
1295  if (ftok->varId())
1296  return true;
1297 
1298  return !matchArguments(ftok, getFunctionName(ftok));
1299 }
1300 
1301 bool Library::matchArguments(const Token *ftok, const std::string &functionName) const
1302 {
1303  if (functionName.empty())
1304  return false;
1305  const int callargs = numberOfArgumentsWithoutAst(ftok);
1306  const std::unordered_map<std::string, Function>::const_iterator it = functions.find(functionName);
1307  if (it == functions.cend())
1308  return false;
1309  int args = 0;
1310  int firstOptionalArg = -1;
1311  for (const std::pair<const int, Library::ArgumentChecks> & argCheck : it->second.argumentChecks) {
1312  if (argCheck.first > args)
1313  args = argCheck.first;
1314  if (argCheck.second.optional && (firstOptionalArg == -1 || firstOptionalArg > argCheck.first))
1315  firstOptionalArg = argCheck.first;
1316 
1317  if (argCheck.second.formatstr || argCheck.second.variadic)
1318  return args <= callargs;
1319  }
1320  return (firstOptionalArg < 0) ? args == callargs : (callargs >= firstOptionalArg-1 && callargs <= args);
1321 }
1322 
1324 {
1325  if (isNotLibraryFunction(ftok))
1326  return nullptr;
1327  const std::map<std::string, WarnInfo>::const_iterator i = functionwarn.find(getFunctionName(ftok));
1328  if (i == functionwarn.cend())
1329  return nullptr;
1330  return &i->second;
1331 }
1332 
1334 {
1335  if (!p || !*p)
1336  return false;
1337 
1338  bool error = false;
1339  bool range = false;
1340  bool has_dot = false;
1341  bool has_E = false;
1342 
1343  error = *p == '.';
1344  for (; *p; p++) {
1345  if (std::isdigit(*p)) {
1346  error |= (*(p + 1) == '-');
1347  }
1348  else if (*p == ':') {
1349  // cppcheck-suppress bitwiseOnBoolean - TODO: fix this
1350  error |= range | (*(p + 1) == '.');
1351  range = true;
1352  has_dot = false;
1353  has_E = false;
1354  }
1355  else if ((*p == '-') || (*p == '+')) {
1356  error |= (!std::isdigit(*(p + 1)));
1357  }
1358  else if (*p == ',') {
1359  range = false;
1360  error |= *(p + 1) == '.';
1361  has_dot = false;
1362  has_E = false;
1363  } else if (*p == '.') {
1364  // cppcheck-suppress bitwiseOnBoolean - TODO: fix this
1365  error |= has_dot | (!std::isdigit(*(p + 1)));
1366  has_dot = true;
1367  } else if (*p == 'E' || *p == 'e') {
1368  error |= has_E;
1369  has_E = true;
1370  } else if (*p == '!') {
1371  error |= !((*(p+1) == '-') || (*(p+1) == '+') || (std::isdigit(*(p + 1))));
1372  } else
1373  return false;
1374  }
1375  return !error;
1376 }
1377 
1378 bool Library::formatstr_function(const Token* ftok) const
1379 {
1380  if (isNotLibraryFunction(ftok))
1381  return false;
1382 
1383  const std::unordered_map<std::string, Function>::const_iterator it = functions.find(getFunctionName(ftok));
1384  if (it != functions.cend())
1385  return it->second.formatstr;
1386  return false;
1387 }
1388 
1389 int Library::formatstr_argno(const Token* ftok) const
1390 {
1391  const std::map<int, Library::ArgumentChecks>& argumentChecksFunc = functions.at(getFunctionName(ftok)).argumentChecks;
1392  auto it = std::find_if(argumentChecksFunc.cbegin(), argumentChecksFunc.cend(), [](const std::pair<const int, Library::ArgumentChecks>& a) {
1393  return a.second.formatstr;
1394  });
1395  return it == argumentChecksFunc.cend() ? -1 : it->first - 1;
1396 }
1397 
1398 bool Library::formatstr_scan(const Token* ftok) const
1399 {
1400  return functions.at(getFunctionName(ftok)).formatstr_scan;
1401 }
1402 
1403 bool Library::formatstr_secure(const Token* ftok) const
1404 {
1405  return functions.at(getFunctionName(ftok)).formatstr_secure;
1406 }
1407 
1409 {
1410  if (isNotLibraryFunction(ftok))
1411  return nullptr;
1412  const std::unordered_map<std::string, NonOverlappingData>::const_iterator it = mNonOverlappingData.find(getFunctionName(ftok));
1413  return (it != mNonOverlappingData.cend()) ? &it->second : nullptr;
1414 }
1415 
1417 {
1418  if (isNotLibraryFunction(ftok)) {
1419  if (Token::simpleMatch(ftok->astParent(), ".")) {
1420  const Token* contTok = ftok->astParent()->astOperand1();
1421  using Yield = Library::Container::Yield;
1422  const Yield yield = astContainerYield(contTok);
1423  if (yield == Yield::START_ITERATOR || yield == Yield::END_ITERATOR || yield == Yield::AT_INDEX ||
1424  yield == Yield::SIZE || yield == Yield::EMPTY || yield == Yield::BUFFER || yield == Yield::BUFFER_NT ||
1425  ((yield == Yield::ITEM || yield == Yield::ITERATOR) && astContainerAction(contTok) == Library::Container::Action::NO_ACTION))
1427  }
1429  }
1430  const std::unordered_map<std::string, Function>::const_iterator it = functions.find(getFunctionName(ftok));
1431  if (it != functions.cend())
1432  return it->second.useretval;
1434 }
1435 
1436 const std::string& Library::returnValue(const Token *ftok) const
1437 {
1438  if (isNotLibraryFunction(ftok))
1439  return emptyString;
1440  const std::map<std::string, std::string>::const_iterator it = mReturnValue.find(getFunctionName(ftok));
1441  return it != mReturnValue.cend() ? it->second : emptyString;
1442 }
1443 
1444 const std::string& Library::returnValueType(const Token *ftok) const
1445 {
1446  if (isNotLibraryFunction(ftok)) {
1447  if (Token::simpleMatch(ftok->astParent(), ".") && ftok->astParent()->astOperand1()) {
1448  const Token* contTok = ftok->astParent()->astOperand1();
1449  if (contTok->valueType() && contTok->valueType()->container)
1450  return contTok->valueType()->container->getReturnType(ftok->str());
1451  }
1452  return emptyString;
1453  }
1454  const std::map<std::string, std::string>::const_iterator it = mReturnValueType.find(getFunctionName(ftok));
1455  return it != mReturnValueType.cend() ? it->second : emptyString;
1456 }
1457 
1458 int Library::returnValueContainer(const Token *ftok) const
1459 {
1460  if (isNotLibraryFunction(ftok))
1461  return -1;
1462  const std::map<std::string, int>::const_iterator it = mReturnValueContainer.find(getFunctionName(ftok));
1463  return it != mReturnValueContainer.cend() ? it->second : -1;
1464 }
1465 
1466 std::vector<MathLib::bigint> Library::unknownReturnValues(const Token *ftok) const
1467 {
1468  if (isNotLibraryFunction(ftok))
1469  return std::vector<MathLib::bigint>();
1470  const std::map<std::string, std::vector<MathLib::bigint>>::const_iterator it = mUnknownReturnValues.find(getFunctionName(ftok));
1471  return (it == mUnknownReturnValues.cend()) ? std::vector<MathLib::bigint>() : it->second;
1472 }
1473 
1475 {
1476  if (isNotLibraryFunction(ftok))
1477  return nullptr;
1478  const std::unordered_map<std::string, Function>::const_iterator it1 = functions.find(getFunctionName(ftok));
1479  if (it1 == functions.cend())
1480  return nullptr;
1481  return &it1->second;
1482 }
1483 
1484 
1485 bool Library::hasminsize(const Token *ftok) const
1486 {
1487  if (isNotLibraryFunction(ftok))
1488  return false;
1489  const std::unordered_map<std::string, Function>::const_iterator it = functions.find(getFunctionName(ftok));
1490  if (it == functions.cend())
1491  return false;
1492  return std::any_of(it->second.argumentChecks.cbegin(), it->second.argumentChecks.cend(), [](const std::pair<const int, Library::ArgumentChecks>& a) {
1493  return !a.second.minsizes.empty();
1494  });
1495 }
1496 
1498 {
1499  const ArgumentChecks* arg = getarg(ftok, argnr);
1500  if (arg)
1501  return arg->direction;
1502  if (formatstr_function(ftok)) {
1503  const int fs_argno = formatstr_argno(ftok);
1504  if (fs_argno >= 0 && argnr >= fs_argno) {
1505  if (formatstr_scan(ftok))
1508  }
1509  }
1511 }
1512 
1513 bool Library::ignorefunction(const std::string& functionName) const
1514 {
1515  const std::unordered_map<std::string, Function>::const_iterator it = functions.find(functionName);
1516  if (it != functions.cend())
1517  return it->second.ignore;
1518  return false;
1519 }
1520 bool Library::isUse(const std::string& functionName) const
1521 {
1522  const std::unordered_map<std::string, Function>::const_iterator it = functions.find(functionName);
1523  if (it != functions.cend())
1524  return it->second.use;
1525  return false;
1526 }
1527 bool Library::isLeakIgnore(const std::string& functionName) const
1528 {
1529  const std::unordered_map<std::string, Function>::const_iterator it = functions.find(functionName);
1530  if (it != functions.cend())
1531  return it->second.leakignore;
1532  return false;
1533 }
1534 bool Library::isFunctionConst(const std::string& functionName, bool pure) const
1535 {
1536  const std::unordered_map<std::string, Function>::const_iterator it = functions.find(functionName);
1537  if (it != functions.cend())
1538  return pure ? it->second.ispure : it->second.isconst;
1539  return false;
1540 }
1541 bool Library::isFunctionConst(const Token *ftok) const
1542 {
1543  if (ftok->function() && ftok->function()->isConst())
1544  return true;
1545  if (isNotLibraryFunction(ftok)) {
1546  if (Token::simpleMatch(ftok->astParent(), ".")) {
1547  using Yield = Library::Container::Yield;
1548  const Yield yield = astContainerYield(ftok->astParent()->astOperand1());
1549  if (yield == Yield::EMPTY || yield == Yield::SIZE || yield == Yield::BUFFER_NT)
1550  return true;
1551  }
1552  return false;
1553  }
1554  const std::unordered_map<std::string, Function>::const_iterator it = functions.find(getFunctionName(ftok));
1555  return (it != functions.cend() && it->second.isconst);
1556 }
1557 
1558 bool Library::isnoreturn(const Token *ftok) const
1559 {
1560  if (ftok->function() && ftok->function()->isAttributeNoreturn())
1561  return true;
1562  if (isNotLibraryFunction(ftok)) {
1563  if (Token::simpleMatch(ftok->astParent(), ".")) {
1564  const Token* contTok = ftok->astParent()->astOperand1();
1567  return false;
1568  }
1569  return false;
1570  }
1571  const std::unordered_map<std::string, FalseTrueMaybe>::const_iterator it = mNoReturn.find(getFunctionName(ftok));
1572  if (it == mNoReturn.end())
1573  return false;
1574  if (it->second == FalseTrueMaybe::Maybe)
1575  return true;
1576  return it->second == FalseTrueMaybe::True;
1577 }
1578 
1579 bool Library::isnotnoreturn(const Token *ftok) const
1580 {
1581  if (ftok->function() && ftok->function()->isAttributeNoreturn())
1582  return false;
1583  if (isNotLibraryFunction(ftok))
1584  return false;
1585  const std::unordered_map<std::string, FalseTrueMaybe>::const_iterator it = mNoReturn.find(getFunctionName(ftok));
1586  if (it == mNoReturn.end())
1587  return false;
1588  if (it->second == FalseTrueMaybe::Maybe)
1589  return false;
1590  return it->second == FalseTrueMaybe::False;
1591 }
1592 
1593 bool Library::markupFile(const std::string &path) const
1594 {
1596 }
1597 
1598 bool Library::processMarkupAfterCode(const std::string &path) const
1599 {
1600  const std::map<std::string, bool>::const_iterator it = mProcessAfterCode.find(Path::getFilenameExtensionInLowerCase(path));
1601  return (it == mProcessAfterCode.cend() || it->second);
1602 }
1603 
1604 bool Library::reportErrors(const std::string &path) const
1605 {
1606  const std::map<std::string, bool>::const_iterator it = mReportErrors.find(Path::getFilenameExtensionInLowerCase(path));
1607  return (it == mReportErrors.cend() || it->second);
1608 }
1609 
1610 bool Library::isexecutableblock(const std::string &file, const std::string &token) const
1611 {
1612  const std::unordered_map<std::string, CodeBlock>::const_iterator it = mExecutableBlocks.find(Path::getFilenameExtensionInLowerCase(file));
1613  return (it != mExecutableBlocks.cend() && it->second.isBlock(token));
1614 }
1615 
1616 int Library::blockstartoffset(const std::string &file) const
1617 {
1618  int offset = -1;
1619  const std::unordered_map<std::string, CodeBlock>::const_iterator map_it
1621 
1622  if (map_it != mExecutableBlocks.end()) {
1623  offset = map_it->second.offset();
1624  }
1625  return offset;
1626 }
1627 
1628 const std::string& Library::blockstart(const std::string &file) const
1629 {
1630  const std::unordered_map<std::string, CodeBlock>::const_iterator map_it
1632 
1633  if (map_it != mExecutableBlocks.end()) {
1634  return map_it->second.start();
1635  }
1636  return emptyString;
1637 }
1638 
1639 const std::string& Library::blockend(const std::string &file) const
1640 {
1641  const std::unordered_map<std::string, CodeBlock>::const_iterator map_it
1643 
1644  if (map_it != mExecutableBlocks.end()) {
1645  return map_it->second.end();
1646  }
1647  return emptyString;
1648 }
1649 
1650 bool Library::iskeyword(const std::string &file, const std::string &keyword) const
1651 {
1652  const std::map<std::string, std::set<std::string>>::const_iterator it =
1654  return (it != mKeywords.end() && it->second.count(keyword));
1655 }
1656 
1657 bool Library::isimporter(const std::string& file, const std::string &importer) const
1658 {
1659  const std::map<std::string, std::set<std::string>>::const_iterator it =
1661  return (it != mImporters.end() && it->second.count(importer) > 0);
1662 }
1663 
1665 {
1666  if (!tok)
1667  return nullptr;
1668  if (Token::Match(tok->tokAt(-2), ". %name% (")) {
1669  const Token* containerTok = tok->tokAt(-2)->astOperand1();
1670  if (!astIsContainer(containerTok))
1671  return nullptr;
1672  if (containerTok->valueType()->container &&
1673  containerTok->valueType()->container->getYield(tok->strAt(-1)) == yield)
1674  return containerTok;
1675  if (yield == Library::Container::Yield::EMPTY && Token::simpleMatch(tok->tokAt(-1), "empty ( )"))
1676  return containerTok;
1677  if (yield == Library::Container::Yield::SIZE && Token::Match(tok->tokAt(-1), "size|length ( )"))
1678  return containerTok;
1679  } else if (Token::Match(tok->previous(), "%name% (")) {
1680  if (const Library::Function* f = this->getFunction(tok->previous())) {
1681  if (f->containerYield == yield) {
1682  return tok->astOperand2();
1683  }
1684  }
1685  }
1686  return nullptr;
1687 }
1688 
1689 // cppcheck-suppress unusedFunction
1691 {
1692  if (!tok)
1693  return nullptr;
1694  if (Token::Match(tok->tokAt(-2), ". %name% (")) {
1695  const Token* containerTok = tok->tokAt(-2)->astOperand1();
1696  if (!astIsContainer(containerTok))
1697  return nullptr;
1698  if (containerTok->valueType()->container &&
1699  containerTok->valueType()->container->getAction(tok->strAt(-1)) == action)
1700  return containerTok;
1701  if (Token::simpleMatch(tok->tokAt(-1), "empty ( )"))
1702  return containerTok;
1703  } else if (Token::Match(tok->previous(), "%name% (")) {
1704  if (const Library::Function* f = this->getFunction(tok->previous())) {
1705  if (f->containerAction == action) {
1706  return tok->astOperand2();
1707  }
1708  }
1709  }
1710  return nullptr;
1711 }
1712 
1713 bool Library::isSmartPointer(const Token* tok) const
1714 {
1715  return detectSmartPointer(tok);
1716 }
1717 
1718 const Library::SmartPointer* Library::detectSmartPointer(const Token* tok, bool withoutStd) const
1719 {
1720  std::string typestr = withoutStd ? "std::" : "";
1721  while (Token::Match(tok, "%name%|::")) {
1722  typestr += tok->str();
1723  tok = tok->next();
1724  }
1725  auto it = smartPointers.find(typestr);
1726  if (it == smartPointers.end())
1727  return nullptr;
1728  return &it->second;
1729 }
1730 
1732 {
1733  if (!tok)
1734  return nullptr;
1735  // TODO: Support dereferencing iterators
1736  // TODO: Support dereferencing with ->
1737  if (tok->isUnaryOp("*") && astIsPointer(tok->astOperand1())) {
1738  for (const ValueFlow::Value& v:tok->astOperand1()->values()) {
1739  if (!v.isLocalLifetimeValue())
1740  continue;
1741  if (v.lifetimeKind != ValueFlow::Value::LifetimeKind::Address)
1742  continue;
1743  return getLibraryContainer(v.tokvalue);
1744  }
1745  }
1746  if (!tok->valueType())
1747  return nullptr;
1748  return tok->valueType()->container;
1749 }
1750 
1751 Library::TypeCheck Library::getTypeCheck(std::string check, std::string typeName) const
1752 {
1753  auto it = mTypeChecks.find(std::pair<std::string, std::string>(std::move(check), std::move(typeName)));
1754  return it == mTypeChecks.end() ? TypeCheck::def : it->second;
1755 }
1756 
1757 bool Library::hasAnyTypeCheck(const std::string& typeName) const
1758 {
1759  return std::any_of(mTypeChecks.begin(), mTypeChecks.end(), [&](const std::pair<std::pair<std::string, std::string>, Library::TypeCheck>& tc) {
1760  return tc.first.second == typeName;
1761  });
1762 }
1763 
1764 std::shared_ptr<Token> createTokenFromExpression(const std::string& returnValue,
1765  const Settings& settings,
1766  bool cpp,
1767  std::unordered_map<nonneg int, const Token*>* lookupVarId)
1768 {
1769  std::shared_ptr<TokenList> tokenList = std::make_shared<TokenList>(&settings);
1770  {
1771  const std::string code = "return " + returnValue + ";";
1772  std::istringstream istr(code);
1773  if (!tokenList->createTokens(istr, cpp ? Standards::Language::CPP : Standards::Language::C))
1774  return nullptr;
1775  }
1776 
1777  // combine operators, set links, etc..
1778  std::stack<Token*> lpar;
1779  for (Token* tok2 = tokenList->front(); tok2; tok2 = tok2->next()) {
1780  if (Token::Match(tok2, "[!<>=] =")) {
1781  tok2->str(tok2->str() + "=");
1782  tok2->deleteNext();
1783  } else if (tok2->str() == "(")
1784  lpar.push(tok2);
1785  else if (tok2->str() == ")") {
1786  if (lpar.empty())
1787  return nullptr;
1788  Token::createMutualLinks(lpar.top(), tok2);
1789  lpar.pop();
1790  }
1791  }
1792  if (!lpar.empty())
1793  return nullptr;
1794 
1795  // set varids
1796  for (Token* tok2 = tokenList->front(); tok2; tok2 = tok2->next()) {
1797  if (!startsWith(tok2->str(), "arg"))
1798  continue;
1799  nonneg int const id = strToInt<nonneg int>(tok2->str().c_str() + 3);
1800  tok2->varId(id);
1801  if (lookupVarId)
1802  (*lookupVarId)[id] = tok2;
1803  }
1804 
1805  // Evaluate expression
1806  tokenList->createAst();
1807  Token* expr = tokenList->front()->astOperand1();
1808  ValueFlow::valueFlowConstantFoldAST(expr, settings);
1809  return {tokenList, expr};
1810 }
int numberOfArgumentsWithoutAst(const Token *start)
Get number of arguments without using AST.
Definition: astutils.cpp:3067
bool astIsContainer(const Token *tok)
Definition: astutils.cpp:244
bool astIsPointer(const Token *tok)
Definition: astutils.cpp:220
Library::Container::Action astContainerAction(const Token *tok, const Token **ftok)
Definition: astutils.cpp:287
std::string astCanonicalType(const Token *expr, bool pointedToType)
Get canonical type of expression.
Definition: astutils.cpp:326
Library::Container::Yield astContainerYield(const Token *tok, const Token **ftok)
Definition: astutils.cpp:297
static int sign(const T v)
static bool isIterator(const Variable *var, bool &inconclusiveType)
Definition: checkstl.cpp:419
const std::string & getReturnType(const std::string &function) const
Definition: library.h:262
bool hasInitializerListConstructor
Definition: library.h:243
static Yield yieldFrom(const std::string &yieldName)
Definition: library.cpp:144
int size_templateArgNo
Definition: library.h:238
static Action actionFrom(const std::string &actionName)
Definition: library.cpp:166
std::string startPattern2
Definition: library.h:234
bool arrayLike_indexOp
Definition: library.h:239
std::vector< RangeItemRecordTypeItem > rangeItemRecordType
Definition: library.h:237
std::map< std::string, Function > functions
Definition: library.h:235
int type_templateArgNo
Definition: library.h:236
Action getAction(const std::string &function) const
Definition: library.h:248
std::string startPattern
Definition: library.h:234
std::string endPattern
Definition: library.h:234
Yield getYield(const std::string &function) const
Definition: library.h:255
std::string itEndPattern
Definition: library.h:234
bool stdAssociativeLike
Definition: library.h:241
ErrorCode errorcode
Definition: library.h:74
const Container * detectContainerOrIterator(const Token *typeStart, bool *isIterator=nullptr, bool withoutStd=false) const
Definition: library.cpp:1241
bool isexecutableblock(const std::string &file, const std::string &token) const
Definition: library.cpp:1610
std::map< std::string, AllocFunc > mAlloc
Definition: library.h:572
std::set< std::string > mFiles
Definition: library.h:571
ArgumentChecks::Direction getArgDirection(const Token *ftok, int argnr) const
Definition: library.cpp:1497
static bool isresource(const int id)
is allocation type resource?
Definition: library.h:148
std::map< std::string, std::vector< MathLib::bigint > > mUnknownReturnValues
Definition: library.h:579
bool isuninitargbad(const Token *ftok, int argnr, int indirect=0, bool *hasIndirect=nullptr) const
Definition: library.cpp:1060
int getAllocId(const Token *tok, int arg) const
get allocation id for function
Definition: library.cpp:1104
static bool isContainerYield(const Token *const cond, Library::Container::Yield y, const std::string &fallback=emptyString)
Definition: library.cpp:1250
std::vector< MathLib::bigint > unknownReturnValues(const Token *ftok) const
Definition: library.cpp:1466
const NonOverlappingData * getNonOverlappingData(const Token *ftok) const
Definition: library.cpp:1408
const Token * getContainerFromAction(const Token *tok, Container::Action action) const
Definition: library.cpp:1690
bool isnullargbad(const Token *ftok, int argnr) const
Definition: library.cpp:1047
Error loadFunction(const tinyxml2::XMLElement *const node, const std::string &name, std::set< std::string > &unknown_elements)
Definition: library.cpp:676
const Token * getContainerFromYield(const Token *tok, Container::Yield yield) const
Definition: library.cpp:1664
bool formatstr_function(const Token *ftok) const
Definition: library.cpp:1378
const SmartPointer * detectSmartPointer(const Token *tok, bool withoutStd=false) const
Definition: library.cpp:1718
std::map< std::string, std::set< std::string > > mKeywords
Definition: library.h:583
const Container * detectIterator(const Token *typeStart) const
Definition: library.cpp:1236
bool hasAnyTypeCheck(const std::string &typeName) const
Definition: library.cpp:1757
bool isSmartPointer(const Token *tok) const
Definition: library.cpp:1713
std::map< std::string, std::set< std::string > > mImporters
Definition: library.h:586
std::map< std::pair< std::string, std::string >, TypeCheck > mTypeChecks
Definition: library.h:591
static bool ismemory(const int id)
is allocation type memory?
Definition: library.h:140
int getDeallocId(const Token *tok, int arg) const
get deallocation id for function
Definition: library.cpp:1111
bool isFloatArgValid(const Token *ftok, int argnr, double argvalue) const
Definition: library.cpp:947
const std::string & blockstart(const std::string &file) const
Definition: library.cpp:1628
const std::string & returnValue(const Token *ftok) const
Definition: library.cpp:1436
bool isIntArgValid(const Token *ftok, int argnr, const MathLib::bigint argvalue) const
Definition: library.cpp:925
bool formatstr_secure(const Token *ftok) const
Definition: library.cpp:1403
int mAllocId
Definition: library.h:570
static const AllocFunc * getAllocDealloc(const std::map< std::string, AllocFunc > &data, const std::string &name)
Definition: library.h:599
bool isnoreturn(const Token *ftok) const
Definition: library.cpp:1558
bool hasminsize(const Token *ftok) const
Definition: library.cpp:1485
bool isLeakIgnore(const std::string &functionName) const
Definition: library.cpp:1527
std::map< std::string, ExportedFunctions > mExporters
Definition: library.h:585
bool isnotnoreturn(const Token *ftok) const
Definition: library.cpp:1579
const ArgumentChecks * getarg(const Token *ftok, int argnr) const
Definition: library.cpp:1125
int getReallocId(const Token *tok, int arg) const
get reallocation id for function
Definition: library.cpp:1118
const std::string & blockend(const std::string &file) const
Definition: library.cpp:1639
Error load(const char exename[], const char path[])
Definition: library.cpp:68
UseRetValType getUseRetValType(const Token *ftok) const
Definition: library.cpp:1416
UseRetValType
Definition: library.h:182
const AllocFunc * getAllocFuncInfo(const Token *tok) const
get allocation info for function
Definition: library.cpp:1077
DetectContainer
Definition: library.h:604
@ Both
Definition: library.h:604
@ IteratorOnly
Definition: library.h:604
@ ContainerOnly
Definition: library.h:604
const Library::Container * detectContainerInternal(const Token *typeStart, DetectContainer detect, bool *isIterator=nullptr, bool withoutStd=false) const
Definition: library.cpp:1182
int formatstr_argno(const Token *ftok) const
Definition: library.cpp:1389
std::unordered_set< std::string > mEntrypoints
Definition: library.h:593
std::map< std::string, AllocFunc > mDealloc
Definition: library.h:573
static Library::Container::Yield getContainerYield(const Token *const cond)
Definition: library.cpp:1269
const WarnInfo * getWarnInfo(const Token *ftok) const
Definition: library.cpp:1323
bool isScopeNoReturn(const Token *end, std::string *unknownFunc) const
Definition: library.cpp:1141
std::set< std::string > mMarkupExtensions
Definition: library.h:582
TypeCheck getTypeCheck(std::string check, std::string typeName) const
Definition: library.cpp:1751
static bool isCompliantValidationExpression(const char *p)
Definition: library.cpp:1333
const AllocFunc * getReallocFuncInfo(const Token *tok) const
get reallocation info for function
Definition: library.cpp:1095
std::set< std::string > defines
Definition: library.h:434
TypeCheck
Suppress/check a type.
Definition: library.h:503
std::map< std::string, std::string > mReturnValue
Definition: library.h:576
std::map< std::string, int > mReturnValueContainer
Definition: library.h:578
bool reportErrors(const std::string &path) const
Definition: library.cpp:1604
const Function * getFunction(const Token *ftok) const
Definition: library.cpp:1474
bool iskeyword(const std::string &file, const std::string &keyword) const
Definition: library.cpp:1650
std::map< std::string, bool > mProcessAfterCode
Definition: library.h:581
std::string getFunctionName(const Token *ftok) const
Get function name for function call.
Definition: library.cpp:1016
std::unordered_map< std::string, CodeBlock > mExecutableBlocks
Definition: library.h:584
const AllocFunc * getDeallocFuncInfo(const Token *tok) const
get deallocation info for function
Definition: library.cpp:1086
std::map< std::string, bool > mReportErrors
Definition: library.h:580
std::map< std::string, std::string > mReturnValueType
Definition: library.h:577
std::map< std::string, PlatformType > mPlatformTypes
Definition: library.h:589
bool isUse(const std::string &functionName) const
Definition: library.cpp:1520
int returnValueContainer(const Token *ftok) const
Definition: library.cpp:1458
bool markupFile(const std::string &path) const
Definition: library.cpp:1593
std::map< std::string, WarnInfo > functionwarn
Definition: library.h:174
std::unordered_map< std::string, Container > containers
Definition: library.h:270
std::unordered_map< std::string, SmartPointer > smartPointers
Definition: library.h:441
std::unordered_map< std::string, PodType > mPodTypes
Definition: library.h:588
bool isimporter(const std::string &file, const std::string &importer) const
Definition: library.cpp:1657
std::unordered_map< std::string, NonOverlappingData > mNonOverlappingData
Definition: library.h:592
bool isNotLibraryFunction(const Token *ftok) const
Definition: library.cpp:1286
std::unordered_map< std::string, FalseTrueMaybe > mNoReturn
Definition: library.h:575
const Container * detectContainer(const Token *typeStart) const
Definition: library.cpp:1231
std::map< std::string, AllocFunc > mRealloc
Definition: library.h:574
const std::string & returnValueType(const Token *ftok) const
Definition: library.cpp:1444
std::unordered_map< std::string, Function > functions
Definition: library.h:330
bool matchArguments(const Token *ftok, const std::string &functionName) const
Definition: library.cpp:1301
bool processMarkupAfterCode(const std::string &path) const
Definition: library.cpp:1598
bool isFunctionConst(const std::string &functionName, bool pure) const
Definition: library.cpp:1534
bool ignorefunction(const std::string &functionName) const
Definition: library.cpp:1513
const PlatformType * platform_type(const std::string &name, const std::string &platform) const
Definition: library.h:485
int blockstartoffset(const std::string &file) const
Definition: library.cpp:1616
std::map< std::string, int > mReflection
Definition: library.h:587
std::map< std::string, Platform > mPlatforms
Definition: library.h:590
bool formatstr_scan(const Token *ftok) const
Definition: library.cpp:1398
static std::string toString(T value)=delete
static bool isEqual(const std::string &first, const std::string &second)
Definition: mathlib.cpp:1209
long long bigint
Definition: mathlib.h:68
static bool isNotEqual(const std::string &first, const std::string &second)
Definition: mathlib.cpp:1216
static bigint toBigNumber(const std::string &str)
for conversion of numeric literals - for atoi-like conversions please use strToInt()
Definition: mathlib.cpp:368
static bool isFloat(const std::string &str)
Definition: mathlib.cpp:535
static double toDoubleNumber(const std::string &str)
for conversion of numeric literals
Definition: mathlib.cpp:487
static std::string getFilenameExtension(const std::string &path, bool lowercase=false)
Get an extension of the filename.
Definition: path.cpp:109
static std::string fromNativeSeparators(std::string path)
Convert path to use internal path separators.
Definition: path.cpp:75
static std::string getCurrentExecutablePath(const char *fallback)
Returns the absolute path to the current executable.
Definition: path.cpp:143
static std::string getPathFromFilename(const std::string &filename)
Lookup the path part from a filename (e.g., '/tmp/a.h' -> '/tmp/', 'a.h' -> '')
Definition: path.cpp:88
static std::string getAbsoluteFilePath(const std::string &filePath)
Get an absolute file path from a relative one.
Definition: path.cpp:284
static std::string getFilenameExtensionInLowerCase(const std::string &path)
Get an extension of the filename in lower case.
Definition: path.cpp:124
This is just a container for general settings so that we don't need to pass individual values to func...
Definition: settings.h:95
const Token * front() const
get first token of list
Definition: tokenlist.h:119
bool createTokens(std::istream &code, const std::string &file0)
Create tokens from code.
Definition: tokenlist.cpp:336
The token list that the TokenList generates is a linked-list of this class.
Definition: token.h:150
void str(T &&s)
Definition: token.h:179
Token * astTop()
Definition: token.h:1416
static bool Match(const Token *tok, const char pattern[], nonneg int varid=0)
Match given token (or list of tokens) to a pattern list.
Definition: token.cpp:688
bool isKeyword() const
Definition: token.h:358
const std::string & originalName() const
Definition: token.h:1193
bool isName() const
Definition: token.h:361
static void createMutualLinks(Token *begin, Token *end)
Links two elements against each other.
Definition: token.cpp:1248
bool isCpp() const
Definition: token.cpp:2718
const ValueType * valueType() const
Definition: token.h:331
const std::string & strAt(int index) const
Definition: token.cpp:423
void astOperand1(Token *tok)
Definition: token.cpp:1456
void function(const Function *f)
Associate this token with given function.
Definition: token.cpp:1093
nonneg int varId() const
Definition: token.h:870
bool isUnaryOp(const std::string &s) const
Definition: token.h:413
const Token * tokAt(int index) const
Definition: token.cpp:393
void astOperand2(Token *tok)
Definition: token.cpp:1468
void scope(const Scope *s)
Associate this token with given scope.
Definition: token.h:1042
void link(Token *linkToToken)
Create link to given token.
Definition: token.h:1015
const Token * linkAt(int index) const
Definition: token.cpp:413
Token * previous()
Definition: token.h:862
bool isStandardType() const
Definition: token.h:449
Token * next()
Definition: token.h:830
static bool simpleMatch(const Token *tok, const char(&pattern)[count])
Match given token (or list of tokens) to a pattern list.
Definition: token.h:252
void astParent(Token *tok)
Definition: token.cpp:1437
const Library::Container * container
If the type is a container defined in a cfg file, this is the used.
static const std::string emptyString
Definition: config.h:127
#define nonneg
Definition: config.h:138
std::shared_ptr< Token > createTokenFromExpression(const std::string &returnValue, const Settings &settings, bool cpp, std::unordered_map< nonneg int, const Token * > *lookupVarId)
Definition: library.cpp:1764
Severity severityFromString(const std::string &severity)
Definition: errortypes.cpp:76
const Library::Container * getLibraryContainer(const Token *tok)
Definition: library.cpp:1731
@ error
Programming error.
static void gettokenlistfromvalid(const std::string &valid, bool cpp, TokenList &tokenList)
Definition: library.cpp:56
static std::vector< std::string > getnames(const char *names)
Definition: library.cpp:45
const Value * valueFlowConstantFoldAST(Token *expr, const Settings &settings)
Constant folding of expression. This can be used before the full ValueFlow has been executed (ValueFl...
Definition: valueflow.cpp:9408
BufferSize bufferSize
Definition: library.h:85
std::vector< MinSize > minsizes
Definition: library.h:302
std::string valid
Definition: library.h:283
IteratorInfo iteratorInfo
Definition: library.h:291
@ DIR_UNKNOWN
direction not known / specified
@ DIR_IN
Input to called function. Data is treated as read-only.
@ DIR_OUT
Output to caller. Data is passed by reference or address and is potentially written.
@ DIR_INOUT
Input to called function, and output to caller. Data is passed by reference or address and is potenti...
std::string returnType
Definition: library.h:326
bool formatstr_secure
Definition: library.h:323
UseRetValType useretval
Definition: library.h:319
std::map< int, ArgumentChecks > argumentChecks
Definition: library.h:314
bool formatstr_scan
Definition: library.h:322
Container::Action containerAction
Definition: library.h:324
Container::Yield containerYield
Definition: library.h:325
std::string mType
Definition: library.h:468
enum Library::PodType::Type stdtype
unsigned int size
Definition: library.h:446
std::string name
Definition: library.h:437
Standards standards
Definition: library.h:171
Severity severity
Definition: library.h:172
std::string message
Definition: library.h:170
bool setC(const std::string &str)
Definition: standards.h:48
enum Standards::cstd_t c
bool setCPP(std::string str)
Definition: standards.h:97
enum Standards::cppstd_t cpp
bool startsWith(const std::string &str, const char start[], std::size_t startlen)
Definition: utils.h:94
bool endsWith(const std::string &str, char c)
Definition: utils.h:110