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
|
/* Distributed under the OSI-approved BSD 3-Clause License. See accompanying
file Copyright.txt or https://cmake.org/licensing for details. */
#include "cmExportFileGenerator.h"
#include <array>
#include <cassert>
#include <cstring>
#include <sstream>
#include <utility>
#include <cm/memory>
#include <cmext/string_view>
#include "cmsys/FStream.hxx"
#include "cmComputeLinkInformation.h"
#include "cmFileSet.h"
#include "cmGeneratedFileStream.h"
#include "cmGeneratorTarget.h"
#include "cmLinkItem.h"
#include "cmList.h"
#include "cmLocalGenerator.h"
#include "cmMakefile.h"
#include "cmMessageType.h"
#include "cmOutputConverter.h"
#include "cmPolicies.h"
#include "cmPropertyMap.h"
#include "cmStateTypes.h"
#include "cmStringAlgorithms.h"
#include "cmSystemTools.h"
#include "cmTarget.h"
#include "cmValue.h"
static std::string cmExportFileGeneratorEscape(std::string const& str)
{
// Escape a property value for writing into a .cmake file.
std::string result = cmOutputConverter::EscapeForCMake(str);
// Un-escape variable references generated by our own export code.
cmSystemTools::ReplaceString(result, "\\${_IMPORT_PREFIX}",
"${_IMPORT_PREFIX}");
cmSystemTools::ReplaceString(result, "\\${CMAKE_IMPORT_LIBRARY_SUFFIX}",
"${CMAKE_IMPORT_LIBRARY_SUFFIX}");
return result;
}
cmExportFileGenerator::cmExportFileGenerator()
{
this->AppendMode = false;
this->ExportOld = false;
}
void cmExportFileGenerator::AddConfiguration(const std::string& config)
{
this->Configurations.push_back(config);
}
void cmExportFileGenerator::SetExportFile(const char* mainFile)
{
this->MainImportFile = mainFile;
this->FileDir = cmSystemTools::GetFilenamePath(this->MainImportFile);
this->FileBase =
cmSystemTools::GetFilenameWithoutLastExtension(this->MainImportFile);
this->FileExt =
cmSystemTools::GetFilenameLastExtension(this->MainImportFile);
}
const std::string& cmExportFileGenerator::GetMainExportFileName() const
{
return this->MainImportFile;
}
bool cmExportFileGenerator::GenerateImportFile()
{
// Open the output file to generate it.
std::unique_ptr<cmsys::ofstream> foutPtr;
if (this->AppendMode) {
// Open for append.
auto openmodeApp = std::ios::app;
foutPtr = cm::make_unique<cmsys::ofstream>(this->MainImportFile.c_str(),
openmodeApp);
} else {
// Generate atomically and with copy-if-different.
std::unique_ptr<cmGeneratedFileStream> ap(
new cmGeneratedFileStream(this->MainImportFile, true));
ap->SetCopyIfDifferent(true);
foutPtr = std::move(ap);
}
if (!foutPtr || !*foutPtr) {
std::string se = cmSystemTools::GetLastSystemError();
std::ostringstream e;
e << "cannot write to file \"" << this->MainImportFile << "\": " << se;
cmSystemTools::Error(e.str());
return false;
}
std::ostream& os = *foutPtr;
// Start with the import file header.
this->GeneratePolicyHeaderCode(os);
this->GenerateImportHeaderCode(os);
// Create all the imported targets.
bool result = this->GenerateMainFile(os);
// End with the import file footer.
this->GenerateImportFooterCode(os);
this->GeneratePolicyFooterCode(os);
return result;
}
void cmExportFileGenerator::GenerateImportConfig(std::ostream& os,
const std::string& config)
{
// Construct the property configuration suffix.
std::string suffix = "_";
if (!config.empty()) {
suffix += cmSystemTools::UpperCase(config);
} else {
suffix += "NOCONFIG";
}
// Generate the per-config target information.
this->GenerateImportTargetsConfig(os, config, suffix);
}
void cmExportFileGenerator::PopulateInterfaceProperty(
const std::string& propName, cmGeneratorTarget const* target,
ImportPropertyMap& properties)
{
cmValue input = target->GetProperty(propName);
if (input) {
properties[propName] = *input;
}
}
void cmExportFileGenerator::PopulateInterfaceProperty(
const std::string& propName, const std::string& outputName,
cmGeneratorTarget const* target,
cmGeneratorExpression::PreprocessContext preprocessRule,
ImportPropertyMap& properties)
{
cmValue input = target->GetProperty(propName);
if (input) {
if (input->empty()) {
// Set to empty
properties[outputName].clear();
return;
}
std::string prepro =
cmGeneratorExpression::Preprocess(*input, preprocessRule);
if (!prepro.empty()) {
this->ResolveTargetsInGeneratorExpressions(prepro, target);
properties[outputName] = prepro;
}
}
}
void cmExportFileGenerator::GenerateRequiredCMakeVersion(
std::ostream& os, const char* versionString)
{
/* clang-format off */
os << "if(CMAKE_VERSION VERSION_LESS " << versionString << ")\n"
" message(FATAL_ERROR \"This file relies on consumers using "
"CMake " << versionString << " or greater.\")\n"
"endif()\n\n";
/* clang-format on */
}
bool cmExportFileGenerator::PopulateInterfaceLinkLibrariesProperty(
cmGeneratorTarget const* target,
cmGeneratorExpression::PreprocessContext preprocessRule,
ImportPropertyMap& properties)
{
if (!target->IsLinkable()) {
return false;
}
static const std::array<std::string, 3> linkIfaceProps = {
{ "INTERFACE_LINK_LIBRARIES", "INTERFACE_LINK_LIBRARIES_DIRECT",
"INTERFACE_LINK_LIBRARIES_DIRECT_EXCLUDE" }
};
bool hadINTERFACE_LINK_LIBRARIES = false;
for (std::string const& linkIfaceProp : linkIfaceProps) {
if (cmValue input = target->GetProperty(linkIfaceProp)) {
std::string prepro =
cmGeneratorExpression::Preprocess(*input, preprocessRule);
if (!prepro.empty()) {
this->ResolveTargetsInGeneratorExpressions(prepro, target,
ReplaceFreeTargets);
properties[linkIfaceProp] = prepro;
hadINTERFACE_LINK_LIBRARIES = true;
}
}
}
return hadINTERFACE_LINK_LIBRARIES;
}
static bool isSubDirectory(std::string const& a, std::string const& b)
{
return (cmSystemTools::ComparePath(a, b) ||
cmSystemTools::IsSubDirectory(a, b));
}
static bool checkInterfaceDirs(const std::string& prepro,
cmGeneratorTarget const* target,
const std::string& prop)
{
std::string const& installDir =
target->Makefile->GetSafeDefinition("CMAKE_INSTALL_PREFIX");
std::string const& topSourceDir =
target->GetLocalGenerator()->GetSourceDirectory();
std::string const& topBinaryDir =
target->GetLocalGenerator()->GetBinaryDirectory();
std::vector<std::string> parts;
cmGeneratorExpression::Split(prepro, parts);
const bool inSourceBuild = topSourceDir == topBinaryDir;
bool hadFatalError = false;
for (std::string const& li : parts) {
size_t genexPos = cmGeneratorExpression::Find(li);
if (genexPos == 0) {
continue;
}
if (cmHasLiteralPrefix(li, "${_IMPORT_PREFIX}")) {
continue;
}
MessageType messageType = MessageType::FATAL_ERROR;
std::ostringstream e;
if (genexPos != std::string::npos) {
if (prop == "INTERFACE_INCLUDE_DIRECTORIES") {
switch (target->GetPolicyStatusCMP0041()) {
case cmPolicies::WARN:
messageType = MessageType::WARNING;
e << cmPolicies::GetPolicyWarning(cmPolicies::CMP0041) << "\n";
break;
case cmPolicies::OLD:
continue;
case cmPolicies::REQUIRED_IF_USED:
case cmPolicies::REQUIRED_ALWAYS:
case cmPolicies::NEW:
hadFatalError = true;
break; // Issue fatal message.
}
} else {
hadFatalError = true;
}
}
if (!cmSystemTools::FileIsFullPath(li)) {
/* clang-format off */
e << "Target \"" << target->GetName() << "\" " << prop <<
" property contains relative path:\n"
" \"" << li << "\"";
/* clang-format on */
target->GetLocalGenerator()->IssueMessage(messageType, e.str());
}
bool inBinary = isSubDirectory(li, topBinaryDir);
bool inSource = isSubDirectory(li, topSourceDir);
if (isSubDirectory(li, installDir)) {
// The include directory is inside the install tree. If the
// install tree is not inside the source tree or build tree then
// fall through to the checks below that the include directory is not
// also inside the source tree or build tree.
bool shouldContinue =
(!inBinary || isSubDirectory(installDir, topBinaryDir)) &&
(!inSource || isSubDirectory(installDir, topSourceDir));
if (prop == "INTERFACE_INCLUDE_DIRECTORIES") {
if (!shouldContinue) {
switch (target->GetPolicyStatusCMP0052()) {
case cmPolicies::WARN: {
std::ostringstream s;
s << cmPolicies::GetPolicyWarning(cmPolicies::CMP0052) << "\n";
s << "Directory:\n \"" << li
<< "\"\nin "
"INTERFACE_INCLUDE_DIRECTORIES of target \""
<< target->GetName()
<< "\" is a subdirectory of the install "
"directory:\n \""
<< installDir
<< "\"\nhowever it is also "
"a subdirectory of the "
<< (inBinary ? "build" : "source") << " tree:\n \""
<< (inBinary ? topBinaryDir : topSourceDir) << "\"\n";
target->GetLocalGenerator()->IssueMessage(
MessageType::AUTHOR_WARNING, s.str());
CM_FALLTHROUGH;
}
case cmPolicies::OLD:
shouldContinue = true;
break;
case cmPolicies::REQUIRED_ALWAYS:
case cmPolicies::REQUIRED_IF_USED:
case cmPolicies::NEW:
break;
}
}
}
if (shouldContinue) {
continue;
}
}
if (inBinary) {
/* clang-format off */
e << "Target \"" << target->GetName() << "\" " << prop <<
" property contains path:\n"
" \"" << li << "\"\nwhich is prefixed in the build directory.";
/* clang-format on */
target->GetLocalGenerator()->IssueMessage(messageType, e.str());
}
if (!inSourceBuild) {
if (inSource) {
e << "Target \"" << target->GetName() << "\" " << prop
<< " property contains path:\n"
" \""
<< li << "\"\nwhich is prefixed in the source directory.";
target->GetLocalGenerator()->IssueMessage(messageType, e.str());
}
}
}
return !hadFatalError;
}
static void prefixItems(std::string& exportDirs)
{
std::vector<std::string> entries;
cmGeneratorExpression::Split(exportDirs, entries);
exportDirs.clear();
const char* sep = "";
for (std::string const& e : entries) {
exportDirs += sep;
sep = ";";
if (!cmSystemTools::FileIsFullPath(e) &&
e.find("${_IMPORT_PREFIX}") == std::string::npos) {
exportDirs += "${_IMPORT_PREFIX}/";
}
exportDirs += e;
}
}
void cmExportFileGenerator::PopulateSourcesInterface(
cmGeneratorTarget const* gt,
cmGeneratorExpression::PreprocessContext preprocessRule,
ImportPropertyMap& properties)
{
assert(preprocessRule == cmGeneratorExpression::InstallInterface);
const char* propName = "INTERFACE_SOURCES";
cmValue input = gt->GetProperty(propName);
if (!input) {
return;
}
if (input->empty()) {
properties[propName].clear();
return;
}
std::string prepro =
cmGeneratorExpression::Preprocess(*input, preprocessRule, true);
if (!prepro.empty()) {
this->ResolveTargetsInGeneratorExpressions(prepro, gt);
if (!checkInterfaceDirs(prepro, gt, propName)) {
return;
}
properties[propName] = prepro;
}
}
void cmExportFileGenerator::PopulateIncludeDirectoriesInterface(
cmGeneratorTarget const* target,
cmGeneratorExpression::PreprocessContext preprocessRule,
ImportPropertyMap& properties, cmTargetExport const& te,
std::string& includesDestinationDirs)
{
assert(preprocessRule == cmGeneratorExpression::InstallInterface);
includesDestinationDirs.clear();
const char* propName = "INTERFACE_INCLUDE_DIRECTORIES";
cmValue input = target->GetProperty(propName);
cmGeneratorExpression ge(*target->Makefile->GetCMakeInstance());
std::string dirs = cmGeneratorExpression::Preprocess(
cmList::to_string(target->Target->GetInstallIncludeDirectoriesEntries(te)),
preprocessRule, true);
this->ReplaceInstallPrefix(dirs);
std::unique_ptr<cmCompiledGeneratorExpression> cge = ge.Parse(dirs);
std::string exportDirs =
cge->Evaluate(target->GetLocalGenerator(), "", target);
if (cge->GetHadContextSensitiveCondition()) {
cmLocalGenerator* lg = target->GetLocalGenerator();
std::ostringstream e;
e << "Target \"" << target->GetName()
<< "\" is installed with "
"INCLUDES DESTINATION set to a context sensitive path. Paths which "
"depend on the configuration, policy values or the link interface "
"are "
"not supported. Consider using target_include_directories instead.";
lg->IssueMessage(MessageType::FATAL_ERROR, e.str());
return;
}
if (!input && exportDirs.empty()) {
return;
}
if ((input && input->empty()) && exportDirs.empty()) {
// Set to empty
properties[propName].clear();
return;
}
prefixItems(exportDirs);
includesDestinationDirs = exportDirs;
std::string includes = (input ? *input : "");
const char* sep = input ? ";" : "";
includes += sep + exportDirs;
std::string prepro =
cmGeneratorExpression::Preprocess(includes, preprocessRule, true);
if (!prepro.empty()) {
this->ResolveTargetsInGeneratorExpressions(prepro, target);
if (!checkInterfaceDirs(prepro, target, propName)) {
return;
}
properties[propName] = prepro;
}
}
void cmExportFileGenerator::PopulateLinkDependsInterface(
cmGeneratorTarget const* gt,
cmGeneratorExpression::PreprocessContext preprocessRule,
ImportPropertyMap& properties)
{
assert(preprocessRule == cmGeneratorExpression::InstallInterface);
const char* propName = "INTERFACE_LINK_DEPENDS";
cmValue input = gt->GetProperty(propName);
if (!input) {
return;
}
if (input->empty()) {
properties[propName].clear();
return;
}
std::string prepro =
cmGeneratorExpression::Preprocess(*input, preprocessRule, true);
if (!prepro.empty()) {
this->ResolveTargetsInGeneratorExpressions(prepro, gt);
if (!checkInterfaceDirs(prepro, gt, propName)) {
return;
}
properties[propName] = prepro;
}
}
void cmExportFileGenerator::PopulateLinkDirectoriesInterface(
cmGeneratorTarget const* gt,
cmGeneratorExpression::PreprocessContext preprocessRule,
ImportPropertyMap& properties)
{
assert(preprocessRule == cmGeneratorExpression::InstallInterface);
const char* propName = "INTERFACE_LINK_DIRECTORIES";
cmValue input = gt->GetProperty(propName);
if (!input) {
return;
}
if (input->empty()) {
properties[propName].clear();
return;
}
std::string prepro =
cmGeneratorExpression::Preprocess(*input, preprocessRule, true);
if (!prepro.empty()) {
this->ResolveTargetsInGeneratorExpressions(prepro, gt);
if (!checkInterfaceDirs(prepro, gt, propName)) {
return;
}
properties[propName] = prepro;
}
}
void cmExportFileGenerator::PopulateInterfaceProperty(
const std::string& propName, cmGeneratorTarget const* target,
cmGeneratorExpression::PreprocessContext preprocessRule,
ImportPropertyMap& properties)
{
this->PopulateInterfaceProperty(propName, propName, target, preprocessRule,
properties);
}
static void getPropertyContents(cmGeneratorTarget const* tgt,
const std::string& prop,
std::set<std::string>& ifaceProperties)
{
cmValue p = tgt->GetProperty(prop);
if (!p) {
return;
}
cmList content{ *p };
ifaceProperties.insert(content.begin(), content.end());
}
static void getCompatibleInterfaceProperties(
cmGeneratorTarget const* target, std::set<std::string>& ifaceProperties,
const std::string& config)
{
if (target->GetType() == cmStateEnums::OBJECT_LIBRARY) {
// object libraries have no link information, so nothing to compute
return;
}
cmComputeLinkInformation* info = target->GetLinkInformation(config);
if (!info) {
cmLocalGenerator* lg = target->GetLocalGenerator();
std::ostringstream e;
e << "Exporting the target \"" << target->GetName()
<< "\" is not "
"allowed since its linker language cannot be determined";
lg->IssueMessage(MessageType::FATAL_ERROR, e.str());
return;
}
const cmComputeLinkInformation::ItemVector& deps = info->GetItems();
for (auto const& dep : deps) {
if (!dep.Target || dep.Target->GetType() == cmStateEnums::OBJECT_LIBRARY) {
continue;
}
getPropertyContents(dep.Target, "COMPATIBLE_INTERFACE_BOOL",
ifaceProperties);
getPropertyContents(dep.Target, "COMPATIBLE_INTERFACE_STRING",
ifaceProperties);
getPropertyContents(dep.Target, "COMPATIBLE_INTERFACE_NUMBER_MIN",
ifaceProperties);
getPropertyContents(dep.Target, "COMPATIBLE_INTERFACE_NUMBER_MAX",
ifaceProperties);
}
}
void cmExportFileGenerator::PopulateCompatibleInterfaceProperties(
cmGeneratorTarget const* gtarget, ImportPropertyMap& properties)
{
this->PopulateInterfaceProperty("COMPATIBLE_INTERFACE_BOOL", gtarget,
properties);
this->PopulateInterfaceProperty("COMPATIBLE_INTERFACE_STRING", gtarget,
properties);
this->PopulateInterfaceProperty("COMPATIBLE_INTERFACE_NUMBER_MIN", gtarget,
properties);
this->PopulateInterfaceProperty("COMPATIBLE_INTERFACE_NUMBER_MAX", gtarget,
properties);
std::set<std::string> ifaceProperties;
getPropertyContents(gtarget, "COMPATIBLE_INTERFACE_BOOL", ifaceProperties);
getPropertyContents(gtarget, "COMPATIBLE_INTERFACE_STRING", ifaceProperties);
getPropertyContents(gtarget, "COMPATIBLE_INTERFACE_NUMBER_MIN",
ifaceProperties);
getPropertyContents(gtarget, "COMPATIBLE_INTERFACE_NUMBER_MAX",
ifaceProperties);
if (gtarget->GetType() != cmStateEnums::INTERFACE_LIBRARY) {
std::vector<std::string> configNames =
gtarget->Target->GetMakefile()->GetGeneratorConfigs(
cmMakefile::IncludeEmptyConfig);
for (std::string const& cn : configNames) {
getCompatibleInterfaceProperties(gtarget, ifaceProperties, cn);
}
}
for (std::string const& ip : ifaceProperties) {
this->PopulateInterfaceProperty("INTERFACE_" + ip, gtarget, properties);
}
}
void cmExportFileGenerator::GenerateInterfaceProperties(
const cmGeneratorTarget* target, std::ostream& os,
const ImportPropertyMap& properties)
{
if (!properties.empty()) {
std::string targetName =
cmStrCat(this->Namespace, target->GetExportName());
os << "set_target_properties(" << targetName << " PROPERTIES\n";
for (auto const& property : properties) {
os << " " << property.first << " "
<< cmExportFileGeneratorEscape(property.second) << "\n";
}
os << ")\n\n";
}
}
bool cmExportFileGenerator::AddTargetNamespace(std::string& input,
cmGeneratorTarget const* target,
cmLocalGenerator const* lg)
{
cmGeneratorTarget::TargetOrString resolved =
target->ResolveTargetReference(input, lg);
cmGeneratorTarget* tgt = resolved.Target;
if (!tgt) {
input = resolved.String;
return false;
}
if (tgt->IsImported()) {
input = tgt->GetName();
return true;
}
if (this->ExportedTargets.find(tgt) != this->ExportedTargets.end()) {
input = this->Namespace + tgt->GetExportName();
} else {
std::string namespacedTarget;
this->HandleMissingTarget(namespacedTarget, target, tgt);
if (!namespacedTarget.empty()) {
input = namespacedTarget;
} else {
input = tgt->GetName();
}
}
return true;
}
void cmExportFileGenerator::ResolveTargetsInGeneratorExpressions(
std::string& input, cmGeneratorTarget const* target,
FreeTargetsReplace replace)
{
cmLocalGenerator const* lg = target->GetLocalGenerator();
if (replace == NoReplaceFreeTargets) {
this->ResolveTargetsInGeneratorExpression(input, target, lg);
return;
}
std::vector<std::string> parts;
cmGeneratorExpression::Split(input, parts);
std::string sep;
input.clear();
for (std::string& li : parts) {
if (target->IsLinkLookupScope(li, lg)) {
continue;
}
if (cmGeneratorExpression::Find(li) == std::string::npos) {
this->AddTargetNamespace(li, target, lg);
} else {
this->ResolveTargetsInGeneratorExpression(li, target, lg);
}
input += sep + li;
sep = ";";
}
}
void cmExportFileGenerator::ResolveTargetsInGeneratorExpression(
std::string& input, cmGeneratorTarget const* target,
cmLocalGenerator const* lg)
{
std::string::size_type pos = 0;
std::string::size_type lastPos = pos;
while ((pos = input.find("$<TARGET_PROPERTY:", lastPos)) !=
std::string::npos) {
std::string::size_type nameStartPos = pos + cmStrLen("$<TARGET_PROPERTY:");
std::string::size_type closePos = input.find('>', nameStartPos);
std::string::size_type commaPos = input.find(',', nameStartPos);
std::string::size_type nextOpenPos = input.find("$<", nameStartPos);
if (commaPos == std::string::npos // Implied 'this' target
|| closePos == std::string::npos // Incomplete expression.
|| closePos < commaPos // Implied 'this' target
|| nextOpenPos < commaPos) // Non-literal
{
lastPos = nameStartPos;
continue;
}
std::string targetName =
input.substr(nameStartPos, commaPos - nameStartPos);
if (this->AddTargetNamespace(targetName, target, lg)) {
input.replace(nameStartPos, commaPos - nameStartPos, targetName);
}
lastPos = nameStartPos + targetName.size() + 1;
}
std::string errorString;
pos = 0;
lastPos = pos;
while ((pos = input.find("$<TARGET_NAME:", lastPos)) != std::string::npos) {
std::string::size_type nameStartPos = pos + cmStrLen("$<TARGET_NAME:");
std::string::size_type endPos = input.find('>', nameStartPos);
if (endPos == std::string::npos) {
errorString = "$<TARGET_NAME:...> expression incomplete";
break;
}
std::string targetName = input.substr(nameStartPos, endPos - nameStartPos);
if (targetName.find("$<") != std::string::npos) {
errorString = "$<TARGET_NAME:...> requires its parameter to be a "
"literal.";
break;
}
if (!this->AddTargetNamespace(targetName, target, lg)) {
errorString = "$<TARGET_NAME:...> requires its parameter to be a "
"reachable target.";
break;
}
input.replace(pos, endPos - pos + 1, targetName);
lastPos = pos + targetName.size();
}
pos = 0;
lastPos = pos;
while (errorString.empty() &&
(pos = input.find("$<LINK_ONLY:", lastPos)) != std::string::npos) {
std::string::size_type nameStartPos = pos + cmStrLen("$<LINK_ONLY:");
std::string::size_type endPos = input.find('>', nameStartPos);
if (endPos == std::string::npos) {
errorString = "$<LINK_ONLY:...> expression incomplete";
break;
}
std::string libName = input.substr(nameStartPos, endPos - nameStartPos);
if (cmGeneratorExpression::IsValidTargetName(libName) &&
this->AddTargetNamespace(libName, target, lg)) {
input.replace(nameStartPos, endPos - nameStartPos, libName);
}
lastPos = nameStartPos + libName.size() + 1;
}
while (errorString.empty() &&
(pos = input.find("$<COMPILE_ONLY:", lastPos)) != std::string::npos) {
std::string::size_type nameStartPos = pos + cmStrLen("$<COMPILE_ONLY:");
std::string::size_type endPos = input.find('>', nameStartPos);
if (endPos == std::string::npos) {
errorString = "$<COMPILE_ONLY:...> expression incomplete";
break;
}
std::string libName = input.substr(nameStartPos, endPos - nameStartPos);
if (cmGeneratorExpression::IsValidTargetName(libName) &&
this->AddTargetNamespace(libName, target, lg)) {
input.replace(nameStartPos, endPos - nameStartPos, libName);
}
lastPos = nameStartPos + libName.size() + 1;
}
this->ReplaceInstallPrefix(input);
if (!errorString.empty()) {
target->GetLocalGenerator()->IssueMessage(MessageType::FATAL_ERROR,
errorString);
}
}
void cmExportFileGenerator::ReplaceInstallPrefix(std::string& /*unused*/)
{
// Do nothing
}
void cmExportFileGenerator::SetImportLinkInterface(
const std::string& config, std::string const& suffix,
cmGeneratorExpression::PreprocessContext preprocessRule,
cmGeneratorTarget const* target, ImportPropertyMap& properties)
{
// Add the transitive link dependencies for this configuration.
cmLinkInterface const* iface = target->GetLinkInterface(config, target);
if (!iface) {
return;
}
if (iface->ImplementationIsInterface) {
// Policy CMP0022 must not be NEW.
this->SetImportLinkProperty(
suffix, target, "IMPORTED_LINK_INTERFACE_LIBRARIES", iface->Libraries,
properties, ImportLinkPropertyTargetNames::Yes);
return;
}
cmValue propContent;
if (cmValue prop_suffixed =
target->GetProperty("LINK_INTERFACE_LIBRARIES" + suffix)) {
propContent = prop_suffixed;
} else if (cmValue prop = target->GetProperty("LINK_INTERFACE_LIBRARIES")) {
propContent = prop;
} else {
return;
}
const bool newCMP0022Behavior =
target->GetPolicyStatusCMP0022() != cmPolicies::WARN &&
target->GetPolicyStatusCMP0022() != cmPolicies::OLD;
if (newCMP0022Behavior && !this->ExportOld) {
cmLocalGenerator* lg = target->GetLocalGenerator();
std::ostringstream e;
e << "Target \"" << target->GetName()
<< "\" has policy CMP0022 enabled, "
"but also has old-style LINK_INTERFACE_LIBRARIES properties "
"populated, but it was exported without the "
"EXPORT_LINK_INTERFACE_LIBRARIES to export the old-style properties";
lg->IssueMessage(MessageType::FATAL_ERROR, e.str());
return;
}
if (propContent->empty()) {
properties["IMPORTED_LINK_INTERFACE_LIBRARIES" + suffix].clear();
return;
}
std::string prepro =
cmGeneratorExpression::Preprocess(*propContent, preprocessRule);
if (!prepro.empty()) {
this->ResolveTargetsInGeneratorExpressions(prepro, target,
ReplaceFreeTargets);
properties["IMPORTED_LINK_INTERFACE_LIBRARIES" + suffix] = prepro;
}
}
void cmExportFileGenerator::SetImportDetailProperties(
const std::string& config, std::string const& suffix,
cmGeneratorTarget* target, ImportPropertyMap& properties)
{
// Get the makefile in which to lookup target information.
cmMakefile* mf = target->Makefile;
// Add the soname for unix shared libraries.
if (target->GetType() == cmStateEnums::SHARED_LIBRARY ||
target->GetType() == cmStateEnums::MODULE_LIBRARY) {
if (!target->IsDLLPlatform()) {
std::string prop;
std::string value;
if (target->HasSOName(config)) {
if (mf->IsOn("CMAKE_PLATFORM_HAS_INSTALLNAME")) {
value = this->InstallNameDir(target, config);
}
prop = "IMPORTED_SONAME";
value += target->GetSOName(config);
} else {
prop = "IMPORTED_NO_SONAME";
value = "TRUE";
}
prop += suffix;
properties[prop] = value;
}
}
// Add the transitive link dependencies for this configuration.
if (cmLinkInterface const* iface =
target->GetLinkInterface(config, target)) {
this->SetImportLinkProperty(
suffix, target, "IMPORTED_LINK_INTERFACE_LANGUAGES", iface->Languages,
properties, ImportLinkPropertyTargetNames::No);
// Export IMPORTED_LINK_DEPENDENT_LIBRARIES to help consuming linkers
// find private dependencies of shared libraries.
std::size_t oldMissingTargetsSize = this->MissingTargets.size();
this->SetImportLinkProperty(
suffix, target, "IMPORTED_LINK_DEPENDENT_LIBRARIES", iface->SharedDeps,
properties, ImportLinkPropertyTargetNames::Yes);
// Avoid enforcing shared library private dependencies as public package
// dependencies by ignoring missing targets added for them.
this->MissingTargets.resize(oldMissingTargetsSize);
if (iface->Multiplicity > 0) {
std::string prop =
cmStrCat("IMPORTED_LINK_INTERFACE_MULTIPLICITY", suffix);
properties[prop] = std::to_string(iface->Multiplicity);
}
}
// Add information if this target is a managed target
if (target->GetManagedType(config) !=
cmGeneratorTarget::ManagedType::Native) {
std::string prop = cmStrCat("IMPORTED_COMMON_LANGUAGE_RUNTIME", suffix);
std::string propval;
if (cmValue p = target->GetProperty("COMMON_LANGUAGE_RUNTIME")) {
propval = *p;
} else if (target->IsCSharpOnly()) {
// C# projects do not have the /clr flag, so we set the property
// here to mark the target as (only) managed (i.e. no .lib file
// to link to). Otherwise the COMMON_LANGUAGE_RUNTIME target
// property would have to be set manually for C# targets to make
// exporting/importing work.
propval = "CSharp";
}
properties[prop] = propval;
}
}
static std::string const& asString(std::string const& l)
{
return l;
}
static std::string const& asString(cmLinkItem const& l)
{
return l.AsStr();
}
template <typename T>
void cmExportFileGenerator::SetImportLinkProperty(
std::string const& suffix, cmGeneratorTarget const* target,
const std::string& propName, std::vector<T> const& entries,
ImportPropertyMap& properties, ImportLinkPropertyTargetNames targetNames)
{
// Skip the property if there are no entries.
if (entries.empty()) {
return;
}
cmLocalGenerator const* lg = target->GetLocalGenerator();
// Construct the property value.
std::string link_entries;
const char* sep = "";
for (T const& l : entries) {
// Separate this from the previous entry.
link_entries += sep;
sep = ";";
if (targetNames == ImportLinkPropertyTargetNames::Yes) {
std::string temp = asString(l);
this->AddTargetNamespace(temp, target, lg);
link_entries += temp;
} else {
link_entries += asString(l);
}
}
// Store the property.
std::string prop = cmStrCat(propName, suffix);
properties[prop] = link_entries;
}
void cmExportFileGenerator::GeneratePolicyHeaderCode(std::ostream& os)
{
// Protect that file against use with older CMake versions.
/* clang-format off */
os << "# Generated by CMake\n\n";
os << "if(\"${CMAKE_MAJOR_VERSION}.${CMAKE_MINOR_VERSION}\" LESS 2.8)\n"
<< " message(FATAL_ERROR \"CMake >= 2.8.0 required\")\n"
<< "endif()\n"
<< "if(CMAKE_VERSION VERSION_LESS \"2.8.3\")\n"
<< " message(FATAL_ERROR \"CMake >= 2.8.3 required\")\n"
<< "endif()\n";
/* clang-format on */
// Isolate the file policy level.
// Support CMake versions as far back as 2.6 but also support using NEW
// policy settings for up to CMake 3.26 (this upper limit may be reviewed
// and increased from time to time). This reduces the opportunity for CMake
// warnings when an older export file is later used with newer CMake
// versions.
/* clang-format off */
os << "cmake_policy(PUSH)\n"
<< "cmake_policy(VERSION 2.8.3...3.26)\n";
/* clang-format on */
}
void cmExportFileGenerator::GeneratePolicyFooterCode(std::ostream& os)
{
os << "cmake_policy(POP)\n";
}
void cmExportFileGenerator::GenerateImportHeaderCode(std::ostream& os,
const std::string& config)
{
os << "#----------------------------------------------------------------\n"
<< "# Generated CMake target import file";
if (!config.empty()) {
os << " for configuration \"" << config << "\".\n";
} else {
os << ".\n";
}
os << "#----------------------------------------------------------------\n"
<< "\n";
this->GenerateImportVersionCode(os);
}
void cmExportFileGenerator::GenerateImportFooterCode(std::ostream& os)
{
os << "# Commands beyond this point should not need to know the version.\n"
<< "set(CMAKE_IMPORT_FILE_VERSION)\n";
}
void cmExportFileGenerator::GenerateImportVersionCode(std::ostream& os)
{
// Store an import file format version. This will let us change the
// format later while still allowing old import files to work.
/* clang-format off */
os << "# Commands may need to know the format version.\n"
<< "set(CMAKE_IMPORT_FILE_VERSION 1)\n"
<< "\n";
/* clang-format on */
}
void cmExportFileGenerator::GenerateExpectedTargetsCode(
std::ostream& os, const std::string& expectedTargets)
{
/* clang-format off */
os << "# Protect against multiple inclusion, which would fail when already "
"imported targets are added once more.\n"
"set(_cmake_targets_defined \"\")\n"
"set(_cmake_targets_not_defined \"\")\n"
"set(_cmake_expected_targets \"\")\n"
"foreach(_cmake_expected_target IN ITEMS " << expectedTargets << ")\n"
" list(APPEND _cmake_expected_targets \"${_cmake_expected_target}\")\n"
" if(TARGET \"${_cmake_expected_target}\")\n"
" list(APPEND _cmake_targets_defined \"${_cmake_expected_target}\")\n"
" else()\n"
" list(APPEND _cmake_targets_not_defined \"${_cmake_expected_target}\")\n"
" endif()\n"
"endforeach()\n"
"unset(_cmake_expected_target)\n"
"if(_cmake_targets_defined STREQUAL _cmake_expected_targets)\n"
" unset(_cmake_targets_defined)\n"
" unset(_cmake_targets_not_defined)\n"
" unset(_cmake_expected_targets)\n"
" unset(CMAKE_IMPORT_FILE_VERSION)\n"
" cmake_policy(POP)\n"
" return()\n"
"endif()\n"
"if(NOT _cmake_targets_defined STREQUAL \"\")\n"
" string(REPLACE \";\" \", \" _cmake_targets_defined_text \"${_cmake_targets_defined}\")\n"
" string(REPLACE \";\" \", \" _cmake_targets_not_defined_text \"${_cmake_targets_not_defined}\")\n"
" message(FATAL_ERROR \"Some (but not all) targets in this export "
"set were already defined.\\nTargets Defined: ${_cmake_targets_defined_text}\\n"
"Targets not yet defined: ${_cmake_targets_not_defined_text}\\n\")\n"
"endif()\n"
"unset(_cmake_targets_defined)\n"
"unset(_cmake_targets_not_defined)\n"
"unset(_cmake_expected_targets)\n"
"\n\n";
/* clang-format on */
}
void cmExportFileGenerator::GenerateImportTargetCode(
std::ostream& os, cmGeneratorTarget const* target,
cmStateEnums::TargetType targetType)
{
// Construct the imported target name.
std::string targetName = this->Namespace;
targetName += target->GetExportName();
// Create the imported target.
os << "# Create imported target " << targetName << "\n";
switch (targetType) {
case cmStateEnums::EXECUTABLE:
os << "add_executable(" << targetName << " IMPORTED)\n";
break;
case cmStateEnums::STATIC_LIBRARY:
os << "add_library(" << targetName << " STATIC IMPORTED)\n";
break;
case cmStateEnums::SHARED_LIBRARY:
os << "add_library(" << targetName << " SHARED IMPORTED)\n";
break;
case cmStateEnums::MODULE_LIBRARY:
os << "add_library(" << targetName << " MODULE IMPORTED)\n";
break;
case cmStateEnums::UNKNOWN_LIBRARY:
os << "add_library(" << targetName << " UNKNOWN IMPORTED)\n";
break;
case cmStateEnums::OBJECT_LIBRARY:
os << "add_library(" << targetName << " OBJECT IMPORTED)\n";
break;
case cmStateEnums::INTERFACE_LIBRARY:
os << "add_library(" << targetName << " INTERFACE IMPORTED)\n";
break;
default: // should never happen
break;
}
// Mark the imported executable if it has exports.
if (target->IsExecutableWithExports() ||
(target->IsSharedLibraryWithExports() && target->HasImportLibrary(""))) {
os << "set_property(TARGET " << targetName
<< " PROPERTY ENABLE_EXPORTS 1)\n";
}
// Mark the imported library if it is a framework.
if (target->IsFrameworkOnApple()) {
os << "set_property(TARGET " << targetName << " PROPERTY FRAMEWORK 1)\n";
}
// Mark the imported executable if it is an application bundle.
if (target->IsAppBundleOnApple()) {
os << "set_property(TARGET " << targetName
<< " PROPERTY MACOSX_BUNDLE 1)\n";
}
if (target->IsCFBundleOnApple()) {
os << "set_property(TARGET " << targetName << " PROPERTY BUNDLE 1)\n";
}
// generate DEPRECATION
if (target->IsDeprecated()) {
os << "set_property(TARGET " << targetName << " PROPERTY DEPRECATION "
<< cmExportFileGeneratorEscape(target->GetDeprecation()) << ")\n";
}
if (target->GetPropertyAsBool("IMPORTED_NO_SYSTEM")) {
os << "set_property(TARGET " << targetName
<< " PROPERTY IMPORTED_NO_SYSTEM 1)\n";
}
if (target->GetPropertyAsBool("EXPORT_NO_SYSTEM")) {
os << "set_property(TARGET " << targetName << " PROPERTY SYSTEM 0)\n";
}
os << "\n";
}
void cmExportFileGenerator::GenerateImportPropertyCode(
std::ostream& os, const std::string& config, cmGeneratorTarget const* target,
ImportPropertyMap const& properties)
{
// Construct the imported target name.
std::string targetName = this->Namespace;
targetName += target->GetExportName();
// Set the import properties.
os << "# Import target \"" << targetName << "\" for configuration \""
<< config << "\"\n";
os << "set_property(TARGET " << targetName
<< " APPEND PROPERTY IMPORTED_CONFIGURATIONS ";
if (!config.empty()) {
os << cmSystemTools::UpperCase(config);
} else {
os << "NOCONFIG";
}
os << ")\n";
os << "set_target_properties(" << targetName << " PROPERTIES\n";
for (auto const& property : properties) {
os << " " << property.first << " "
<< cmExportFileGeneratorEscape(property.second) << "\n";
}
os << " )\n"
<< "\n";
}
void cmExportFileGenerator::GenerateMissingTargetsCheckCode(std::ostream& os)
{
if (this->MissingTargets.empty()) {
/* clang-format off */
os << "# This file does not depend on other imported targets which have\n"
"# been exported from the same project but in a separate "
"export set.\n\n";
/* clang-format on */
return;
}
/* clang-format off */
os << "# Make sure the targets which have been exported in some other\n"
"# export set exist.\n"
"unset(${CMAKE_FIND_PACKAGE_NAME}_NOT_FOUND_MESSAGE_targets)\n"
"foreach(_target ";
/* clang-format on */
std::set<std::string> emitted;
for (std::string const& missingTarget : this->MissingTargets) {
if (emitted.insert(missingTarget).second) {
os << "\"" << missingTarget << "\" ";
}
}
/* clang-format off */
os << ")\n"
" if(NOT TARGET \"${_target}\" )\n"
" set(${CMAKE_FIND_PACKAGE_NAME}_NOT_FOUND_MESSAGE_targets \""
"${${CMAKE_FIND_PACKAGE_NAME}_NOT_FOUND_MESSAGE_targets} ${_target}\")"
"\n"
" endif()\n"
"endforeach()\n"
"\n"
"if(DEFINED ${CMAKE_FIND_PACKAGE_NAME}_NOT_FOUND_MESSAGE_targets)\n"
" if(CMAKE_FIND_PACKAGE_NAME)\n"
" set( ${CMAKE_FIND_PACKAGE_NAME}_FOUND FALSE)\n"
" set( ${CMAKE_FIND_PACKAGE_NAME}_NOT_FOUND_MESSAGE "
"\"The following imported targets are "
"referenced, but are missing: "
"${${CMAKE_FIND_PACKAGE_NAME}_NOT_FOUND_MESSAGE_targets}\")\n"
" else()\n"
" message(FATAL_ERROR \"The following imported targets are "
"referenced, but are missing: "
"${${CMAKE_FIND_PACKAGE_NAME}_NOT_FOUND_MESSAGE_targets}\")\n"
" endif()\n"
"endif()\n"
"unset(${CMAKE_FIND_PACKAGE_NAME}_NOT_FOUND_MESSAGE_targets)\n"
"\n";
/* clang-format on */
}
void cmExportFileGenerator::GenerateImportedFileCheckLoop(std::ostream& os)
{
// Add code which verifies at cmake time that the file which is being
// imported actually exists on disk. This should in theory always be theory
// case, but still when packages are split into normal and development
// packages this might get broken (e.g. the Config.cmake could be part of
// the non-development package, something similar happened to me without
// on SUSE with a mysql pkg-config file, which claimed everything is fine,
// but the development package was not installed.).
/* clang-format off */
os << "# Loop over all imported files and verify that they actually exist\n"
"foreach(_cmake_target IN LISTS _cmake_import_check_targets)\n"
" foreach(_cmake_file IN LISTS \"_cmake_import_check_files_for_${_cmake_target}\")\n"
" if(NOT EXISTS \"${_cmake_file}\")\n"
" message(FATAL_ERROR \"The imported target \\\"${_cmake_target}\\\""
" references the file\n"
" \\\"${_cmake_file}\\\"\n"
"but this file does not exist. Possible reasons include:\n"
"* The file was deleted, renamed, or moved to another location.\n"
"* An install or uninstall procedure did not complete successfully.\n"
"* The installation package was faulty and contained\n"
" \\\"${CMAKE_CURRENT_LIST_FILE}\\\"\n"
"but not all the files it references.\n"
"\")\n"
" endif()\n"
" endforeach()\n"
" unset(_cmake_file)\n"
" unset(\"_cmake_import_check_files_for_${_cmake_target}\")\n"
"endforeach()\n"
"unset(_cmake_target)\n"
"unset(_cmake_import_check_targets)\n"
"\n";
/* clang-format on */
}
void cmExportFileGenerator::GenerateImportedFileChecksCode(
std::ostream& os, cmGeneratorTarget* target,
ImportPropertyMap const& properties,
const std::set<std::string>& importedLocations)
{
// Construct the imported target name.
std::string targetName = cmStrCat(this->Namespace, target->GetExportName());
os << "list(APPEND _cmake_import_check_targets " << targetName
<< " )\n"
"list(APPEND _cmake_import_check_files_for_"
<< targetName << " ";
for (std::string const& li : importedLocations) {
auto pi = properties.find(li);
if (pi != properties.end()) {
os << cmExportFileGeneratorEscape(pi->second) << " ";
}
}
os << ")\n\n";
}
enum class PropertyType
{
Strings,
Paths,
IncludePaths,
};
namespace {
bool PropertyTypeIsForPaths(PropertyType pt)
{
switch (pt) {
case PropertyType::Strings:
return false;
case PropertyType::Paths:
case PropertyType::IncludePaths:
return true;
}
return false;
}
}
struct ModulePropertyTable
{
cm::static_string_view Name;
PropertyType Type;
};
bool cmExportFileGenerator::PopulateCxxModuleExportProperties(
cmGeneratorTarget const* gte, ImportPropertyMap& properties,
cmGeneratorExpression::PreprocessContext ctx,
std::string const& includesDestinationDirs, std::string& errorMessage)
{
if (!gte->HaveCxx20ModuleSources(&errorMessage)) {
return true;
}
const cm::static_string_view exportedDirectModuleProperties[] = {
"CXX_EXTENSIONS"_s,
};
for (auto const& propName : exportedDirectModuleProperties) {
auto const propNameStr = std::string(propName);
cmValue prop = gte->Target->GetComputedProperty(
propNameStr, *gte->Target->GetMakefile());
if (!prop) {
prop = gte->Target->GetProperty(propNameStr);
}
if (prop) {
properties[propNameStr] = cmGeneratorExpression::Preprocess(*prop, ctx);
}
}
const ModulePropertyTable exportedModuleProperties[] = {
{ "INCLUDE_DIRECTORIES"_s, PropertyType::IncludePaths },
{ "COMPILE_DEFINITIONS"_s, PropertyType::Strings },
{ "COMPILE_OPTIONS"_s, PropertyType::Strings },
{ "COMPILE_FEATURES"_s, PropertyType::Strings },
};
for (auto const& propEntry : exportedModuleProperties) {
auto const propNameStr = std::string(propEntry.Name);
cmValue prop = gte->Target->GetComputedProperty(
propNameStr, *gte->Target->GetMakefile());
if (!prop) {
prop = gte->Target->GetProperty(propNameStr);
}
if (prop) {
auto const exportedPropName =
cmStrCat("IMPORTED_CXX_MODULES_", propEntry.Name);
properties[exportedPropName] =
cmGeneratorExpression::Preprocess(*prop, ctx);
if (ctx == cmGeneratorExpression::InstallInterface &&
PropertyTypeIsForPaths(propEntry.Type)) {
this->ReplaceInstallPrefix(properties[exportedPropName]);
prefixItems(properties[exportedPropName]);
if (propEntry.Type == PropertyType::IncludePaths &&
!includesDestinationDirs.empty()) {
if (!properties[exportedPropName].empty()) {
properties[exportedPropName] += ';';
}
properties[exportedPropName] += includesDestinationDirs;
}
}
}
}
const cm::static_string_view exportedLinkModuleProperties[] = {
"LINK_LIBRARIES"_s,
};
for (auto const& propName : exportedLinkModuleProperties) {
auto const propNameStr = std::string(propName);
cmValue prop = gte->Target->GetComputedProperty(
propNameStr, *gte->Target->GetMakefile());
if (!prop) {
prop = gte->Target->GetProperty(propNameStr);
}
if (prop) {
auto const exportedPropName =
cmStrCat("IMPORTED_CXX_MODULES_", propName);
auto value = cmGeneratorExpression::Preprocess(*prop, ctx);
this->ResolveTargetsInGeneratorExpressions(
value, gte, cmExportFileGenerator::ReplaceFreeTargets);
std::vector<std::string> wrappedValues;
for (auto& item : cmList{ value }) {
wrappedValues.push_back(cmStrCat("$<COMPILE_ONLY:", item, '>'));
}
properties[exportedPropName] = cmJoin(wrappedValues, ";");
}
}
return true;
}
bool cmExportFileGenerator::PopulateExportProperties(
cmGeneratorTarget const* gte, ImportPropertyMap& properties,
std::string& errorMessage)
{
const auto& targetProperties = gte->Target->GetProperties();
if (cmValue exportProperties =
targetProperties.GetPropertyValue("EXPORT_PROPERTIES")) {
for (auto& prop : cmList{ *exportProperties }) {
/* Black list reserved properties */
if (cmHasLiteralPrefix(prop, "IMPORTED_") ||
cmHasLiteralPrefix(prop, "INTERFACE_")) {
std::ostringstream e;
e << "Target \"" << gte->Target->GetName() << "\" contains property \""
<< prop << "\" in EXPORT_PROPERTIES but IMPORTED_* and INTERFACE_* "
<< "properties are reserved.";
errorMessage = e.str();
return false;
}
cmValue propertyValue = targetProperties.GetPropertyValue(prop);
if (!propertyValue) {
// Asked to export a property that isn't defined on the target. Do not
// consider this an error, there's just nothing to export.
continue;
}
std::string evaluatedValue = cmGeneratorExpression::Preprocess(
*propertyValue, cmGeneratorExpression::StripAllGeneratorExpressions);
if (evaluatedValue != *propertyValue) {
std::ostringstream e;
e << "Target \"" << gte->Target->GetName() << "\" contains property \""
<< prop << "\" in EXPORT_PROPERTIES but this property contains a "
<< "generator expression. This is not allowed.";
errorMessage = e.str();
return false;
}
properties[prop] = *propertyValue;
}
}
return true;
}
void cmExportFileGenerator::GenerateTargetFileSets(cmGeneratorTarget* gte,
std::ostream& os,
cmTargetExport* te)
{
auto interfaceFileSets = gte->Target->GetAllInterfaceFileSets();
if (!interfaceFileSets.empty()) {
std::string targetName = cmStrCat(this->Namespace, gte->GetExportName());
os << "if(NOT CMAKE_VERSION VERSION_LESS \"3.23.0\")\n"
" target_sources("
<< targetName << "\n";
for (auto const& name : interfaceFileSets) {
auto* fileSet = gte->Target->GetFileSet(name);
if (!fileSet) {
gte->Makefile->IssueMessage(
MessageType::FATAL_ERROR,
cmStrCat("File set \"", name,
"\" is listed in interface file sets of ", gte->GetName(),
" but has not been created"));
return;
}
os << " INTERFACE"
<< "\n FILE_SET " << cmOutputConverter::EscapeForCMake(name)
<< "\n TYPE "
<< cmOutputConverter::EscapeForCMake(fileSet->GetType())
<< "\n BASE_DIRS "
<< this->GetFileSetDirectories(gte, fileSet, te) << "\n FILES "
<< this->GetFileSetFiles(gte, fileSet, te) << "\n";
}
os << " )\nelse()\n set_property(TARGET " << targetName
<< "\n APPEND PROPERTY INTERFACE_INCLUDE_DIRECTORIES";
for (auto const& name : interfaceFileSets) {
auto* fileSet = gte->Target->GetFileSet(name);
if (!fileSet) {
gte->Makefile->IssueMessage(
MessageType::FATAL_ERROR,
cmStrCat("File set \"", name,
"\" is listed in interface file sets of ", gte->GetName(),
" but has not been created"));
return;
}
os << "\n " << this->GetFileSetDirectories(gte, fileSet, te);
}
os << "\n )\nendif()\n\n";
}
}
void cmExportFileGenerator::GenerateCxxModuleInformation(std::ostream& os)
{
auto const cxx_module_dirname = this->GetCxxModulesDirectory();
if (cxx_module_dirname.empty()) {
return;
}
// Write the include.
os << "# Include C++ module properties\n"
<< "include(\"${CMAKE_CURRENT_LIST_DIR}/" << cxx_module_dirname
<< "/cxx-modules.cmake\")\n\n";
// Get the path to the file we're going to write.
std::string path = this->MainImportFile;
path = cmSystemTools::GetFilenamePath(path);
auto trampoline_path =
cmStrCat(path, '/', cxx_module_dirname, "/cxx-modules.cmake");
// Include all configuration-specific include files.
cmGeneratedFileStream ap(trampoline_path, true);
ap.SetCopyIfDifferent(true);
this->GenerateCxxModuleConfigInformation(ap);
}
|