1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497
|
/*
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2025 Cppcheck team.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "importproject.h"
#include "path.h"
#include "settings.h"
#include "standards.h"
#include "suppressions.h"
#include "token.h"
#include "tokenlist.h"
#include "utils.h"
#include <algorithm>
#include <cstdlib>
#include <cstring>
#include <fstream>
#include <iostream>
#include <iterator>
#include <sstream>
#include <stack>
#include <unordered_set>
#include <utility>
#include "xml.h"
#include "json.h"
// TODO: align the exclusion logic with PathMatch
void ImportProject::ignorePaths(const std::vector<std::string> &ipaths)
{
for (auto it = fileSettings.cbegin(); it != fileSettings.cend();) {
bool ignore = false;
for (std::string i : ipaths) {
if (it->filename().size() > i.size() && it->filename().compare(0,i.size(),i)==0) {
ignore = true;
break;
}
if (isValidGlobPattern(i) && matchglob(i, it->filename())) {
ignore = true;
break;
}
if (!Path::isAbsolute(i)) {
i = mPath + i;
if (it->filename().size() > i.size() && it->filename().compare(0,i.size(),i)==0) {
ignore = true;
break;
}
}
}
if (ignore)
it = fileSettings.erase(it);
else
++it;
}
}
void ImportProject::ignoreOtherConfigs(const std::string &cfg)
{
for (auto it = fileSettings.cbegin(); it != fileSettings.cend();) {
if (it->cfg != cfg)
it = fileSettings.erase(it);
else
++it;
}
}
void ImportProject::fsSetDefines(FileSettings& fs, std::string defs)
{
while (defs.find(";%(") != std::string::npos) {
const std::string::size_type pos1 = defs.find(";%(");
const std::string::size_type pos2 = defs.find(';', pos1+1);
defs.erase(pos1, pos2 == std::string::npos ? pos2 : (pos2-pos1));
}
while (defs.find(";;") != std::string::npos)
defs.erase(defs.find(";;"),1);
while (!defs.empty() && defs[0] == ';')
defs.erase(0, 1);
while (!defs.empty() && endsWith(defs,';'))
defs.erase(defs.size() - 1U); // TODO: Use std::string::pop_back() as soon as travis supports it
bool eq = false;
for (std::size_t pos = 0; pos < defs.size(); ++pos) {
if (defs[pos] == '(' || defs[pos] == '=')
eq = true;
else if (defs[pos] == ';') {
if (!eq) {
defs.insert(pos,"=1");
pos += 3;
}
if (pos < defs.size())
eq = false;
}
}
if (!eq && !defs.empty())
defs += "=1";
fs.defines.swap(defs);
}
static bool simplifyPathWithVariables(std::string &s, std::map<std::string, std::string, cppcheck::stricmp> &variables)
{
std::set<std::string, cppcheck::stricmp> expanded;
std::string::size_type start = 0;
while ((start = s.find("$(")) != std::string::npos) {
const std::string::size_type end = s.find(')',start);
if (end == std::string::npos)
break;
const std::string var = s.substr(start+2,end-start-2);
if (expanded.find(var) != expanded.end())
break;
expanded.insert(var);
auto it1 = utils::as_const(variables).find(var);
// variable was not found within defined variables
if (it1 == variables.end()) {
const char *envValue = std::getenv(var.c_str());
if (!envValue) {
//! \todo generate a debug/info message about undefined variable
break;
}
variables[var] = std::string(envValue);
it1 = variables.find(var);
}
s.replace(start, end - start + 1, it1->second);
}
if (s.find("$(") != std::string::npos)
return false;
s = Path::simplifyPath(std::move(s));
return true;
}
void ImportProject::fsSetIncludePaths(FileSettings& fs, const std::string &basepath, const std::list<std::string> &in, std::map<std::string, std::string, cppcheck::stricmp> &variables)
{
std::set<std::string> found;
// NOLINTNEXTLINE(performance-unnecessary-copy-initialization)
const std::list<std::string> copyIn(in);
fs.includePaths.clear();
for (const std::string &ipath : copyIn) {
if (ipath.empty())
continue;
if (startsWith(ipath,"%("))
continue;
std::string s(Path::fromNativeSeparators(ipath));
if (!found.insert(s).second)
continue;
if (s[0] == '/' || (s.size() > 1U && s.compare(1,2,":/") == 0)) {
if (!endsWith(s,'/'))
s += '/';
fs.includePaths.push_back(std::move(s));
continue;
}
if (endsWith(s,'/')) // this is a temporary hack, simplifyPath can crash if path ends with '/'
s.pop_back();
if (s.find("$(") == std::string::npos) {
s = Path::simplifyPath(basepath + s);
} else {
if (!simplifyPathWithVariables(s, variables))
continue;
}
if (s.empty())
continue;
fs.includePaths.push_back(s.back() == '/' ? s : (s + '/'));
}
}
ImportProject::Type ImportProject::import(const std::string &filename, Settings *settings, Suppressions *supprs)
{
std::ifstream fin(filename);
if (!fin.is_open())
return ImportProject::Type::MISSING;
mPath = Path::getPathFromFilename(Path::fromNativeSeparators(filename));
if (!mPath.empty() && !endsWith(mPath,'/'))
mPath += '/';
const std::vector<std::string> fileFilters =
settings ? settings->fileFilters : std::vector<std::string>();
if (endsWith(filename, ".json")) {
if (importCompileCommands(fin)) {
setRelativePaths(filename);
return ImportProject::Type::COMPILE_DB;
}
} else if (endsWith(filename, ".sln")) {
if (importSln(fin, mPath, fileFilters)) {
setRelativePaths(filename);
return ImportProject::Type::VS_SLN;
}
} else if (endsWith(filename, ".vcxproj")) {
std::map<std::string, std::string, cppcheck::stricmp> variables;
std::vector<SharedItemsProject> sharedItemsProjects;
if (importVcxproj(filename, variables, "", fileFilters, sharedItemsProjects)) {
setRelativePaths(filename);
return ImportProject::Type::VS_VCXPROJ;
}
} else if (endsWith(filename, ".bpr")) {
if (importBcb6Prj(filename)) {
setRelativePaths(filename);
return ImportProject::Type::BORLAND;
}
} else if (settings && supprs && endsWith(filename, ".cppcheck")) {
if (importCppcheckGuiProject(fin, *settings, *supprs)) {
setRelativePaths(filename);
return ImportProject::Type::CPPCHECK_GUI;
}
} else {
return ImportProject::Type::UNKNOWN;
}
return ImportProject::Type::FAILURE;
}
static std::string readUntil(const std::string &command, std::string::size_type *pos, const char until[])
{
std::string ret;
bool escapedString = false;
bool str = false;
bool escape = false;
for (; *pos < command.size() && (str || !std::strchr(until, command[*pos])); (*pos)++) {
if (escape)
escape = false;
else if (command[*pos] == '\\') {
if (str)
escape = true;
else if (command[*pos + 1] == '"') {
if (escapedString)
return ret + "\\\"";
escapedString = true;
ret += "\\\"";
(*pos)++;
continue;
}
} else if (command[*pos] == '\"')
str = !str;
ret += command[*pos];
}
return ret;
}
static std::string unescape(const std::string &in)
{
std::string out;
bool escape = false;
for (const char c: in) {
if (escape) {
escape = false;
if (!std::strchr("\\\"\'",c))
out += "\\";
out += c;
} else if (c == '\\')
escape = true;
else
out += c;
}
return out;
}
void ImportProject::fsParseCommand(FileSettings& fs, const std::string& command)
{
std::string defs;
// Parse command..
std::string::size_type pos = 0;
while (std::string::npos != (pos = command.find(' ',pos))) {
while (pos < command.size() && command[pos] == ' ')
pos++;
if (pos >= command.size())
break;
if (command[pos] != '/' && command[pos] != '-')
continue;
pos++;
if (pos >= command.size())
break;
const char F = command[pos++];
if (std::strchr("DUI", F)) {
while (pos < command.size() && command[pos] == ' ')
++pos;
}
const std::string fval = readUntil(command, &pos, " =");
if (F=='D') {
std::string defval = readUntil(command, &pos, " ");
defs += fval;
if (defval.size() >= 3 && startsWith(defval,"=\"") && defval.back()=='\"')
defval = "=" + unescape(defval.substr(2, defval.size() - 3));
else if (defval.size() >= 5 && startsWith(defval, "=\\\"") && endsWith(defval, "\\\""))
defval = "=\"" + unescape(defval.substr(3, defval.size() - 5)) + "\"";
if (!defval.empty())
defs += defval;
defs += ';';
} else if (F=='U')
fs.undefs.insert(fval);
else if (F=='I') {
std::string i = fval;
if (i.size() > 1 && i[0] == '\"' && i.back() == '\"')
i = unescape(i.substr(1, i.size() - 2));
if (std::find(fs.includePaths.cbegin(), fs.includePaths.cend(), i) == fs.includePaths.cend())
fs.includePaths.push_back(std::move(i));
} else if (F=='s' && startsWith(fval,"td")) {
++pos;
fs.standard = readUntil(command, &pos, " ");
} else if (F == 'i' && fval == "system") {
++pos;
std::string isystem = readUntil(command, &pos, " ");
fs.systemIncludePaths.push_back(std::move(isystem));
} else if (F=='m') {
if (fval == "unicode") {
defs += "UNICODE";
defs += ";";
}
} else if (F=='f') {
if (fval == "pic") {
defs += "__pic__";
defs += ";";
} else if (fval == "PIC") {
defs += "__PIC__";
defs += ";";
} else if (fval == "pie") {
defs += "__pie__";
defs += ";";
} else if (fval == "PIE") {
defs += "__PIE__";
defs += ";";
}
// TODO: support -fsigned-char and -funsigned-char?
// we can only set it globally but in this context it needs to be treated per file
}
}
fsSetDefines(fs, std::move(defs));
}
bool ImportProject::importCompileCommands(std::istream &istr)
{
picojson::value compileCommands;
istr >> compileCommands;
if (!compileCommands.is<picojson::array>()) {
printError("compilation database is not a JSON array");
return false;
}
for (const picojson::value &fileInfo : compileCommands.get<picojson::array>()) {
picojson::object obj = fileInfo.get<picojson::object>();
std::string dirpath = Path::fromNativeSeparators(obj["directory"].get<std::string>());
/* CMAKE produces the directory without trailing / so add it if not
* there - it is needed by setIncludePaths() */
if (!endsWith(dirpath, '/'))
dirpath += '/';
const std::string directory = std::move(dirpath);
std::string command;
if (obj.count("arguments")) {
if (obj["arguments"].is<picojson::array>()) {
for (const picojson::value& arg : obj["arguments"].get<picojson::array>()) {
if (arg.is<std::string>()) {
std::string str = arg.get<std::string>();
if (str.find(' ') != std::string::npos)
str = "\"" + str + "\"";
command += str + " ";
}
}
} else {
printError("'arguments' field in compilation database entry is not a JSON array");
return false;
}
} else if (obj.count("command")) {
if (obj["command"].is<std::string>()) {
command = obj["command"].get<std::string>();
} else {
printError("'command' field in compilation database entry is not a string");
return false;
}
} else {
printError("no 'arguments' or 'command' field found in compilation database entry");
return false;
}
if (!obj.count("file") || !obj["file"].is<std::string>()) {
printError("skip compilation database entry because it does not have a proper 'file' field");
continue;
}
const std::string file = Path::fromNativeSeparators(obj["file"].get<std::string>());
// Accept file?
if (!Path::acceptFile(file))
continue;
std::string path;
if (Path::isAbsolute(file))
path = Path::simplifyPath(file);
#ifdef _WIN32
else if (file[0] == '/' && directory.size() > 2 && std::isalpha(directory[0]) && directory[1] == ':')
// directory: C:\foo\bar
// file: /xy/z.c
// => c:/xy/z.c
path = Path::simplifyPath(directory.substr(0,2) + file);
#endif
else
path = Path::simplifyPath(directory + file);
if (!sourceFileExists(path)) {
printError("'" + path + "' from compilation database does not exist");
return false;
}
FileSettings fs{std::move(path)};
fsParseCommand(fs, command); // read settings; -D, -I, -U, -std, -m*, -f*
std::map<std::string, std::string, cppcheck::stricmp> variables;
fsSetIncludePaths(fs, directory, fs.includePaths, variables);
fileSettings.push_back(std::move(fs));
}
return true;
}
bool ImportProject::importSln(std::istream &istr, const std::string &path, const std::vector<std::string> &fileFilters)
{
std::string line;
if (!std::getline(istr,line)) {
printError("Visual Studio solution file is empty");
return false;
}
if (!startsWith(line, "Microsoft Visual Studio Solution File")) {
// Skip BOM
if (!std::getline(istr, line) || !startsWith(line, "Microsoft Visual Studio Solution File")) {
printError("Visual Studio solution file header not found");
return false;
}
}
std::map<std::string,std::string,cppcheck::stricmp> variables;
variables["SolutionDir"] = path;
bool found = false;
std::vector<SharedItemsProject> sharedItemsProjects;
while (std::getline(istr,line)) {
if (!startsWith(line,"Project("))
continue;
const std::string::size_type pos = line.find(".vcxproj");
if (pos == std::string::npos)
continue;
const std::string::size_type pos1 = line.rfind('\"',pos);
if (pos1 == std::string::npos)
continue;
std::string vcxproj(line.substr(pos1+1, pos-pos1+7));
vcxproj = Path::toNativeSeparators(std::move(vcxproj));
if (!Path::isAbsolute(vcxproj))
vcxproj = path + vcxproj;
vcxproj = Path::fromNativeSeparators(std::move(vcxproj));
if (!importVcxproj(vcxproj, variables, "", fileFilters, sharedItemsProjects)) {
printError("failed to load '" + vcxproj + "' from Visual Studio solution");
return false;
}
found = true;
}
if (!found) {
printError("no projects found in Visual Studio solution file");
return false;
}
return true;
}
namespace {
struct ProjectConfiguration {
explicit ProjectConfiguration(const tinyxml2::XMLElement *cfg) {
const char *a = cfg->Attribute("Include");
if (a)
name = a;
for (const tinyxml2::XMLElement *e = cfg->FirstChildElement(); e; e = e->NextSiblingElement()) {
const char * const text = e->GetText();
if (!text)
continue;
const char * ename = e->Name();
if (std::strcmp(ename,"Configuration")==0)
configuration = text;
else if (std::strcmp(ename,"Platform")==0) {
platformStr = text;
if (platformStr == "Win32")
platform = Win32;
else if (platformStr == "x64")
platform = x64;
else
platform = Unknown;
}
}
}
std::string name;
std::string configuration;
enum : std::uint8_t { Win32, x64, Unknown } platform = Unknown;
std::string platformStr;
};
struct ItemDefinitionGroup {
explicit ItemDefinitionGroup(const tinyxml2::XMLElement *idg, std::string includePaths) : additionalIncludePaths(std::move(includePaths)) {
const char *condAttr = idg->Attribute("Condition");
if (condAttr)
condition = condAttr;
for (const tinyxml2::XMLElement *e1 = idg->FirstChildElement(); e1; e1 = e1->NextSiblingElement()) {
const char* name = e1->Name();
if (std::strcmp(name, "ClCompile") == 0) {
enhancedInstructionSet = "StreamingSIMDExtensions2";
for (const tinyxml2::XMLElement *e = e1->FirstChildElement(); e; e = e->NextSiblingElement()) {
const char * const text = e->GetText();
if (!text)
continue;
const char * const ename = e->Name();
if (std::strcmp(ename, "PreprocessorDefinitions") == 0)
preprocessorDefinitions = text;
else if (std::strcmp(ename, "AdditionalIncludeDirectories") == 0) {
if (!additionalIncludePaths.empty())
additionalIncludePaths += ';';
additionalIncludePaths += text;
} else if (std::strcmp(ename, "LanguageStandard") == 0) {
if (std::strcmp(text, "stdcpp14") == 0)
cppstd = Standards::CPP14;
else if (std::strcmp(text, "stdcpp17") == 0)
cppstd = Standards::CPP17;
else if (std::strcmp(text, "stdcpp20") == 0)
cppstd = Standards::CPP20;
else if (std::strcmp(text, "stdcpplatest") == 0)
cppstd = Standards::CPPLatest;
} else if (std::strcmp(ename, "EnableEnhancedInstructionSet") == 0) {
enhancedInstructionSet = text;
}
}
}
else if (std::strcmp(name, "Link") == 0) {
for (const tinyxml2::XMLElement *e = e1->FirstChildElement(); e; e = e->NextSiblingElement()) {
const char * const text = e->GetText();
if (!text)
continue;
if (std::strcmp(e->Name(), "EntryPointSymbol") == 0) {
entryPointSymbol = text;
}
}
}
}
}
static void replaceAll(std::string &c, const std::string &from, const std::string &to) {
std::string::size_type pos;
while ((pos = c.find(from)) != std::string::npos) {
c.erase(pos,from.size());
c.insert(pos,to);
}
}
// see https://learn.microsoft.com/en-us/visualstudio/msbuild/msbuild-conditions
// properties are .NET String objects and you can call any of its members on them
bool conditionIsTrue(const ProjectConfiguration &p) const {
if (condition.empty())
return true;
std::string c = '(' + condition + ");";
replaceAll(c, "$(Configuration)", p.configuration);
replaceAll(c, "$(Platform)", p.platformStr);
// TODO: improve evaluation
const Settings s;
TokenList tokenlist(&s);
std::istringstream istr(c);
tokenlist.createTokens(istr, Standards::Language::C); // TODO: check result
// TODO: put in a helper
// generate links
{
std::stack<Token*> lpar;
for (Token* tok2 = tokenlist.front(); tok2; tok2 = tok2->next()) {
if (tok2->str() == "(")
lpar.push(tok2);
else if (tok2->str() == ")") {
if (lpar.empty())
break;
Token::createMutualLinks(lpar.top(), tok2);
lpar.pop();
}
}
}
tokenlist.createAst();
for (const Token *tok = tokenlist.front(); tok; tok = tok->next()) {
if (tok->str() == "(" && tok->astOperand1() && tok->astOperand2()) {
// TODO: this is wrong - it is Contains() not Equals()
if (tok->astOperand1()->expressionString() == "Configuration.Contains")
return ('\'' + p.configuration + '\'') == tok->astOperand2()->str();
}
if (tok->str() == "==" && tok->astOperand1() && tok->astOperand2() && tok->astOperand1()->str() == tok->astOperand2()->str())
return true;
}
return false;
}
std::string condition;
std::string enhancedInstructionSet;
std::string preprocessorDefinitions;
std::string additionalIncludePaths;
std::string entryPointSymbol; // TODO: use this
Standards::cppstd_t cppstd = Standards::CPPLatest;
};
}
static std::list<std::string> toStringList(const std::string &s)
{
std::list<std::string> ret;
std::string::size_type pos1 = 0;
std::string::size_type pos2;
while ((pos2 = s.find(';',pos1)) != std::string::npos) {
ret.push_back(s.substr(pos1, pos2-pos1));
pos1 = pos2 + 1;
if (pos1 >= s.size())
break;
}
if (pos1 < s.size())
ret.push_back(s.substr(pos1));
return ret;
}
static void importPropertyGroup(const tinyxml2::XMLElement *node, std::map<std::string,std::string,cppcheck::stricmp> &variables, std::string &includePath, bool *useOfMfc)
{
if (useOfMfc) {
for (const tinyxml2::XMLElement *e = node->FirstChildElement(); e; e = e->NextSiblingElement()) {
if (std::strcmp(e->Name(), "UseOfMfc") == 0) {
*useOfMfc = true;
break;
}
}
}
const char* labelAttribute = node->Attribute("Label");
if (labelAttribute && std::strcmp(labelAttribute, "UserMacros") == 0) {
for (const tinyxml2::XMLElement *propertyGroup = node->FirstChildElement(); propertyGroup; propertyGroup = propertyGroup->NextSiblingElement()) {
const char* name = propertyGroup->Name();
const char *text = empty_if_null(propertyGroup->GetText());
variables[name] = text;
}
} else if (!labelAttribute) {
for (const tinyxml2::XMLElement *propertyGroup = node->FirstChildElement(); propertyGroup; propertyGroup = propertyGroup->NextSiblingElement()) {
if (std::strcmp(propertyGroup->Name(), "IncludePath") != 0)
continue;
const char *text = propertyGroup->GetText();
if (!text)
continue;
std::string path(text);
const std::string::size_type pos = path.find("$(IncludePath)");
if (pos != std::string::npos)
path.replace(pos, 14U, includePath);
includePath = std::move(path);
}
}
}
static void loadVisualStudioProperties(const std::string &props, std::map<std::string,std::string,cppcheck::stricmp> &variables, std::string &includePath, const std::string &additionalIncludeDirectories, std::list<ItemDefinitionGroup> &itemDefinitionGroupList)
{
std::string filename(props);
// variables can't be resolved
if (!simplifyPathWithVariables(filename, variables))
return;
// prepend project dir (if it exists) to transform relative paths into absolute ones
if (!Path::isAbsolute(filename) && variables.count("ProjectDir") > 0)
filename = Path::getAbsoluteFilePath(variables.at("ProjectDir") + filename);
tinyxml2::XMLDocument doc;
if (doc.LoadFile(filename.c_str()) != tinyxml2::XML_SUCCESS)
return;
const tinyxml2::XMLElement * const rootnode = doc.FirstChildElement();
if (rootnode == nullptr)
return;
for (const tinyxml2::XMLElement *node = rootnode->FirstChildElement(); node; node = node->NextSiblingElement()) {
const char* name = node->Name();
if (std::strcmp(name, "ImportGroup") == 0) {
const char *labelAttribute = node->Attribute("Label");
if (labelAttribute == nullptr || std::strcmp(labelAttribute, "PropertySheets") != 0)
continue;
for (const tinyxml2::XMLElement *importGroup = node->FirstChildElement(); importGroup; importGroup = importGroup->NextSiblingElement()) {
if (std::strcmp(importGroup->Name(), "Import") == 0) {
const char *projectAttribute = importGroup->Attribute("Project");
if (projectAttribute == nullptr)
continue;
std::string loadprj(projectAttribute);
if (loadprj.find('$') == std::string::npos) {
loadprj = Path::getPathFromFilename(filename) + loadprj;
}
loadVisualStudioProperties(loadprj, variables, includePath, additionalIncludeDirectories, itemDefinitionGroupList);
}
}
} else if (std::strcmp(name,"PropertyGroup")==0) {
importPropertyGroup(node, variables, includePath, nullptr);
} else if (std::strcmp(name,"ItemDefinitionGroup")==0) {
itemDefinitionGroupList.emplace_back(node, additionalIncludeDirectories);
}
}
}
bool ImportProject::importVcxproj(const std::string &filename, std::map<std::string, std::string, cppcheck::stricmp> &variables, const std::string &additionalIncludeDirectories, const std::vector<std::string> &fileFilters, std::vector<SharedItemsProject> &cache)
{
variables["ProjectDir"] = Path::simplifyPath(Path::getPathFromFilename(filename));
std::list<ProjectConfiguration> projectConfigurationList;
std::list<std::string> compileList;
std::list<ItemDefinitionGroup> itemDefinitionGroupList;
std::string includePath;
std::vector<SharedItemsProject> sharedItemsProjects;
bool useOfMfc = false;
tinyxml2::XMLDocument doc;
const tinyxml2::XMLError error = doc.LoadFile(filename.c_str());
if (error != tinyxml2::XML_SUCCESS) {
printError(std::string("Visual Studio project file is not a valid XML - ") + tinyxml2::XMLDocument::ErrorIDToName(error));
return false;
}
const tinyxml2::XMLElement * const rootnode = doc.FirstChildElement();
if (rootnode == nullptr) {
printError("Visual Studio project file has no XML root node");
return false;
}
for (const tinyxml2::XMLElement *node = rootnode->FirstChildElement(); node; node = node->NextSiblingElement()) {
const char* name = node->Name();
if (std::strcmp(name, "ItemGroup") == 0) {
const char *labelAttribute = node->Attribute("Label");
if (labelAttribute && std::strcmp(labelAttribute, "ProjectConfigurations") == 0) {
for (const tinyxml2::XMLElement *cfg = node->FirstChildElement(); cfg; cfg = cfg->NextSiblingElement()) {
if (std::strcmp(cfg->Name(), "ProjectConfiguration") == 0) {
const ProjectConfiguration p(cfg);
if (p.platform != ProjectConfiguration::Unknown) {
projectConfigurationList.emplace_back(cfg);
mAllVSConfigs.insert(p.configuration);
}
}
}
} else {
for (const tinyxml2::XMLElement *e = node->FirstChildElement(); e; e = e->NextSiblingElement()) {
if (std::strcmp(e->Name(), "ClCompile") == 0) {
const char *include = e->Attribute("Include");
if (include && Path::acceptFile(include)) {
std::string toInclude = Path::simplifyPath(Path::isAbsolute(include) ? include : Path::getPathFromFilename(filename) + include);
compileList.emplace_back(toInclude);
}
}
}
}
} else if (std::strcmp(name, "ItemDefinitionGroup") == 0) {
itemDefinitionGroupList.emplace_back(node, additionalIncludeDirectories);
} else if (std::strcmp(name, "PropertyGroup") == 0) {
importPropertyGroup(node, variables, includePath, &useOfMfc);
} else if (std::strcmp(name, "ImportGroup") == 0) {
const char *labelAttribute = node->Attribute("Label");
if (labelAttribute && std::strcmp(labelAttribute, "PropertySheets") == 0) {
for (const tinyxml2::XMLElement *e = node->FirstChildElement(); e; e = e->NextSiblingElement()) {
if (std::strcmp(e->Name(), "Import") == 0) {
const char *projectAttribute = e->Attribute("Project");
if (projectAttribute)
loadVisualStudioProperties(projectAttribute, variables, includePath, additionalIncludeDirectories, itemDefinitionGroupList);
}
}
} else if (labelAttribute && std::strcmp(labelAttribute, "Shared") == 0) {
for (const tinyxml2::XMLElement *e = node->FirstChildElement(); e; e = e->NextSiblingElement()) {
if (std::strcmp(e->Name(), "Import") == 0) {
const char *projectAttribute = e->Attribute("Project");
if (projectAttribute) {
// Path to shared items project is relative to current project directory,
// unless the string starts with $(SolutionDir)
std::string pathToSharedItemsFile;
if (std::string(projectAttribute).rfind("$(SolutionDir)", 0) == 0) {
pathToSharedItemsFile = projectAttribute;
} else {
pathToSharedItemsFile = variables["ProjectDir"] + projectAttribute;
}
if (!simplifyPathWithVariables(pathToSharedItemsFile, variables)) {
printError("Could not simplify path to referenced shared items project");
return false;
}
SharedItemsProject toAdd = importVcxitems(pathToSharedItemsFile, fileFilters, cache);
if (!toAdd.successful) {
printError("Could not load shared items project \"" + pathToSharedItemsFile + "\" from original path \"" + std::string(projectAttribute) + "\".");
return false;
}
sharedItemsProjects.emplace_back(toAdd);
}
}
}
}
}
}
// # TODO: support signedness of char via /J (and potential XML option for it)?
// we can only set it globally but in this context it needs to be treated per file
// Include shared items project files
std::vector<std::string> sharedItemsIncludePaths;
for (const auto& sharedProject : sharedItemsProjects) {
for (const auto &file : sharedProject.sourceFiles) {
std::string pathToFile = Path::simplifyPath(Path::getPathFromFilename(sharedProject.pathToProjectFile) + file);
compileList.emplace_back(std::move(pathToFile));
}
for (const auto &p : sharedProject.includePaths) {
std::string path = Path::simplifyPath(Path::getPathFromFilename(sharedProject.pathToProjectFile) + p);
sharedItemsIncludePaths.emplace_back(std::move(path));
}
}
// Project files
for (const std::string &cfilename : compileList) {
if (!fileFilters.empty() && !matchglobs(fileFilters, cfilename))
continue;
for (const ProjectConfiguration &p : projectConfigurationList) {
if (!guiProject.checkVsConfigs.empty()) {
const bool doChecking = std::any_of(guiProject.checkVsConfigs.cbegin(), guiProject.checkVsConfigs.cend(), [&](const std::string& c) {
return c == p.configuration;
});
if (!doChecking)
continue;
}
FileSettings fs{cfilename};
fs.cfg = p.name;
// TODO: detect actual MSC version
fs.msc = true;
fs.useMfc = useOfMfc;
fs.defines = "_WIN32=1";
if (p.platform == ProjectConfiguration::Win32)
fs.platformType = Platform::Type::Win32W;
else if (p.platform == ProjectConfiguration::x64) {
fs.platformType = Platform::Type::Win64;
fs.defines += ";_WIN64=1";
}
std::string additionalIncludePaths;
for (const ItemDefinitionGroup &i : itemDefinitionGroupList) {
if (!i.conditionIsTrue(p))
continue;
fs.standard = Standards::getCPP(i.cppstd);
fs.defines += ';' + i.preprocessorDefinitions;
if (i.enhancedInstructionSet == "StreamingSIMDExtensions")
fs.defines += ";__SSE__";
else if (i.enhancedInstructionSet == "StreamingSIMDExtensions2")
fs.defines += ";__SSE2__";
else if (i.enhancedInstructionSet == "AdvancedVectorExtensions")
fs.defines += ";__AVX__";
else if (i.enhancedInstructionSet == "AdvancedVectorExtensions2")
fs.defines += ";__AVX2__";
else if (i.enhancedInstructionSet == "AdvancedVectorExtensions512")
fs.defines += ";__AVX512__";
additionalIncludePaths += ';' + i.additionalIncludePaths;
}
fsSetDefines(fs, fs.defines);
fsSetIncludePaths(fs, Path::getPathFromFilename(filename), toStringList(includePath + ';' + additionalIncludePaths), variables);
for (const auto &path : sharedItemsIncludePaths) {
fs.includePaths.emplace_back(path);
}
fileSettings.push_back(std::move(fs));
}
}
return true;
}
ImportProject::SharedItemsProject ImportProject::importVcxitems(const std::string& filename, const std::vector<std::string>& fileFilters, std::vector<SharedItemsProject> &cache)
{
auto isInCacheCheck = [filename](const ImportProject::SharedItemsProject& e) -> bool {
return filename == e.pathToProjectFile;
};
const auto iterator = std::find_if(cache.begin(), cache.end(), isInCacheCheck);
if (iterator != std::end(cache)) {
return *iterator;
}
SharedItemsProject result;
result.pathToProjectFile = filename;
tinyxml2::XMLDocument doc;
const tinyxml2::XMLError error = doc.LoadFile(filename.c_str());
if (error != tinyxml2::XML_SUCCESS) {
printError(std::string("Visual Studio project file is not a valid XML - ") + tinyxml2::XMLDocument::ErrorIDToName(error));
return result;
}
const tinyxml2::XMLElement * const rootnode = doc.FirstChildElement();
if (rootnode == nullptr) {
printError("Visual Studio project file has no XML root node");
return result;
}
for (const tinyxml2::XMLElement *node = rootnode->FirstChildElement(); node; node = node->NextSiblingElement()) {
if (std::strcmp(node->Name(), "ItemGroup") == 0) {
for (const tinyxml2::XMLElement *e = node->FirstChildElement(); e; e = e->NextSiblingElement()) {
if (std::strcmp(e->Name(), "ClCompile") == 0) {
const char* include = e->Attribute("Include");
if (include && Path::acceptFile(include)) {
std::string file(include);
findAndReplace(file, "$(MSBuildThisFileDirectory)", "./");
// Don't include file if it matches the filter
if (!fileFilters.empty() && !matchglobs(fileFilters, file))
continue;
result.sourceFiles.emplace_back(file);
} else {
printError("Could not find shared items source file");
return result;
}
}
}
} else if (std::strcmp(node->Name(), "ItemDefinitionGroup") == 0) {
ItemDefinitionGroup temp(node, "");
for (const auto& includePath : toStringList(temp.additionalIncludePaths)) {
if (includePath == "%(AdditionalIncludeDirectories)")
continue;
std::string toAdd(includePath);
findAndReplace(toAdd, "$(MSBuildThisFileDirectory)", "./");
result.includePaths.emplace_back(toAdd);
}
}
}
result.successful = true;
cache.emplace_back(result);
return result;
}
bool ImportProject::importBcb6Prj(const std::string &projectFilename)
{
tinyxml2::XMLDocument doc;
const tinyxml2::XMLError error = doc.LoadFile(projectFilename.c_str());
if (error != tinyxml2::XML_SUCCESS) {
printError(std::string("Borland project file is not a valid XML - ") + tinyxml2::XMLDocument::ErrorIDToName(error));
return false;
}
const tinyxml2::XMLElement * const rootnode = doc.FirstChildElement();
if (rootnode == nullptr) {
printError("Borland project file has no XML root node");
return false;
}
const std::string& projectDir = Path::simplifyPath(Path::getPathFromFilename(projectFilename));
std::list<std::string> compileList;
std::string includePath;
std::string userdefines;
std::string sysdefines;
std::string cflag1;
for (const tinyxml2::XMLElement *node = rootnode->FirstChildElement(); node; node = node->NextSiblingElement()) {
const char* name = node->Name();
if (std::strcmp(name, "FILELIST") == 0) {
for (const tinyxml2::XMLElement *f = node->FirstChildElement(); f; f = f->NextSiblingElement()) {
if (std::strcmp(f->Name(), "FILE") == 0) {
const char *filename = f->Attribute("FILENAME");
if (filename && Path::acceptFile(filename))
compileList.emplace_back(filename);
}
}
} else if (std::strcmp(name, "MACROS") == 0) {
for (const tinyxml2::XMLElement *m = node->FirstChildElement(); m; m = m->NextSiblingElement()) {
const char* mname = m->Name();
if (std::strcmp(mname, "INCLUDEPATH") == 0) {
const char *v = m->Attribute("value");
if (v)
includePath = v;
} else if (std::strcmp(mname, "USERDEFINES") == 0) {
const char *v = m->Attribute("value");
if (v)
userdefines = v;
} else if (std::strcmp(mname, "SYSDEFINES") == 0) {
const char *v = m->Attribute("value");
if (v)
sysdefines = v;
}
}
} else if (std::strcmp(name, "OPTIONS") == 0) {
for (const tinyxml2::XMLElement *m = node->FirstChildElement(); m; m = m->NextSiblingElement()) {
if (std::strcmp(m->Name(), "CFLAG1") == 0) {
const char *v = m->Attribute("value");
if (v)
cflag1 = v;
}
}
}
}
std::set<std::string> cflags;
// parse cflag1 and fill the cflags set
{
std::string arg;
for (const char i : cflag1) {
if (i == ' ' && !arg.empty()) {
cflags.insert(arg);
arg.clear();
continue;
}
arg += i;
}
if (!arg.empty()) {
cflags.insert(arg);
}
// cleanup: -t is "An alternate name for the -Wxxx switches; there is no difference"
// -> Remove every known -txxx argument and replace it with its -Wxxx counterpart.
// This way, we know what we have to check for later on.
static const std::map<std::string, std::string> synonyms = {
{ "-tC","-WC" },
{ "-tCDR","-WCDR" },
{ "-tCDV","-WCDV" },
{ "-tW","-W" },
{ "-tWC","-WC" },
{ "-tWCDR","-WCDR" },
{ "-tWCDV","-WCDV" },
{ "-tWD","-WD" },
{ "-tWDR","-WDR" },
{ "-tWDV","-WDV" },
{ "-tWM","-WM" },
{ "-tWP","-WP" },
{ "-tWR","-WR" },
{ "-tWU","-WU" },
{ "-tWV","-WV" }
};
for (auto i = synonyms.cbegin(); i != synonyms.cend(); ++i) {
if (cflags.erase(i->first) > 0) {
cflags.insert(i->second);
}
}
}
std::string predefines;
std::string cppPredefines;
// Collecting predefines. See BCB6 help topic "Predefined macros"
{
cppPredefines +=
// Defined if you've selected C++ compilation; will increase in later releases.
// value 0x0560 (but 0x0564 for our BCB6 SP4)
// @see http://docwiki.embarcadero.com/RADStudio/Tokyo/en/Predefined_Macros#C.2B.2B_Compiler_Versions_in_Predefined_Macros
";__BCPLUSPLUS__=0x0560"
// Defined if in C++ mode; otherwise, undefined.
";__cplusplus=1"
// Defined as 1 for C++ files(meaning that templates are supported); otherwise, it is undefined.
";__TEMPLATES__=1"
// Defined only for C++ programs to indicate that wchar_t is an intrinsically defined data type.
";_WCHAR_T"
// Defined only for C++ programs to indicate that wchar_t is an intrinsically defined data type.
";_WCHAR_T_DEFINED"
// Defined in any compiler that has an optimizer.
";__BCOPT__=1"
// Version number.
// BCB6 is 0x056X (SP4 is 0x0564)
// @see http://docwiki.embarcadero.com/RADStudio/Tokyo/en/Predefined_Macros#C.2B.2B_Compiler_Versions_in_Predefined_Macros
";__BORLANDC__=0x0560"
";__TCPLUSPLUS__=0x0560"
";__TURBOC__=0x0560";
// Defined if Calling Convention is set to cdecl; otherwise undefined.
const bool useCdecl = (cflags.find("-p") == cflags.end()
&& cflags.find("-pm") == cflags.end()
&& cflags.find("-pr") == cflags.end()
&& cflags.find("-ps") == cflags.end());
if (useCdecl)
predefines += ";__CDECL=1";
// Defined by default indicating that the default char is unsigned char. Use the -K compiler option to undefine this macro.
const bool treatCharAsUnsignedChar = (cflags.find("-K") != cflags.end());
if (treatCharAsUnsignedChar)
predefines += ";_CHAR_UNSIGNED=1";
// Defined whenever one of the CodeGuard compiler options is used; otherwise it is undefined.
const bool codeguardUsed = (cflags.find("-vGd") != cflags.end()
|| cflags.find("-vGt") != cflags.end()
|| cflags.find("-vGc") != cflags.end());
if (codeguardUsed)
predefines += ";__CODEGUARD__";
// When defined, the macro indicates that the program is a console application.
const bool isConsoleApp = (cflags.find("-WC") != cflags.end());
if (isConsoleApp)
predefines += ";__CONSOLE__=1";
// Enable stack unwinding. This is true by default; use -xd- to disable.
const bool enableStackUnwinding = (cflags.find("-xd-") == cflags.end());
if (enableStackUnwinding)
predefines += ";_CPPUNWIND=1";
// Defined whenever the -WD compiler option is used; otherwise it is undefined.
const bool isDLL = (cflags.find("-WD") != cflags.end());
if (isDLL)
predefines += ";__DLL__=1";
// Defined when compiling in 32-bit flat memory model.
// TODO: not sure how to switch to another memory model or how to read configuration from project file
predefines += ";__FLAT__=1";
// Always defined. The default value is 300. You can change the value to 400 or 500 by using the /4 or /5 compiler options.
if (cflags.find("-6") != cflags.end())
predefines += ";_M_IX86=600";
else if (cflags.find("-5") != cflags.end())
predefines += ";_M_IX86=500";
else if (cflags.find("-4") != cflags.end())
predefines += ";_M_IX86=400";
else
predefines += ";_M_IX86=300";
// Defined only if the -WM option is used. It specifies that the multithread library is to be linked.
const bool linkMtLib = (cflags.find("-WM") != cflags.end());
if (linkMtLib)
predefines += ";__MT__=1";
// Defined if Calling Convention is set to Pascal; otherwise undefined.
const bool usePascalCallingConvention = (cflags.find("-p") != cflags.end());
if (usePascalCallingConvention)
predefines += ";__PASCAL__=1";
// Defined if you compile with the -A compiler option; otherwise, it is undefined.
const bool useAnsiKeywordExtensions = (cflags.find("-A") != cflags.end());
if (useAnsiKeywordExtensions)
predefines += ";__STDC__=1";
// Thread Local Storage. Always true in C++Builder.
predefines += ";__TLC__=1";
// Defined for Windows-only code.
const bool isWindowsTarget = (cflags.find("-WC") != cflags.end()
|| cflags.find("-WCDR") != cflags.end()
|| cflags.find("-WCDV") != cflags.end()
|| cflags.find("-WD") != cflags.end()
|| cflags.find("-WDR") != cflags.end()
|| cflags.find("-WDV") != cflags.end()
|| cflags.find("-WM") != cflags.end()
|| cflags.find("-WP") != cflags.end()
|| cflags.find("-WR") != cflags.end()
|| cflags.find("-WU") != cflags.end()
|| cflags.find("-WV") != cflags.end());
if (isWindowsTarget)
predefines += ";_Windows";
// Defined for console and GUI applications.
// TODO: I'm not sure about the difference to define "_Windows".
// From description, I would assume __WIN32__ is only defined for
// executables, while _Windows would also be defined for DLLs, etc.
// However, in a newly created DLL project, both __WIN32__ and
// _Windows are defined. -> treating them the same for now.
// Also boost uses __WIN32__ for OS identification.
const bool isConsoleOrGuiApp = isWindowsTarget;
if (isConsoleOrGuiApp)
predefines += ";__WIN32__=1";
}
// Include paths may contain variables like "$(BCB)\include" or "$(BCB)\include\vcl".
// Those get resolved by ImportProject::FileSettings::setIncludePaths by
// 1. checking the provided variables map ("BCB" => "C:\\Program Files (x86)\\Borland\\CBuilder6")
// 2. checking env variables as a fallback
// Setting env is always possible. Configuring the variables via cli might be an addition.
// Reading the BCB6 install location from registry in windows environments would also be possible,
// but I didn't see any such functionality around the source. Not in favor of adding it only
// for the BCB6 project loading.
std::map<std::string, std::string, cppcheck::stricmp> variables;
const std::string defines = predefines + ";" + sysdefines + ";" + userdefines;
const std::string cppDefines = cppPredefines + ";" + defines;
const bool forceCppMode = (cflags.find("-P") != cflags.end());
for (const std::string &c : compileList) {
// C++ compilation is selected by file extension by default, so these
// defines have to be configured on a per-file base.
//
// > Files with the .CPP extension compile as C++ files. Files with a .C
// > extension, with no extension, or with extensions other than .CPP,
// > .OBJ, .LIB, or .ASM compile as C files.
// (http://docwiki.embarcadero.com/RADStudio/Tokyo/en/BCC32.EXE,_the_C%2B%2B_32-bit_Command-Line_Compiler)
//
// We can also force C++ compilation for all files using the -P command line switch.
const bool cppMode = forceCppMode || Path::getFilenameExtensionInLowerCase(c) == ".cpp";
FileSettings fs{Path::simplifyPath(Path::isAbsolute(c) ? c : projectDir + c)};
fsSetIncludePaths(fs, projectDir, toStringList(includePath), variables);
fsSetDefines(fs, cppMode ? cppDefines : defines);
fileSettings.push_back(std::move(fs));
}
return true;
}
static std::string joinRelativePath(const std::string &path1, const std::string &path2)
{
if (!path1.empty() && !Path::isAbsolute(path2))
return path1 + path2;
return path2;
}
static std::list<std::string> readXmlStringList(const tinyxml2::XMLElement *node, const std::string &path, const char name[], const char attribute[])
{
std::list<std::string> ret;
for (const tinyxml2::XMLElement *child = node->FirstChildElement(); child; child = child->NextSiblingElement()) {
if (strcmp(child->Name(), name) != 0)
continue;
const char *attr = attribute ? child->Attribute(attribute) : child->GetText();
if (attr)
ret.push_back(joinRelativePath(path, attr));
}
return ret;
}
static std::string join(const std::list<std::string> &strlist, const char *sep)
{
std::string ret;
for (const std::string &s : strlist) {
ret += (ret.empty() ? "" : sep) + s;
}
return ret;
}
static std::string istream_to_string(std::istream &istr)
{
std::istreambuf_iterator<char> eos;
return std::string(std::istreambuf_iterator<char>(istr), eos);
}
bool ImportProject::importCppcheckGuiProject(std::istream &istr, Settings &settings, Suppressions &supprs)
{
tinyxml2::XMLDocument doc;
const std::string xmldata = istream_to_string(istr);
const tinyxml2::XMLError error = doc.Parse(xmldata.data(), xmldata.size());
if (error != tinyxml2::XML_SUCCESS) {
printError(std::string("Cppcheck GUI project file is not a valid XML - ") + tinyxml2::XMLDocument::ErrorIDToName(error));
return false;
}
const tinyxml2::XMLElement * const rootnode = doc.FirstChildElement();
if (rootnode == nullptr || strcmp(rootnode->Name(), CppcheckXml::ProjectElementName) != 0) {
printError("Cppcheck GUI project file has no XML root node");
return false;
}
const std::string &path = mPath;
std::list<std::string> paths;
std::list<SuppressionList::Suppression> suppressions;
Settings temp;
// default to --check-level=normal for import for now
temp.setCheckLevel(Settings::CheckLevel::normal);
guiProject.analyzeAllVsConfigs.clear();
// TODO: this should support all available command-line options
for (const tinyxml2::XMLElement *node = rootnode->FirstChildElement(); node; node = node->NextSiblingElement()) {
const char* name = node->Name();
if (strcmp(name, CppcheckXml::RootPathName) == 0) {
const char* attr = node->Attribute(CppcheckXml::RootPathNameAttrib);
if (attr) {
temp.basePaths.push_back(Path::fromNativeSeparators(joinRelativePath(path, attr)));
temp.relativePaths = true;
}
} else if (strcmp(name, CppcheckXml::BuildDirElementName) == 0)
temp.buildDir = joinRelativePath(path, empty_if_null(node->GetText()));
else if (strcmp(name, CppcheckXml::IncludeDirElementName) == 0)
temp.includePaths = readXmlStringList(node, path, CppcheckXml::DirElementName, CppcheckXml::DirNameAttrib);
else if (strcmp(name, CppcheckXml::DefinesElementName) == 0)
temp.userDefines = join(readXmlStringList(node, "", CppcheckXml::DefineName, CppcheckXml::DefineNameAttrib), ";");
else if (strcmp(name, CppcheckXml::UndefinesElementName) == 0) {
for (const std::string &u : readXmlStringList(node, "", CppcheckXml::UndefineName, nullptr))
temp.userUndefs.insert(u);
} else if (strcmp(name, CppcheckXml::ImportProjectElementName) == 0) {
const std::string t_str = empty_if_null(node->GetText());
if (!t_str.empty())
guiProject.projectFile = path + t_str;
}
else if (strcmp(name, CppcheckXml::PathsElementName) == 0)
paths = readXmlStringList(node, path, CppcheckXml::PathName, CppcheckXml::PathNameAttrib);
else if (strcmp(name, CppcheckXml::ExcludeElementName) == 0)
guiProject.excludedPaths = readXmlStringList(node, "", CppcheckXml::ExcludePathName, CppcheckXml::ExcludePathNameAttrib);
else if (strcmp(name, CppcheckXml::FunctionContracts) == 0)
;
else if (strcmp(name, CppcheckXml::VariableContractsElementName) == 0)
;
else if (strcmp(name, CppcheckXml::IgnoreElementName) == 0)
guiProject.excludedPaths = readXmlStringList(node, "", CppcheckXml::IgnorePathName, CppcheckXml::IgnorePathNameAttrib);
else if (strcmp(name, CppcheckXml::LibrariesElementName) == 0)
guiProject.libraries = readXmlStringList(node, "", CppcheckXml::LibraryElementName, nullptr);
else if (strcmp(name, CppcheckXml::SuppressionsElementName) == 0) {
for (const tinyxml2::XMLElement *child = node->FirstChildElement(); child; child = child->NextSiblingElement()) {
if (strcmp(child->Name(), CppcheckXml::SuppressionElementName) != 0)
continue;
SuppressionList::Suppression s;
s.errorId = empty_if_null(child->GetText());
s.fileName = empty_if_null(child->Attribute("fileName"));
if (!s.fileName.empty())
s.fileName = joinRelativePath(path, s.fileName);
s.lineNumber = child->IntAttribute("lineNumber", SuppressionList::Suppression::NO_LINE);
s.symbolName = empty_if_null(child->Attribute("symbolName"));
s.hash = strToInt<std::size_t>(default_if_null(child->Attribute("hash"), "0"));
suppressions.push_back(std::move(s));
}
} else if (strcmp(name, CppcheckXml::VSConfigurationElementName) == 0)
guiProject.checkVsConfigs = readXmlStringList(node, "", CppcheckXml::VSConfigurationName, nullptr);
else if (strcmp(name, CppcheckXml::PlatformElementName) == 0)
guiProject.platform = empty_if_null(node->GetText());
else if (strcmp(name, CppcheckXml::AnalyzeAllVsConfigsElementName) == 0)
guiProject.analyzeAllVsConfigs = empty_if_null(node->GetText());
else if (strcmp(name, CppcheckXml::Parser) == 0)
temp.clang = true;
else if (strcmp(name, CppcheckXml::AddonsElementName) == 0) {
const auto& addons = readXmlStringList(node, "", CppcheckXml::AddonElementName, nullptr);
temp.addons.insert(addons.cbegin(), addons.cend());
}
else if (strcmp(name, CppcheckXml::TagsElementName) == 0)
node->Attribute(CppcheckXml::TagElementName); // FIXME: Write some warning
else if (strcmp(name, CppcheckXml::ToolsElementName) == 0) {
const std::list<std::string> toolList = readXmlStringList(node, "", CppcheckXml::ToolElementName, nullptr);
for (const std::string &toolName : toolList) {
if (toolName == CppcheckXml::ClangTidy)
temp.clangTidy = true;
}
} else if (strcmp(name, CppcheckXml::CheckHeadersElementName) == 0)
temp.checkHeaders = (strcmp(default_if_null(node->GetText(), ""), "true") == 0);
else if (strcmp(name, CppcheckXml::CheckLevelReducedElementName) == 0)
temp.setCheckLevel(Settings::CheckLevel::reduced);
else if (strcmp(name, CppcheckXml::CheckLevelNormalElementName) == 0)
temp.setCheckLevel(Settings::CheckLevel::normal);
else if (strcmp(name, CppcheckXml::CheckLevelExhaustiveElementName) == 0)
temp.setCheckLevel(Settings::CheckLevel::exhaustive);
else if (strcmp(name, CppcheckXml::CheckUnusedTemplatesElementName) == 0)
temp.checkUnusedTemplates = (strcmp(default_if_null(node->GetText(), ""), "true") == 0);
else if (strcmp(name, CppcheckXml::InlineSuppression) == 0)
temp.inlineSuppressions = (strcmp(default_if_null(node->GetText(), ""), "true") == 0);
else if (strcmp(name, CppcheckXml::MaxCtuDepthElementName) == 0)
temp.maxCtuDepth = strToInt<int>(default_if_null(node->GetText(), "2")); // TODO: bail out when missing?
else if (strcmp(name, CppcheckXml::MaxTemplateRecursionElementName) == 0)
temp.maxTemplateRecursion = strToInt<int>(default_if_null(node->GetText(), "100")); // TODO: bail out when missing?
else if (strcmp(name, CppcheckXml::CheckUnknownFunctionReturn) == 0)
; // TODO
else if (strcmp(name, Settings::SafeChecks::XmlRootName) == 0) {
for (const tinyxml2::XMLElement *child = node->FirstChildElement(); child; child = child->NextSiblingElement()) {
const char* childname = child->Name();
if (strcmp(childname, Settings::SafeChecks::XmlClasses) == 0)
temp.safeChecks.classes = true;
else if (strcmp(childname, Settings::SafeChecks::XmlExternalFunctions) == 0)
temp.safeChecks.externalFunctions = true;
else if (strcmp(childname, Settings::SafeChecks::XmlInternalFunctions) == 0)
temp.safeChecks.internalFunctions = true;
else if (strcmp(childname, Settings::SafeChecks::XmlExternalVariables) == 0)
temp.safeChecks.externalVariables = true;
else {
printError("Unknown '" + std::string(Settings::SafeChecks::XmlRootName) + "' element '" + childname + "' in Cppcheck project file");
return false;
}
}
} else if (strcmp(name, CppcheckXml::TagWarningsElementName) == 0)
; // TODO
// Cppcheck Premium features
else if (strcmp(name, CppcheckXml::BughuntingElementName) == 0)
temp.premiumArgs += " --bughunting";
else if (strcmp(name, CppcheckXml::CertIntPrecisionElementName) == 0)
temp.premiumArgs += std::string(" --cert-c-int-precision=") + default_if_null(node->GetText(), "0");
else if (strcmp(name, CppcheckXml::CodingStandardsElementName) == 0) {
for (const tinyxml2::XMLElement *child = node->FirstChildElement(); child; child = child->NextSiblingElement()) {
if (strcmp(child->Name(), CppcheckXml::CodingStandardElementName) == 0) {
const char* text = child->GetText();
if (text)
temp.premiumArgs += std::string(" --") + text;
}
}
}
else if (strcmp(name, CppcheckXml::ProjectNameElementName) == 0)
; // no-op
else {
printError("Unknown element '" + std::string(name) + "' in Cppcheck project file");
return false;
}
}
settings.basePaths = temp.basePaths;
settings.relativePaths |= temp.relativePaths;
settings.buildDir = temp.buildDir;
settings.includePaths = temp.includePaths;
settings.userDefines = temp.userDefines;
settings.userUndefs = temp.userUndefs;
settings.addons = temp.addons;
settings.clang = temp.clang;
settings.clangTidy = temp.clangTidy;
if (!settings.premiumArgs.empty())
settings.premiumArgs += temp.premiumArgs;
else if (!temp.premiumArgs.empty())
settings.premiumArgs = temp.premiumArgs.substr(1);
for (const std::string &p : paths)
guiProject.pathNames.push_back(Path::fromNativeSeparators(p));
supprs.nomsg.addSuppressions(std::move(suppressions)); // TODO: check result
settings.checkHeaders = temp.checkHeaders;
settings.checkUnusedTemplates = temp.checkUnusedTemplates;
settings.maxCtuDepth = temp.maxCtuDepth;
settings.maxTemplateRecursion = temp.maxTemplateRecursion;
settings.inlineSuppressions |= temp.inlineSuppressions;
settings.safeChecks = temp.safeChecks;
settings.setCheckLevel(temp.checkLevel);
return true;
}
void ImportProject::selectOneVsConfig(Platform::Type platform)
{
std::set<std::string> filenames;
for (auto it = fileSettings.cbegin(); it != fileSettings.cend();) {
if (it->cfg.empty()) {
++it;
continue;
}
const FileSettings &fs = *it;
bool remove = false;
if (!startsWith(fs.cfg,"Debug"))
remove = true;
if (platform == Platform::Type::Win64 && fs.platformType != platform)
remove = true;
else if ((platform == Platform::Type::Win32A || platform == Platform::Type::Win32W) && fs.platformType == Platform::Type::Win64)
remove = true;
else if (filenames.find(fs.filename()) != filenames.end())
remove = true;
if (remove) {
it = fileSettings.erase(it);
} else {
filenames.insert(fs.filename());
++it;
}
}
}
// cppcheck-suppress unusedFunction - used by GUI only
void ImportProject::selectVsConfigurations(Platform::Type platform, const std::vector<std::string> &configurations)
{
for (auto it = fileSettings.cbegin(); it != fileSettings.cend();) {
if (it->cfg.empty()) {
++it;
continue;
}
const FileSettings &fs = *it;
const auto config = fs.cfg.substr(0, fs.cfg.find('|'));
bool remove = false;
if (std::find(configurations.begin(), configurations.end(), config) == configurations.end())
remove = true;
if (platform == Platform::Type::Win64 && fs.platformType != platform)
remove = true;
else if ((platform == Platform::Type::Win32A || platform == Platform::Type::Win32W) && fs.platformType == Platform::Type::Win64)
remove = true;
if (remove) {
it = fileSettings.erase(it);
} else {
++it;
}
}
}
// cppcheck-suppress unusedFunction - used by GUI only
std::list<std::string> ImportProject::getVSConfigs()
{
return std::list<std::string>(mAllVSConfigs.cbegin(), mAllVSConfigs.cend());
}
void ImportProject::setRelativePaths(const std::string &filename)
{
if (Path::isAbsolute(filename))
return;
const std::vector<std::string> basePaths{Path::fromNativeSeparators(Path::getCurrentPath())};
for (auto &fs: fileSettings) {
fs.file = FileWithDetails{Path::getRelativePath(fs.filename(), basePaths)};
for (auto &includePath: fs.includePaths)
includePath = Path::getRelativePath(includePath, basePaths);
}
}
void ImportProject::printError(const std::string &message)
{
std::cout << "cppcheck: error: " << message << std::endl;
}
bool ImportProject::sourceFileExists(const std::string &file)
{
return Path::isFile(file);
}
|