Repository navigation
Expand file tree
/
Copy pathimportproject.cpp
More file actions
5970 lines (5371 loc) · 270 KB
/
Copy pathimportproject.cpp
File metadata and controls
5970 lines (5371 loc) · 270 KB
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
/*
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2026 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 "pathmatch.h"
#include "settings.h"
#include "standards.h"
#include "suppressions.h"
#include "utils.h"
#include <algorithm>
#include <cctype>
#include <climits>
#include <cmath>
#include <cstdlib>
#include <cstring>
#include <fstream>
#include <initializer_list>
#include <iostream>
#include <iterator>
#include <map>
#include <set>
#include <sstream>
#include <stdexcept>
#include <string>
#include <unordered_set>
#include <utility>
#include <vector>
// Directory listing for wildcard <Import> support -- see listDirectoryFiles()
// just above processImport().
#ifndef _WIN32
#include <dirent.h>
#else
#ifndef NOMINMAX
#define NOMINMAX
#endif
#ifndef WIN32_LEAN_AND_MEAN
#define WIN32_LEAN_AND_MEAN
#endif
#include <windows.h>
#endif
#include "xml.h"
#include "json.h"
std::string ImportProject::collectArgs(const std::string &cmd, std::vector<std::string> &args)
{
args.clear();
std::string::size_type pos = 0;
const std::string::size_type end = cmd.size();
std::string arg;
bool inDoubleQuotes = false;
bool inSingleQuotes = false;
while (pos < end) {
char c = cmd[pos++];
if (c == ' ') {
if (inDoubleQuotes || inSingleQuotes) {
arg.push_back(c);
continue;
}
if (!arg.empty())
args.push_back(arg);
arg.clear();
pos = cmd.find_first_not_of(' ', pos);
continue;
}
if (c == '\"' && !inSingleQuotes) {
inDoubleQuotes = !inDoubleQuotes;
continue;
}
if (c == '\'' && !inDoubleQuotes) {
inSingleQuotes = !inSingleQuotes;
continue;
}
if (c == '\\' && !inSingleQuotes) {
if (pos == end) {
arg.push_back('\\');
break;
}
c = cmd[pos++];
if (!std::strchr("\\\"\' ", c))
arg.push_back('\\');
arg.push_back(c);
continue;
}
arg.push_back(c);
}
if (inSingleQuotes || inDoubleQuotes)
return "Missing closing quote in command string";
if (!arg.empty())
args.push_back(std::move(arg));
return "";
}
void ImportProject::parseArgs(FileSettings &fs, const std::vector<std::string> &args)
{
// Accept index by value, return a completion state pair to prevent loop corruption
const auto getOptArg = [&args](std::initializer_list<std::string> optNames,
std::size_t i) -> std::pair<std::string, bool> {
const auto &arg = args[i];
const auto *const it = std::find_if(optNames.begin(),
optNames.end(),
[&arg](const std::string &optName) {
return startsWith(arg, optName);
});
if (it == optNames.end())
return std::make_pair(std::string(), false);
const std::size_t optLen = it->size();
if (arg.size() == optLen) {
// Space-separated argument format (e.g., /I path)
if (i + 1 >= args.size())
return std::make_pair(std::string(), false);
return std::make_pair(args[i + 1], true); // true flags lookahead consumption
}
// Glued argument format (e.g., /Ipath)
return std::make_pair(arg.substr(optLen), false);
};
std::string defs;
for (std::size_t i = 0; i < args.size(); i++) {
if (args[i].empty())
continue;
std::pair<std::string, bool> optResult;
if (!(optResult = getOptArg({ "-I", "/I" }, i)).first.empty()) {
if (std::none_of(fs.includePaths.cbegin(), fs.includePaths.cend(),
[&](const std::string &path) {
return path == optResult.first;
})) {
fs.includePaths.push_back(std::move(optResult.first));
}
if (optResult.second)
i++; // Safely advance only if the separate lookahead was consumed
continue;
}
if (!(optResult = getOptArg({ "-isystem" }, i)).first.empty()) {
fs.systemIncludePaths.push_back(std::move(optResult.first));
if (optResult.second)
i++;
continue;
}
if (!(optResult = getOptArg({ "-include", "/FI", "-FI" }, i)).first.empty()) {
fs.forcedIncludes.push_back(std::move(optResult.first));
if (optResult.second)
i++;
continue;
}
if (!(optResult = getOptArg({ "-D", "/D" }, i)).first.empty()) {
defs += optResult.first + ";";
if (optResult.second)
i++;
continue;
}
if (!(optResult = getOptArg({ "-U", "/U" }, i)).first.empty()) {
fs.undefs.insert(std::move(optResult.first));
if (optResult.second)
i++;
continue;
}
if (!(optResult = getOptArg({ "-std=", "/std:" }, i)).first.empty()) {
fs.standard = std::move(optResult.first);
if (optResult.second)
i++;
continue;
}
if (!(optResult = getOptArg({ "-f" }, i)).first.empty()) {
if (optResult.first == "pic")
defs += "__pic__;";
else if (optResult.first == "PIC")
defs += "__PIC__;";
else if (optResult.first == "pie")
defs += "__pie__;";
else if (optResult.first == "PIE")
defs += "__PIE__;";
if (optResult.second)
i++;
continue;
}
if (!(optResult = getOptArg({ "-m" }, i)).first.empty()) {
if (optResult.first == "unicode")
defs += "UNICODE;";
if (optResult.second)
i++;
continue;
}
}
fsSetDefines(fs, std::move(defs));
}
std::vector<std::string> ImportProject::ignorePaths(const std::vector<std::string> &ipaths, bool debug)
{
PathMatch matcher(ipaths, Path::getCurrentPath());
for (auto it = fileSettings.cbegin(); it != fileSettings.cend();) {
if (matcher.match(it->filename())) {
if (debug)
std::cout << "ignored path: " << it->filename() << std::endl;
it = fileSettings.erase(it);
}
else
++it;
}
return matcher.unmatched();
}
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;
}
}
// Decode %XX sequences back to their original characters.
static std::string msbuildUnescape(const std::string &s)
{
std::string result;
result.reserve(s.size());
for (std::size_t i = 0; i < s.size(); ++i) {
if (s[i] == '%' && i + 2 < s.size() &&
std::isxdigit(static_cast<unsigned char>(s[i + 1])) &&
std::isxdigit(static_cast<unsigned char>(s[i + 2]))) {
result += static_cast<char>(std::stoi(s.substr(i + 1, 2), nullptr, 16));
i += 2;
} else {
result += s[i];
}
}
return result;
}
void ImportProject::fsSetDefines(FileSettings& fs, std::string defs)
{
// Strip %(metadata) tokens at the start of the string (no preceding semicolon).
while (startsWith(defs, "%(")) {
const std::string::size_type pos2 = defs.find(';');
defs.erase(0, pos2 == std::string::npos ? std::string::npos : pos2 + 1);
}
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.pop_back();
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";
defs = msbuildUnescape(defs);
fs.defines.swap(defs);
}
void ImportProject::addDebug(const std::string &msg) {
for (const auto &debug : debugs) {
// cppcheck-suppress useStlAlgorithm
if (debug == msg)
return;
}
debugs.emplace_back(msg);
}
// Find the ')' that matches the '(' at position parenPos.
// Tracks depth for every '(' and ')', not just '$(' pairs: bare parentheses
// inside static-function argument lists (e.g. Pow(2,3), Format(...)) must
// also open and close a nesting level, otherwise the inner ')' would be
// mistaken for the match of the outer one.
static std::string::size_type findMatchingParen(const std::string &s, std::string::size_type parenPos) {
if (parenPos >= s.size() || s[parenPos] != '(')
return std::string::npos;
int depth = 0;
char quote = '\0';
for (std::string::size_type i = parenPos; i < s.size(); ++i) {
const char c = s[i];
if (quote != '\0') {
if (c == quote) {
// A doubled quote represents a literal quote.
if (i + 1 < s.size() && s[i + 1] == quote) {
++i;
continue;
}
quote = '\0';
}
continue;
}
if (c == '\'' || c == '"') {
quote = c;
} else if (c == '(') {
++depth;
} else if (c == ')') {
--depth;
if (depth == 0)
return i;
}
}
return std::string::npos;
}
// Apply an MSBuild property string method (ToLower, Replace, etc.).
// Used by both the condition evaluator and the property value expander.
static std::string applyPropertyMethod(std::string value,
const std::string &method,
const std::vector<std::string> &args) {
if (caseInsensitiveStringCompare(method, "ToUpper") == 0) {
if (!args.empty())
throw std::runtime_error("ToUpper takes no arguments");
std::transform(value.cbegin(), value.cend(), value.begin(), static_cast<int (*)(int)>(std::toupper));
return value;
}
if (caseInsensitiveStringCompare(method, "ToLower") == 0) {
if (!args.empty())
throw std::runtime_error("ToLower takes no arguments");
std::transform(value.cbegin(), value.cend(), value.begin(), static_cast<int (*)(int)>(std::tolower));
return value;
}
if (caseInsensitiveStringCompare(method, "Contains") == 0) {
if (args.size() != 1)
throw std::runtime_error("Contains requires one argument");
// .NET String.Contains is case-sensitive by default
return value.find(args[0]) != std::string::npos ? "True" : "False";
}
if (caseInsensitiveStringCompare(method, "StartsWith") == 0) {
if (args.size() != 1)
throw std::runtime_error("StartsWith requires one argument");
// .NET String.StartsWith is case-sensitive by default
if (args[0].size() > value.size())
return "False";
return value.compare(0, args[0].size(), args[0]) == 0 ? "True" : "False";
}
if (caseInsensitiveStringCompare(method, "EndsWith") == 0) {
if (args.size() != 1)
throw std::runtime_error("EndsWith requires one argument");
// .NET String.EndsWith is case-sensitive by default
if (args[0].size() > value.size())
return "False";
return value.compare(value.size() - args[0].size(), args[0].size(), args[0]) == 0 ? "True" : "False";
}
if (caseInsensitiveStringCompare(method, "Trim") == 0) {
if (args.empty()) {
const std::size_t first = value.find_first_not_of(" \t\r\n");
if (first == std::string::npos)
return "";
const std::size_t last = value.find_last_not_of(" \t\r\n");
return value.substr(first, last - first + 1);
}
std::string chars;
for (const std::string &arg : args)
chars += arg;
const std::size_t first = value.find_first_not_of(chars);
if (first == std::string::npos)
return "";
const std::size_t last = value.find_last_not_of(chars);
return value.substr(first, last - first + 1);
}
if (caseInsensitiveStringCompare(method, "TrimStart") == 0) {
if (args.empty()) {
const std::size_t first = value.find_first_not_of(" \t\r\n");
return first == std::string::npos ? "" : value.substr(first);
}
std::string chars;
for (const std::string &arg : args)
chars += arg;
const std::size_t first = value.find_first_not_of(chars);
return first == std::string::npos ? "" : value.substr(first);
}
if (caseInsensitiveStringCompare(method, "TrimEnd") == 0) {
if (args.empty()) {
const std::size_t last = value.find_last_not_of(" \t\r\n");
return last == std::string::npos ? "" : value.substr(0, last + 1);
}
std::string chars;
for (const std::string &arg : args)
chars += arg;
const std::size_t last = value.find_last_not_of(chars);
return last == std::string::npos ? "" : value.substr(0, last + 1);
}
if (caseInsensitiveStringCompare(method, "Substring") == 0) {
if (args.size() != 1 && args.size() != 2)
throw std::runtime_error("Substring requires one or two arguments");
char *end = nullptr;
const long start = std::strtol(args[0].c_str(), &end, 10);
if (end == args[0].c_str() || *end != '\0')
throw std::runtime_error("Invalid Substring start index");
if (start < 0 || static_cast<unsigned long>(start) > value.size())
throw std::runtime_error("Substring start index out of range");
const auto index = static_cast<std::size_t>(start);
if (args.size() == 1)
return value.substr(index);
end = nullptr;
const long length = std::strtol(args[1].c_str(), &end, 10);
if (end == args[1].c_str() || *end != '\0')
throw std::runtime_error("Invalid Substring length");
if (length < 0 || static_cast<unsigned long>(length) > value.size() - index)
throw std::runtime_error("Substring length out of range");
return value.substr(index, static_cast<std::size_t>(length));
}
if (caseInsensitiveStringCompare(method, "Replace") == 0) {
if (args.size() != 2)
throw std::runtime_error("Replace requires two arguments");
if (args[0].empty())
throw std::runtime_error("Replace search string cannot be empty");
std::size_t pos = 0;
while ((pos = value.find(args[0], pos)) != std::string::npos) {
value.replace(pos, args[0].size(), args[1]);
pos += args[1].size();
}
return value;
}
if (caseInsensitiveStringCompare(method, "IndexOf") == 0) {
if (args.empty() || args.size() > 2)
throw std::runtime_error("IndexOf requires one or two arguments");
std::size_t from = 0;
if (args.size() == 2) {
char *end = nullptr;
const long idx = std::strtol(args[1].c_str(), &end, 10);
if (end == args[1].c_str() || *end != '\0')
throw std::runtime_error("Invalid IndexOf start index");
if (idx < 0 || static_cast<unsigned long>(idx) > value.size())
throw std::runtime_error("IndexOf start index out of range");
from = static_cast<std::size_t>(idx);
}
const std::size_t found = value.find(args[0], from);
return std::to_string(found == std::string::npos ? -1L : static_cast<long>(found));
}
if (caseInsensitiveStringCompare(method, "LastIndexOf") == 0) {
if (args.empty() || args.size() > 2)
throw std::runtime_error("LastIndexOf requires one or two arguments");
std::size_t from = std::string::npos;
if (args.size() == 2) {
char *end = nullptr;
const long idx = std::strtol(args[1].c_str(), &end, 10);
if (end == args[1].c_str() || *end != '\0')
throw std::runtime_error("Invalid LastIndexOf start index");
if (idx < 0 || static_cast<unsigned long>(idx) > value.size())
throw std::runtime_error("LastIndexOf start index out of range");
from = static_cast<std::size_t>(idx);
}
const std::size_t found = value.rfind(args[0], from);
return std::to_string(found == std::string::npos ? -1L : static_cast<long>(found));
}
const bool isPadLeft = caseInsensitiveStringCompare(method, "PadLeft") == 0;
if (isPadLeft || caseInsensitiveStringCompare(method, "PadRight") == 0) {
if (args.empty() || args.size() > 2)
throw std::runtime_error(method + " requires one or two arguments");
char *end = nullptr;
const long totalWidth = std::strtol(args[0].c_str(), &end, 10);
if (end == args[0].c_str() || *end != '\0' || totalWidth < 0)
throw std::runtime_error(method + " totalWidth must be a non-negative integer");
const char padChar = (args.size() == 2 && !args[1].empty()) ? args[1][0] : ' ';
const auto width = static_cast<std::size_t>(totalWidth);
if (value.size() >= width)
return value;
const std::string padding(width - value.size(), padChar);
return isPadLeft ? padding + value : value + padding;
}
throw std::runtime_error("Unhandled method '" + method + "'");
}
static std::string findFileAbove(const std::string &startDirectory, const std::string &file)
{
// startDirectory comes from MSBuildThisFileDirectory which is already
// normalized to '/' separators by Path::simplifyPath.
std::string currentDir = startDirectory;
if (currentDir.size() > 1 && currentDir.back() == '/' && currentDir[currentDir.size() - 2] != ':')
currentDir.pop_back();
while (!currentDir.empty()) {
std::string targetFile = Path::join(currentDir, file);
if (Path::isFile(targetFile))
return targetFile;
if (currentDir.back() == '/' || (currentDir.back() == ':' && currentDir.size() == 2))
break;
const std::size_t lastSlash = currentDir.rfind('/');
if (lastSlash == std::string::npos)
break;
currentDir.resize(lastSlash);
}
return "";
}
/// Five-way Windows/Unix path classification used by pathCombineAppend and isPathRooted.
enum class PathKind : std::uint8_t {
Empty, ///< ""
UNC, ///< \\server\share or //server/share
DriveAbsolute, ///< C:\foo or C:/foo
RootRelative, ///< \foo or /foo (no drive letter)
DriveRelative, ///< C:foo (drive letter, no separator)
Relative, ///< foo (everything else)
};
static PathKind classifyPath(const std::string &path)
{
if (path.empty())
return PathKind::Empty;
// UNC: two leading separators.
if ((path[0] == '/' || path[0] == '\\') &&
path.size() >= 2 && (path[1] == '/' || path[1] == '\\'))
return PathKind::UNC;
// Windows drive letter.
if (path.size() >= 2 &&
std::isalpha(static_cast<unsigned char>(path[0])) &&
path[1] == ':') {
if (path.size() >= 3 && (path[2] == '/' || path[2] == '\\'))
return PathKind::DriveAbsolute;
return PathKind::DriveRelative;
}
// Single leading separator.
if (path[0] == '/' || path[0] == '\\')
return PathKind::RootRelative;
return PathKind::Relative;
}
static bool isRelative(const std::string &path) {
return classifyPath(path) >= PathKind::DriveRelative;
}
// Append one path segment to `result` using Windows path-combination semantics.
// classifyPath() is the sole authority for path kind; Path::isAbsolute() is
// intentionally NOT used here because it is host-dependent and would misclassify
// root-relative Windows paths (\foo -> /foo after fromNativeSeparators) as
// fully-absolute on Linux.
//
// Returns true if the segment was fully resolved, false if it could not be
// resolved correctly and `result` was left unchanged. Callers must emit a
// diagnostic on false; they must NOT silently continue with a wrong path.
//
// Two modes, selected by `checkIsAbsolute`:
//
// false -- MSBuild property-evaluation combine (e.g. $(A)\$(B)):
// UNC / DriveAbsolute -> full reset, returns true
// RootRelative \foo -> reset path, inherit drive: "C:" + "\foo" = "C:/foo", returns true
// DriveRelative C:foo -> UNSUPPORTED: resolving "C:foo" requires the per-drive CWD
// for drive C:, which is a Windows kernel concept unavailable
// here. Leaves result unchanged and returns false.
// Relative / Empty -> plain join, returns true
//
// true -- System.IO.Path.Combine semantics:
// UNC / DriveAbsolute -> full reset, returns true
// RootRelative \foo -> full reset (Path.IsPathRooted = true; drive NOT inherited,
// matching .NET Path.Combine behaviour), returns true
// DriveRelative C:foo -> full reset (Path.IsPathRooted = true for "C:foo"), returns true
// Relative / Empty -> plain join, returns true
static bool pathCombineAppend(std::string &result, const std::string &seg, bool checkIsAbsolute = false) {
if (seg.empty())
return true;
switch (classifyPath(seg)) {
case PathKind::UNC:
case PathKind::DriveAbsolute:
// Full reset in both modes.
result = seg;
return true;
case PathKind::RootRelative:
if (checkIsAbsolute) {
// System.IO.Path.Combine: root-relative is rooted; discard accumulated
// base (including any drive letter) and return the segment as-is.
result = seg;
} else {
// MSBuild property eval: reset the path component but preserve the
// accumulated drive letter so "\foo" on "C:/project/" -> "C:/foo".
if (result.size() >= 2 && std::isalpha(static_cast<unsigned char>(result[0])) && result[1] == ':')
result.replace(0, 2, seg);
else
result = seg;
}
return true;
case PathKind::DriveRelative:
if (checkIsAbsolute) {
// System.IO.Path.Combine: drive-relative is rooted (Path.IsPathRooted
// returns true for "C:foo"); discard the accumulated base.
result = seg;
return true;
}
// MSBuild property eval: "C:foo" means foo relative to the current directory
// of drive C:, a per-drive CWD that is a Windows kernel concept. We have no
// way to resolve this correctly in a cross-platform context. Leave result
// unchanged and signal the caller to emit a diagnostic.
return false;
case PathKind::Relative:
case PathKind::Empty:
if (!result.empty() && result.back() != '/' && result.back() != '\\')
result += '/';
result += seg;
return true;
}
return true; // unreachable; silences -Wreturn-type
}
// MSBuild special characters that must be percent-encoded in property values.
static const char MSBUILD_SPECIAL_CHARS[] = "%$@';?*!";
// Encode every MSBuild special character in `s` as %XX.
static std::string msbuildEscape(const std::string &s)
{
static const char hex[] = "0123456789ABCDEF";
std::string result;
result.reserve(s.size());
for (const unsigned char c : s) {
if (std::strchr(MSBUILD_SPECIAL_CHARS, static_cast<char>(c))) {
result += '%';
result += hex[c >> 4];
result += hex[c & 0xF];
} else {
result += static_cast<char>(c);
}
}
return result;
}
static std::string stripDirectoryPart(const std::string &filename) {
const auto slash = filename.rfind('/');
return (slash != std::string::npos) ? filename.substr(slash + 1) : filename;
}
/// Return the stem of \p filename (basename with its final extension removed).
/// Strips only the tail extension so "foo.targets.props" -> "foo.targets", not "foo".
static std::string fileStem(const std::string &filename) {
const std::string ext = Path::getFilenameExtension(filename);
if (ext.empty() || filename.size() <= ext.size())
return filename;
return filename.substr(0, filename.size() - ext.size());
}
static bool isPathRooted(const std::string &filename) {
switch (classifyPath(filename)) {
case PathKind::UNC:
case PathKind::DriveAbsolute:
case PathKind::RootRelative:
case PathKind::DriveRelative: // "C:foo" -- Path.IsPathRooted returns true on Windows
return true;
default:
return false;
}
}
static std::string getRelativePath(const std::string &absolutePath, const std::vector<std::string> &basePaths) {
const std::string normAbs = Path::fromNativeSeparators(absolutePath);
// Split a forward-slash path into components where the first element is
// the root token -- keeping roots distinct prevents the common-prefix
// algorithm from emitting relative paths that cross root boundaries.
//
// UNC absolute //server/share/a -> ["//server/share", "a"]
// Drive absolute C:/foo/a -> ["C:", "foo", "a"]
// Root relative /foo/a -> ["/", "foo", "a"]
// Relative foo/a -> ["foo", "a"] (no root token)
//
// Cross-root pairs (different drive letters, or UNC paths whose server OR
// share differs) will get common == 0 and be rejected before any ".." are
// emitted, which is correct: no well-formed relative path can cross roots.
const auto split = [](const std::string &s) {
std::vector<std::string> parts;
std::size_t pos = 0;
if (s.size() >= 2 && s[0] == '/' && s[1] == '/') {
// UNC path: root is the "//server/share" unit.
const std::size_t serverEnd = s.find('/', 2);
if (serverEnd == std::string::npos) {
// Degenerate "//server" with no share -- treat whole string as root.
parts.push_back(s);
return parts;
}
const std::size_t shareEnd = s.find('/', serverEnd + 1);
if (shareEnd == std::string::npos) {
// "//server/share" with no trailing path.
parts.push_back(s);
return parts;
}
parts.push_back(s.substr(0, shareEnd)); // "//server/share"
pos = shareEnd + 1;
} else if (s.size() >= 2 && std::isalpha(static_cast<unsigned char>(s[0])) && s[1] == ':') {
// Drive-letter path: root is the two-character drive token "C:".
parts.push_back(s.substr(0, 2));
pos = 2;
if (pos < s.size() && s[pos] == '/')
++pos;
} else if (!s.empty() && s[0] == '/') {
// Root-relative path: root is "/".
parts.emplace_back("/");
pos = 1;
}
// else: relative path -- no root token is prepended.
while (pos < s.size()) {
const std::size_t slash = s.find('/', pos);
std::string seg = s.substr(pos, slash == std::string::npos ? std::string::npos : slash - pos);
if (!seg.empty())
parts.push_back(std::move(seg));
if (slash == std::string::npos)
break;
pos = slash + 1;
}
return parts;
};
for (const std::string &bp : basePaths) {
if (absolutePath == bp || bp.empty()) // Seems to be a file, or path is empty
continue;
const std::string normBase = Path::fromNativeSeparators(bp);
// Fast path: absolutePath is directly under basePath -- strip the prefix.
if (normAbs.compare(0, normBase.length(), normBase) == 0) {
if (endsWith(normBase, '/'))
return normAbs.substr(normBase.length());
if (normAbs.size() > normBase.size() && normAbs[normBase.size()] == '/')
return normAbs.substr(normBase.size() + 1);
}
// Slow path: build a relative path using ".." when absolutePath is above
// or beside basePath but shares a common ancestor.
std::string base = normBase;
if (!base.empty() && base.back() != '/')
base += '/';
const std::vector<std::string> absParts = split(normAbs);
const std::vector<std::string> baseParts_ = split(base);
// Find the length of the common component prefix.
std::size_t common = 0;
while (common < absParts.size() && common < baseParts_.size() &&
Path::sameFileName(absParts[common], baseParts_[common]))
++common;
if (common == 0)
continue; // truly different roots -- skip this basePath
// One ".." for every extra component in base beyond the common prefix,
// then the remaining components of absolutePath.
std::string rel;
for (std::size_t i = common; i < baseParts_.size(); ++i) {
if (!rel.empty())
rel += '/';
rel += "..";
}
for (std::size_t i = common; i < absParts.size(); ++i) {
if (!rel.empty())
rel += '/';
rel += absParts[i];
}
if (!rel.empty())
return rel;
}
// No base path shares a root with absolutePath. Return the normalized form
// so the caller always gets forward slashes, consistent with every other
// path in the property map.
return normAbs;
}
#if defined(__clang__)
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wmissing-format-attribute"
#pragma clang diagnostic ignored "-Wformat-nonliteral"
#endif
template<typename ... Args>
static std::string safeFormat(const char *fmt, Args... args) {
const int needed = std::snprintf(nullptr, 0, fmt, args ...);
if (needed < 0)
return std::string();
std::vector<char> buf(static_cast<std::size_t>(needed) + 1);
std::snprintf(buf.data(), buf.size(), fmt, args ...);
return std::string(buf.data());
}
#if defined(__clang__)
#pragma clang diagnostic pop
#endif
// MSBuild evaluates the [MSBuild]::Add/Subtract/Multiply intrinsics in .NET's
// default unchecked context, so on overflow the result wraps (two's complement).
// Do the arithmetic on unsigned operands to get the same result without
// signed-overflow UB.
static long long wrapAdd(long long a, long long b) {
return static_cast<long long>(static_cast<unsigned long long>(a) + static_cast<unsigned long long>(b));
}
static long long wrapSub(long long a, long long b) {
return static_cast<long long>(static_cast<unsigned long long>(a) - static_cast<unsigned long long>(b));
}
static long long wrapMul(long long a, long long b) {
return static_cast<long long>(static_cast<unsigned long long>(a) * static_cast<unsigned long long>(b));
}
// Evaluate a $([ClassName]::Method(args)) static property function.
// Returns an empty string for unknown or unimplementable functions rather
// than throwing, so import can continue gracefully.
std::string ImportProject::applyMSBuildStaticFunction(const std::string &className,
const std::string &member,
const std::vector<std::string> &args,
const PropertiesMap *properties) {
const auto toInt = [](const std::string &s, long long &out) -> bool {
if (s.empty())
return false;
try {
size_t idx = 0;
out = std::stoll(s, &idx);
return idx == s.length();
}
catch (...) {
return false;
}
};
if (caseInsensitiveStringCompare(className, "MSBuild") == 0) {
// $([MSBuild]::IsOSPlatform('Windows'|'Linux'|'OSX'))
if (caseInsensitiveStringCompare(member, "IsOSPlatform") == 0 && args.size() == 1) {
#if defined(_WIN32)
const bool onWindows = true, onLinux = false, onOSX = false;
#elif defined(__APPLE__)
const bool onWindows = false, onLinux = false, onOSX = true;
#else
const bool onWindows = false, onLinux = true, onOSX = false;
#endif
if (caseInsensitiveStringCompare(args[0], "Windows") == 0)
return onWindows ? "True" : "False";
if (caseInsensitiveStringCompare(args[0], "Linux") == 0)
return onLinux ? "True" : "False";
if (caseInsensitiveStringCompare(args[0], "OSX") == 0 ||
caseInsensitiveStringCompare(args[0], "MacOS") == 0)
return onOSX ? "True" : "False";
return "False";
}
// Arithmetic: Add, Subtract, Multiply, Divide, Modulo
if (args.size() == 2) {
long long a = 0, b = 0;
if (toInt(args[0], a) && toInt(args[1], b)) {
if (caseInsensitiveStringCompare(member, "Add") == 0)
return std::to_string(wrapAdd(a, b));
if (caseInsensitiveStringCompare(member, "Subtract") == 0)
return std::to_string(wrapSub(a, b));
if (caseInsensitiveStringCompare(member, "Multiply") == 0)
return std::to_string(wrapMul(a, b));
if (caseInsensitiveStringCompare(member, "Divide") == 0) {
if (b == 0) {
addDebug("MSBuild::Divide: division by zero");
return std::string();
}
if (a == LLONG_MIN && b == -1) {
addDebug("MSBuild::Divide: integer overflow");
return std::string();
}
return std::to_string(a / b);
}
if (caseInsensitiveStringCompare(member, "Modulo") == 0) {
if (b == 0) {
addDebug("MSBuild::Modulo: division by zero");
return std::string();
}
if (a == LLONG_MIN && b == -1) {
addDebug("MSBuild::Modulo: integer overflow");
return std::string();
}
return std::to_string(a % b);
}
}
// $([MSBuild]::ValueOrDefault(value, default))
if (caseInsensitiveStringCompare(member, "ValueOrDefault") == 0)
return args[0].empty() ? args[1] : args[0];
// $([MSBuild]::MakeRelative(basePath, path))
// Returns path expressed relative to basePath. If the two paths
// share no common root (e.g. different drive letters) path is
// returned unchanged.
if (caseInsensitiveStringCompare(member, "MakeRelative") == 0)
return getRelativePath(args[1], {args[0]});
// $([MSBuild]::GetDirectoryNameOfFileAbove(startingDirectory, fileName))
// Walks up from startingDirectory looking for fileName; returns the
// containing directory (no trailing separator) or "" if not found.
if (caseInsensitiveStringCompare(member, "GetDirectoryNameOfFileAbove") == 0) {
const std::string found = findFileAbove(args[0], args[1]);
if (found.empty())
return "";
std::string dir = Path::getPathFromFilename(found);
if (!dir.empty() && (dir.back() == '/' || dir.back() == '\\'))
dir.pop_back();
return dir;
}
// $([MSBuild]::GetPathOfFileAbove(file, startingDirectory))
// Walks up from startingDirectory looking for file; returns the full
// path of the file or "" if not found.
if (caseInsensitiveStringCompare(member, "GetPathOfFileAbove") == 0)
return findFileAbove(args[1], args[0]);
}
// $([MSBuild]::GetPathOfFileAbove(file)) -- 1-arg form. MSBuild uses the
// directory of the file being evaluated (MSBuildThisFileDirectory) as the
// start directory. We read it from the supplied properties map when available;
// if absent (properties is null or the key is missing) findFile receives an
// empty start directory and returns "" without crashing.
if (caseInsensitiveStringCompare(member, "GetPathOfFileAbove") == 0 && args.size() == 1) {
std::string startDir;
if (properties) {
const auto it = properties->find("MSBuildThisFileDirectory");
if (it != properties->end())
startDir = it->second;
}
return findFileAbove(startDir, args[0]);
}
// $([MSBuild]::NormalizePath(seg1[, seg2, ...])) -- join segments, normalize
// \ to /, and resolve . and .. components. Internally MSBuild calls
// Path.GetFullPath(Path.Combine(paths)), so multi-segment joining follows
// System.IO.Path.Combine semantics: a rooted segment (UNC, DriveAbsolute,
// RootRelative, or DriveRelative) resets the accumulated path.
if (caseInsensitiveStringCompare(member, "NormalizePath") == 0) {
if (args.empty()) {
addDebug("NormalizePath: called with no arguments");
return "";
}
// If any arg still contains an unexpanded $(...) reference, the property was
// not defined at evaluation time. Log it and bail out rather than treating
// the raw reference text as a literal path component.
for (const std::string &a : args) {
// cppcheck-suppress useStlAlgorithm