Cppcheck
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Groups Pages
preprocessor.cpp
Go to the documentation of this file.
1 /*
2  * Cppcheck - A tool for static C/C++ code analysis
3  * Copyright (C) 2007-2016 Cppcheck team.
4  *
5  * This program is free software: you can redistribute it and/or modify
6  * it under the terms of the GNU General Public License as published by
7  * the Free Software Foundation, either version 3 of the License, or
8  * (at your option) any later version.
9  *
10  * This program is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13  * GNU General Public License for more details.
14  *
15  * You should have received a copy of the GNU General Public License
16  * along with this program. If not, see <http://www.gnu.org/licenses/>.
17  */
18 
19 
20 #include "preprocessor.h"
21 #include "tokenize.h"
22 #include "token.h"
23 #include "path.h"
24 #include "errorlogger.h"
25 #include "settings.h"
26 
27 #include <algorithm>
28 #include <sstream>
29 #include <fstream>
30 #include <cstdlib>
31 #include <cctype>
32 #include <vector>
33 #include <set>
34 #include <stack>
35 
36 /**
37  * Remove heading and trailing whitespaces from the input parameter.
38  * If string is all spaces/tabs, return empty string.
39  * @param s The string to trim.
40  */
41 static std::string trim(const std::string& s)
42 {
43  const std::string::size_type beg = s.find_first_not_of(" \t");
44  if (beg == std::string::npos)
45  return "";
46  const std::string::size_type end = s.find_last_not_of(" \t");
47  return s.substr(beg, end - beg + 1);
48 }
49 
50 Directive::Directive(const std::string &_file, const int _linenr, const std::string &_str):
51  file(_file),
52  linenr(_linenr),
53  str(_str)
54 {
55  // strip C++ comment if there is one
56  std::size_t pos = str.find("//");
57  if (pos != std::string::npos)
58  str.erase(pos);
59  // strip any C comments
60  while ((pos = str.find("/*")) != std::string::npos) {
61  std::size_t end = str.find("*/", pos+2);
62  if (end != std::string::npos) {
63  str.erase(pos, end + 2 - pos);
64  } else { // treat '/*' as '//' if '*/' is missing
65  str.erase(pos);
66  }
67  }
68  str = trim(str);
69 }
70 
73 
74 char Preprocessor::macroChar = char(1);
75 
76 Preprocessor::Preprocessor(Settings& settings, ErrorLogger *errorLogger) : _settings(settings), _errorLogger(errorLogger)
77 {
78 
79 }
80 
81 void Preprocessor::writeError(const std::string &fileName, const unsigned int linenr, ErrorLogger *errorLogger, const std::string &errorType, const std::string &errorText)
82 {
83  if (!errorLogger)
84  return;
85 
86  std::list<ErrorLogger::ErrorMessage::FileLocation> locationList;
87  ErrorLogger::ErrorMessage::FileLocation loc(fileName, linenr);
88  locationList.push_back(loc);
89  errorLogger->reportErr(ErrorLogger::ErrorMessage(locationList,
91  errorText,
92  errorType,
93  false));
94 }
95 
96 static unsigned char readChar(std::istream &istr, unsigned int bom)
97 {
98  unsigned char ch = (unsigned char)istr.get();
99 
100  // For UTF-16 encoded files the BOM is 0xfeff/0xfffe. If the
101  // character is non-ASCII character then replace it with 0xff
102  if (bom == 0xfeff || bom == 0xfffe) {
103  const unsigned char ch2 = (unsigned char)istr.get();
104  const int ch16 = (bom == 0xfeff) ? (ch<<8 | ch2) : (ch2<<8 | ch);
105  ch = (unsigned char)((ch16 >= 0x80) ? 0xff : ch16);
106  }
107 
108  // Handling of newlines..
109  if (ch == '\r') {
110  ch = '\n';
111  if (bom == 0 && (char)istr.peek() == '\n')
112  (void)istr.get();
113  else if (bom == 0xfeff || bom == 0xfffe) {
114  int c1 = istr.get();
115  int c2 = istr.get();
116  int ch16 = (bom == 0xfeff) ? (c1<<8 | c2) : (c2<<8 | c1);
117  if (ch16 != '\n') {
118  istr.unget();
119  istr.unget();
120  }
121  }
122  }
123 
124  return ch;
125 }
126 
127 // Concatenates a list of strings, inserting a separator between parts
128 static std::string join(const std::set<std::string>& list, char separator)
129 {
130  std::string s;
131  for (std::set<std::string>::const_iterator it = list.begin(); it != list.end(); ++it) {
132  if (!s.empty())
133  s += separator;
134 
135  s += *it;
136  }
137  return s;
138 }
139 
140 // Removes duplicate string portions separated by the specified separator
141 static std::string unify(const std::string &s, char separator)
142 {
143  std::set<std::string> parts;
144 
145  std::string::size_type prevPos = 0;
146  for (std::string::size_type pos = 0; pos < s.length(); ++pos) {
147  if (s[pos] == separator) {
148  if (pos > prevPos)
149  parts.insert(s.substr(prevPos, pos - prevPos));
150  prevPos = pos + 1;
151  }
152  }
153  if (prevPos < s.length())
154  parts.insert(s.substr(prevPos));
155 
156  return join(parts, separator);
157 }
158 
159 
160 bool Preprocessor::cplusplus(const Settings *settings, const std::string &filename)
161 {
162  const bool undef = settings && settings->userUndefs.find("__cplusplus") != settings->userUndefs.end();
163  const bool cpplang = settings && settings->enforcedLang == Settings::CPP;
164  const bool cppfile = (!settings || settings->enforcedLang == Settings::None) && Path::isCPP(filename);
165  return (!undef && (cpplang || cppfile));
166 }
167 
168 /**
169  * Get cfgmap - a map of macro names and values
170  */
171 static std::map<std::string,std::string> getcfgmap(const std::string &cfg, const Settings *settings, const std::string &filename)
172 {
173  std::map<std::string, std::string> cfgmap;
174 
175  if (!cfg.empty()) {
176  std::string::size_type pos = 0;
177  for (;;) {
178  std::string::size_type pos2 = cfg.find_first_of(";=", pos);
179  if (pos2 == std::string::npos) {
180  cfgmap[cfg.substr(pos)] = "";
181  break;
182  }
183  if (cfg[pos2] == ';') {
184  cfgmap[cfg.substr(pos, pos2-pos)] = "";
185  } else {
186  std::string::size_type pos3 = pos2;
187  pos2 = cfg.find(';', pos2);
188  if (pos2 == std::string::npos) {
189  cfgmap[cfg.substr(pos, pos3-pos)] = cfg.substr(pos3 + 1);
190  break;
191  } else {
192  cfgmap[cfg.substr(pos, pos3-pos)] = cfg.substr(pos3 + 1, pos2 - pos3 - 1);
193  }
194  }
195  pos = pos2 + 1;
196  }
197  }
198 
199  if (cfgmap.find("__cplusplus") == cfgmap.end() && Preprocessor::cplusplus(settings,filename))
200  cfgmap["__cplusplus"] = "1";
201 
202  return cfgmap;
203 }
204 
205 
206 /** Just read the code into a string. Perform simple cleanup of the code */
207 std::string Preprocessor::read(std::istream &istr, const std::string &filename)
208 {
209  // The UTF-16 BOM is 0xfffe or 0xfeff.
210  unsigned int bom = 0;
211  if (istr.peek() >= 0xfe) {
212  bom = ((unsigned char)istr.get() << 8);
213  if (istr.peek() >= 0xfe)
214  bom |= (unsigned char)istr.get();
215  else
216  bom = 0; // allowed boms are 0/0xfffe/0xfeff
217  }
218 
219  if (_settings.terminated())
220  return "";
221 
223  return readpreprocessor(istr,bom);
224 
225  // ------------------------------------------------------------------------------------------
226  //
227  // handling <backslash><newline>
228  // when this is encountered the <backslash><newline> will be "skipped".
229  // on the next <newline>, extra newlines will be added
230  std::ostringstream code;
231  unsigned int newlines = 0;
232  for (unsigned char ch = readChar(istr,bom); istr.good(); ch = readChar(istr,bom)) {
233  // Replace assorted special chars with spaces..
234  if (((ch & 0x80) == 0) && (ch != '\n') && (std::isspace(ch) || std::iscntrl(ch)))
235  ch = ' ';
236 
237  // <backslash><newline>..
238  // for gcc-compatibility the trailing spaces should be ignored
239  // for vs-compatibility the trailing spaces should be kept
240  // See tickets #640 and #1869
241  // The solution for now is to have a compiler-dependent behaviour.
242  if (ch == '\\') {
243  unsigned char chNext;
244 
245  std::string spaces;
246 
247 #ifdef __GNUC__
248  // gcc-compatibility: ignore spaces
249  for (;; spaces += ' ') {
250  chNext = (unsigned char)istr.peek();
251  if (chNext != '\n' && chNext != '\r' &&
252  (std::isspace(chNext) || std::iscntrl(chNext))) {
253  // Skip whitespace between <backslash> and <newline>
254  (void)readChar(istr,bom);
255  continue;
256  }
257 
258  break;
259  }
260 #else
261  // keep spaces
262  chNext = (unsigned char)istr.peek();
263 #endif
264  if (chNext == '\n' || chNext == '\r') {
265  ++newlines;
266  (void)readChar(istr,bom); // Skip the "<backslash><newline>"
267  } else {
268  code << "\\" << spaces;
269  }
270  } else {
271  code << char(ch);
272 
273  // if there has been <backslash><newline> sequences, add extra newlines..
274  if (ch == '\n' && newlines > 0) {
275  code << std::string(newlines, '\n');
276  newlines = 0;
277  }
278  }
279  }
280 
281  // ------------------------------------------------------------------------------------------
282  //
283  // Remove all comments..
284  std::string result = removeComments(code.str(), filename);
285  if (_settings.terminated())
286  return "";
287  code.str("");
288 
289  // ------------------------------------------------------------------------------------------
290  //
291  // Clean up all preprocessor statements
292  result = preprocessCleanupDirectives(result);
293  if (_settings.terminated())
294  return "";
295 
296  // ------------------------------------------------------------------------------------------
297  //
298  // Clean up preprocessor #if statements with Parentheses
299  result = removeParentheses(result);
300  if (_settings.terminated())
301  return "";
302 
303  // Remove '#if 0' blocks
304  if (result.find("#if 0\n") != std::string::npos)
305  result = removeIf0(result);
306  if (_settings.terminated())
307  return "";
308 
309  return result;
310 }
311 
312 
313 /** read preprocessor statements */
314 std::string Preprocessor::readpreprocessor(std::istream &istr, const unsigned int bom)
315 {
316  enum { NEWLINE, SPACE, PREPROCESSOR, BACKSLASH, OTHER } state = NEWLINE;
317  std::ostringstream code;
318  unsigned int newlines = 1;
319  unsigned char chPrev = ' ';
320  for (unsigned char ch = readChar(istr,bom); istr.good(); ch = readChar(istr,bom)) {
321  // Replace assorted special chars with spaces..
322  if (((ch & 0x80) == 0) && (ch != '\n') && (std::isspace(ch) || std::iscntrl(ch)))
323  ch = ' ';
324 
325  if (ch == ' ' && chPrev == ' ')
326  continue;
327  if (state == PREPROCESSOR && chPrev == '/' && (ch == '/' || ch == '*'))
328  state = OTHER;
329  chPrev = ch;
330 
331  if (ch == '\n') {
332  if (state != BACKSLASH) {
333  state = NEWLINE;
334  code << std::string(newlines, '\n');
335  newlines = 1;
336  } else {
337  ++newlines;
338  state = PREPROCESSOR;
339  }
340  continue;
341  }
342 
343  switch (state) {
344  case NEWLINE:
345  if (ch==' ')
346  state = SPACE;
347  else if (ch == '#') {
348  state = PREPROCESSOR;
349  code << ch;
350  } else
351  state = OTHER;
352  break;
353  case SPACE:
354  if (ch == '#') {
355  state = PREPROCESSOR;
356  code << ch;
357  } else if (ch != ' ')
358  state = OTHER;
359  break;
360  case PREPROCESSOR:
361  code << ch;
362  if (ch == '\\')
363  state = BACKSLASH;
364  break;
365  case BACKSLASH:
366  code << ch;
367  if (ch != ' ')
368  state = PREPROCESSOR;
369  break;
370  case OTHER:
371  break;
372  };
373  }
374 
375  std::string result = preprocessCleanupDirectives(code.str());
376  result = removeParentheses(result);
377  return removeIf0(result);
378 }
379 
380 std::string Preprocessor::preprocessCleanupDirectives(const std::string &processedFile)
381 {
382  std::ostringstream code;
383  std::istringstream sstr(processedFile);
384 
385  std::string line;
386  while (std::getline(sstr, line)) {
387  // Trim lines..
388  if (!line.empty() && line[0] == ' ')
389  line.erase(0, line.find_first_not_of(" "));
390  if (!line.empty() && line.back() == ' ')
391  line.erase(line.find_last_not_of(" ") + 1);
392 
393  // Preprocessor
394  if (!line.empty() && line[0] == '#') {
395  enum {
396  ESC_NONE,
397  ESC_SINGLE,
398  ESC_DOUBLE
399  } escapeStatus = ESC_NONE;
400 
401  char prev = ' '; // hack to make it skip spaces between # and the directive
402  code << "#";
403  std::string::const_iterator i = line.begin();
404  ++i;
405 
406  // need space.. #if( => #if (
407  bool needSpace = true;
408  while (i != line.end()) {
409  // disable esc-mode
410  if (escapeStatus != ESC_NONE) {
411  if (prev != '\\' && escapeStatus == ESC_SINGLE && *i == '\'') {
412  escapeStatus = ESC_NONE;
413  }
414  if (prev != '\\' && escapeStatus == ESC_DOUBLE && *i == '"') {
415  escapeStatus = ESC_NONE;
416  }
417  } else {
418  // enable esc-mode
419  if (escapeStatus == ESC_NONE && *i == '"')
420  escapeStatus = ESC_DOUBLE;
421  if (escapeStatus == ESC_NONE && *i == '\'')
422  escapeStatus = ESC_SINGLE;
423  }
424  // skip double whitespace between arguments
425  if (escapeStatus == ESC_NONE && prev == ' ' && *i == ' ') {
426  ++i;
427  continue;
428  }
429  // Convert #if( to "#if ("
430  if (escapeStatus == ESC_NONE) {
431  if (needSpace) {
432  if (*i == '(' || *i == '!')
433  code << " ";
434  else if (!std::isalpha((unsigned char)*i))
435  needSpace = false;
436  }
437  if (*i == '#')
438  needSpace = true;
439  }
440  code << *i;
441  if (escapeStatus != ESC_NONE && prev == '\\' && *i == '\\') {
442  prev = ' ';
443  } else {
444  prev = *i;
445  }
446  ++i;
447  }
448  if (escapeStatus != ESC_NONE) {
449  // unmatched quotes.. compiler should probably complain about this..
450  }
451  } else {
452  // Do not mess with regular code..
453  code << line;
454  }
455  code << (sstr.eof()?"":"\n");
456  }
457 
458  return code.str();
459 }
460 
461 static bool hasbom(const std::string &str)
462 {
463  return bool(str.size() >= 3 &&
464  static_cast<unsigned char>(str[0]) == 0xef &&
465  static_cast<unsigned char>(str[1]) == 0xbb &&
466  static_cast<unsigned char>(str[2]) == 0xbf);
467 }
468 
469 
470 // This wrapper exists because Sun's CC does not allow a static_cast
471 // from extern "C" int(*)(int) to int(*)(int).
472 static int tolowerWrapper(int c)
473 {
474  return std::tolower(c);
475 }
476 
477 
478 static bool isFallThroughComment(std::string comment)
479 {
480  // convert comment to lower case without whitespace
481  for (std::string::iterator i = comment.begin(); i != comment.end();) {
482  if (std::isspace(static_cast<unsigned char>(*i)))
483  i = comment.erase(i);
484  else
485  ++i;
486  }
487  std::transform(comment.begin(), comment.end(), comment.begin(), tolowerWrapper);
488 
489  return comment.find("fallthr") != std::string::npos ||
490  comment.find("fallsthr") != std::string::npos ||
491  comment.find("fall-thr") != std::string::npos ||
492  comment.find("dropthr") != std::string::npos ||
493  comment.find("passthr") != std::string::npos ||
494  comment.find("nobreak") != std::string::npos ||
495  comment == "fall";
496 }
497 
498 std::string Preprocessor::removeComments(const std::string &str, const std::string &filename)
499 {
500  // For the error report
501  unsigned int lineno = 1;
502 
503  // handling <backslash><newline>
504  // when this is encountered the <backslash><newline> will be "skipped".
505  // on the next <newline>, extra newlines will be added
506  unsigned int newlines = 0;
507  std::ostringstream code;
508  unsigned char previous = 0;
509  bool inPreprocessorLine = false;
510  std::vector<std::string> suppressionIDs;
511  const bool detectFallThroughComments = _settings.experimental && _settings.isEnabled("style");
512  bool fallThroughComment = false;
513 
514  for (std::string::size_type i = hasbom(str) ? 3U : 0U; i < str.length(); ++i) {
515  unsigned char ch = static_cast<unsigned char>(str[i]);
516  if (ch & 0x80) {
517  std::ostringstream errmsg;
518  errmsg << "(character code = 0x" << std::hex << (int(ch) & 0xff) << ")";
519  std::string info = errmsg.str();
520  errmsg.str("");
521  errmsg << "The code contains unhandled characters " << info << ". Checking continues, but do not expect valid results.\n"
522  << "The code contains characters that are unhandled " << info << ". Neither unicode nor extended ASCII are supported. Checking continues, but do not expect valid results.";
523  writeError(Path::simplifyPath(filename), lineno, _errorLogger, "unhandledCharacters", errmsg.str());
524  }
525 
526  if (_settings.terminated())
527  return "";
528 
529  // First skip over any whitespace that may be present
530  if (std::isspace(ch)) {
531  if (ch == ' ' && previous == ' ') {
532  // Skip double white space
533  } else {
534  code << char(ch);
535  previous = ch;
536  }
537 
538  // if there has been <backslash><newline> sequences, add extra newlines..
539  if (ch == '\n') {
540  if (previous != '\\')
541  inPreprocessorLine = false;
542  ++lineno;
543  if (newlines > 0) {
544  code << std::string(newlines, '\n');
545  newlines = 0;
546  previous = '\n';
547  }
548  }
549 
550  continue;
551  }
552 
553  if ((ch == '#') && (str.compare(i+1, 6, "error ") == 0 || str.compare(i+1, 8, "warning ") == 0)) {
554  if (str.compare(i, 6, "#error") == 0)
555  code << "#error";
556 
557  i = str.find('\n', i);
558  if (i == std::string::npos)
559  break;
560 
561  --i;
562  continue;
563  }
564 
565  // Remove comments..
566  if (str.compare(i, 2, "//") == 0) {
567  const std::size_t commentStart = i + 2;
568  i = str.find('\n', i);
569  if (i == std::string::npos)
570  break;
571  std::string comment(str, commentStart, i - commentStart);
572 
574  std::istringstream iss(comment);
575  std::string word;
576  iss >> word;
577  if (word == "cppcheck-suppress") {
578  iss >> word;
579  if (iss)
580  suppressionIDs.push_back(word);
581  }
582  }
583 
584  if (detectFallThroughComments && isFallThroughComment(comment)) {
585  fallThroughComment = true;
586  }
587 
588  code << "\n";
589  previous = '\n';
590  ++lineno;
591  } else if (str.compare(i, 2, "/*") == 0) {
592  const std::size_t commentStart = i + 2;
593  unsigned char chPrev = 0;
594  ++i;
595  while (i < str.length() && (chPrev != '*' || ch != '/')) {
596  chPrev = ch;
597  ++i;
598  ch = static_cast<unsigned char>(str[i]);
599  if (ch == '\n') {
600  ++newlines;
601  ++lineno;
602  }
603  }
604  std::string comment(str, commentStart, i - commentStart - 1);
605 
606  if (detectFallThroughComments && isFallThroughComment(comment)) {
607  fallThroughComment = true;
608  }
609 
611  std::istringstream iss(comment);
612  std::string word;
613  iss >> word;
614  if (word == "cppcheck-suppress") {
615  iss >> word;
616  if (iss)
617  suppressionIDs.push_back(word);
618  }
619  }
620  } else if ((i == 0 || std::isspace((unsigned char)str[i-1])) && str.compare(i, 5, "__asm") == 0) {
621  while (i < str.size() && (std::isalpha((unsigned char)str[i]) || str[i] == '_'))
622  code << str[i++];
623  while (i < str.size() && std::isspace((unsigned char)str[i])) {
624  if (str[i] == '\n')
625  lineno++;
626  code << str[i++];
627  }
628  if (str[i] == '{') {
629  // Ticket 4873: Extract comments from the __asm / __asm__'s content
630  std::string asmBody;
631  while (i < str.size() && str[i] != '}') {
632  if (str[i] == ';') {
633  std::string::size_type backslashN = str.find('\n', i);
634  if (backslashN != std::string::npos) // Ticket #4922: Don't go in infinite loop or crash if there is no '\n'
635  i = backslashN;
636  }
637  if (str[i] == '\n')
638  lineno++;
639  asmBody += str[i++];
640  }
641  code << removeComments(asmBody, filename);
642  code << '}';
643  } else
644  --i;
645  } else if (ch == '#' && previous == '\n') {
646  code << ch;
647  previous = ch;
648  inPreprocessorLine = true;
649 
650  // Add any pending inline suppressions that have accumulated.
651  if (!suppressionIDs.empty()) {
652  // Add the suppressions.
653  for (std::size_t j = 0; j < suppressionIDs.size(); ++j) {
654  const std::string errmsg(_settings.nomsg.addSuppression(suppressionIDs[j], filename, lineno));
655  if (!errmsg.empty()) {
656  writeError(filename, lineno, _errorLogger, "cppcheckError", errmsg);
657  }
658  }
659  suppressionIDs.clear();
660  }
661  } else {
662  if (!inPreprocessorLine) {
663  // Not whitespace, not a comment, and not preprocessor.
664  // Must be code here!
665 
666  // First check for a "fall through" comment match, but only
667  // add a suppression if the next token is 'case' or 'default'
668  if (detectFallThroughComments && fallThroughComment) {
669  const std::string::size_type j = str.find_first_not_of("abcdefghijklmnopqrstuvwxyz", i);
670  if (str.compare(i, j-i, "case") == 0 || str.compare(i, j-i, "default") == 0)
671  suppressionIDs.push_back("switchCaseFallThrough");
672  fallThroughComment = false;
673  }
674 
675  // Add any pending inline suppressions that have accumulated.
676  if (!suppressionIDs.empty()) {
677  // Relative filename
678  std::string relativeFilename(filename);
679  if (_settings.relativePaths) {
680  for (std::size_t j = 0U; j < _settings.basePaths.size(); ++j) {
681  const std::string bp = _settings.basePaths[j] + "/";
682  if (relativeFilename.compare(0,bp.size(),bp)==0) {
683  relativeFilename = relativeFilename.substr(bp.size());
684  }
685  }
686  }
687 
688  // Add the suppressions.
689  for (std::size_t j = 0; j < suppressionIDs.size(); ++j) {
690  const std::string errmsg(_settings.nomsg.addSuppression(suppressionIDs[j], relativeFilename, lineno));
691  if (!errmsg.empty()) {
692  writeError(filename, lineno, _errorLogger, "cppcheckError", errmsg);
693  }
694  }
695  suppressionIDs.clear();
696  }
697  }
698 
699  // C++14 digit separators
700  if (ch == '\'' && std::isxdigit(previous))
701  ; // Just skip it.
702 
703  // String or char constants..
704  else if (ch == '\"' || ch == '\'') {
705  code << char(ch);
706  char chNext;
707  do {
708  ++i;
709  chNext = str[i];
710  if (chNext == '\\') {
711  ++i;
712  const char chSeq = str[i];
713  if (chSeq == '\n')
714  ++newlines;
715  else {
716  code << chNext;
717  code << chSeq;
718  previous = static_cast<unsigned char>(chSeq);
719  }
720  } else {
721  code << chNext;
722  previous = static_cast<unsigned char>(chNext);
723  }
724  } while (i < str.length() && chNext != ch && chNext != '\n');
725  }
726 
727  // Rawstring..
728  else if (str.compare(i,2,"R\"")==0) {
729  std::string delim;
730  for (std::string::size_type i2 = i+2; i2 < str.length(); ++i2) {
731  if (i2 > 16 + i ||
732  std::isspace(str[i2]) ||
733  std::iscntrl(str[i2]) ||
734  str[i2] == ')' ||
735  str[i2] == '\\') {
736  delim = " ";
737  break;
738  } else if (str[i2] == '(')
739  break;
740 
741  delim += str[i2];
742  }
743  const std::string::size_type endpos = str.find(")" + delim + "\"", i);
744  if (delim != " " && endpos != std::string::npos) {
745  unsigned int rawstringnewlines = 0;
746  code << '\"';
747  for (std::string::size_type p = i + 3 + delim.size(); p < endpos; ++p) {
748  if (str[p] == '\n') {
749  rawstringnewlines++;
750  code << "\\n";
751  } else if (std::iscntrl((unsigned char)str[p]) ||
752  std::isspace((unsigned char)str[p])) {
753  code << " ";
754  } else if (str[p] == '\\') {
755  code << "\\\\";
756  } else if (str[p] == '\"') {
757  code << "\\" << (char)str[p];
758  } else {
759  code << (char)str[p];
760  }
761  }
762  code << "\"";
763  if (rawstringnewlines > 0)
764  code << std::string(rawstringnewlines, '\n');
765  i = endpos + delim.size() + 1;
766  } else {
767  code << "R";
768  previous = 'R';
769  }
770  } else {
771  code << char(ch);
772  previous = ch;
773  }
774  }
775  }
776 
777  return code.str();
778 }
779 
780 std::string Preprocessor::removeIf0(const std::string &code)
781 {
782  std::ostringstream ret;
783  std::istringstream istr(code);
784  std::string line;
785  while (std::getline(istr,line)) {
786  ret << line << "\n";
787  if (line == "#if 0") {
788  // goto the end of the '#if 0' block
789  unsigned int level = 1;
790  bool in = false;
791  while (level > 0 && std::getline(istr,line)) {
792  if (line.compare(0,3,"#if") == 0)
793  ++level;
794  else if (line == "#endif")
795  --level;
796  else if ((line == "#else") || (line.compare(0, 5, "#elif") == 0)) {
797  if (level == 1)
798  in = true;
799  } else {
800  if (in)
801  ret << line << "\n";
802  else
803  // replace code within '#if 0' block with empty lines
804  ret << "\n";
805  continue;
806  }
807 
808  ret << line << "\n";
809  }
810  }
811  }
812  return ret.str();
813 }
814 
815 
816 std::string Preprocessor::removeParentheses(const std::string &str)
817 {
818  if (str.find("\n#if") == std::string::npos && str.compare(0, 3, "#if") != 0)
819  return str;
820 
821  std::istringstream istr(str);
822  std::ostringstream ret;
823  std::string line;
824  while (std::getline(istr, line)) {
825  if (line.compare(0, 3, "#if") == 0 || line.compare(0, 5, "#elif") == 0) {
826  std::string::size_type pos;
827  pos = 0;
828  while ((pos = line.find(" (", pos)) != std::string::npos)
829  line.erase(pos, 1);
830  pos = 0;
831  while ((pos = line.find("( ", pos)) != std::string::npos)
832  line.erase(pos + 1, 1);
833  pos = 0;
834  while ((pos = line.find(" )", pos)) != std::string::npos)
835  line.erase(pos, 1);
836  pos = 0;
837  while ((pos = line.find(") ", pos)) != std::string::npos)
838  line.erase(pos + 1, 1);
839 
840  // Remove inner parentheses "((..))"..
841  pos = 0;
842  while ((pos = line.find("((", pos)) != std::string::npos) {
843  ++pos;
844  std::string::size_type pos2 = line.find_first_of("()", pos + 1);
845  if (pos2 != std::string::npos && line[pos2] == ')') {
846  line.erase(pos2, 1);
847  line.erase(pos, 1);
848  }
849  }
850 
851  // "#if(A) => #if A", but avoid "#if (defined A) || defined (B)"
852  if ((line.compare(0, 4, "#if(") == 0 || line.compare(0, 6, "#elif(") == 0) &&
853  line[line.length() - 1] == ')') {
854  int ind = 0;
855  for (std::string::size_type i = 0; i < line.length(); ++i) {
856  if (line[i] == '(')
857  ++ind;
858  else if (line[i] == ')') {
859  --ind;
860  if (ind == 0) {
861  if (i == line.length() - 1) {
862  line[line.find('(')] = ' ';
863  line.erase(line.length() - 1);
864  }
865  break;
866  }
867  }
868  }
869  }
870 
871  if (line.compare(0, 4, "#if(") == 0)
872  line.insert(3, " ");
873  else if (line.compare(0, 6, "#elif(") == 0)
874  line.insert(5, " ");
875  }
876  ret << line << "\n";
877  }
878 
879  return ret.str();
880 }
881 
882 
883 void Preprocessor::removeAsm(std::string &str)
884 {
885  std::string::size_type pos = 0;
886  while ((pos = str.find("#asm\n", pos)) != std::string::npos) {
887  str.replace(pos, 4, "asm(");
888 
889  std::string::size_type pos2 = str.find("#endasm", pos);
890  if (pos2 != std::string::npos) {
891  str.replace(pos2, 7, ");");
892  pos = pos2;
893  }
894  }
895 }
896 
897 
898 void Preprocessor::preprocess(std::istream &istr, std::map<std::string, std::string> &result, const std::string &filename, const std::list<std::string> &includePaths)
899 {
900  std::list<std::string> configs;
901  std::string data;
902  preprocess(istr, data, configs, filename, includePaths);
903  for (std::list<std::string>::const_iterator it = configs.begin(); it != configs.end(); ++it) {
904  if (_settings.userUndefs.find(*it) == _settings.userUndefs.end()) {
905  result[ *it ] = getcode(data, *it, filename);
906  }
907  }
908 }
909 
910 std::string Preprocessor::removeSpaceNearNL(const std::string &str)
911 {
912  std::string tmp;
913  char prev = '\n'; // treat start of file as newline
914  for (std::size_t i = 0; i < str.size(); i++) {
915  if (str[i] == ' ' &&
916  (prev == '\n' ||
917  i + 1 >= str.size() || // treat end of file as newline
918  str[i+1] == '\n'
919  )
920  ) {
921  // Ignore space that has new line in either side of it
922  } else {
923  tmp.append(1, str[i]);
924  prev = str[i];
925  }
926  }
927 
928  return tmp;
929 }
930 
931 void Preprocessor::replaceIfDefined(std::string &str) const
932 {
933  std::string::size_type pos = 0;
934  while ((pos = str.find("#if defined(", pos)) != std::string::npos) {
935  std::string::size_type pos2 = str.find(')', pos + 9);
936  if (pos2 > str.length() - 1)
937  break;
938  if (str[pos2+1] == '\n') {
939  str.erase(pos2, 1);
940  str.erase(pos + 3, 9);
941  str.insert(pos + 3, "def ");
942  }
943  ++pos;
944 
945  if (_settings.terminated())
946  return;
947  }
948 
949  pos = 0;
950  while ((pos = str.find("#if !defined(", pos)) != std::string::npos) {
951  std::string::size_type pos2 = str.find(')', pos + 9);
952  if (pos2 > str.length() - 1)
953  break;
954  if (str[pos2+1] == '\n') {
955  str.erase(pos2, 1);
956  str.erase(pos + 3, 10);
957  str.insert(pos + 3, "ndef ");
958  }
959  ++pos;
960 
961  if (_settings.terminated())
962  return;
963  }
964 
965  pos = 0;
966  while ((pos = str.find("#elif defined(", pos)) != std::string::npos) {
967  std::string::size_type pos2 = str.find(')', pos + 9);
968  if (pos2 > str.length() - 1)
969  break;
970  if (str[pos2+1] == '\n') {
971  str.erase(pos2, 1);
972  str.erase(pos + 6, 8);
973  }
974  ++pos;
975 
976  if (_settings.terminated())
977  return;
978  }
979 }
980 
981 void Preprocessor::preprocessWhitespaces(std::string &processedFile)
982 {
983  // Replace all tabs with spaces..
984  std::replace(processedFile.begin(), processedFile.end(), '\t', ' ');
985 
986  // Remove space characters that are after or before new line character
987  processedFile = removeSpaceNearNL(processedFile);
988 }
989 
990 void Preprocessor::preprocess(std::istream &srcCodeStream, std::string &processedFile, std::list<std::string> &resultConfigurations, const std::string &filename, const std::list<std::string> &includePaths)
991 {
992  std::string forcedIncludes;
993 
994  if (file0.empty())
995  file0 = filename;
996 
997  processedFile = read(srcCodeStream, filename);
998 
999  for (std::list<std::string>::iterator it = _settings.userIncludes.begin();
1000  it != _settings.userIncludes.end();
1001  ++it) {
1002  const std::string& cur = *it;
1003 
1004  // try to open file
1005  std::ifstream fin;
1006 
1007  fin.open(cur.c_str());
1008  if (!fin.is_open()) {
1009  missingInclude(cur,
1010  1,
1011  cur,
1012  UserHeader
1013  );
1014  continue;
1015  }
1016  const std::string fileData = read(fin, filename);
1017 
1018  fin.close();
1019 
1020  forcedIncludes +=
1021  "#file \"" + cur + "\"\n" +
1022  "#line 1\n" +
1023  fileData + "\n" +
1024  "#endfile\n"
1025  ;
1026  }
1027 
1028  for (std::vector<std::string>::iterator it = _settings.library.defines.begin();
1029  it != _settings.library.defines.end();
1030  ++it) {
1031  forcedIncludes += *it;
1032  }
1033 
1034  if (!forcedIncludes.empty()) {
1035  processedFile =
1036  forcedIncludes +
1037  "#file \"" + filename + "\"\n" +
1038  "#line 1\n" +
1039  processedFile +
1040  "#endfile\n"
1041  ;
1042  }
1043 
1044  // Remove asm(...)
1045  removeAsm(processedFile);
1046 
1047  // Replace "defined A" with "defined(A)"
1048  {
1049  std::istringstream istr(processedFile);
1050  std::ostringstream ostr;
1051  std::string line;
1052  while (std::getline(istr, line)) {
1053  if (line.compare(0, 4, "#if ") == 0 || line.compare(0, 6, "#elif ") == 0) {
1054  std::string::size_type pos = 0;
1055  while ((pos = line.find(" defined ")) != std::string::npos) {
1056  line[pos+8] = '(';
1057  pos = line.find_first_of(" |&", pos + 8);
1058  if (pos == std::string::npos)
1059  line += ")";
1060  else
1061  line.insert(pos, ")");
1062 
1063  if (_settings.terminated())
1064  return;
1065  }
1066  }
1067  ostr << line << "\n";
1068  }
1069  processedFile = ostr.str();
1070  }
1071 
1072  std::map<std::string, std::string> defs(getcfgmap(_settings.userDefines, &_settings, filename));
1073 
1074  if (_settings.maxConfigs == 1U) {
1075  std::set<std::string> pragmaOnce;
1076  std::list<std::string> includes;
1077  processedFile = handleIncludes(processedFile, filename, includePaths, defs, pragmaOnce, includes);
1078  resultConfigurations = getcfgs(processedFile, filename, defs);
1079  } else {
1080  handleIncludes(processedFile, filename, includePaths);
1081 
1082  replaceIfDefined(processedFile);
1083 
1084  // Get all possible configurations..
1085  resultConfigurations = getcfgs(processedFile, filename, defs);
1086 
1087  // Remove configurations that are disabled by -U
1088  handleUndef(resultConfigurations);
1089  }
1090 }
1091 
1092 void Preprocessor::handleUndef(std::list<std::string> &configurations) const
1093 {
1094  if (!_settings.userUndefs.empty()) {
1095  for (std::list<std::string>::iterator cfg = configurations.begin(); cfg != configurations.end();) {
1096  bool undef = false;
1097  for (std::set<std::string>::const_iterator it = _settings.userUndefs.begin(); it != _settings.userUndefs.end(); ++it) {
1098  if (*it == *cfg)
1099  undef = true;
1100  else if (cfg->compare(0,it->length(),*it)==0 && cfg->find_first_of(";=") == it->length())
1101  undef = true;
1102  else if (cfg->find(";" + *it) == std::string::npos)
1103  continue;
1104  else if (cfg->find(";" + *it + ";") != std::string::npos)
1105  undef = true;
1106  else if (cfg->find(";" + *it + "=") != std::string::npos)
1107  undef = true;
1108  else if (cfg->find(";" + *it) + it->size() + 1U == cfg->size())
1109  undef = true;
1110  if (undef)
1111  break;
1112  }
1113 
1114  if (undef)
1115  configurations.erase(cfg++);
1116  else
1117  ++cfg;
1118  }
1119  }
1120 }
1121 
1122 // Get the DEF in this line: "#ifdef DEF"
1123 std::string Preprocessor::getdef(std::string line, bool def)
1124 {
1125  if (line.empty() || line[0] != '#')
1126  return "";
1127 
1128  // If def is true, the line must start with "#ifdef"
1129  if (def && line.compare(1, 6, "ifdef ") != 0 && line.compare(1, 3, "if ") != 0
1130  && (line.compare(1, 5, "elif ") != 0 || line.compare(1, 6, "elif !") == 0)) {
1131  return "";
1132  }
1133 
1134  // If def is false, the line must start with "#ifndef"
1135  if (!def && line.compare(1, 7, "ifndef ") != 0 && line.compare(1, 6, "elif !") != 0) {
1136  return "";
1137  }
1138 
1139  // Remove the "#ifdef" or "#ifndef"
1140  if (line.compare(1, 11, "if defined ") == 0)
1141  line.erase(0, 11);
1142  else if (line.compare(1, 14, "elif !defined(") == 0) {
1143  line.erase(0, 15);
1144  std::string::size_type pos = line.find(')');
1145  // if pos == ::npos then another part of the code will complain
1146  // about the mismatch
1147  if (pos != std::string::npos)
1148  line.erase(pos, 1);
1149  } else
1150  line.erase(0, line.find(' '));
1151 
1152  // Remove all spaces.
1153  std::string::size_type pos = 0;
1154  while ((pos = line.find(' ', pos)) != std::string::npos) {
1155  const unsigned char chprev(static_cast<unsigned char>((pos > 0) ? line[pos-1] : 0));
1156  const unsigned char chnext(static_cast<unsigned char>((pos + 1 < line.length()) ? line[pos+1] : 0));
1157  if ((std::isalnum(chprev) || chprev == '_') && (std::isalnum(chnext) || chnext == '_'))
1158  ++pos;
1159  else
1160  line.erase(pos, 1);
1161  }
1162 
1163  // The remaining string is our result.
1164  return line;
1165 }
1166 
1167 /** Simplify variable in variable map. */
1168 static Token *simplifyVarMapExpandValue(Token *tok, const std::map<std::string, std::string> &variables, std::set<std::string> seenVariables, const Settings& settings)
1169 {
1170  // TODO: handle function-macros too.
1171 
1172  // Prevent infinite recursion..
1173  if (seenVariables.find(tok->str()) != seenVariables.end())
1174  return tok;
1175  seenVariables.insert(tok->str());
1176 
1177  const std::map<std::string, std::string>::const_iterator it = variables.find(tok->str());
1178  if (it != variables.end()) {
1179  TokenList tokenList(&settings);
1180  std::istringstream istr(it->second);
1181  if (tokenList.createTokens(istr)) {
1182  // expand token list
1183  for (Token *tok2 = tokenList.front(); tok2; tok2 = tok2->next()) {
1184  if (tok2->isName()) {
1185  tok2 = simplifyVarMapExpandValue(tok2, variables, seenVariables, settings);
1186  }
1187  }
1188 
1189  // insert token list into "parent" token list
1190  for (const Token *tok2 = tokenList.front(); tok2; tok2 = tok2->next()) {
1191  if (tok2->previous()) {
1192  tok->insertToken(tok2->str());
1193  tok = tok->next();
1194  } else
1195  tok->str(tok2->str());
1196  }
1197  }
1198  }
1199 
1200  return tok;
1201 }
1202 
1203 /**
1204  * Simplifies the variable map. For example if the map contains A=>B, B=>1, then A=>B is simplified to A=>1.
1205  * @param [in,out] variables - a map of variable name to variable value. This map will be modified.
1206  * @param [in] settings Current settings being used
1207  */
1208 static void simplifyVarMap(std::map<std::string, std::string> &variables, const Settings& settings)
1209 {
1210  for (std::map<std::string, std::string>::iterator i = variables.begin(); i != variables.end(); ++i) {
1211  TokenList tokenList(&settings);
1212  std::istringstream istr(i->second);
1213  if (tokenList.createTokens(istr)) {
1214  for (Token *tok = tokenList.front(); tok; tok = tok->next()) {
1215  if (tok->isName()) {
1216  std::set<std::string> seenVariables;
1217  tok = simplifyVarMapExpandValue(tok, variables, seenVariables, settings);
1218  }
1219  }
1220 
1221  std::string str;
1222  for (const Token *tok = tokenList.front(); tok; tok = tok->next())
1223  str.append((tok->previous() ? " " : "") + tok->str());
1224  i->second = str;
1225  }
1226  }
1227 }
1228 
1229 std::list<std::string> Preprocessor::getcfgs(const std::string &filedata, const std::string &filename, const std::map<std::string, std::string> &defs)
1230 {
1231  std::list<std::string> ret;
1232  ret.push_back("");
1233 
1234  std::list<std::string> deflist, ndeflist;
1235 
1236  // constants defined through "#define" in the code..
1237  std::set<std::string> defines;
1238  std::map<std::string, std::string> alldefinesmap(defs);
1239  std::stack<std::pair<std::string,bool> > includeStack;
1240  includeStack.push(std::pair<std::string,bool>(filename,false));
1241 
1242  // How deep into included files are we currently parsing?
1243  // 0=>Source file, 1=>Included by source file, 2=>included by header that was included by source file, etc
1244  int filelevel = 0;
1245 
1246  bool includeguard = false;
1247  unsigned int linenr = 0;
1248  std::istringstream istr(filedata);
1249  std::string line;
1250  const bool printDebug = _settings.debugwarnings;
1251  while (std::getline(istr, line)) {
1252  ++linenr;
1253 
1254  if (_settings.terminated())
1255  return ret;
1256 
1257  if (_errorLogger)
1258  _errorLogger->reportProgress(filename, "Preprocessing (get configurations 1)", 0);
1259 
1260  if (line.empty())
1261  continue;
1262 
1263  if (line.compare(0, 6, "#file ") == 0) {
1264  includeguard = true;
1265  const std::string::size_type start=line.find('\"');
1266  const std::string::size_type end=line.find('\"',start+1);
1267  const std::string includeFile=line.substr(start+1,end-start-1);
1268  ++filelevel;
1269  bool fileExcluded = _settings.configurationExcluded(includeFile);
1270  includeStack.push(std::pair<std::string,bool>(includeFile,fileExcluded));
1271  continue;
1272  }
1273 
1274  else if (line == "#endfile") {
1275  includeguard = false;
1276  includeStack.pop();
1277  if (filelevel > 0)
1278  --filelevel;
1279  continue;
1280  }
1281 
1282  if (line.compare(0, 8, "#define ") == 0) {
1283  bool valid = false;
1284  for (std::string::size_type pos = 8; pos < line.size(); ++pos) {
1285  const char ch = line[pos];
1286  if (ch=='_' || (ch>='a' && ch<='z') || (ch>='A' && ch<='Z') || (pos>8 && ch>='0' && ch<='9')) {
1287  valid = true;
1288  continue;
1289  }
1290  if (ch==' ' || ch=='(') {
1291  if (valid)
1292  break;
1293  }
1294  valid = false;
1295  break;
1296  }
1297  if (!valid)
1298  line.clear();
1299  else {
1300  std::string definestr = line.substr(8);
1301  const std::string::size_type spacepos = definestr.find(' ');
1302  if (spacepos != std::string::npos)
1303  definestr[spacepos] = '=';
1304  defines.insert(definestr);
1305 
1306  const std::string::size_type separatorpos = definestr.find_first_of("=(");
1307  if (separatorpos != std::string::npos && definestr[separatorpos] == '=') {
1308  const std::string varname(definestr.substr(0, separatorpos));
1309  const std::string value(definestr.substr(separatorpos + 1));
1310  alldefinesmap[varname] = value;
1311  }
1312  }
1313  }
1314 
1315  if (!line.empty() && line.compare(0, 3, "#if") != 0)
1316  includeguard = false;
1317 
1318  if (line.empty() || line[0] != '#')
1319  continue;
1320 
1321  if (includeguard)
1322  continue;
1323 
1324  if (line.compare(0, 5, "#line") == 0)
1325  continue;
1326 
1327  bool from_negation = false;
1328 
1329  std::string def = getdef(line, true);
1330  if (def.empty()) {
1331  def = getdef(line, false);
1332  // sub conditionals of ndef blocks need to be
1333  // constructed _without_ the negated define
1334  if (!def.empty())
1335  from_negation = true;
1336  }
1337  if (!def.empty()) {
1338  int par = 0;
1339  for (std::string::size_type pos = 0; pos < def.length(); ++pos) {
1340  if (def[pos] == '(')
1341  ++par;
1342  else if (def[pos] == ')') {
1343  --par;
1344  if (par < 0)
1345  break;
1346  }
1347  }
1348  if (par != 0) {
1349  std::ostringstream lineStream;
1350  lineStream << __LINE__;
1351  const std::string errorId = "preprocessor" + lineStream.str();
1352  const std::string errorText = "mismatching number of '(' and ')' in this line: " + def;
1353  writeError(filename, linenr, _errorLogger, errorId, errorText);
1354  ret.clear();
1355  return ret;
1356  }
1357 
1358  // Replace defined constants
1359  simplifyCondition(alldefinesmap, def, false);
1360 
1361  if (! deflist.empty() && line.compare(0, 6, "#elif ") == 0)
1362  deflist.pop_back();
1363 
1364  // translate A==1 condition to A=1 configuration
1365  if (def.find("==") != std::string::npos) {
1366  // Check if condition match pattern "%name% == %num%"
1367  // %name%
1368  std::string::size_type pos = 0;
1369  if (std::isalpha((unsigned char)def[pos]) || def[pos] == '_') {
1370  ++pos;
1371  while (std::isalnum((unsigned char)def[pos]) || def[pos] == '_')
1372  ++pos;
1373  }
1374 
1375  // ==
1376  if (def.compare(pos,2,"==")==0)
1377  pos += 2;
1378 
1379  // %num%
1380  if (pos<def.size() && std::isdigit(def[pos])) {
1381  if (def.compare(pos,2,"0x")==0) {
1382  pos += 2;
1383  if (pos >= def.size())
1384  pos = 0;
1385  while (pos < def.size() && std::isxdigit((unsigned char)def[pos]))
1386  ++pos;
1387  } else {
1388  while (pos < def.size() && std::isdigit((unsigned char)def[pos]))
1389  ++pos;
1390  }
1391 
1392  // Does the condition match the pattern "%name% == %num%"?
1393  if (pos == def.size()) {
1394  def.erase(def.find("=="),1);
1395  }
1396  }
1397  }
1398 
1399  deflist.push_back(def);
1400  def = "";
1401 
1402  for (std::list<std::string>::const_iterator it = deflist.begin(); it != deflist.end(); ++it) {
1403  if (*it == "0")
1404  break;
1405  if (*it == "1" || *it == "!")
1406  continue;
1407 
1408  // don't add "T;T":
1409  // treat two and more similar nested conditions as one
1410  if (def != *it) {
1411  if (! def.empty())
1412  def += ";";
1413  def += *it;
1414  }
1415 
1416  /* TODO: Fix TestPreprocessor::test7e (#2552)
1417  else
1418  {
1419  std::ostringstream lineStream;
1420  lineStream << __LINE__;
1421 
1422  ErrorLogger::ErrorMessage errmsg;
1423  ErrorLogger::ErrorMessage::FileLocation loc;
1424  loc.setfile(filename);
1425  loc.line = linenr;
1426  errmsg._callStack.push_back(loc);
1427  errmsg._severity = Severity::error;
1428  errmsg.setmsg(*it+" is already guaranteed to be defined");
1429  errmsg._id = "preprocessor" + lineStream.str();
1430  _errorLogger->reportErr(errmsg);
1431  }
1432  */
1433  }
1434  if (from_negation) {
1435  ndeflist.push_back(deflist.back());
1436  deflist.back() = "!";
1437  }
1438 
1439  if (std::find(ret.begin(), ret.end(), def) == ret.end()) {
1440  if (!includeStack.top().second) {
1441  ret.push_back(def);
1442  } else {
1443  if (_errorLogger && printDebug) {
1444  std::list<ErrorLogger::ErrorMessage::FileLocation> locationList;
1445  const ErrorLogger::ErrorMessage errmsg(locationList, Severity::debug,
1446  "Configuration not considered: " + def +" for file:"+includeStack.top().first, "debug", false);
1447  _errorLogger->reportErr(errmsg);
1448  }
1449  }
1450  }
1451  }
1452 
1453  else if (line.compare(0, 5, "#else") == 0 && ! deflist.empty()) {
1454  if (deflist.back() == "!" && !ndeflist.empty()) {
1455  deflist.back() = ndeflist.back();
1456  ndeflist.pop_back();
1457  } else {
1458  std::string tempDef((deflist.back() == "1") ? "0" : "1");
1459  deflist.back() = tempDef;
1460  }
1461  }
1462 
1463  else if (line.compare(0, 6, "#endif") == 0 && ! deflist.empty()) {
1464  if (deflist.back() == "!" && !ndeflist.empty())
1465  ndeflist.pop_back();
1466  deflist.pop_back();
1467  }
1468  }
1469 
1470  // Remove defined constants from ifdef configurations..
1471  std::size_t count = 0;
1472  for (std::list<std::string>::iterator it = ret.begin(); it != ret.end(); ++it) {
1473  if (_errorLogger)
1474  _errorLogger->reportProgress(filename, "Preprocessing (get configurations 2)", (100 * count++) / ret.size());
1475 
1476  std::string cfg(*it);
1477  for (std::set<std::string>::const_iterator it2 = defines.begin(); it2 != defines.end(); ++it2) {
1478  std::string::size_type pos = 0;
1479 
1480  // Get name of define
1481  std::string defineName(*it2);
1482  const std::string::size_type end = defineName.find_first_of("=(");
1483  if (end != std::string::npos)
1484  defineName.erase(end);
1485 
1486  // Remove ifdef configurations that match the defineName
1487  while ((pos = cfg.find(defineName, pos)) != std::string::npos) {
1488  const std::string::size_type pos1 = pos;
1489  ++pos;
1490  if (pos1 > 0 && cfg[pos1-1] != ';')
1491  continue;
1492  const std::string::size_type pos2 = pos1 + defineName.length();
1493  if (pos2 < cfg.length() && cfg[pos2] != ';')
1494  continue;
1495  --pos;
1496  cfg.erase(pos, defineName.length());
1497  }
1498  }
1499  if (cfg.length() != it->length()) {
1500  while (cfg.length() > 0 && cfg[0] == ';')
1501  cfg.erase(0, 1);
1502 
1503  while (cfg.length() > 0 && cfg.back() == ';')
1504  cfg.erase(cfg.length() - 1);
1505 
1506  std::string::size_type pos = 0;
1507  while ((pos = cfg.find(";;", pos)) != std::string::npos)
1508  cfg.erase(pos, 1);
1509 
1510  *it = cfg;
1511  }
1512  }
1513 
1514  // convert configurations: "defined(A) && defined(B)" => "A;B"
1515  for (std::list<std::string>::iterator it = ret.begin(); it != ret.end(); ++it) {
1516  std::string s(*it);
1517 
1518  if (s.find("&&") != std::string::npos) {
1519  Tokenizer tokenizer(&_settings, _errorLogger);
1520  if (!tokenizer.tokenizeCondition(s)) {
1521  std::ostringstream lineStream;
1522  lineStream << __LINE__;
1523 
1526  loc.setfile(filename);
1527  loc.line = 1;
1528  errmsg._callStack.push_back(loc);
1529  errmsg._severity = Severity::error;
1530  errmsg.setmsg("Error parsing this: " + s);
1531  errmsg._id = "preprocessor" + lineStream.str();
1532  _errorLogger->reportErr(errmsg);
1533  }
1534 
1535 
1536  const Token *tok = tokenizer.tokens();
1537  std::set<std::string> varList;
1538  while (tok) {
1539  if (Token::Match(tok, "defined ( %name% )")) {
1540  varList.insert(tok->strAt(2));
1541  tok = tok->tokAt(4);
1542  if (tok && tok->str() == "&&") {
1543  tok = tok->next();
1544  }
1545  } else if (Token::Match(tok, "%name% ;")) {
1546  varList.insert(tok->str());
1547  tok = tok->tokAt(2);
1548  } else {
1549  break;
1550  }
1551  }
1552 
1553  s = join(varList, ';');
1554 
1555  if (!s.empty())
1556  *it = s;
1557  }
1558  }
1559 
1560  // Convert configurations into a canonical form: B;C;A or C;A;B => A;B;C
1561  for (std::list<std::string>::iterator it = ret.begin(); it != ret.end(); ++it)
1562  *it = unify(*it, ';');
1563 
1564  // Remove duplicates from the ret list..
1565  ret.sort();
1566  ret.unique();
1567 
1568  // cleanup unhandled configurations..
1569  for (std::list<std::string>::iterator it = ret.begin(); it != ret.end();) {
1570  const std::string s(*it + ";");
1571 
1572  bool unhandled = false;
1573 
1574  for (std::string::size_type pos = 0; pos < s.length(); ++pos) {
1575  const unsigned char c = static_cast<unsigned char>(s[pos]);
1576 
1577  // ok with ";"
1578  if (c == ';')
1579  continue;
1580 
1581  // identifier..
1582  if (std::isalpha(c) || c == '_') {
1583  while (std::isalnum((unsigned char)s[pos]) || s[pos] == '_')
1584  ++pos;
1585  if (s[pos] == '=') {
1586  ++pos;
1587  while (std::isdigit((unsigned char)s[pos]))
1588  ++pos;
1589  if (s[pos] != ';') {
1590  unhandled = true;
1591  break;
1592  }
1593  }
1594 
1595  --pos;
1596  continue;
1597  }
1598 
1599  // not ok..
1600  else {
1601  unhandled = true;
1602  break;
1603  }
1604  }
1605 
1606  if (unhandled) {
1607  // unhandled ifdef configuration..
1608  if (_errorLogger && printDebug) {
1609  std::list<ErrorLogger::ErrorMessage::FileLocation> locationList;
1610  const ErrorLogger::ErrorMessage errmsg(locationList, Severity::debug, "unhandled configuration: " + *it, "debug", false);
1611  _errorLogger->reportErr(errmsg);
1612  }
1613 
1614  ret.erase(it++);
1615  } else {
1616  ++it;
1617  }
1618  }
1619 
1620  return ret;
1621 }
1622 
1623 
1624 void Preprocessor::simplifyCondition(const std::map<std::string, std::string> &cfg, std::string &condition, bool match)
1625 {
1626  Tokenizer tokenizer(&_settings, _errorLogger);
1627  if (!tokenizer.tokenizeCondition("(" + condition + ")")) {
1628  // If tokenize returns false, then there is syntax error in the
1629  // code which we can't handle. So stop here.
1630  return;
1631  }
1632 
1633  if (Token::Match(tokenizer.tokens(), "( %name% )")) {
1634  std::map<std::string,std::string>::const_iterator var = cfg.find(tokenizer.tokens()->strAt(1));
1635  if (var != cfg.end()) {
1636  const std::string &value = var->second;
1637  condition = (value == "0") ? "0" : "1";
1638  } else if (match)
1639  condition = "0";
1640  return;
1641  }
1642 
1643  if (Token::Match(tokenizer.tokens(), "( ! %name% )")) {
1644  std::map<std::string,std::string>::const_iterator var = cfg.find(tokenizer.tokens()->strAt(2));
1645 
1646  if (var == cfg.end())
1647  condition = "1";
1648  else if (var->second == "0")
1649  condition = "1";
1650  else if (match)
1651  condition = "0";
1652  return;
1653  }
1654 
1655  // replace variable names with values..
1656  for (Token *tok = const_cast<Token *>(tokenizer.tokens()); tok; tok = tok->next()) {
1657  if (!tok->isName())
1658  continue;
1659 
1660  if (Token::Match(tok, "defined ( %name% )")) {
1661  if (cfg.find(tok->strAt(2)) != cfg.end())
1662  tok->str("1");
1663  else if (match)
1664  tok->str("0");
1665  else
1666  continue;
1667  tok->deleteNext(3);
1668  continue;
1669  }
1670 
1671  if (Token::Match(tok, "defined %name%")) {
1672  if (cfg.find(tok->strAt(1)) != cfg.end())
1673  tok->str("1");
1674  else if (match)
1675  tok->str("0");
1676  else
1677  continue;
1678  tok->deleteNext();
1679  continue;
1680  }
1681 
1682  const std::map<std::string, std::string>::const_iterator it = cfg.find(tok->str());
1683  if (it != cfg.end()) {
1684  if (!it->second.empty()) {
1685  // Tokenize the value
1686  Tokenizer tokenizer2(&_settings, _errorLogger);
1687  tokenizer2.tokenizeCondition(it->second);
1688 
1689  // Copy the value tokens
1690  std::stack<Token *> link;
1691  for (const Token *tok2 = tokenizer2.tokens(); tok2; tok2 = tok2->next()) {
1692  tok->str(tok2->str());
1693 
1694  if (Token::Match(tok2,"[{([]"))
1695  link.push(tok);
1696  else if (!link.empty() && Token::Match(tok2,"[})]]")) {
1697  Token::createMutualLinks(link.top(), tok);
1698  link.pop();
1699  }
1700 
1701  if (tok2->next()) {
1702  tok->insertToken("");
1703  tok = tok->next();
1704  }
1705  }
1706  } else if ((!tok->previous() || Token::Match(tok->previous(), "&&|%oror%|(")) &&
1707  (!tok->next() || Token::Match(tok->next(), "&&|%oror%|)")))
1708  tok->str("1");
1709  else
1710  tok->deleteThis();
1711  }
1712  }
1713 
1714  // simplify calculations..
1716  bool modified = true;
1717  while (modified) {
1718  modified = false;
1719  modified |= tokenizer.simplifySizeof();
1720  modified |= tokenizer.simplifyCalculations();
1721  modified |= tokenizer.simplifyConstTernaryOp();
1722  modified |= tokenizer.simplifyRedundantParentheses();
1723  for (Token *tok = const_cast<Token *>(tokenizer.tokens()); tok; tok = tok->next()) {
1724  if (Token::Match(tok, "! %num%")) {
1725  tok->deleteThis();
1726  tok->str(tok->str() == "0" ? "1" : "0");
1727  modified = true;
1728  }
1729  }
1730  }
1731 
1732  for (Token *tok = const_cast<Token *>(tokenizer.tokens()); tok; tok = tok->next()) {
1733  if (Token::Match(tok, "(|%oror%|&& %num% &&|%oror%|)")) {
1734  if (tok->next()->str() != "0") {
1735  tok->next()->str("1");
1736  }
1737  }
1738  }
1739 
1740  for (Token *tok = const_cast<Token *>(tokenizer.tokens()); tok; tok = tok->next()) {
1741  while (Token::Match(tok, "(|%oror% %any% %oror% 1")) {
1742  tok->deleteNext(2);
1743  if (tok->tokAt(-3))
1744  tok = tok->tokAt(-3);
1745  }
1746  }
1747 
1748  if (Token::simpleMatch(tokenizer.tokens(), "( 1 )") ||
1749  Token::simpleMatch(tokenizer.tokens(), "( 1 ||"))
1750  condition = "1";
1751  else if (Token::simpleMatch(tokenizer.tokens(), "( 0 )"))
1752  condition = "0";
1753 }
1754 
1755 bool Preprocessor::match_cfg_def(std::map<std::string, std::string> cfg, std::string def)
1756 {
1757  /*
1758  std::cout << "cfg: \"";
1759  for (std::map<std::string, std::string>::const_iterator it = cfg.begin(); it != cfg.end(); ++it)
1760  {
1761  std::cout << it->first;
1762  if (!it->second.empty())
1763  std::cout << "=" << it->second;
1764  std::cout << ";";
1765  }
1766  std::cout << "\" ";
1767  std::cout << "def: \"" << def << "\"\n";
1768  */
1769 
1770  simplifyVarMap(cfg, _settings);
1771  simplifyCondition(cfg, def, true);
1772 
1773  if (cfg.find(def) != cfg.end())
1774  return true;
1775 
1776  if (def == "0")
1777  return false;
1778 
1779  if (def == "1")
1780  return true;
1781 
1782  return false;
1783 }
1784 
1785 std::string Preprocessor::getcode(const std::string &filedata, const std::string &cfg, const std::string &filename)
1786 {
1787  // For the error report and preprocessor dump:
1788  // line number relative to current (included) file
1789  // (may decrease when popping back from an included file)
1790  unsigned int lineno = 0;
1791 
1792  std::ostringstream ret;
1793 
1794  bool match = true;
1795  std::list<bool> matching_ifdef;
1796  std::list<bool> matched_ifdef;
1797 
1798  // Create a map for the cfg for faster access to defines
1799  std::map<std::string, std::string> cfgmap(getcfgmap(cfg, &_settings, filename));
1800 
1801  std::stack<std::string> filenames;
1802  filenames.push(filename);
1803  std::stack<unsigned int> lineNumbers;
1804  std::istringstream istr(filedata);
1805  std::string line;
1806  directives.clear();
1807  while (std::getline(istr, line)) {
1808  ++lineno;
1809 
1810  if (line.empty()) {
1811  ret << '\n';
1812  continue;
1813  }
1814 
1815  // record directive for addons / checkers
1816  if ((line[0] == '#')
1817  && (line.compare(0, 6, "#line ") != 0)
1818  && (line.compare(0, 8, "#endfile") != 0)) {
1819  // for clarity, turn "#file ..." back into "#include ..."
1820  std::string orig_line = line;
1821  if (orig_line.compare(0, 6, "#file ")==0)
1822  orig_line.replace(1, 4, "include");
1823  // record directive and extra
1824  directives.push_back(Directive(filenames.top(), lineno,
1825  orig_line));
1826  }
1827 
1828  if (_settings.terminated())
1829  return "";
1830 
1831  if (line.compare(0, 11, "#pragma asm") == 0) {
1832  ret << "\n";
1833  bool found_end = false;
1834  while (getline(istr, line)) {
1835  if (line.compare(0, 14, "#pragma endasm") == 0) {
1836  found_end = true;
1837  break;
1838  }
1839 
1840  ret << "\n";
1841  }
1842  if (!found_end)
1843  break;
1844 
1845  if (line.find('=') != std::string::npos) {
1846  Tokenizer tokenizer(&_settings, _errorLogger);
1847  line.erase(0, sizeof("#pragma endasm"));
1848  std::istringstream tempIstr(line);
1849  tokenizer.tokenize(tempIstr, "", "", true);
1850  if (Token::Match(tokenizer.tokens(), "( %name% = %any% )")) {
1851  ret << "asm(" << tokenizer.tokens()->strAt(1) << ");";
1852  }
1853  }
1854 
1855  ret << "\n";
1856 
1857  continue;
1858  }
1859 
1860  const std::string def = getdef(line, true);
1861  const std::string ndef = getdef(line, false);
1862 
1863  const bool emptymatch = matching_ifdef.empty() || matched_ifdef.empty();
1864 
1865  if (line.compare(0, 8, "#define ") == 0) {
1866  match = true;
1867 
1868 
1869  typedef std::set<std::string>::const_iterator It;
1870  for (It it = _settings.userUndefs.begin(); it != _settings.userUndefs.end(); ++it) {
1871  const std::string::size_type symbolPos = line.find_first_not_of(' ', 8);
1872  if (symbolPos == std::string::npos)
1873  continue;
1874  const std::string::size_type undefMatchPos = line.find(*it, symbolPos);
1875  if (undefMatchPos == std::string::npos)
1876  continue;
1877  const std::string::size_type behindUndefPos = undefMatchPos + (*it).size();
1878  if ((line.size() == behindUndefPos) ||
1879  (line[behindUndefPos] == ' ') ||
1880  (line[behindUndefPos] == '(')) {
1881  match = false;
1882  break;
1883  }
1884  }
1885 
1886  if (match) {
1887  for (std::list<bool>::const_iterator it = matching_ifdef.begin(); it != matching_ifdef.end(); ++it) {
1888  if (!bool(*it)) {
1889  match = false;
1890  break;
1891  }
1892  }
1893  }
1894 
1895  if (match) {
1896  const std::string::size_type pos = line.find_first_of(" (", 8);
1897  if (pos == std::string::npos)
1898  cfgmap[line.substr(8)] = "";
1899  else if (line[pos] == ' ') {
1900  std::string value(line.substr(pos + 1));
1901  std::map<std::string, std::string>::const_iterator cfgpos = cfgmap.find(value);
1902  if (cfgpos != cfgmap.end())
1903  value = cfgpos->second;
1904  cfgmap[line.substr(8, pos - 8)] = value;
1905  } else
1906  cfgmap[line.substr(8, pos - 8)] = "";
1907  }
1908  }
1909 
1910  else if (line.compare(0, 7, "#undef ") == 0) {
1911  const std::string name(line.substr(7));
1912  cfgmap.erase(name);
1913  }
1914 
1915  else if (!emptymatch && line.compare(0, 7, "#elif !") == 0) {
1916  if (matched_ifdef.back()) {
1917  matching_ifdef.back() = false;
1918  } else {
1919  if (!match_cfg_def(cfgmap, ndef)) {
1920  matching_ifdef.back() = true;
1921  matched_ifdef.back() = true;
1922  }
1923  }
1924  }
1925 
1926  else if (!emptymatch && line.compare(0, 6, "#elif ") == 0) {
1927  if (matched_ifdef.back()) {
1928  matching_ifdef.back() = false;
1929  } else {
1930  if (match_cfg_def(cfgmap, def)) {
1931  matching_ifdef.back() = true;
1932  matched_ifdef.back() = true;
1933  }
1934  }
1935  }
1936 
1937  else if (line.compare(0,4,"#if ") == 0) {
1938  matching_ifdef.push_back(match_cfg_def(cfgmap, line.substr(4)));
1939  matched_ifdef.push_back(matching_ifdef.back());
1940  }
1941 
1942  else if (! def.empty()) {
1943  matching_ifdef.push_back(cfgmap.find(def) != cfgmap.end());
1944  matched_ifdef.push_back(matching_ifdef.back());
1945  }
1946 
1947  else if (! ndef.empty()) {
1948  matching_ifdef.push_back(cfgmap.find(ndef) == cfgmap.end());
1949  matched_ifdef.push_back(matching_ifdef.back());
1950  }
1951 
1952  else if (!emptymatch && line == "#else") {
1953  if (! matched_ifdef.empty())
1954  matching_ifdef.back() = ! matched_ifdef.back();
1955  }
1956 
1957  else if (line.compare(0, 6, "#endif") == 0) {
1958  if (! matched_ifdef.empty())
1959  matched_ifdef.pop_back();
1960  if (! matching_ifdef.empty())
1961  matching_ifdef.pop_back();
1962  }
1963 
1964  if (!line.empty() && line[0] == '#') {
1965  match = true;
1966  for (std::list<bool>::const_iterator it = matching_ifdef.begin(); it != matching_ifdef.end(); ++it) {
1967  if (!bool(*it)) {
1968  match = false;
1969  break;
1970  }
1971  }
1972  }
1973 
1974  // #error => return ""
1975  if (match && line.compare(0, 6, "#error") == 0) {
1976  if (!_settings.userDefines.empty() && !_settings.force) {
1977  error(Path::simplifyPath(filenames.top()), lineno, line);
1978  }
1979  return "";
1980  }
1981 
1982  if (!match && (line.compare(0, 8, "#define ") == 0 ||
1983  line.compare(0, 6, "#undef") == 0)) {
1984  // Remove define that is not part of this configuration
1985  line = "";
1986  } else if (line.compare(0, 7, "#file \"") == 0 ||
1987  line.compare(0, 8, "#endfile") == 0 ||
1988  line.compare(0, 8, "#define ") == 0 ||
1989  line.compare(0, 6, "#line ") == 0 ||
1990  line.compare(0, 6, "#undef") == 0) {
1991  // We must not remove #file tags or line numbers
1992  // are corrupted. File tags are removed by the tokenizer.
1993 
1994  // Keep location info updated
1995  if (line.compare(0, 7, "#file \"") == 0) {
1996  filenames.push(line.substr(7, line.size() - 8));
1997  lineNumbers.push(lineno);
1998  lineno = 0;
1999  } else if (line.compare(0, 8, "#endfile") == 0) {
2000  if (filenames.size() > 1U)
2001  filenames.pop();
2002 
2003  if (!lineNumbers.empty()) {
2004  lineno = lineNumbers.top();
2005  lineNumbers.pop();
2006  }
2007  }
2008  } else if (!match || line.compare(0, 1, "#") == 0) {
2009  // Remove #if, #else, #pragma etc, leaving only
2010  // #define, #undef, #file and #endfile. and also lines
2011  // which are not part of this configuration.
2012  line = "";
2013  }
2014 
2015  ret << line << "\n";
2016  }
2017 
2018  if (!validateCfg(ret.str(), cfg)) {
2019  return "";
2020  }
2021 
2022  return expandMacros(ret.str(), filename, cfg, _errorLogger);
2023 }
2024 
2025 void Preprocessor::error(const std::string &filename, unsigned int linenr, const std::string &msg)
2026 {
2027  std::list<ErrorLogger::ErrorMessage::FileLocation> locationList;
2028  if (!filename.empty()) {
2029  ErrorLogger::ErrorMessage::FileLocation loc(filename, linenr);
2030  locationList.push_back(loc);
2031  }
2034  msg,
2035  "preprocessorErrorDirective",
2036  false));
2037 }
2038 
2040 {
2041  std::string::size_type i = str.find_first_of("<\"");
2042  if (i == std::string::npos) {
2043  str = "";
2044  return NoHeader;
2045  }
2046 
2047  char c = str[i];
2048  if (c == '<')
2049  c = '>';
2050 
2051  std::string result;
2052  for (i = i + 1; i < str.length(); ++i) {
2053  if (str[i] == c)
2054  break;
2055 
2056  result.append(1, str[i]);
2057  }
2058 
2059  // Linux can't open include paths with \ separator, so fix them
2060  std::replace(result.begin(), result.end(), '\\', '/');
2061 
2062  str = result;
2063 
2064  return (c == '\"') ? UserHeader : SystemHeader;
2065 }
2066 
2067 /**
2068  * Try to open header
2069  * @param filename header name (in/out)
2070  * @param includePaths paths where to look for the file
2071  * @param filePath path to the header file
2072  * @param fin file input stream (in/out)
2073  * @return if file is opened then true is returned
2074  */
2075 static bool openHeader(std::string &filename, const std::list<std::string> &includePaths, const std::string &filePath, std::ifstream &fin)
2076 {
2077  fin.open((filePath + filename).c_str());
2078  if (fin.is_open()) {
2079  filename = filePath + filename;
2080  return true;
2081  }
2082 
2083  fin.open(filename.c_str());
2084  if (fin.is_open())
2085  return true;
2086 
2087  for (std::list<std::string>::const_iterator iter = includePaths.begin(); iter != includePaths.end(); ++iter) {
2088  const std::string nativePath(Path::toNativeSeparators(*iter));
2089  fin.open((nativePath + filename).c_str());
2090  if (fin.is_open()) {
2091  filename = nativePath + filename;
2092  return true;
2093  }
2094  fin.clear();
2095  }
2096 
2097  return false;
2098 }
2099 
2100 
2101 std::string Preprocessor::handleIncludes(const std::string &code, const std::string &filePath, const std::list<std::string> &includePaths, std::map<std::string,std::string> &defs, std::set<std::string> &pragmaOnce, std::list<std::string> includes)
2102 {
2103  std::string path;
2104  std::string::size_type sep_pos = filePath.find_last_of("\\/");
2105  if (sep_pos != std::string::npos)
2106  path = filePath.substr(0, 1 + sep_pos);
2107 
2108  // current #if indent level.
2109  std::stack<bool>::size_type indent = 0;
2110 
2111  // how deep does the #if match? this can never be bigger than "indent".
2112  std::stack<bool>::size_type indentmatch = 0;
2113 
2114  // has there been a true #if condition at the current indentmatch level?
2115  // then no more #elif or #else can be true before the #endif is seen.
2116  std::stack<bool> elseIsTrueStack;
2117 
2118  unsigned int linenr = 0;
2119 
2120  const std::set<std::string> &undefs = _settings.userUndefs;
2121 
2122  if (_errorLogger)
2123  _errorLogger->reportProgress(filePath, "Preprocessor (handleIncludes)", 0);
2124 
2125  std::ostringstream ostr;
2126  std::istringstream istr(code);
2127  std::string line;
2128  bool suppressCurrentCodePath = false;
2129  while (std::getline(istr,line)) {
2130  ++linenr;
2131 
2132  if (_settings.terminated())
2133  return "";
2134 
2135  // has there been a true #if condition at the current indentmatch level?
2136  // then no more #elif or #else can be true before the #endif is seen.
2137  while (elseIsTrueStack.size() != indentmatch + 1) {
2138  if (elseIsTrueStack.size() < indentmatch + 1) {
2139  elseIsTrueStack.push(true);
2140  } else {
2141  elseIsTrueStack.pop();
2142  }
2143  }
2144 
2145  if (elseIsTrueStack.empty()) {
2146  writeError(filePath, linenr, _errorLogger, "syntaxError", "Syntax error in preprocessor code");
2147  return "";
2148  }
2149 
2150  std::stack<bool>::reference elseIsTrue = elseIsTrueStack.top();
2151 
2152  if (line == "#pragma once") {
2153  pragmaOnce.insert(filePath);
2154  } else if (line.compare(0,7,"#ifdef ") == 0) {
2155  if (indent == indentmatch) {
2156  const std::string tag = getdef(line,true);
2157  if (defs.find(tag) != defs.end()) {
2158  elseIsTrue = false;
2159  indentmatch++;
2160  } else if (undefs.find(tag) != undefs.end()) {
2161  elseIsTrue = true;
2162  indentmatch++;
2163  suppressCurrentCodePath = true;
2164  }
2165  }
2166  ++indent;
2167 
2168  if (indent == indentmatch + 1)
2169  elseIsTrue = true;
2170  } else if (line.compare(0,8,"#ifndef ") == 0) {
2171  if (indent == indentmatch) {
2172  const std::string tag = getdef(line,false);
2173  if (defs.find(tag) == defs.end()) {
2174  elseIsTrue = false;
2175  indentmatch++;
2176  } else if (undefs.find(tag) != undefs.end()) {
2177  elseIsTrue = false;
2178  indentmatch++;
2179  suppressCurrentCodePath = false;
2180  }
2181  }
2182  ++indent;
2183 
2184  if (indent == indentmatch + 1)
2185  elseIsTrue = true;
2186 
2187  } else if (line.compare(0,4,"#if ") == 0) {
2188  if (!suppressCurrentCodePath && indent == indentmatch && match_cfg_def(defs, line.substr(4))) {
2189  elseIsTrue = false;
2190  indentmatch++;
2191  }
2192  ++indent;
2193 
2194  if (indent == indentmatch + 1)
2195  elseIsTrue = true; // this value doesn't matter when suppressCurrentCodePath is true
2196  } else if (line.compare(0,6,"#elif ") == 0 || line.compare(0,5,"#else") == 0) {
2197  if (!elseIsTrue) {
2198  if ((indentmatch > 0) && (indentmatch == indent)) {
2199  indentmatch = indent - 1;
2200  }
2201  } else {
2202  if ((indentmatch > 0) && (indentmatch == indent)) {
2203  indentmatch = indent - 1;
2204  } else if ((indent > 0) && indentmatch == indent - 1) {
2205  if (line.compare(0,5,"#else")==0 || match_cfg_def(defs,line.substr(6))) {
2206  indentmatch = indent;
2207  elseIsTrue = false;
2208  }
2209  }
2210  }
2211  } else if (line.compare(0, 6, "#endif") == 0) {
2212  if (indent > 0)
2213  --indent;
2214  if (indentmatch > indent || indent == 0) {
2215  indentmatch = indent;
2216  elseIsTrue = false;
2217  suppressCurrentCodePath = false;
2218  }
2219  } else if (indentmatch == indent) {
2220  if (!suppressCurrentCodePath && line.compare(0, 8, "#define ") == 0) {
2221  const unsigned int endOfDefine = 8;
2222  std::string::size_type endOfTag = line.find_first_of("( ", endOfDefine);
2223  std::string tag;
2224 
2225  // define a symbol
2226  if (endOfTag == std::string::npos) {
2227  tag = line.substr(endOfDefine);
2228  defs[tag] = "";
2229  } else {
2230  tag = line.substr(endOfDefine, endOfTag-endOfDefine);
2231 
2232  // define a function-macro
2233  if (line[endOfTag] == '(') {
2234  defs[tag] = "";
2235  }
2236  // define value
2237  else {
2238  ++endOfTag;
2239 
2240  const std::string& value = line.substr(endOfTag, line.size()-endOfTag);
2241 
2242  if (defs.find(value) != defs.end())
2243  defs[tag] = defs[value];
2244  else
2245  defs[tag] = value;
2246  }
2247  }
2248 
2249  if (undefs.find(tag) != undefs.end()) {
2250  defs.erase(tag);
2251  }
2252  }
2253 
2254  else if (!suppressCurrentCodePath && line.compare(0,7,"#undef ") == 0) {
2255  defs.erase(line.substr(7));
2256  }
2257 
2258  else if (!suppressCurrentCodePath && line.compare(0,9,"#include ")==0) {
2259  std::string filename(line.substr(9));
2260 
2261  const HeaderTypes headerType = getHeaderFileName(filename);
2262  if (headerType == NoHeader) {
2263  ostr << std::endl;
2264  continue;
2265  }
2266 
2267  // try to open file
2268  std::string filepath;
2269  if (headerType == UserHeader)
2270  filepath = path;
2271  std::ifstream fin;
2272  if (!openHeader(filename, includePaths, filepath, fin)) {
2274  linenr,
2275  filename,
2276  headerType
2277  );
2278  ostr << std::endl;
2279  continue;
2280  }
2281 
2282  // Prevent that files are recursively included
2283  if (std::find(includes.begin(), includes.end(), filename) != includes.end()) {
2284  ostr << std::endl;
2285  continue;
2286  }
2287 
2288  includes.push_back(filename);
2289 
2290  // Don't include header if it's already included and contains #pragma once
2291  if (pragmaOnce.find(filename) != pragmaOnce.end()) {
2292  ostr << std::endl;
2293  continue;
2294  }
2295 
2296  ostr << "#file \"" << filename << "\"\n"
2297  << handleIncludes(read(fin, filename), filename, includePaths, defs, pragmaOnce, includes) << std::endl
2298  << "#endfile\n";
2299  continue;
2300  }
2301 
2302  if (!suppressCurrentCodePath)
2303  ostr << line;
2304  }
2305 
2306  // A line has been read..
2307  ostr << "\n";
2308  }
2309 
2310  return ostr.str();
2311 }
2312 
2313 
2314 void Preprocessor::handleIncludes(std::string &code, const std::string &filePath, const std::list<std::string> &includePaths)
2315 {
2316  std::list<std::string> paths;
2317  std::string path = filePath;
2318  const std::string::size_type sep_pos = path.find_last_of("\\/");
2319  if (sep_pos != std::string::npos)
2320  path.erase(1 + sep_pos);
2321  paths.push_back(path);
2322  std::string::size_type pos = 0;
2323  std::string::size_type endfilePos = 0;
2324  if (code.compare(0,7U,"#file \"")==0) {
2325  const std::string::size_type start = code.find("#file \"" + filePath, 7U);
2326  if (start != std::string::npos)
2327  endfilePos = start;
2328  }
2329  std::set<std::string> handledFiles;
2330  while ((pos = code.find("#include", pos)) != std::string::npos) {
2331  if (_settings.terminated())
2332  return;
2333 
2334  // Accept only includes that are at the start of a line
2335  if (pos > 0 && code[pos-1] != '\n') {
2336  pos += 8; // length of "#include"
2337  continue;
2338  }
2339 
2340  // If endfile is encountered, we have moved to a next file in our stack,
2341  // so remove last path in our list.
2342  while (!paths.empty() && (endfilePos = code.find("\n#endfile", endfilePos)) != std::string::npos && endfilePos < pos) {
2343  paths.pop_back();
2344  endfilePos += 9; // size of #endfile
2345  }
2346 
2347  endfilePos = pos;
2348  std::string::size_type end = code.find('\n', pos);
2349  std::string filename = code.substr(pos, end - pos);
2350 
2351  // Remove #include clause
2352  code.erase(pos, end - pos);
2353 
2354  HeaderTypes headerType = getHeaderFileName(filename);
2355  if (headerType == NoHeader)
2356  continue;
2357 
2358  // filename contains now a file name e.g. "menu.h"
2359  std::string processedFile;
2360  std::string filepath;
2361  if (headerType == UserHeader && !paths.empty())
2362  filepath = paths.back();
2363  std::ifstream fin;
2364  const bool fileOpened(openHeader(filename, includePaths, filepath, fin));
2365 
2366  if (fileOpened) {
2367  filename = Path::simplifyPath(filename);
2368  std::string tempFile = filename;
2369  std::transform(tempFile.begin(), tempFile.end(), tempFile.begin(), tolowerWrapper);
2370  if (handledFiles.find(tempFile) != handledFiles.end()) {
2371  // We have processed this file already once, skip
2372  // it this time to avoid eternal loop.
2373  fin.close();
2374  continue;
2375  }
2376 
2377  handledFiles.insert(tempFile);
2378  processedFile = Preprocessor::read(fin, filename);
2379  fin.close();
2380  }
2381 
2382  if (!processedFile.empty()) {
2383  // Remove space characters that are after or before new line character
2384  processedFile = "#file \"" + Path::fromNativeSeparators(filename) + "\"\n" + processedFile + "\n#endfile";
2385  code.insert(pos, processedFile);
2386 
2387  path = filename;
2388  path.erase(1 + path.find_last_of("\\/"));
2389  paths.push_back(path);
2390  } else if (!fileOpened) {
2391  std::string f = filePath;
2392 
2393  // Determine line number of include
2394  unsigned int linenr = 1;
2395  unsigned int level = 0;
2396  for (std::string::size_type p = 1; p <= pos; ++p) {
2397  if (level == 0 && code[pos-p] == '\n')
2398  ++linenr;
2399  else if (code.compare(pos-p, 9, "#endfile\n") == 0) {
2400  ++level;
2401  } else if (code.compare(pos-p, 6, "#file ") == 0) {
2402  if (level == 0) {
2403  linenr--;
2404  const std::string::size_type pos1 = pos - p + 7;
2405  const std::string::size_type pos2 = code.find_first_of("\"\n", pos1);
2406  f = code.substr(pos1, (pos2 == std::string::npos) ? pos2 : (pos2 - pos1));
2407  break;
2408  }
2409  --level;
2410  }
2411  }
2412 
2414  linenr,
2415  filename,
2416  headerType);
2417  }
2418  }
2419 }
2420 
2421 // Report that include is missing
2422 void Preprocessor::missingInclude(const std::string &filename, unsigned int linenr, const std::string &header, HeaderTypes headerType)
2423 {
2424  const std::string fname = Path::fromNativeSeparators(filename);
2425  if (_settings.nomsg.isSuppressed("missingInclude", fname, linenr))
2426  return;
2427  if (headerType == SystemHeader && _settings.nomsg.isSuppressed("missingIncludeSystem", fname, linenr))
2428  return;
2429 
2430  if (headerType == SystemHeader)
2431  missingSystemIncludeFlag = true;
2432  else
2433  missingIncludeFlag = true;
2435 
2436  std::list<ErrorLogger::ErrorMessage::FileLocation> locationList;
2437  if (!filename.empty()) {
2439  loc.line = linenr;
2440  loc.setfile(Path::toNativeSeparators(filename));
2441  locationList.push_back(loc);
2442  }
2443  ErrorLogger::ErrorMessage errmsg(locationList, Severity::information,
2444  (headerType==SystemHeader) ?
2445  "Include file: <" + header + "> not found. Please note: Cppcheck does not need standard library headers to get proper results." :
2446  "Include file: \"" + header + "\" not found.",
2447  (headerType==SystemHeader) ? "missingIncludeSystem" : "missingInclude",
2448  false);
2449  errmsg.file0 = file0;
2450  _errorLogger->reportInfo(errmsg);
2451  }
2452 }
2453 
2454 /**
2455  * Skip string in line. A string begins and ends with either a &quot; or a &apos;
2456  * @param line the string
2457  * @param pos in=start position of string, out=end position of string
2458  */
2459 static void skipstring(const std::string &line, std::string::size_type &pos)
2460 {
2461  const char ch = line[pos];
2462 
2463  ++pos;
2464  while (pos < line.size() && line[pos] != ch) {
2465  if (line[pos] == '\\')
2466  ++pos;
2467  ++pos;
2468  }
2469 }
2470 
2471 /**
2472  * @brief get parameters from code. For example 'foo(1,2)' => '1','2'
2473  * @param line in: The code
2474  * @param pos in: Position to the '('. out: Position to the ')'
2475  * @param params out: The extracted parameters
2476  * @param numberOfNewlines out: number of newlines in the macro call
2477  * @param endFound out: was the end parentheses found?
2478  */
2479 static void getparams(const std::string &line,
2480  std::string::size_type &pos,
2481  std::vector<std::string> &params,
2482  unsigned int &numberOfNewlines,
2483  bool &endFound)
2484 {
2485  params.clear();
2486  numberOfNewlines = 0;
2487  endFound = false;
2488 
2489  if (line[pos] == ' ')
2490  pos++;
2491 
2492  if (line[pos] != '(')
2493  return;
2494 
2495  // parentheses level
2496  int parlevel = 0;
2497 
2498  // current parameter data
2499  std::string par;
2500 
2501  // scan for parameters..
2502  for (; pos < line.length(); ++pos) {
2503  // increase parentheses level
2504  if (line[pos] == '(') {
2505  ++parlevel;
2506  if (parlevel == 1)
2507  continue;
2508  }
2509 
2510  // decrease parentheses level
2511  else if (line[pos] == ')') {
2512  --parlevel;
2513  if (parlevel <= 0) {
2514  endFound = true;
2515  params.push_back(trim(par));
2516  break;
2517  }
2518  }
2519 
2520  // string
2521  else if (line[pos] == '\"' || line[pos] == '\'') {
2522  const std::string::size_type p = pos;
2523  skipstring(line, pos);
2524  if (pos == line.length())
2525  break;
2526  par += line.substr(p, pos + 1 - p);
2527  continue;
2528  }
2529 
2530  // count newlines. the expanded macro must have the same number of newlines
2531  else if (line[pos] == '\n') {
2532  ++numberOfNewlines;
2533  continue;
2534  }
2535 
2536  // new parameter
2537  if (parlevel == 1 && line[pos] == ',') {
2538  params.push_back(trim(par));
2539  par = "";
2540  }
2541 
2542  // spaces are only added if needed
2543  else if (line[pos] == ' ') {
2544  // Add space only if it is needed
2545  if (par.size() && std::isalnum((unsigned char)par.back())) {
2546  par += ' ';
2547  }
2548  }
2549 
2550  // add character to current parameter
2551  else if (parlevel >= 1 && line[pos] != Preprocessor::macroChar) {
2552  par.append(1, line[pos]);
2553  }
2554  }
2555 }
2556 
2557 /** @brief Class that the preprocessor uses when it expands macros. This class represents a preprocessor macro */
2559 private:
2560  /** tokens of this macro */
2562 
2563  /** macro parameters */
2564  std::vector<std::string> _params;
2565 
2566  /** macro definition in plain text */
2567  const std::string _macro;
2568 
2569  /** does this macro take a variable number of parameters? */
2571 
2572  /** The macro has parentheses but no parameters.. "AAA()" */
2573  bool _nopar;
2574 
2575  /** disabled assignment operator */
2576  void operator=(const PreprocessorMacro &);
2577 
2578  /** @brief expand inner macro */
2579  std::vector<std::string> expandInnerMacros(const std::vector<std::string> &params1,
2580  const std::map<std::string, PreprocessorMacro *> &macros) const {
2581  std::string innerMacroName;
2582 
2583  // Is there an inner macro..
2584  {
2585  const Token *tok = Token::findsimplematch(tokens(), ")");
2586  if (!Token::Match(tok, ") %name% ("))
2587  return params1;
2588  innerMacroName = tok->strAt(1);
2589  tok = tok->tokAt(3);
2590  unsigned int par = 0;
2591  while (Token::Match(tok, "%name% ,|)")) {
2592  tok = tok->tokAt(2);
2593  par++;
2594  }
2595  if (tok || par != params1.size())
2596  return params1;
2597  }
2598 
2599  std::vector<std::string> params2(params1);
2600 
2601  for (std::size_t ipar = 0; ipar < params1.size(); ++ipar) {
2602  const std::string s(innerMacroName + "(");
2603  const std::string param(params1[ipar]);
2604  if (param.compare(0,s.length(),s)==0 && param.back() == ')') {
2605  std::vector<std::string> innerparams;
2606  std::string::size_type pos = s.length() - 1;
2607  unsigned int num = 0;
2608  bool endFound = false;
2609  getparams(param, pos, innerparams, num, endFound);
2610  if (pos == param.length()-1 && num==0 && endFound && innerparams.size() == params1.size()) {
2611  // Is inner macro defined?
2612  std::map<std::string, PreprocessorMacro *>::const_iterator it = macros.find(innerMacroName);
2613  if (it != macros.end()) {
2614  // expand the inner macro
2615  const PreprocessorMacro *innerMacro = it->second;
2616 
2617  std::string innercode;
2618  std::map<std::string,PreprocessorMacro *> innermacros = macros;
2619  innermacros.erase(innerMacroName);
2620  innerMacro->code(innerparams, innermacros, innercode);
2621  params2[ipar] = innercode;
2622  }
2623  }
2624  }
2625  }
2626 
2627  return params2;
2628  }
2629 
2630 public:
2631  /**
2632  * @brief Constructor for PreprocessorMacro. This is the "setter"
2633  * for this class - everything is setup here.
2634  * @param [in] macro The code after define, until end of line,
2635  * e.g. "A(x) foo(x);"
2636  * @param [in] settings Current settings being used
2637  */
2638  PreprocessorMacro(const std::string &macro, const Settings* settings)
2639  : tokenlist(settings), _macro(macro) {
2640 
2641  // Tokenize the macro to make it easier to handle
2642  std::istringstream istr(macro);
2643  tokenlist.createTokens(istr);
2644 
2645  // initialize parameters to default values
2646  _variadic = _nopar = false;
2647 
2648  const std::string::size_type pos = macro.find_first_of(" (");
2649  if (pos != std::string::npos && macro[pos] == '(') {
2650  // Extract macro parameters
2651  if (Token::Match(tokens(), "%name% ( %name%")) {
2652  for (const Token *tok = tokens()->tokAt(2); tok; tok = tok->next()) {
2653  if (tok->str() == ")")
2654  break;
2655  if (Token::simpleMatch(tok, ". . . )")) {
2656  if (tok->previous()->str() == ",")
2657  _params.push_back("__VA_ARGS__");
2658  _variadic = true;
2659  break;
2660  }
2661  if (tok->isName())
2662  _params.push_back(tok->str());
2663  }
2664  }
2665 
2666  else if (Token::Match(tokens(), "%name% ( . . . )"))
2667  _variadic = true;
2668 
2669  else if (Token::Match(tokens(), "%name% ( )"))
2670  _nopar = true;
2671  }
2672  }
2673 
2674  /** return tokens of this macro */
2675  const Token *tokens() const {
2676  return tokenlist.front();
2677  }
2678 
2679  /** read parameters of this macro */
2680  const std::vector<std::string> &params() const {
2681  return _params;
2682  }
2683 
2684  /** check if this is macro has a variable number of parameters */
2685  bool variadic() const {
2686  return _variadic;
2687  }
2688 
2689  /** Check if this macro has parentheses but no parameters */
2690  bool nopar() const {
2691  return _nopar;
2692  }
2693 
2694  /** name of macro */
2695  const std::string &name() const {
2696  return tokens() ? tokens()->str() : emptyString;
2697  }
2698 
2699  /**
2700  * get expanded code for this macro
2701  * @param params2 macro parameters
2702  * @param macros macro definitions (recursion)
2703  * @param macrocode output string
2704  * @return true if the expanding was successful
2705  */
2706  bool code(const std::vector<std::string> &params2, const std::map<std::string, PreprocessorMacro *> &macros, std::string &macrocode) const {
2707  if (_nopar || (_params.empty() && _variadic)) {
2708  macrocode = _macro.substr(1 + _macro.find(')'));
2709  if (macrocode.empty())
2710  return true;
2711 
2712  std::string::size_type pos = 0;
2713  // Remove leading spaces
2714  if ((pos = macrocode.find_first_not_of(" ")) > 0)
2715  macrocode.erase(0, pos);
2716  // Remove ending newline
2717  if ((pos = macrocode.find_first_of("\r\n")) != std::string::npos)
2718  macrocode.erase(pos);
2719 
2720  // Replace "__VA_ARGS__" with parameters
2721  if (!_nopar) {
2722  std::string s;
2723  for (std::size_t i = 0; i < params2.size(); ++i) {
2724  if (i > 0)
2725  s += ",";
2726  s += params2[i];
2727  }
2728 
2729  pos = 0;
2730  while ((pos = macrocode.find("__VA_ARGS__", pos)) != std::string::npos) {
2731  macrocode.erase(pos, 11);
2732  macrocode.insert(pos, s);
2733  pos += s.length();
2734  }
2735  }
2736  }
2737 
2738  else if (_params.empty()) {
2739  std::string::size_type pos = _macro.find_first_of(" \"");
2740  if (pos == std::string::npos)
2741  macrocode = "";
2742  else {
2743  if (_macro[pos] == ' ')
2744  pos++;
2745  macrocode = _macro.substr(pos);
2746  if ((pos = macrocode.find_first_of("\r\n")) != std::string::npos)
2747  macrocode.erase(pos);
2748  }
2749  }
2750 
2751  else {
2752  const std::vector<std::string> givenparams = expandInnerMacros(params2, macros);
2753 
2754  const Token *tok = tokens();
2755  while (tok && tok->str() != ")")
2756  tok = tok->next();
2757  if (tok) {
2758  bool optcomma = false;
2759  while (nullptr != (tok = tok->next())) {
2760  std::string str = tok->str();
2761  if (str[0] == '#' || tok->isName()) {
2762  if (str == "##")
2763  continue;
2764 
2765  const bool stringify(str[0] == '#');
2766  if (stringify) {
2767  str = str.erase(0, 1);
2768  }
2769  for (std::size_t i = 0; i < _params.size(); ++i) {
2770  if (str == _params[i]) {
2771  if (_variadic &&
2772  (i == _params.size() - 1 ||
2773  (givenparams.size() + 2 == _params.size() && i + 1 == _params.size() - 1))) {
2774  str = "";
2775  for (std::size_t j = _params.size() - 1; j < givenparams.size(); ++j) {
2776  if (optcomma || j > _params.size() - 1)
2777  str += ",";
2778  optcomma = false;
2779  str += givenparams[j];
2780  }
2781  } else if (i >= givenparams.size()) {
2782  // Macro had more parameters than caller used.
2783  macrocode = "";
2784  return false;
2785  } else if (stringify) {
2786  const std::string &s(givenparams[i]);
2787  std::ostringstream ostr;
2788  ostr << "\"";
2789  for (std::string::size_type j = 0; j < s.size(); ++j) {
2790  if (s[j] == '\\' || s[j] == '\"')
2791  ostr << '\\';
2792  ostr << s[j];
2793  }
2794  str = ostr.str() + "\"";
2795  } else
2796  str = givenparams[i];
2797 
2798  break;
2799  }
2800  }
2801 
2802  // expand nopar macro
2803  if (tok->strAt(-1) != "##") {
2804  const std::map<std::string, PreprocessorMacro *>::const_iterator it = macros.find(str);
2805  if (it != macros.end() && it->second->_macro.find('(') == std::string::npos) {
2806  const std::string& macro = it->second->_macro;
2807  const std::string::size_type whitespacePos = macro.find(' ');
2808  if (whitespacePos != std::string::npos)
2809  str = macro.substr(whitespacePos);
2810  else
2811  str = "";
2812  }
2813  }
2814  }
2815  if (_variadic && tok->str() == "," && tok->next() && tok->next()->str() == "##") {
2816  optcomma = true;
2817  continue;
2818  }
2819  optcomma = false;
2820  // separate ++ and -- with space
2821  if (!str.empty() && !macrocode.empty() && (str[0] == '+' || str[0] == '-') && str[0] == macrocode[macrocode.size()-1U])
2822  macrocode += ' ';
2823  macrocode += str;
2824  if (Token::Match(tok, "%name% %name%|%num%") ||
2825  Token::Match(tok, "%num% %name%") ||
2826  Token::simpleMatch(tok, "> >"))
2827  macrocode += ' ';
2828  }
2829  }
2830  }
2831 
2832  return true;
2833  }
2834 };
2835 
2836 /**
2837  * Get data from a input string. This is an extended version of std::getline.
2838  * The std::getline only get a single line at a time. It can therefore happen that it
2839  * contains a partial statement. This function ensures that the returned data
2840  * doesn't end in the middle of a statement. The "getlines" name indicate that
2841  * this function will return multiple lines if needed.
2842  * @param istr input stream
2843  * @param line output data
2844  * @return success
2845  */
2846 static bool getlines(std::istream &istr, std::string &line)
2847 {
2848  if (!istr.good())
2849  return false;
2850  line = "";
2851  int parlevel = 0;
2852  bool directive = false;
2853  for (char ch = (char)istr.get(); istr.good(); ch = (char)istr.get()) {
2854  if (ch == '\'' || ch == '\"') {
2855  line += ch;
2856  char c = 0;
2857  while (istr.good() && c != ch) {
2858  if (c == '\\') {
2859  c = (char)istr.get();
2860  if (!istr.good())
2861  return true;
2862  line += c;
2863  }
2864 
2865  c = (char)istr.get();
2866  if (!istr.good())
2867  return true;
2868  if (c == '\n' && directive)
2869  return true;
2870  line += c;
2871  }
2872  continue;
2873  }
2874  if (ch == '(')
2875  ++parlevel;
2876  else if (ch == ')')
2877  --parlevel;
2878  else if (ch == '\n') {
2879  if (directive)
2880  return true;
2881 
2882  if (istr.peek() == '#') {
2883  line += ch;
2884  return true;
2885  }
2886  } else if (!directive && parlevel <= 0 && ch == ';') {
2887  line += ";";
2888  return true;
2889  }
2890 
2891  if (ch == '#' && line.empty())
2892  directive = true;
2893  line += ch;
2894  }
2895  return true;
2896 }
2897 
2898 bool Preprocessor::validateCfg(const std::string &code, const std::string &cfg)
2899 {
2900  const bool printInformation = _settings.isEnabled("information");
2901 
2902  // fill up "macros" with empty configuration macros
2903  std::set<std::string> macros;
2904  for (std::string::size_type pos = 0; pos < cfg.size();) {
2905  const std::string::size_type pos2 = cfg.find_first_of(";=", pos);
2906  if (pos2 == std::string::npos) {
2907  macros.insert(cfg.substr(pos));
2908  break;
2909  }
2910  if (cfg[pos2] == ';')
2911  macros.insert(cfg.substr(pos, pos2-pos));
2912  pos = cfg.find(';', pos2);
2913  if (pos != std::string::npos)
2914  ++pos;
2915  }
2916 
2917  // check if any empty macros are used in code
2918  for (std::set<std::string>::const_iterator it = macros.begin(); it != macros.end(); ++it) {
2919  const std::string &macro = *it;
2920  std::string::size_type pos = 0;
2921  while ((pos = code.find_first_of(std::string("#\"'")+macro[0], pos)) != std::string::npos) {
2922  const std::string::size_type pos1 = pos;
2923  const std::string::size_type pos2 = pos + macro.size();
2924  pos++;
2925 
2926  // skip string..
2927  if (code[pos1] == '\"' || code[pos1] == '\'') {
2928  while (pos < code.size() && code[pos] != code[pos1]) {
2929  if (code[pos] == '\\')
2930  ++pos;
2931  ++pos;
2932  }
2933  ++pos;
2934  }
2935 
2936  // skip preprocessor statement..
2937  else if (code[pos1] == '#') {
2938  if (pos1 == 0 || code[pos1-1] == '\n')
2939  pos = code.find('\n', pos);
2940  }
2941 
2942  // is macro used in code?
2943  else if (code.compare(pos1,macro.size(),macro) == 0) {
2944  if (pos1 > 0 && (std::isalnum((unsigned char)code[pos1-1U]) || code[pos1-1U] == '_'))
2945  continue;
2946  if (pos2 < code.size() && (std::isalnum((unsigned char)code[pos2]) || code[pos2] == '_'))
2947  continue;
2948  // macro is used in code, return false
2949  if (printInformation)
2950  validateCfgError(cfg, macro);
2951  return false;
2952  }
2953  }
2954  }
2955 
2956  return true;
2957 }
2958 
2959 void Preprocessor::validateCfgError(const std::string &cfg, const std::string &macro)
2960 {
2961  const std::string id = "ConfigurationNotChecked";
2962  std::list<ErrorLogger::ErrorMessage::FileLocation> locationList;
2964  locationList.push_back(loc);
2965  ErrorLogger::ErrorMessage errmsg(locationList, Severity::information, "Skipping configuration '" + cfg + "' since the value of '" + macro + "' is unknown. Use -D if you want to check it. You can use -U to skip it explicitly.", id, false);
2966  _errorLogger->reportInfo(errmsg);
2967 }
2968 
2969 std::string Preprocessor::expandMacros(const std::string &code, std::string filename, const std::string &cfg, ErrorLogger *errorLogger)
2970 {
2971  // Search for macros and expand them..
2972  // --------------------------------------------
2973 
2974  // Available macros (key=macroname, value=macro).
2975  std::map<std::string, PreprocessorMacro *> macros;
2976  const Settings settings;
2977 
2978  {
2979  // fill up "macros" with user defined macros
2980  const std::map<std::string,std::string> cfgmap(getcfgmap(cfg,nullptr,""));
2981  std::map<std::string, std::string>::const_iterator it;
2982  for (it = cfgmap.begin(); it != cfgmap.end(); ++it) {
2983  std::string s = it->first;
2984  if (!it->second.empty())
2985  s += " " + it->second;
2986  PreprocessorMacro *macro = new PreprocessorMacro(s, &settings);
2987  macros[it->first] = macro;
2988  }
2989  }
2990 
2991  // Current line number
2992  unsigned int linenr = 1;
2993 
2994  // linenr, filename
2995  std::stack< std::pair<unsigned int, std::string> > fileinfo;
2996 
2997  // output stream
2998  std::ostringstream ostr;
2999 
3000  // read code..
3001  std::istringstream istr(code);
3002  std::string line;
3003  while (getlines(istr, line)) {
3004  if (line.empty())
3005  continue;
3006 
3007  // Preprocessor directive
3008  if (line[0] == '#') {
3009  // defining a macro..
3010  if (line.compare(1, 7, "define ") == 0) {
3011  PreprocessorMacro *macro = new PreprocessorMacro(line.substr(8), &settings);
3012  if (macro->name().empty() || macro->name() == "NULL") {
3013  delete macro;
3014  } else if (macro->name() == "BOOST_FOREACH") {
3015  // BOOST_FOREACH is currently too complex to parse, so skip it.
3016  delete macro;
3017  } else {
3018  std::map<std::string, PreprocessorMacro *>::iterator it;
3019  it = macros.find(macro->name());
3020  if (it != macros.end())
3021  delete it->second;
3022  macros[macro->name()] = macro;
3023  }
3024  line = "\n";
3025  }
3026 
3027  // undefining a macro..
3028  else if (line.compare(1, 6, "undef ") == 0) {
3029  std::map<std::string, PreprocessorMacro *>::iterator it;
3030  it = macros.find(line.substr(7));
3031  if (it != macros.end()) {
3032  delete it->second;
3033  macros.erase(it);
3034  }
3035  line = "\n";
3036  }
3037 
3038  // entering a file, update position..
3039  else if (line.compare(1, 6, "file \"") == 0) {
3040  fileinfo.push(std::pair<unsigned int, std::string>(linenr, filename));
3041  filename = line.substr(7, line.length() - 8);
3042  linenr = 0;
3043  line += "\n";
3044  }
3045 
3046  // leaving a file, update position..
3047  else if (line == "#endfile") {
3048  if (!fileinfo.empty()) {
3049  linenr = fileinfo.top().first;
3050  filename = fileinfo.top().second;
3051  fileinfo.pop();
3052  }
3053  line += "\n";
3054  }
3055 
3056  // all other preprocessor directives are just replaced with a newline
3057  else
3058  line += "\n";
3059  }
3060 
3061  // expand macros..
3062  else {
3063  // Limit for each macro.
3064  // The limit specify a position in the "line" variable.
3065  // For a "recursive macro" where the expanded text contains
3066  // the macro again, the macro should not be expanded again.
3067  // The limits are used to prevent recursive expanding.
3068  // * When a macro is expanded its limit position is set to
3069  // the last expanded character.
3070  // * macros are only allowed to be expanded when the
3071  // the position is beyond the limit.
3072  // * The limit is relative to the end of the "line"
3073  // variable. Inserting and deleting text before the limit
3074  // without updating the limit is safe.
3075  // * when pos goes beyond a limit the limit needs to be
3076  // deleted because it is unsafe to insert/delete text
3077  // after the limit otherwise
3078  std::map<const PreprocessorMacro *, std::size_t> limits;
3079 
3080  // pos is the current position in line
3081  std::string::size_type pos = 0;
3082 
3083  // scan line to see if there are any macros to expand..
3084  unsigned int tmpLinenr = 0;
3085  while (pos < line.size()) {
3086  if (line[pos] == '\n')
3087  ++tmpLinenr;
3088 
3089  // skip strings..
3090  if (line[pos] == '\"' || line[pos] == '\'') {
3091  const char ch = line[pos];
3092 
3093  skipstring(line, pos);
3094  ++pos;
3095 
3096  if (pos >= line.size()) {
3097  writeError(Path::simplifyPath(filename),
3098  linenr + tmpLinenr,
3099  errorLogger,
3100  "noQuoteCharPair",
3101  std::string("No pair for character (") + ch + "). Can't process file. File is either invalid or unicode, which is currently not supported.");
3102 
3103  std::map<std::string, PreprocessorMacro *>::iterator it;
3104  for (it = macros.begin(); it != macros.end(); ++it)
3105  delete it->second;
3106  macros.clear();
3107  return "";
3108  }
3109 
3110  continue;
3111  }
3112 
3113  if (!std::isalpha((unsigned char)line[pos]) && line[pos] != '_')
3114  ++pos;
3115 
3116  // found an identifier..
3117  // the "while" is used in case the expanded macro will immediately call another macro
3118  while (pos < line.length() && (std::isalpha((unsigned char)line[pos]) || line[pos] == '_')) {
3119  // pos1 = start position of macro
3120  const std::string::size_type pos1 = pos++;
3121 
3122  // find the end of the identifier
3123  while (pos < line.size() && (std::isalnum((unsigned char)line[pos]) || line[pos] == '_'))
3124  ++pos;
3125 
3126  // get identifier
3127  const std::string id = line.substr(pos1, pos - pos1);
3128 
3129  // is there a macro with this name?
3130  std::map<std::string, PreprocessorMacro *>::const_iterator it;
3131  it = macros.find(id);
3132  if (it == macros.end())
3133  break; // no macro with this name exist
3134 
3135  const PreprocessorMacro * const macro = it->second;
3136 
3137  // check that pos is within allowed limits for this
3138  // macro
3139  {
3140  const std::map<const PreprocessorMacro *, std::size_t>::const_iterator it2 = limits.find(macro);
3141  if (it2 != limits.end() && pos <= line.length() - it2->second)
3142  break;
3143  }
3144 
3145  // get parameters from line..
3146  if (macro->params().size() && pos >= line.length())
3147  break;
3148  std::vector<std::string> params;
3149  std::string::size_type pos2 = pos;
3150 
3151  // number of newlines within macro use
3152  unsigned int numberOfNewlines = 0;
3153 
3154  // if the macro has parentheses, get parameters
3155  if (macro->variadic() || macro->nopar() || macro->params().size()) {
3156  // is the end parentheses found?
3157  bool endFound = false;
3158 
3159  getparams(line,pos2,params,numberOfNewlines,endFound);
3160 
3161  // something went wrong so bail out
3162  if (!endFound)
3163  break;
3164  }
3165 
3166  // Just an empty parameter => clear
3167  if (params.size() == 1 && params[0] == "")
3168  params.clear();
3169 
3170  // Check that it's the same number of parameters..
3171  if (!macro->variadic() && params.size() != macro->params().size())
3172  break;
3173 
3174  // Create macro code..
3175  std::string tempMacro;
3176  if (!macro->code(params, macros, tempMacro)) {
3177  // Syntax error in code
3178  writeError(filename,
3179  linenr + tmpLinenr,
3180  errorLogger,
3181  "syntaxError",
3182  std::string("Syntax error. Not enough parameters for macro '") + macro->name() + "'.");
3183 
3184  std::map<std::string, PreprocessorMacro *>::iterator iter;
3185  for (iter = macros.begin(); iter != macros.end(); ++iter)
3186  delete iter->second;
3187  macros.clear();
3188  return "";
3189  }
3190 
3191  // make sure number of newlines remain the same..
3192  std::string macrocode(std::string(numberOfNewlines, '\n') + tempMacro);
3193 
3194  // Insert macro code..
3195  if (macro->variadic() || macro->nopar() || !macro->params().empty())
3196  ++pos2;
3197 
3198  // Remove old limits
3199  for (std::map<const PreprocessorMacro *, std::size_t>::iterator iter = limits.begin();
3200  iter != limits.end();) {
3201  if ((line.length() - pos1) < iter->second) {
3202  // We have gone past this limit, so just delete it
3203  limits.erase(iter++);
3204  } else {
3205  ++iter;
3206  }
3207  }
3208 
3209  // don't allow this macro to be expanded again before pos2
3210  limits[macro] = line.length() - pos2;
3211 
3212  // erase macro
3213  line.erase(pos1, pos2 - pos1);
3214 
3215  // Don't glue this macro into variable or number after it
3216  if (!line.empty() && (std::isalnum((unsigned char)line[pos1]) || line[pos1] == '_'))
3217  macrocode.append(1,' ');
3218 
3219  // insert macrochar before each symbol/nr/operator
3220  bool str = false;
3221  bool chr = false;
3222  for (std::size_t i = 0U; i < macrocode.size(); ++i) {
3223  if (macrocode[i] == '\\') {
3224  i++;
3225  continue;
3226  } else if (macrocode[i] == '\"')
3227  str = !str;
3228  else if (macrocode[i] == '\'')
3229  chr = !chr;
3230  else if (str || chr)
3231  continue;
3232  else if (macrocode[i] == '.') { // 5. / .5
3233  if ((i > 0U && std::isdigit((unsigned char)macrocode[i-1])) ||
3234  (i+1 < macrocode.size() && std::isdigit((unsigned char)macrocode[i+1]))) {
3235  if (i > 0U && !std::isdigit((unsigned char)macrocode[i-1])) {
3236  macrocode.insert(i, 1U, macroChar);
3237  i++;
3238  }
3239  i++;
3240  if (i<macrocode.size() && std::isdigit((unsigned char)macrocode[i]))
3241  i++;
3242  if (i+1U < macrocode.size() &&
3243  (macrocode[i] == 'e' || macrocode[i] == 'E') &&
3244  (macrocode[i+1] == '+' || macrocode[i+1] == '-')) {
3245  i+=2;
3246  }
3247  }
3248  } else if (std::isalnum((unsigned char)macrocode[i]) || macrocode[i] == '_') {
3249  if ((i > 0U) &&
3250  (!std::isalnum((unsigned char)macrocode[i-1])) &&
3251  (macrocode[i-1] != '_') &&
3252  (macrocode[i-1] != macroChar)) {
3253  macrocode.insert(i, 1U, macroChar);
3254  }
3255 
3256  // 1e-7 / 1e+7
3257  if (i+3U < macrocode.size() &&
3258  (std::isdigit((unsigned char)macrocode[i]) || macrocode[i]=='.') &&
3259  (macrocode[i+1] == 'e' || macrocode[i+1] == 'E') &&
3260  (macrocode[i+2] == '-' || macrocode[i+2] == '+') &&
3261  std::isdigit((unsigned char)macrocode[i+3])) {
3262  i += 3U;
3263  }
3264 
3265  // 1.f / 1.e7
3266  if (i+2U < macrocode.size() &&
3267  std::isdigit((unsigned char)macrocode[i]) &&
3268  macrocode[i+1] == '.' &&
3269  std::isalpha((unsigned char)macrocode[i+2])) {
3270  i += 2U;
3271  if (i+2U < macrocode.size() &&
3272  (macrocode[i+0] == 'e' || macrocode[i+0] == 'E') &&
3273  (macrocode[i+1] == '-' || macrocode[i+1] == '+') &&
3274  std::isdigit((unsigned char)macrocode[i+2])) {
3275  i += 2U;
3276  }
3277  }
3278  }
3279  }
3280  line.insert(pos1, macroChar + macrocode);
3281 
3282  // position = start position.
3283  pos = pos1;
3284  }
3285  }
3286  }
3287 
3288  // the line has been processed in various ways. Now add it to the output stream
3289  ostr << line;
3290 
3291  // update linenr
3292  for (std::string::size_type p = 0; p < line.length(); ++p) {
3293  if (line[p] == '\n')
3294  ++linenr;
3295  }
3296  }
3297 
3298  for (std::map<std::string, PreprocessorMacro *>::iterator it = macros.begin(); it != macros.end(); ++it)
3299  delete it->second;
3300  macros.clear();
3301 
3302  return ostr.str();
3303 }
3304 
3305 
3306 void Preprocessor::getErrorMessages(ErrorLogger *errorLogger, const Settings *settings)
3307 {
3308  Settings settings2(*settings);
3309  Preprocessor preprocessor(settings2, errorLogger);
3310  settings2.checkConfiguration=true;
3311  preprocessor.missingInclude("", 1, "", UserHeader);
3312  preprocessor.missingInclude("", 1, "", SystemHeader);
3313  preprocessor.validateCfgError("X", "X");
3314  preprocessor.error("", 1, "#error message"); // #error ..
3315 }
3316 
3317 void Preprocessor::dump(std::ostream &out) const
3318 {
3319  // Create a xml directive dump.
3320  // The idea is not that this will be readable for humans. It's a
3321  // data dump that 3rd party tools could load and get useful info from.
3322  std::list<Directive>::const_iterator it;
3323 
3324  out << " <directivelist>" << std::endl;
3325 
3326  for (it = directives.begin(); it != directives.end(); ++it) {
3327  out << " <directive "
3328  << "file=\"" << it->file << "\" "
3329  << "linenr=\"" << it->linenr << "\" "
3330  // str might contain characters such as '"', '<' or '>' which
3331  // could result in invalid XML, so run it through toxml().
3332  << "str=\"" << ErrorLogger::toxml(it->str) << "\"/>" << std::endl;
3333  }
3334  out << " </directivelist>" << std::endl;
3335 }