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 errorId;
1350  errorId << "preprocessor" << __LINE__;
1351  const std::string errorText = "mismatching number of '(' and ')' in this line: " + def;
1352  writeError(filename, linenr, _errorLogger, errorId.str(), errorText);
1353  ret.clear();
1354  return ret;
1355  }
1356 
1357  // Replace defined constants
1358  simplifyCondition(alldefinesmap, def, false);
1359 
1360  if (! deflist.empty() && line.compare(0, 6, "#elif ") == 0)
1361  deflist.pop_back();
1362 
1363  // translate A==1 condition to A=1 configuration
1364  if (def.find("==") != std::string::npos) {
1365  // Check if condition match pattern "%name% == %num%"
1366  // %name%
1367  std::string::size_type pos = 0;
1368  if (std::isalpha((unsigned char)def[pos]) || def[pos] == '_') {
1369  ++pos;
1370  while (std::isalnum((unsigned char)def[pos]) || def[pos] == '_')
1371  ++pos;
1372  }
1373 
1374  // ==
1375  if (def.compare(pos,2,"==")==0)
1376  pos += 2;
1377 
1378  // %num%
1379  if (pos<def.size() && std::isdigit(def[pos])) {
1380  if (def.compare(pos,2,"0x")==0) {
1381  pos += 2;
1382  if (pos >= def.size())
1383  pos = 0;
1384  while (pos < def.size() && std::isxdigit((unsigned char)def[pos]))
1385  ++pos;
1386  } else {
1387  while (pos < def.size() && std::isdigit((unsigned char)def[pos]))
1388  ++pos;
1389  }
1390 
1391  // Does the condition match the pattern "%name% == %num%"?
1392  if (pos == def.size()) {
1393  def.erase(def.find("=="),1);
1394  }
1395  }
1396  }
1397 
1398  deflist.push_back(def);
1399  def = "";
1400 
1401  for (std::list<std::string>::const_iterator it = deflist.begin(); it != deflist.end(); ++it) {
1402  if (*it == "0")
1403  break;
1404  if (*it == "1" || *it == "!")
1405  continue;
1406 
1407  // don't add "T;T":
1408  // treat two and more similar nested conditions as one
1409  if (def != *it) {
1410  if (! def.empty())
1411  def += ";";
1412  def += *it;
1413  }
1414 
1415  /* TODO: Fix TestPreprocessor::test7e (#2552)
1416  else
1417  {
1418  std::ostringstream lineStream;
1419  lineStream << __LINE__;
1420 
1421  ErrorLogger::ErrorMessage errmsg;
1422  ErrorLogger::ErrorMessage::FileLocation loc;
1423  loc.setfile(filename);
1424  loc.line = linenr;
1425  errmsg._callStack.push_back(loc);
1426  errmsg._severity = Severity::error;
1427  errmsg.setmsg(*it+" is already guaranteed to be defined");
1428  errmsg._id = "preprocessor" + lineStream.str();
1429  _errorLogger->reportErr(errmsg);
1430  }
1431  */
1432  }
1433  if (from_negation) {
1434  ndeflist.push_back(deflist.back());
1435  deflist.back() = "!";
1436  }
1437 
1438  if (std::find(ret.begin(), ret.end(), def) == ret.end()) {
1439  if (!includeStack.top().second) {
1440  ret.push_back(def);
1441  } else {
1442  if (_errorLogger && printDebug) {
1443  std::list<ErrorLogger::ErrorMessage::FileLocation> locationList;
1444  const ErrorLogger::ErrorMessage errmsg(locationList, Severity::debug,
1445  "Configuration not considered: " + def +" for file:"+includeStack.top().first, "debug", false);
1446  _errorLogger->reportErr(errmsg);
1447  }
1448  }
1449  }
1450  }
1451 
1452  else if (line.compare(0, 5, "#else") == 0 && ! deflist.empty()) {
1453  if (deflist.back() == "!" && !ndeflist.empty()) {
1454  deflist.back() = ndeflist.back();
1455  ndeflist.pop_back();
1456  } else {
1457  deflist.back() = (deflist.back() == "1") ? "0" : "1";
1458  }
1459  }
1460 
1461  else if (line.compare(0, 6, "#endif") == 0 && ! deflist.empty()) {
1462  if (deflist.back() == "!" && !ndeflist.empty())
1463  ndeflist.pop_back();
1464  deflist.pop_back();
1465  }
1466  }
1467 
1468  // Remove defined constants from ifdef configurations..
1469  std::size_t count = 0;
1470  for (std::list<std::string>::iterator it = ret.begin(); it != ret.end(); ++it) {
1471  if (_errorLogger)
1472  _errorLogger->reportProgress(filename, "Preprocessing (get configurations 2)", (100 * count++) / ret.size());
1473 
1474  std::string cfg(*it);
1475  for (std::set<std::string>::const_iterator it2 = defines.begin(); it2 != defines.end(); ++it2) {
1476  std::string::size_type pos = 0;
1477 
1478  // Get name of define
1479  std::string defineName(*it2);
1480  const std::string::size_type end = defineName.find_first_of("=(");
1481  if (end != std::string::npos)
1482  defineName.erase(end);
1483 
1484  // Remove ifdef configurations that match the defineName
1485  while ((pos = cfg.find(defineName, pos)) != std::string::npos) {
1486  const std::string::size_type pos1 = pos;
1487  ++pos;
1488  if (pos1 > 0 && cfg[pos1-1] != ';')
1489  continue;
1490  const std::string::size_type pos2 = pos1 + defineName.length();
1491  if (pos2 < cfg.length() && cfg[pos2] != ';')
1492  continue;
1493  --pos;
1494  cfg.erase(pos, defineName.length());
1495  }
1496  }
1497  if (cfg.length() != it->length()) {
1498  while (cfg.length() > 0 && cfg[0] == ';')
1499  cfg.erase(0, 1);
1500 
1501  while (cfg.length() > 0 && cfg.back() == ';')
1502  cfg.erase(cfg.length() - 1);
1503 
1504  std::string::size_type pos = 0;
1505  while ((pos = cfg.find(";;", pos)) != std::string::npos)
1506  cfg.erase(pos, 1);
1507 
1508  *it = cfg;
1509  }
1510  }
1511 
1512  // convert configurations: "defined(A) && defined(B)" => "A;B"
1513  for (std::list<std::string>::iterator it = ret.begin(); it != ret.end(); ++it) {
1514  std::string s(*it);
1515 
1516  if (s.find("&&") != std::string::npos) {
1517  Tokenizer tokenizer(&_settings, _errorLogger);
1518  if (!tokenizer.tokenizeCondition(s)) {
1519  std::ostringstream lineStream;
1520  lineStream << __LINE__;
1521 
1524  loc.setfile(filename);
1525  loc.line = 1;
1526  errmsg._callStack.push_back(loc);
1527  errmsg._severity = Severity::error;
1528  errmsg.setmsg("Error parsing this: " + s);
1529  errmsg._id = "preprocessor" + lineStream.str();
1530  _errorLogger->reportErr(errmsg);
1531  }
1532 
1533 
1534  const Token *tok = tokenizer.tokens();
1535  std::set<std::string> varList;
1536  while (tok) {
1537  if (Token::Match(tok, "defined ( %name% )")) {
1538  varList.insert(tok->strAt(2));
1539  tok = tok->tokAt(4);
1540  if (tok && tok->str() == "&&") {
1541  tok = tok->next();
1542  }
1543  } else if (Token::Match(tok, "%name% ;")) {
1544  varList.insert(tok->str());
1545  tok = tok->tokAt(2);
1546  } else {
1547  break;
1548  }
1549  }
1550 
1551  s = join(varList, ';');
1552 
1553  if (!s.empty())
1554  *it = s;
1555  }
1556  }
1557 
1558  // Convert configurations into a canonical form: B;C;A or C;A;B => A;B;C
1559  for (std::list<std::string>::iterator it = ret.begin(); it != ret.end(); ++it)
1560  *it = unify(*it, ';');
1561 
1562  // Remove duplicates from the ret list..
1563  ret.sort();
1564  ret.unique();
1565 
1566  // C code => remove __cplusplus configurations..
1567  if (!cplusplus(&_settings, filename) && Path::isC(filename)) {
1568  for (std::list<std::string>::iterator it = ret.begin(); it != ret.end();) {
1569  if (it->find("__cplusplus") != std::string::npos) {
1570  ret.erase(it++);
1571  } else {
1572  ++it;
1573  }
1574  }
1575  }
1576 
1577  // cleanup unhandled configurations..
1578  for (std::list<std::string>::iterator it = ret.begin(); it != ret.end();) {
1579  const std::string s(*it + ";");
1580 
1581  bool unhandled = false;
1582 
1583  for (std::string::size_type pos = 0; pos < s.length(); ++pos) {
1584  const unsigned char c = static_cast<unsigned char>(s[pos]);
1585 
1586  // ok with ";"
1587  if (c == ';')
1588  continue;
1589 
1590  // identifier..
1591  if (std::isalpha(c) || c == '_') {
1592  while (std::isalnum((unsigned char)s[pos]) || s[pos] == '_')
1593  ++pos;
1594  if (s[pos] == '=') {
1595  ++pos;
1596  while (std::isdigit((unsigned char)s[pos]))
1597  ++pos;
1598  if (s[pos] != ';') {
1599  unhandled = true;
1600  break;
1601  }
1602  }
1603 
1604  --pos;
1605  continue;
1606  }
1607 
1608  // not ok..
1609  else {
1610  unhandled = true;
1611  break;
1612  }
1613  }
1614 
1615  if (unhandled) {
1616  // unhandled ifdef configuration..
1617  if (_errorLogger && printDebug) {
1618  std::list<ErrorLogger::ErrorMessage::FileLocation> locationList;
1619  const ErrorLogger::ErrorMessage errmsg(locationList, Severity::debug, "unhandled configuration: " + *it, "debug", false);
1620  _errorLogger->reportErr(errmsg);
1621  }
1622 
1623  ret.erase(it++);
1624  } else {
1625  ++it;
1626  }
1627  }
1628 
1629  return ret;
1630 }
1631 
1632 
1633 void Preprocessor::simplifyCondition(const std::map<std::string, std::string> &cfg, std::string &condition, bool match)
1634 {
1635  Tokenizer tokenizer(&_settings, _errorLogger);
1636  if (!tokenizer.tokenizeCondition("(" + condition + ")")) {
1637  // If tokenize returns false, then there is syntax error in the
1638  // code which we can't handle. So stop here.
1639  return;
1640  }
1641 
1642  if (Token::Match(tokenizer.tokens(), "( %name% )")) {
1643  std::map<std::string,std::string>::const_iterator var = cfg.find(tokenizer.tokens()->strAt(1));
1644  if (var != cfg.end()) {
1645  const std::string &value = var->second;
1646  condition = (value == "0") ? "0" : "1";
1647  } else if (match)
1648  condition = "0";
1649  return;
1650  }
1651 
1652  if (Token::Match(tokenizer.tokens(), "( ! %name% )")) {
1653  std::map<std::string,std::string>::const_iterator var = cfg.find(tokenizer.tokens()->strAt(2));
1654 
1655  if (var == cfg.end())
1656  condition = "1";
1657  else if (var->second == "0")
1658  condition = "1";
1659  else if (match)
1660  condition = "0";
1661  return;
1662  }
1663 
1664  // replace variable names with values..
1665  for (Token *tok = const_cast<Token *>(tokenizer.tokens()); tok; tok = tok->next()) {
1666  if (!tok->isName())
1667  continue;
1668 
1669  if (Token::Match(tok, "defined ( %name% )")) {
1670  if (cfg.find(tok->strAt(2)) != cfg.end())
1671  tok->str("1");
1672  else if (match)
1673  tok->str("0");
1674  else
1675  continue;
1676  tok->deleteNext(3);
1677  continue;
1678  }
1679 
1680  if (Token::Match(tok, "defined %name%")) {
1681  if (cfg.find(tok->strAt(1)) != cfg.end())
1682  tok->str("1");
1683  else if (match)
1684  tok->str("0");
1685  else
1686  continue;
1687  tok->deleteNext();
1688  continue;
1689  }
1690 
1691  const std::map<std::string, std::string>::const_iterator it = cfg.find(tok->str());
1692  if (it != cfg.end()) {
1693  if (!it->second.empty()) {
1694  // Tokenize the value
1695  Tokenizer tokenizer2(&_settings, _errorLogger);
1696  tokenizer2.tokenizeCondition(it->second);
1697 
1698  // Copy the value tokens
1699  std::stack<Token *> link;
1700  for (const Token *tok2 = tokenizer2.tokens(); tok2; tok2 = tok2->next()) {
1701  tok->str(tok2->str());
1702 
1703  if (Token::Match(tok2,"[{([]"))
1704  link.push(tok);
1705  else if (!link.empty() && Token::Match(tok2,"[})]]")) {
1706  Token::createMutualLinks(link.top(), tok);
1707  link.pop();
1708  }
1709 
1710  if (tok2->next()) {
1711  tok->insertToken("");
1712  tok = tok->next();
1713  }
1714  }
1715  } else if ((!tok->previous() || Token::Match(tok->previous(), "&&|%oror%|(")) &&
1716  (!tok->next() || Token::Match(tok->next(), "&&|%oror%|)")))
1717  tok->str("1");
1718  else
1719  tok->deleteThis();
1720  }
1721  }
1722 
1723  // simplify calculations..
1725  bool modified = true;
1726  while (modified) {
1727  modified = false;
1728  modified |= tokenizer.simplifySizeof();
1729  modified |= tokenizer.simplifyCalculations();
1730  modified |= tokenizer.simplifyConstTernaryOp();
1731  modified |= tokenizer.simplifyRedundantParentheses();
1732  for (Token *tok = const_cast<Token *>(tokenizer.tokens()); tok; tok = tok->next()) {
1733  if (Token::Match(tok, "! %num%")) {
1734  tok->deleteThis();
1735  tok->str(tok->str() == "0" ? "1" : "0");
1736  modified = true;
1737  }
1738  }
1739  }
1740 
1741  for (Token *tok = const_cast<Token *>(tokenizer.tokens()); tok; tok = tok->next()) {
1742  if (Token::Match(tok, "(|%oror%|&& %num% &&|%oror%|)")) {
1743  if (tok->next()->str() != "0") {
1744  tok->next()->str("1");
1745  }
1746  }
1747  }
1748 
1749  for (Token *tok = const_cast<Token *>(tokenizer.tokens()); tok; tok = tok->next()) {
1750  while (Token::Match(tok, "(|%oror% %any% %oror% 1")) {
1751  tok->deleteNext(2);
1752  if (tok->tokAt(-3))
1753  tok = tok->tokAt(-3);
1754  }
1755  }
1756 
1757  if (Token::simpleMatch(tokenizer.tokens(), "( 1 )") ||
1758  Token::simpleMatch(tokenizer.tokens(), "( 1 ||"))
1759  condition = "1";
1760  else if (Token::simpleMatch(tokenizer.tokens(), "( 0 )"))
1761  condition = "0";
1762 }
1763 
1764 bool Preprocessor::match_cfg_def(std::map<std::string, std::string> cfg, std::string def)
1765 {
1766  /*
1767  std::cout << "cfg: \"";
1768  for (std::map<std::string, std::string>::const_iterator it = cfg.begin(); it != cfg.end(); ++it)
1769  {
1770  std::cout << it->first;
1771  if (!it->second.empty())
1772  std::cout << "=" << it->second;
1773  std::cout << ";";
1774  }
1775  std::cout << "\" ";
1776  std::cout << "def: \"" << def << "\"\n";
1777  */
1778 
1779  simplifyVarMap(cfg, _settings);
1780  simplifyCondition(cfg, def, true);
1781 
1782  if (cfg.find(def) != cfg.end())
1783  return true;
1784 
1785  if (def == "0")
1786  return false;
1787 
1788  if (def == "1")
1789  return true;
1790 
1791  return false;
1792 }
1793 
1794 std::string Preprocessor::getcode(const std::string &filedata, const std::string &cfg, const std::string &filename)
1795 {
1796  // For the error report and preprocessor dump:
1797  // line number relative to current (included) file
1798  // (may decrease when popping back from an included file)
1799  unsigned int lineno = 0;
1800 
1801  std::ostringstream ret;
1802 
1803  bool match = true;
1804  std::list<bool> matching_ifdef;
1805  std::list<bool> matched_ifdef;
1806 
1807  // Create a map for the cfg for faster access to defines
1808  std::map<std::string, std::string> cfgmap(getcfgmap(cfg, &_settings, filename));
1809 
1810  std::stack<std::string> filenames;
1811  filenames.push(filename);
1812  std::stack<unsigned int> lineNumbers;
1813  std::istringstream istr(filedata);
1814  std::string line;
1815  directives.clear();
1816  while (std::getline(istr, line)) {
1817  ++lineno;
1818 
1819  if (line.empty()) {
1820  ret << '\n';
1821  continue;
1822  }
1823 
1824  // record directive for addons / checkers
1825  if ((line[0] == '#')
1826  && (line.compare(0, 6, "#line ") != 0)
1827  && (line.compare(0, 8, "#endfile") != 0)) {
1828  // for clarity, turn "#file ..." back into "#include ..."
1829  std::string orig_line = line;
1830  if (orig_line.compare(0, 6, "#file ")==0)
1831  orig_line.replace(1, 4, "include");
1832  // record directive and extra
1833  directives.push_back(Directive(filenames.top(), lineno,
1834  orig_line));
1835  }
1836 
1837  if (_settings.terminated())
1838  return "";
1839 
1840  if (line.compare(0, 11, "#pragma asm") == 0) {
1841  ret << "\n";
1842  bool found_end = false;
1843  while (getline(istr, line)) {
1844  if (line.compare(0, 14, "#pragma endasm") == 0) {
1845  found_end = true;
1846  break;
1847  }
1848 
1849  ret << "\n";
1850  }
1851  if (!found_end)
1852  break;
1853 
1854  if (line.find('=') != std::string::npos) {
1855  Tokenizer tokenizer(&_settings, _errorLogger);
1856  line.erase(0, sizeof("#pragma endasm"));
1857  std::istringstream tempIstr(line);
1858  tokenizer.tokenize(tempIstr, "", "", true);
1859  if (Token::Match(tokenizer.tokens(), "( %name% = %any% )")) {
1860  ret << "asm(" << tokenizer.tokens()->strAt(1) << ");";
1861  }
1862  }
1863 
1864  ret << "\n";
1865 
1866  continue;
1867  }
1868 
1869  const std::string def = getdef(line, true);
1870  const std::string ndef = getdef(line, false);
1871 
1872  const bool emptymatch = matching_ifdef.empty() || matched_ifdef.empty();
1873 
1874  if (line.compare(0, 8, "#define ") == 0) {
1875  match = true;
1876 
1877 
1878  typedef std::set<std::string>::const_iterator It;
1879  for (It it = _settings.userUndefs.begin(); it != _settings.userUndefs.end(); ++it) {
1880  const std::string::size_type symbolPos = line.find_first_not_of(' ', 8);
1881  if (symbolPos == std::string::npos)
1882  continue;
1883  const std::string::size_type undefMatchPos = line.find(*it, symbolPos);
1884  if (undefMatchPos == std::string::npos)
1885  continue;
1886  const std::string::size_type behindUndefPos = undefMatchPos + (*it).size();
1887  if ((line.size() == behindUndefPos) ||
1888  (line[behindUndefPos] == ' ') ||
1889  (line[behindUndefPos] == '(')) {
1890  match = false;
1891  break;
1892  }
1893  }
1894 
1895  if (match) {
1896  for (std::list<bool>::const_iterator it = matching_ifdef.begin(); it != matching_ifdef.end(); ++it) {
1897  if (!bool(*it)) {
1898  match = false;
1899  break;
1900  }
1901  }
1902  }
1903 
1904  if (match) {
1905  const std::string::size_type pos = line.find_first_of(" (", 8);
1906  if (pos == std::string::npos)
1907  cfgmap[line.substr(8)] = "";
1908  else if (line[pos] == ' ') {
1909  std::string value(line.substr(pos + 1));
1910  std::map<std::string, std::string>::const_iterator cfgpos = cfgmap.find(value);
1911  if (cfgpos != cfgmap.end())
1912  value = cfgpos->second;
1913  cfgmap[line.substr(8, pos - 8)] = value;
1914  } else
1915  cfgmap[line.substr(8, pos - 8)] = "";
1916  }
1917  }
1918 
1919  else if (line.compare(0, 7, "#undef ") == 0) {
1920  const std::string name(line.substr(7));
1921  cfgmap.erase(name);
1922  }
1923 
1924  else if (!emptymatch && line.compare(0, 7, "#elif !") == 0) {
1925  if (matched_ifdef.back()) {
1926  matching_ifdef.back() = false;
1927  } else {
1928  if (!match_cfg_def(cfgmap, ndef)) {
1929  matching_ifdef.back() = true;
1930  matched_ifdef.back() = true;
1931  }
1932  }
1933  }
1934 
1935  else if (!emptymatch && line.compare(0, 6, "#elif ") == 0) {
1936  if (matched_ifdef.back()) {
1937  matching_ifdef.back() = false;
1938  } else {
1939  if (match_cfg_def(cfgmap, def)) {
1940  matching_ifdef.back() = true;
1941  matched_ifdef.back() = true;
1942  }
1943  }
1944  }
1945 
1946  else if (line.compare(0,4,"#if ") == 0) {
1947  matching_ifdef.push_back(match_cfg_def(cfgmap, line.substr(4)));
1948  matched_ifdef.push_back(matching_ifdef.back());
1949  }
1950 
1951  else if (! def.empty()) {
1952  matching_ifdef.push_back(cfgmap.find(def) != cfgmap.end());
1953  matched_ifdef.push_back(matching_ifdef.back());
1954  }
1955 
1956  else if (! ndef.empty()) {
1957  matching_ifdef.push_back(cfgmap.find(ndef) == cfgmap.end());
1958  matched_ifdef.push_back(matching_ifdef.back());
1959  }
1960 
1961  else if (!emptymatch && line == "#else") {
1962  if (! matched_ifdef.empty())
1963  matching_ifdef.back() = ! matched_ifdef.back();
1964  }
1965 
1966  else if (line.compare(0, 6, "#endif") == 0) {
1967  if (! matched_ifdef.empty())
1968  matched_ifdef.pop_back();
1969  if (! matching_ifdef.empty())
1970  matching_ifdef.pop_back();
1971  }
1972 
1973  if (!line.empty() && line[0] == '#') {
1974  match = true;
1975  for (std::list<bool>::const_iterator it = matching_ifdef.begin(); it != matching_ifdef.end(); ++it) {
1976  if (!bool(*it)) {
1977  match = false;
1978  break;
1979  }
1980  }
1981  }
1982 
1983  // #error => return ""
1984  if (match && line.compare(0, 6, "#error") == 0) {
1985  if (!_settings.userDefines.empty() && !_settings.force) {
1986  error(Path::simplifyPath(filenames.top()), lineno, line);
1987  }
1988  return "";
1989  }
1990 
1991  if (!match && (line.compare(0, 8, "#define ") == 0 ||
1992  line.compare(0, 6, "#undef") == 0)) {
1993  // Remove define that is not part of this configuration
1994  line = "";
1995  } else if (line.compare(0, 7, "#file \"") == 0 ||
1996  line.compare(0, 8, "#endfile") == 0 ||
1997  line.compare(0, 8, "#define ") == 0 ||
1998  line.compare(0, 6, "#line ") == 0 ||
1999  line.compare(0, 6, "#undef") == 0) {
2000  // We must not remove #file tags or line numbers
2001  // are corrupted. File tags are removed by the tokenizer.
2002 
2003  // Keep location info updated
2004  if (line.compare(0, 7, "#file \"") == 0) {
2005  filenames.push(line.substr(7, line.size() - 8));
2006  lineNumbers.push(lineno);
2007  lineno = 0;
2008  } else if (line.compare(0, 8, "#endfile") == 0) {
2009  if (filenames.size() > 1U)
2010  filenames.pop();
2011 
2012  if (!lineNumbers.empty()) {
2013  lineno = lineNumbers.top();
2014  lineNumbers.pop();
2015  }
2016  }
2017  } else if (!match || line.compare(0, 1, "#") == 0) {
2018  // Remove #if, #else, #pragma etc, leaving only
2019  // #define, #undef, #file and #endfile. and also lines
2020  // which are not part of this configuration.
2021  line = "";
2022  }
2023 
2024  ret << line << "\n";
2025  }
2026 
2027  if (!validateCfg(ret.str(), cfg)) {
2028  return "";
2029  }
2030 
2031  return expandMacros(ret.str(), filename, cfg, _errorLogger);
2032 }
2033 
2034 void Preprocessor::error(const std::string &filename, unsigned int linenr, const std::string &msg)
2035 {
2036  std::list<ErrorLogger::ErrorMessage::FileLocation> locationList;
2037  if (!filename.empty()) {
2038  ErrorLogger::ErrorMessage::FileLocation loc(filename, linenr);
2039  locationList.push_back(loc);
2040  }
2043  msg,
2044  "preprocessorErrorDirective",
2045  false));
2046 }
2047 
2049 {
2050  std::string::size_type i = str.find_first_of("<\"");
2051  if (i == std::string::npos) {
2052  str = "";
2053  return NoHeader;
2054  }
2055 
2056  char c = str[i];
2057  if (c == '<')
2058  c = '>';
2059 
2060  std::string result;
2061  for (i = i + 1; i < str.length(); ++i) {
2062  if (str[i] == c)
2063  break;
2064 
2065  result.append(1, str[i]);
2066  }
2067 
2068  // Linux can't open include paths with \ separator, so fix them
2069  std::replace(result.begin(), result.end(), '\\', '/');
2070 
2071  str = result;
2072 
2073  return (c == '\"') ? UserHeader : SystemHeader;
2074 }
2075 
2076 /**
2077  * Try to open header
2078  * @param filename header name (in/out)
2079  * @param includePaths paths where to look for the file
2080  * @param filePath path to the header file
2081  * @param fin file input stream (in/out)
2082  * @return if file is opened then true is returned
2083  */
2084 static bool openHeader(std::string &filename, const std::list<std::string> &includePaths, const std::string &filePath, std::ifstream &fin)
2085 {
2086  fin.open((filePath + filename).c_str());
2087  if (fin.is_open()) {
2088  filename = filePath + filename;
2089  return true;
2090  }
2091 
2092  fin.open(filename.c_str());
2093  if (fin.is_open())
2094  return true;
2095 
2096  for (std::list<std::string>::const_iterator iter = includePaths.begin(); iter != includePaths.end(); ++iter) {
2097  const std::string nativePath(Path::toNativeSeparators(*iter));
2098  fin.open((nativePath + filename).c_str());
2099  if (fin.is_open()) {
2100  filename = nativePath + filename;
2101  return true;
2102  }
2103  fin.clear();
2104  }
2105 
2106  return false;
2107 }
2108 
2109 
2110 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)
2111 {
2112  std::string path;
2113  std::string::size_type sep_pos = filePath.find_last_of("\\/");
2114  if (sep_pos != std::string::npos)
2115  path = filePath.substr(0, 1 + sep_pos);
2116 
2117  // current #if indent level.
2118  std::stack<bool>::size_type indent = 0;
2119 
2120  // how deep does the #if match? this can never be bigger than "indent".
2121  std::stack<bool>::size_type indentmatch = 0;
2122 
2123  // has there been a true #if condition at the current indentmatch level?
2124  // then no more #elif or #else can be true before the #endif is seen.
2125  std::stack<bool> elseIsTrueStack;
2126 
2127  unsigned int linenr = 0;
2128 
2129  const std::set<std::string> &undefs = _settings.userUndefs;
2130 
2131  if (_errorLogger)
2132  _errorLogger->reportProgress(filePath, "Preprocessor (handleIncludes)", 0);
2133 
2134  std::ostringstream ostr;
2135  std::istringstream istr(code);
2136  std::string line;
2137  bool suppressCurrentCodePath = false;
2138  while (std::getline(istr,line)) {
2139  ++linenr;
2140 
2141  if (_settings.terminated())
2142  return "";
2143 
2144  // has there been a true #if condition at the current indentmatch level?
2145  // then no more #elif or #else can be true before the #endif is seen.
2146  while (elseIsTrueStack.size() != indentmatch + 1) {
2147  if (elseIsTrueStack.size() < indentmatch + 1) {
2148  elseIsTrueStack.push(true);
2149  } else {
2150  elseIsTrueStack.pop();
2151  }
2152  }
2153 
2154  if (elseIsTrueStack.empty()) {
2155  writeError(filePath, linenr, _errorLogger, "syntaxError", "Syntax error in preprocessor code");
2156  return "";
2157  }
2158 
2159  std::stack<bool>::reference elseIsTrue = elseIsTrueStack.top();
2160 
2161  if (line == "#pragma once") {
2162  pragmaOnce.insert(filePath);
2163  } else if (line.compare(0,7,"#ifdef ") == 0) {
2164  if (indent == indentmatch) {
2165  const std::string tag = getdef(line,true);
2166  if (defs.find(tag) != defs.end()) {
2167  elseIsTrue = false;
2168  indentmatch++;
2169  } else if (undefs.find(tag) != undefs.end()) {
2170  elseIsTrue = true;
2171  indentmatch++;
2172  suppressCurrentCodePath = true;
2173  }
2174  }
2175  ++indent;
2176 
2177  if (indent == indentmatch + 1)
2178  elseIsTrue = true;
2179  } else if (line.compare(0,8,"#ifndef ") == 0) {
2180  if (indent == indentmatch) {
2181  const std::string tag = getdef(line,false);
2182  if (defs.find(tag) == defs.end()) {
2183  elseIsTrue = false;
2184  indentmatch++;
2185  } else if (undefs.find(tag) != undefs.end()) {
2186  elseIsTrue = false;
2187  indentmatch++;
2188  suppressCurrentCodePath = false;
2189  }
2190  }
2191  ++indent;
2192 
2193  if (indent == indentmatch + 1)
2194  elseIsTrue = true;
2195 
2196  } else if (line.compare(0,4,"#if ") == 0) {
2197  if (!suppressCurrentCodePath && indent == indentmatch && match_cfg_def(defs, line.substr(4))) {
2198  elseIsTrue = false;
2199  indentmatch++;
2200  }
2201  ++indent;
2202 
2203  if (indent == indentmatch + 1)
2204  elseIsTrue = true; // this value doesn't matter when suppressCurrentCodePath is true
2205  } else if (line.compare(0,6,"#elif ") == 0 || line.compare(0,5,"#else") == 0) {
2206  if (!elseIsTrue) {
2207  if ((indentmatch > 0) && (indentmatch == indent)) {
2208  indentmatch = indent - 1;
2209  }
2210  } else {
2211  if ((indentmatch > 0) && (indentmatch == indent)) {
2212  indentmatch = indent - 1;
2213  } else if ((indent > 0) && indentmatch == indent - 1) {
2214  if (line.compare(0,5,"#else")==0 || match_cfg_def(defs,line.substr(6))) {
2215  indentmatch = indent;
2216  elseIsTrue = false;
2217  }
2218  }
2219  }
2220  } else if (line.compare(0, 6, "#endif") == 0) {
2221  if (indent > 0)
2222  --indent;
2223  if (indentmatch > indent || indent == 0) {
2224  indentmatch = indent;
2225  elseIsTrue = false;
2226  suppressCurrentCodePath = false;
2227  }
2228  } else if (indentmatch == indent) {
2229  if (!suppressCurrentCodePath && line.compare(0, 8, "#define ") == 0) {
2230  const unsigned int endOfDefine = 8;
2231  std::string::size_type endOfTag = line.find_first_of("( ", endOfDefine);
2232  std::string tag;
2233 
2234  // define a symbol
2235  if (endOfTag == std::string::npos) {
2236  tag = line.substr(endOfDefine);
2237  defs[tag] = "";
2238  } else {
2239  tag = line.substr(endOfDefine, endOfTag-endOfDefine);
2240 
2241  // define a function-macro
2242  if (line[endOfTag] == '(') {
2243  defs[tag] = "";
2244  }
2245  // define value
2246  else {
2247  ++endOfTag;
2248 
2249  const std::string& value = line.substr(endOfTag, line.size()-endOfTag);
2250 
2251  if (defs.find(value) != defs.end())
2252  defs[tag] = defs[value];
2253  else
2254  defs[tag] = value;
2255  }
2256  }
2257 
2258  if (undefs.find(tag) != undefs.end()) {
2259  defs.erase(tag);
2260  }
2261  }
2262 
2263  else if (!suppressCurrentCodePath && line.compare(0,7,"#undef ") == 0) {
2264  defs.erase(line.substr(7));
2265  }
2266 
2267  else if (!suppressCurrentCodePath && line.compare(0,9,"#include ")==0) {
2268  std::string filename(line.substr(9));
2269 
2270  const HeaderTypes headerType = getHeaderFileName(filename);
2271  if (headerType == NoHeader) {
2272  ostr << std::endl;
2273  continue;
2274  }
2275 
2276  // try to open file
2277  std::string filepath;
2278  if (headerType == UserHeader)
2279  filepath = path;
2280  std::ifstream fin;
2281  if (!openHeader(filename, includePaths, filepath, fin)) {
2283  linenr,
2284  filename,
2285  headerType
2286  );
2287  ostr << std::endl;
2288  continue;
2289  }
2290 
2291  // Prevent that files are recursively included
2292  if (std::find(includes.begin(), includes.end(), filename) != includes.end()) {
2293  ostr << std::endl;
2294  continue;
2295  }
2296 
2297  // #6913 - simplify Path to avoid strange recursion
2298  includes.push_back(Path::simplifyPath(filename));
2299 
2300  // Don't include header if it's already included and contains #pragma once
2301  if (pragmaOnce.find(filename) != pragmaOnce.end()) {
2302  ostr << std::endl;
2303  continue;
2304  }
2305 
2306  ostr << "#file \"" << filename << "\"\n"
2307  << handleIncludes(read(fin, filename), filename, includePaths, defs, pragmaOnce, includes) << std::endl
2308  << "#endfile\n";
2309  continue;
2310  }
2311 
2312  if (!suppressCurrentCodePath)
2313  ostr << line;
2314  }
2315 
2316  // A line has been read..
2317  ostr << "\n";
2318  }
2319 
2320  return ostr.str();
2321 }
2322 
2323 
2324 void Preprocessor::handleIncludes(std::string &code, const std::string &filePath, const std::list<std::string> &includePaths)
2325 {
2326  std::list<std::string> paths;
2327  std::string path = filePath;
2328  const std::string::size_type sep_pos = path.find_last_of("\\/");
2329  if (sep_pos != std::string::npos)
2330  path.erase(1 + sep_pos);
2331  paths.push_back(path);
2332  std::string::size_type pos = 0;
2333  std::string::size_type endfilePos = 0;
2334  if (code.compare(0,7U,"#file \"")==0) {
2335  const std::string::size_type start = code.find("#file \"" + filePath, 7U);
2336  if (start != std::string::npos)
2337  endfilePos = start;
2338  }
2339  std::set<std::string> handledFiles;
2340  while ((pos = code.find("#include", pos)) != std::string::npos) {
2341  if (_settings.terminated())
2342  return;
2343 
2344  // Accept only includes that are at the start of a line
2345  if (pos > 0 && code[pos-1] != '\n') {
2346  pos += 8; // length of "#include"
2347  continue;
2348  }
2349 
2350  // If endfile is encountered, we have moved to a next file in our stack,
2351  // so remove last path in our list.
2352  while (!paths.empty() && (endfilePos = code.find("\n#endfile", endfilePos)) != std::string::npos && endfilePos < pos) {
2353  paths.pop_back();
2354  endfilePos += 9; // size of #endfile
2355  }
2356 
2357  endfilePos = pos;
2358  std::string::size_type end = code.find('\n', pos);
2359  std::string filename = code.substr(pos, end - pos);
2360 
2361  // Remove #include clause
2362  code.erase(pos, end - pos);
2363 
2364  HeaderTypes headerType = getHeaderFileName(filename);
2365  if (headerType == NoHeader)
2366  continue;
2367 
2368  // filename contains now a file name e.g. "menu.h"
2369  std::string processedFile;
2370  std::string filepath;
2371  if (headerType == UserHeader && !paths.empty())
2372  filepath = paths.back();
2373  std::ifstream fin;
2374  const bool fileOpened(openHeader(filename, includePaths, filepath, fin));
2375 
2376  if (fileOpened) {
2377  filename = Path::simplifyPath(filename);
2378  std::string tempFile = filename;
2379  std::transform(tempFile.begin(), tempFile.end(), tempFile.begin(), tolowerWrapper);
2380  if (handledFiles.find(tempFile) != handledFiles.end()) {
2381  // We have processed this file already once, skip
2382  // it this time to avoid eternal loop.
2383  fin.close();
2384  continue;
2385  }
2386 
2387  handledFiles.insert(tempFile);
2388  processedFile = Preprocessor::read(fin, filename);
2389  fin.close();
2390  }
2391 
2392  if (!processedFile.empty()) {
2393  // Remove space characters that are after or before new line character
2394  processedFile = "#file \"" + Path::fromNativeSeparators(filename) + "\"\n" + processedFile + "\n#endfile";
2395  code.insert(pos, processedFile);
2396 
2397  path = filename;
2398  path.erase(1 + path.find_last_of("\\/"));
2399  paths.push_back(path);
2400  } else if (!fileOpened) {
2401  std::string f = filePath;
2402 
2403  // Determine line number of include
2404  unsigned int linenr = 1;
2405  unsigned int level = 0;
2406  for (std::string::size_type p = 1; p <= pos; ++p) {
2407  if (level == 0 && code[pos-p] == '\n')
2408  ++linenr;
2409  else if (code.compare(pos-p, 9, "#endfile\n") == 0) {
2410  ++level;
2411  } else if (code.compare(pos-p, 6, "#file ") == 0) {
2412  if (level == 0) {
2413  linenr--;
2414  const std::string::size_type pos1 = pos - p + 7;
2415  const std::string::size_type pos2 = code.find_first_of("\"\n", pos1);
2416  f = code.substr(pos1, (pos2 == std::string::npos) ? pos2 : (pos2 - pos1));
2417  break;
2418  }
2419  --level;
2420  }
2421  }
2422 
2424  linenr,
2425  filename,
2426  headerType);
2427  }
2428  }
2429 }
2430 
2431 // Report that include is missing
2432 void Preprocessor::missingInclude(const std::string &filename, unsigned int linenr, const std::string &header, HeaderTypes headerType)
2433 {
2434  const std::string fname = Path::fromNativeSeparators(filename);
2435  if (_settings.nomsg.isSuppressed("missingInclude", fname, linenr))
2436  return;
2437  if (headerType == SystemHeader && _settings.nomsg.isSuppressed("missingIncludeSystem", fname, linenr))
2438  return;
2439 
2440  if (headerType == SystemHeader)
2441  missingSystemIncludeFlag = true;
2442  else
2443  missingIncludeFlag = true;
2445 
2446  std::list<ErrorLogger::ErrorMessage::FileLocation> locationList;
2447  if (!filename.empty()) {
2449  loc.line = linenr;
2450  loc.setfile(Path::toNativeSeparators(filename));
2451  locationList.push_back(loc);
2452  }
2453  ErrorLogger::ErrorMessage errmsg(locationList, Severity::information,
2454  (headerType==SystemHeader) ?
2455  "Include file: <" + header + "> not found. Please note: Cppcheck does not need standard library headers to get proper results." :
2456  "Include file: \"" + header + "\" not found.",
2457  (headerType==SystemHeader) ? "missingIncludeSystem" : "missingInclude",
2458  false);
2459  errmsg.file0 = file0;
2460  _errorLogger->reportInfo(errmsg);
2461  }
2462 }
2463 
2464 /**
2465  * Skip string in line. A string begins and ends with either a &quot; or a &apos;
2466  * @param line the string
2467  * @param pos in=start position of string, out=end position of string
2468  */
2469 static void skipstring(const std::string &line, std::string::size_type &pos)
2470 {
2471  const char ch = line[pos];
2472 
2473  ++pos;
2474  while (pos < line.size() && line[pos] != ch) {
2475  if (line[pos] == '\\')
2476  ++pos;
2477  ++pos;
2478  }
2479 }
2480 
2481 /**
2482  * @brief get parameters from code. For example 'foo(1,2)' => '1','2'
2483  * @param line in: The code
2484  * @param pos in: Position to the '('. out: Position to the ')'
2485  * @param params out: The extracted parameters
2486  * @param numberOfNewlines out: number of newlines in the macro call
2487  * @param endFound out: was the end parentheses found?
2488  */
2489 static void getparams(const std::string &line,
2490  std::string::size_type &pos,
2491  std::vector<std::string> &params,
2492  unsigned int &numberOfNewlines,
2493  bool &endFound)
2494 {
2495  params.clear();
2496  numberOfNewlines = 0;
2497  endFound = false;
2498 
2499  if (line[pos] == ' ')
2500  pos++;
2501 
2502  if (line[pos] != '(')
2503  return;
2504 
2505  // parentheses level
2506  int parlevel = 0;
2507 
2508  // current parameter data
2509  std::string par;
2510 
2511  // scan for parameters..
2512  for (; pos < line.length(); ++pos) {
2513  // increase parentheses level
2514  if (line[pos] == '(') {
2515  ++parlevel;
2516  if (parlevel == 1)
2517  continue;
2518  }
2519 
2520  // decrease parentheses level
2521  else if (line[pos] == ')') {
2522  --parlevel;
2523  if (parlevel <= 0) {
2524  endFound = true;
2525  params.push_back(trim(par));
2526  break;
2527  }
2528  }
2529 
2530  // string
2531  else if (line[pos] == '\"' || line[pos] == '\'') {
2532  const std::string::size_type p = pos;
2533  skipstring(line, pos);
2534  if (pos == line.length())
2535  break;
2536  par += line.substr(p, pos + 1 - p);
2537  continue;
2538  }
2539 
2540  // count newlines. the expanded macro must have the same number of newlines
2541  else if (line[pos] == '\n') {
2542  ++numberOfNewlines;
2543  continue;
2544  }
2545 
2546  // new parameter
2547  if (parlevel == 1 && line[pos] == ',') {
2548  params.push_back(trim(par));
2549  par = "";
2550  }
2551 
2552  // spaces are only added if needed
2553  else if (line[pos] == ' ') {
2554  // Add space only if it is needed
2555  if (par.size() && std::isalnum((unsigned char)par.back())) {
2556  par += ' ';
2557  }
2558  }
2559 
2560  // add character to current parameter
2561  else if (parlevel >= 1 && line[pos] != Preprocessor::macroChar) {
2562  par.append(1, line[pos]);
2563  }
2564  }
2565 }
2566 
2567 /** @brief Class that the preprocessor uses when it expands macros. This class represents a preprocessor macro */
2569 private:
2570  /** tokens of this macro */
2572 
2573  /** macro parameters */
2574  std::vector<std::string> _params;
2575 
2576  /** macro definition in plain text */
2577  const std::string _macro;
2578 
2579  /** does this macro take a variable number of parameters? */
2581 
2582  /** The macro has parentheses but no parameters.. "AAA()" */
2583  bool _nopar;
2584 
2585  /** disabled assignment operator */
2586  void operator=(const PreprocessorMacro &);
2587 
2588  /** @brief expand inner macro */
2589  std::vector<std::string> expandInnerMacros(const std::vector<std::string> &params1,
2590  const std::map<std::string, PreprocessorMacro *> &macros) const {
2591  std::string innerMacroName;
2592 
2593  // Is there an inner macro..
2594  {
2595  const Token *tok = Token::findsimplematch(tokens(), ")");
2596  if (!Token::Match(tok, ") %name% ("))
2597  return params1;
2598  innerMacroName = tok->strAt(1);
2599  tok = tok->tokAt(3);
2600  unsigned int par = 0;
2601  while (Token::Match(tok, "%name% ,|)")) {
2602  tok = tok->tokAt(2);
2603  par++;
2604  }
2605  if (tok || par != params1.size())
2606  return params1;
2607  }
2608 
2609  std::vector<std::string> params2(params1);
2610 
2611  for (std::size_t ipar = 0; ipar < params1.size(); ++ipar) {
2612  const std::string s(innerMacroName + "(");
2613  const std::string param(params1[ipar]);
2614  if (param.compare(0,s.length(),s)==0 && param.back() == ')') {
2615  std::vector<std::string> innerparams;
2616  std::string::size_type pos = s.length() - 1;
2617  unsigned int num = 0;
2618  bool endFound = false;
2619  getparams(param, pos, innerparams, num, endFound);
2620  if (pos == param.length()-1 && num==0 && endFound && innerparams.size() == params1.size()) {
2621  // Is inner macro defined?
2622  std::map<std::string, PreprocessorMacro *>::const_iterator it = macros.find(innerMacroName);
2623  if (it != macros.end()) {
2624  // expand the inner macro
2625  const PreprocessorMacro *innerMacro = it->second;
2626 
2627  std::string innercode;
2628  std::map<std::string,PreprocessorMacro *> innermacros = macros;
2629  innermacros.erase(innerMacroName);
2630  innerMacro->code(innerparams, innermacros, innercode);
2631  params2[ipar] = innercode;
2632  }
2633  }
2634  }
2635  }
2636 
2637  return params2;
2638  }
2639 
2640 public:
2641  /**
2642  * @brief Constructor for PreprocessorMacro. This is the "setter"
2643  * for this class - everything is setup here.
2644  * @param [in] macro The code after define, until end of line,
2645  * e.g. "A(x) foo(x);"
2646  * @param [in] settings Current settings being used
2647  */
2648  PreprocessorMacro(const std::string &macro, const Settings* settings)
2649  : tokenlist(settings), _macro(macro) {
2650 
2651  // Tokenize the macro to make it easier to handle
2652  std::istringstream istr(macro);
2653  tokenlist.createTokens(istr);
2654 
2655  // initialize parameters to default values
2656  _variadic = _nopar = false;
2657 
2658  const std::string::size_type pos = macro.find_first_of(" (");
2659  if (pos != std::string::npos && macro[pos] == '(') {
2660  // Extract macro parameters
2661  if (Token::Match(tokens(), "%name% ( %name%")) {
2662  for (const Token *tok = tokens()->tokAt(2); tok; tok = tok->next()) {
2663  if (tok->str() == ")")
2664  break;
2665  if (Token::simpleMatch(tok, ". . . )")) {
2666  if (tok->previous()->str() == ",")
2667  _params.push_back("__VA_ARGS__");
2668  _variadic = true;
2669  break;
2670  }
2671  if (tok->isName())
2672  _params.push_back(tok->str());
2673  }
2674  }
2675 
2676  else if (Token::Match(tokens(), "%name% ( . . . )"))
2677  _variadic = true;
2678 
2679  else if (Token::Match(tokens(), "%name% ( )"))
2680  _nopar = true;
2681  }
2682  }
2683 
2684  /** return tokens of this macro */
2685  const Token *tokens() const {
2686  return tokenlist.front();
2687  }
2688 
2689  /** read parameters of this macro */
2690  const std::vector<std::string> &params() const {
2691  return _params;
2692  }
2693 
2694  /** check if this is macro has a variable number of parameters */
2695  bool variadic() const {
2696  return _variadic;
2697  }
2698 
2699  /** Check if this macro has parentheses but no parameters */
2700  bool nopar() const {
2701  return _nopar;
2702  }
2703 
2704  /** name of macro */
2705  const std::string &name() const {
2706  return tokens() ? tokens()->str() : emptyString;
2707  }
2708 
2709  /**
2710  * get expanded code for this macro
2711  * @param params2 macro parameters
2712  * @param macros macro definitions (recursion)
2713  * @param macrocode output string
2714  * @return true if the expanding was successful
2715  */
2716  bool code(const std::vector<std::string> &params2, const std::map<std::string, PreprocessorMacro *> &macros, std::string &macrocode) const {
2717  if (_nopar || (_params.empty() && _variadic)) {
2718  macrocode = _macro.substr(1 + _macro.find(')'));
2719  if (macrocode.empty())
2720  return true;
2721 
2722  std::string::size_type pos = 0;
2723  // Remove leading spaces
2724  if ((pos = macrocode.find_first_not_of(" ")) > 0)
2725  macrocode.erase(0, pos);
2726  // Remove ending newline
2727  if ((pos = macrocode.find_first_of("\r\n")) != std::string::npos)
2728  macrocode.erase(pos);
2729 
2730  // Replace "__VA_ARGS__" with parameters
2731  if (!_nopar) {
2732  std::string s;
2733  for (std::size_t i = 0; i < params2.size(); ++i) {
2734  if (i > 0)
2735  s += ",";
2736  s += params2[i];
2737  }
2738 
2739  pos = 0;
2740  while ((pos = macrocode.find("__VA_ARGS__", pos)) != std::string::npos) {
2741  macrocode.erase(pos, 11);
2742  macrocode.insert(pos, s);
2743  pos += s.length();
2744  }
2745  }
2746  }
2747 
2748  else if (_params.empty()) {
2749  std::string::size_type pos = _macro.find_first_of(" \"");
2750  if (pos == std::string::npos)
2751  macrocode = "";
2752  else {
2753  if (_macro[pos] == ' ')
2754  pos++;
2755  macrocode = _macro.substr(pos);
2756  if ((pos = macrocode.find_first_of("\r\n")) != std::string::npos)
2757  macrocode.erase(pos);
2758  }
2759  }
2760 
2761  else {
2762  const std::vector<std::string> givenparams = expandInnerMacros(params2, macros);
2763 
2764  const Token *tok = tokens();
2765  while (tok && tok->str() != ")")
2766  tok = tok->next();
2767  if (tok) {
2768  bool optcomma = false;
2769  while (nullptr != (tok = tok->next())) {
2770  std::string str = tok->str();
2771  if (str[0] == '#' || tok->isName()) {
2772  if (str == "##")
2773  continue;
2774 
2775  const bool stringify(str[0] == '#');
2776  if (stringify) {
2777  str = str.erase(0, 1);
2778  }
2779  for (std::size_t i = 0; i < _params.size(); ++i) {
2780  if (str == _params[i]) {
2781  if (_variadic &&
2782  (i == _params.size() - 1 ||
2783  (givenparams.size() + 2 == _params.size() && i + 1 == _params.size() - 1))) {
2784  str = "";
2785  for (std::size_t j = _params.size() - 1; j < givenparams.size(); ++j) {
2786  if (optcomma || j > _params.size() - 1)
2787  str += ",";
2788  optcomma = false;
2789  str += givenparams[j];
2790  }
2791  } else if (i >= givenparams.size()) {
2792  // Macro had more parameters than caller used.
2793  macrocode = "";
2794  return false;
2795  } else if (stringify) {
2796  const std::string &s(givenparams[i]);
2797  std::ostringstream ostr;
2798  ostr << "\"";
2799  for (std::string::size_type j = 0; j < s.size(); ++j) {
2800  if (s[j] == '\\' || s[j] == '\"')
2801  ostr << '\\';
2802  ostr << s[j];
2803  }
2804  str = ostr.str() + "\"";
2805  } else
2806  str = givenparams[i];
2807 
2808  break;
2809  }
2810  }
2811 
2812  // expand nopar macro
2813  if (tok->strAt(-1) != "##") {
2814  const std::map<std::string, PreprocessorMacro *>::const_iterator it = macros.find(str);
2815  if (it != macros.end() && it->second->_macro.find('(') == std::string::npos) {
2816  const std::string& macro = it->second->_macro;
2817  const std::string::size_type whitespacePos = macro.find(' ');
2818  if (whitespacePos != std::string::npos)
2819  str = macro.substr(whitespacePos);
2820  else
2821  str = "";
2822  }
2823  }
2824  }
2825  if (_variadic && tok->str() == "," && tok->next() && tok->next()->str() == "##") {
2826  optcomma = true;
2827  continue;
2828  }
2829  optcomma = false;
2830  // separate ++ and -- with space
2831  if (!str.empty() && !macrocode.empty() && (str[0] == '+' || str[0] == '-') && str[0] == macrocode[macrocode.size()-1U])
2832  macrocode += ' ';
2833  macrocode += str;
2834  if (Token::Match(tok, "%name% %name%|%num%") ||
2835  Token::Match(tok, "%num% %name%") ||
2836  Token::simpleMatch(tok, "> >"))
2837  macrocode += ' ';
2838  }
2839  }
2840  }
2841 
2842  return true;
2843  }
2844 };
2845 
2846 /**
2847  * Get data from a input string. This is an extended version of std::getline.
2848  * The std::getline only get a single line at a time. It can therefore happen that it
2849  * contains a partial statement. This function ensures that the returned data
2850  * doesn't end in the middle of a statement. The "getlines" name indicate that
2851  * this function will return multiple lines if needed.
2852  * @param istr input stream
2853  * @param line output data
2854  * @return success
2855  */
2856 static bool getlines(std::istream &istr, std::string &line)
2857 {
2858  if (!istr.good())
2859  return false;
2860  line = "";
2861  int parlevel = 0;
2862  bool directive = false;
2863  for (char ch = (char)istr.get(); istr.good(); ch = (char)istr.get()) {
2864  if (ch == '\'' || ch == '\"') {
2865  line += ch;
2866  char c = 0;
2867  while (istr.good() && c != ch) {
2868  if (c == '\\') {
2869  c = (char)istr.get();
2870  if (!istr.good())
2871  return true;
2872  line += c;
2873  }
2874 
2875  c = (char)istr.get();
2876  if (!istr.good())
2877  return true;
2878  if (c == '\n' && directive)
2879  return true;
2880  line += c;
2881  }
2882  continue;
2883  }
2884  if (ch == '(')
2885  ++parlevel;
2886  else if (ch == ')')
2887  --parlevel;
2888  else if (ch == '\n') {
2889  if (directive)
2890  return true;
2891 
2892  if (istr.peek() == '#') {
2893  line += ch;
2894  return true;
2895  }
2896  } else if (!directive && parlevel <= 0 && ch == ';') {
2897  line += ";";
2898  return true;
2899  }
2900 
2901  if (ch == '#' && line.empty())
2902  directive = true;
2903  line += ch;
2904  }
2905  return true;
2906 }
2907 
2908 bool Preprocessor::validateCfg(const std::string &code, const std::string &cfg)
2909 {
2910  const bool printInformation = _settings.isEnabled("information");
2911 
2912  // fill up "macros" with empty configuration macros
2913  std::set<std::string> macros;
2914  for (std::string::size_type pos = 0; pos < cfg.size();) {
2915  const std::string::size_type pos2 = cfg.find_first_of(";=", pos);
2916  if (pos2 == std::string::npos) {
2917  macros.insert(cfg.substr(pos));
2918  break;
2919  }
2920  if (cfg[pos2] == ';')
2921  macros.insert(cfg.substr(pos, pos2-pos));
2922  pos = cfg.find(';', pos2);
2923  if (pos != std::string::npos)
2924  ++pos;
2925  }
2926 
2927  // check if any empty macros are used in code
2928  for (std::set<std::string>::const_iterator it = macros.begin(); it != macros.end(); ++it) {
2929  const std::string &macro = *it;
2930  std::string::size_type pos = 0;
2931  while ((pos = code.find_first_of(std::string("#\"'")+macro[0], pos)) != std::string::npos) {
2932  const std::string::size_type pos1 = pos;
2933  const std::string::size_type pos2 = pos + macro.size();
2934  pos++;
2935 
2936  // skip string..
2937  if (code[pos1] == '\"' || code[pos1] == '\'') {
2938  while (pos < code.size() && code[pos] != code[pos1]) {
2939  if (code[pos] == '\\')
2940  ++pos;
2941  ++pos;
2942  }
2943  ++pos;
2944  }
2945 
2946  // skip preprocessor statement..
2947  else if (code[pos1] == '#') {
2948  if (pos1 == 0 || code[pos1-1] == '\n')
2949  pos = code.find('\n', pos);
2950  }
2951 
2952  // is macro used in code?
2953  else if (code.compare(pos1,macro.size(),macro) == 0) {
2954  if (pos1 > 0 && (std::isalnum((unsigned char)code[pos1-1U]) || code[pos1-1U] == '_'))
2955  continue;
2956  if (pos2 < code.size() && (std::isalnum((unsigned char)code[pos2]) || code[pos2] == '_'))
2957  continue;
2958  // macro is used in code, return false
2959  if (printInformation)
2960  validateCfgError(cfg, macro);
2961  return false;
2962  }
2963  }
2964  }
2965 
2966  return true;
2967 }
2968 
2969 void Preprocessor::validateCfgError(const std::string &cfg, const std::string &macro)
2970 {
2971  const std::string id = "ConfigurationNotChecked";
2972  std::list<ErrorLogger::ErrorMessage::FileLocation> locationList;
2974  locationList.push_back(loc);
2975  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);
2976  _errorLogger->reportInfo(errmsg);
2977 }
2978 
2979 std::string Preprocessor::expandMacros(const std::string &code, std::string filename, const std::string &cfg, ErrorLogger *errorLogger)
2980 {
2981  // Search for macros and expand them..
2982  // --------------------------------------------
2983 
2984  // Available macros (key=macroname, value=macro).
2985  std::map<std::string, PreprocessorMacro *> macros;
2986  const Settings settings;
2987 
2988  {
2989  // fill up "macros" with user defined macros
2990  const std::map<std::string,std::string> cfgmap(getcfgmap(cfg,nullptr,""));
2991  std::map<std::string, std::string>::const_iterator it;
2992  for (it = cfgmap.begin(); it != cfgmap.end(); ++it) {
2993  std::string s = it->first;
2994  if (!it->second.empty())
2995  s += " " + it->second;
2996  PreprocessorMacro *macro = new PreprocessorMacro(s, &settings);
2997  macros[it->first] = macro;
2998  }
2999  }
3000 
3001  // Current line number
3002  unsigned int linenr = 1;
3003 
3004  // linenr, filename
3005  std::stack< std::pair<unsigned int, std::string> > fileinfo;
3006 
3007  // output stream
3008  std::ostringstream ostr;
3009 
3010  // read code..
3011  std::istringstream istr(code);
3012  std::string line;
3013  while (getlines(istr, line)) {
3014  if (line.empty())
3015  continue;
3016 
3017  // Preprocessor directive
3018  if (line[0] == '#') {
3019  // defining a macro..
3020  if (line.compare(1, 7, "define ") == 0) {
3021  PreprocessorMacro *macro = new PreprocessorMacro(line.substr(8), &settings);
3022  if (macro->name().empty() || macro->name() == "NULL") {
3023  delete macro;
3024  } else if (macro->name() == "BOOST_FOREACH") {
3025  // BOOST_FOREACH is currently too complex to parse, so skip it.
3026  delete macro;
3027  } else {
3028  std::map<std::string, PreprocessorMacro *>::iterator it;
3029  it = macros.find(macro->name());
3030  if (it != macros.end())
3031  delete it->second;
3032  macros[macro->name()] = macro;
3033  }
3034  line = "\n";
3035  }
3036 
3037  // undefining a macro..
3038  else if (line.compare(1, 6, "undef ") == 0) {
3039  std::map<std::string, PreprocessorMacro *>::iterator it;
3040  it = macros.find(line.substr(7));
3041  if (it != macros.end()) {
3042  delete it->second;
3043  macros.erase(it);
3044  }
3045  line = "\n";
3046  }
3047 
3048  // entering a file, update position..
3049  else if (line.compare(1, 6, "file \"") == 0) {
3050  fileinfo.push(std::pair<unsigned int, std::string>(linenr, filename));
3051  filename = line.substr(7, line.length() - 8);
3052  linenr = 0;
3053  line += "\n";
3054  }
3055 
3056  // leaving a file, update position..
3057  else if (line == "#endfile") {
3058  if (!fileinfo.empty()) {
3059  linenr = fileinfo.top().first;
3060  filename = fileinfo.top().second;
3061  fileinfo.pop();
3062  }
3063  line += "\n";
3064  }
3065 
3066  // all other preprocessor directives are just replaced with a newline
3067  else
3068  line += "\n";
3069  }
3070 
3071  // expand macros..
3072  else {
3073  // Limit for each macro.
3074  // The limit specify a position in the "line" variable.
3075  // For a "recursive macro" where the expanded text contains
3076  // the macro again, the macro should not be expanded again.
3077  // The limits are used to prevent recursive expanding.
3078  // * When a macro is expanded its limit position is set to
3079  // the last expanded character.
3080  // * macros are only allowed to be expanded when the
3081  // the position is beyond the limit.
3082  // * The limit is relative to the end of the "line"
3083  // variable. Inserting and deleting text before the limit
3084  // without updating the limit is safe.
3085  // * when pos goes beyond a limit the limit needs to be
3086  // deleted because it is unsafe to insert/delete text
3087  // after the limit otherwise
3088  std::map<const PreprocessorMacro *, std::size_t> limits;
3089 
3090  // pos is the current position in line
3091  std::string::size_type pos = 0;
3092 
3093  // scan line to see if there are any macros to expand..
3094  unsigned int tmpLinenr = 0;
3095  while (pos < line.size()) {
3096  if (line[pos] == '\n')
3097  ++tmpLinenr;
3098 
3099  // skip strings..
3100  if (line[pos] == '\"' || line[pos] == '\'') {
3101  const char ch = line[pos];
3102 
3103  skipstring(line, pos);
3104  ++pos;
3105 
3106  if (pos >= line.size()) {
3107  writeError(Path::simplifyPath(filename),
3108  linenr + tmpLinenr,
3109  errorLogger,
3110  "noQuoteCharPair",
3111  std::string("No pair for character (") + ch + "). Can't process file. File is either invalid or unicode, which is currently not supported.");
3112 
3113  std::map<std::string, PreprocessorMacro *>::iterator it;
3114  for (it = macros.begin(); it != macros.end(); ++it)
3115  delete it->second;
3116  macros.clear();
3117  return "";
3118  }
3119 
3120  continue;
3121  }
3122 
3123  if (!std::isalpha((unsigned char)line[pos]) && line[pos] != '_')
3124  ++pos;
3125 
3126  // found an identifier..
3127  // the "while" is used in case the expanded macro will immediately call another macro
3128  while (pos < line.length() && (std::isalpha((unsigned char)line[pos]) || line[pos] == '_')) {
3129  // pos1 = start position of macro
3130  const std::string::size_type pos1 = pos++;
3131 
3132  // find the end of the identifier
3133  while (pos < line.size() && (std::isalnum((unsigned char)line[pos]) || line[pos] == '_'))
3134  ++pos;
3135 
3136  // get identifier
3137  const std::string id = line.substr(pos1, pos - pos1);
3138 
3139  // is there a macro with this name?
3140  std::map<std::string, PreprocessorMacro *>::const_iterator it;
3141  it = macros.find(id);
3142  if (it == macros.end())
3143  break; // no macro with this name exist
3144 
3145  const PreprocessorMacro * const macro = it->second;
3146 
3147  // check that pos is within allowed limits for this
3148  // macro
3149  {
3150  const std::map<const PreprocessorMacro *, std::size_t>::const_iterator it2 = limits.find(macro);
3151  if (it2 != limits.end() && pos <= line.length() - it2->second)
3152  break;
3153  }
3154 
3155  // get parameters from line..
3156  if (macro->params().size() && pos >= line.length())
3157  break;
3158  std::vector<std::string> params;
3159  std::string::size_type pos2 = pos;
3160 
3161  // number of newlines within macro use
3162  unsigned int numberOfNewlines = 0;
3163 
3164  // if the macro has parentheses, get parameters
3165  if (macro->variadic() || macro->nopar() || macro->params().size()) {
3166  // is the end parentheses found?
3167  bool endFound = false;
3168 
3169  getparams(line,pos2,params,numberOfNewlines,endFound);
3170 
3171  // something went wrong so bail out
3172  if (!endFound)
3173  break;
3174  }
3175 
3176  // Just an empty parameter => clear
3177  if (params.size() == 1 && params[0] == "")
3178  params.clear();
3179 
3180  // Check that it's the same number of parameters..
3181  if (!macro->variadic() && params.size() != macro->params().size())
3182  break;
3183 
3184  // Create macro code..
3185  std::string tempMacro;
3186  if (!macro->code(params, macros, tempMacro)) {
3187  // Syntax error in code
3188  writeError(filename,
3189  linenr + tmpLinenr,
3190  errorLogger,
3191  "syntaxError",
3192  std::string("Syntax error. Not enough parameters for macro '") + macro->name() + "'.");
3193 
3194  std::map<std::string, PreprocessorMacro *>::iterator iter;
3195  for (iter = macros.begin(); iter != macros.end(); ++iter)
3196  delete iter->second;
3197  macros.clear();
3198  return "";
3199  }
3200 
3201  // make sure number of newlines remain the same..
3202  std::string macrocode(std::string(numberOfNewlines, '\n') + tempMacro);
3203 
3204  // Insert macro code..
3205  if (macro->variadic() || macro->nopar() || !macro->params().empty())
3206  ++pos2;
3207 
3208  // Remove old limits
3209  for (std::map<const PreprocessorMacro *, std::size_t>::iterator iter = limits.begin();
3210  iter != limits.end();) {
3211  if ((line.length() - pos1) < iter->second) {
3212  // We have gone past this limit, so just delete it
3213  limits.erase(iter++);
3214  } else {
3215  ++iter;
3216  }
3217  }
3218 
3219  // don't allow this macro to be expanded again before pos2
3220  limits[macro] = line.length() - pos2;
3221 
3222  // erase macro
3223  line.erase(pos1, pos2 - pos1);
3224 
3225  // Don't glue this macro into variable or number after it
3226  if (!line.empty() && (std::isalnum((unsigned char)line[pos1]) || line[pos1] == '_'))
3227  macrocode.append(1,' ');
3228 
3229  // insert macrochar before each symbol/nr/operator
3230  bool str = false;
3231  bool chr = false;
3232  for (std::size_t i = 0U; i < macrocode.size(); ++i) {
3233  if (macrocode[i] == '\\') {
3234  i++;
3235  continue;
3236  } else if (macrocode[i] == '\"')
3237  str = !str;
3238  else if (macrocode[i] == '\'')
3239  chr = !chr;
3240  else if (str || chr)
3241  continue;
3242  else if (macrocode[i] == '.') { // 5. / .5
3243  if ((i > 0U && std::isdigit((unsigned char)macrocode[i-1])) ||
3244  (i+1 < macrocode.size() && std::isdigit((unsigned char)macrocode[i+1]))) {
3245  if (i > 0U && !std::isdigit((unsigned char)macrocode[i-1])) {
3246  macrocode.insert(i, 1U, macroChar);
3247  i++;
3248  }
3249  i++;
3250  if (i<macrocode.size() && std::isdigit((unsigned char)macrocode[i]))
3251  i++;
3252  if (i+1U < macrocode.size() &&
3253  (macrocode[i] == 'e' || macrocode[i] == 'E') &&
3254  (macrocode[i+1] == '+' || macrocode[i+1] == '-')) {
3255  i+=2;
3256  }
3257  }
3258  } else if (std::isalnum((unsigned char)macrocode[i]) || macrocode[i] == '_') {
3259  if ((i > 0U) &&
3260  (!std::isalnum((unsigned char)macrocode[i-1])) &&
3261  (macrocode[i-1] != '_') &&
3262  (macrocode[i-1] != macroChar)) {
3263  macrocode.insert(i, 1U, macroChar);
3264  }
3265 
3266  // 1e-7 / 1e+7
3267  if (i+3U < macrocode.size() &&
3268  (std::isdigit((unsigned char)macrocode[i]) || macrocode[i]=='.') &&
3269  (macrocode[i+1] == 'e' || macrocode[i+1] == 'E') &&
3270  (macrocode[i+2] == '-' || macrocode[i+2] == '+') &&
3271  std::isdigit((unsigned char)macrocode[i+3])) {
3272  i += 3U;
3273  }
3274 
3275  // 1.f / 1.e7
3276  if (i+2U < macrocode.size() &&
3277  std::isdigit((unsigned char)macrocode[i]) &&
3278  macrocode[i+1] == '.' &&
3279  std::isalpha((unsigned char)macrocode[i+2])) {
3280  i += 2U;
3281  if (i+2U < macrocode.size() &&
3282  (macrocode[i+0] == 'e' || macrocode[i+0] == 'E') &&
3283  (macrocode[i+1] == '-' || macrocode[i+1] == '+') &&
3284  std::isdigit((unsigned char)macrocode[i+2])) {
3285  i += 2U;
3286  }
3287  }
3288  }
3289  }
3290  line.insert(pos1, macroChar + macrocode);
3291 
3292  // position = start position.
3293  pos = pos1;
3294  }
3295  }
3296  }
3297 
3298  // the line has been processed in various ways. Now add it to the output stream
3299  ostr << line;
3300 
3301  // update linenr
3302  for (std::string::size_type p = 0; p < line.length(); ++p) {
3303  if (line[p] == '\n')
3304  ++linenr;
3305  }
3306  }
3307 
3308  for (std::map<std::string, PreprocessorMacro *>::iterator it = macros.begin(); it != macros.end(); ++it)
3309  delete it->second;
3310  macros.clear();
3311 
3312  return ostr.str();
3313 }
3314 
3315 
3316 void Preprocessor::getErrorMessages(ErrorLogger *errorLogger, const Settings *settings)
3317 {
3318  Settings settings2(*settings);
3319  Preprocessor preprocessor(settings2, errorLogger);
3320  settings2.checkConfiguration=true;
3321  preprocessor.missingInclude("", 1, "", UserHeader);
3322  preprocessor.missingInclude("", 1, "", SystemHeader);
3323  preprocessor.validateCfgError("X", "X");
3324  preprocessor.error("", 1, "#error message"); // #error ..
3325 }
3326 
3327 void Preprocessor::dump(std::ostream &out) const
3328 {
3329  // Create a xml directive dump.
3330  // The idea is not that this will be readable for humans. It's a
3331  // data dump that 3rd party tools could load and get useful info from.
3332  std::list<Directive>::const_iterator it;
3333 
3334  out << " <directivelist>" << std::endl;
3335 
3336  for (it = directives.begin(); it != directives.end(); ++it) {
3337  out << " <directive "
3338  << "file=\"" << it->file << "\" "
3339  << "linenr=\"" << it->linenr << "\" "
3340  // str might contain characters such as '"', '<' or '>' which
3341  // could result in invalid XML, so run it through toxml().
3342  << "str=\"" << ErrorLogger::toxml(it->str) << "\"/>" << std::endl;
3343  }
3344  out << " </directivelist>" << std::endl;
3345 }