1 /* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
2    file Copyright.txt or https://cmake.org/licensing for details.  */
3 #include "cmExportFileGenerator.h"
4 
5 #include <cassert>
6 #include <cstring>
7 #include <sstream>
8 #include <utility>
9 
10 #include <cm/memory>
11 
12 #include "cmsys/FStream.hxx"
13 
14 #include "cmComputeLinkInformation.h"
15 #include "cmGeneratedFileStream.h"
16 #include "cmGeneratorTarget.h"
17 #include "cmGlobalGenerator.h"
18 #include "cmLinkItem.h"
19 #include "cmLocalGenerator.h"
20 #include "cmMakefile.h"
21 #include "cmMessageType.h"
22 #include "cmOutputConverter.h"
23 #include "cmPolicies.h"
24 #include "cmPropertyMap.h"
25 #include "cmStateTypes.h"
26 #include "cmStringAlgorithms.h"
27 #include "cmSystemTools.h"
28 #include "cmTarget.h"
29 #include "cmValue.h"
30 
cmExportFileGeneratorEscape(std::string const & str)31 static std::string cmExportFileGeneratorEscape(std::string const& str)
32 {
33   // Escape a property value for writing into a .cmake file.
34   std::string result = cmOutputConverter::EscapeForCMake(str);
35   // Un-escape variable references generated by our own export code.
36   cmSystemTools::ReplaceString(result, "\\${_IMPORT_PREFIX}",
37                                "${_IMPORT_PREFIX}");
38   cmSystemTools::ReplaceString(result, "\\${CMAKE_IMPORT_LIBRARY_SUFFIX}",
39                                "${CMAKE_IMPORT_LIBRARY_SUFFIX}");
40   return result;
41 }
42 
cmExportFileGenerator()43 cmExportFileGenerator::cmExportFileGenerator()
44 {
45   this->AppendMode = false;
46   this->ExportOld = false;
47 }
48 
AddConfiguration(const std::string & config)49 void cmExportFileGenerator::AddConfiguration(const std::string& config)
50 {
51   this->Configurations.push_back(config);
52 }
53 
SetExportFile(const char * mainFile)54 void cmExportFileGenerator::SetExportFile(const char* mainFile)
55 {
56   this->MainImportFile = mainFile;
57   this->FileDir = cmSystemTools::GetFilenamePath(this->MainImportFile);
58   this->FileBase =
59     cmSystemTools::GetFilenameWithoutLastExtension(this->MainImportFile);
60   this->FileExt =
61     cmSystemTools::GetFilenameLastExtension(this->MainImportFile);
62 }
63 
GetMainExportFileName() const64 const std::string& cmExportFileGenerator::GetMainExportFileName() const
65 {
66   return this->MainImportFile;
67 }
68 
GenerateImportFile()69 bool cmExportFileGenerator::GenerateImportFile()
70 {
71   // Open the output file to generate it.
72   std::unique_ptr<cmsys::ofstream> foutPtr;
73   if (this->AppendMode) {
74     // Open for append.
75     auto openmodeApp = std::ios::app;
76     foutPtr = cm::make_unique<cmsys::ofstream>(this->MainImportFile.c_str(),
77                                                openmodeApp);
78   } else {
79     // Generate atomically and with copy-if-different.
80     std::unique_ptr<cmGeneratedFileStream> ap(
81       new cmGeneratedFileStream(this->MainImportFile, true));
82     ap->SetCopyIfDifferent(true);
83     foutPtr = std::move(ap);
84   }
85   if (!foutPtr || !*foutPtr) {
86     std::string se = cmSystemTools::GetLastSystemError();
87     std::ostringstream e;
88     e << "cannot write to file \"" << this->MainImportFile << "\": " << se;
89     cmSystemTools::Error(e.str());
90     return false;
91   }
92   std::ostream& os = *foutPtr;
93 
94   // Start with the import file header.
95   this->GeneratePolicyHeaderCode(os);
96   this->GenerateImportHeaderCode(os);
97 
98   // Create all the imported targets.
99   bool result = this->GenerateMainFile(os);
100 
101   // End with the import file footer.
102   this->GenerateImportFooterCode(os);
103   this->GeneratePolicyFooterCode(os);
104 
105   return result;
106 }
107 
GenerateImportConfig(std::ostream & os,const std::string & config,std::vector<std::string> & missingTargets)108 void cmExportFileGenerator::GenerateImportConfig(
109   std::ostream& os, const std::string& config,
110   std::vector<std::string>& missingTargets)
111 {
112   // Construct the property configuration suffix.
113   std::string suffix = "_";
114   if (!config.empty()) {
115     suffix += cmSystemTools::UpperCase(config);
116   } else {
117     suffix += "NOCONFIG";
118   }
119 
120   // Generate the per-config target information.
121   this->GenerateImportTargetsConfig(os, config, suffix, missingTargets);
122 }
123 
PopulateInterfaceProperty(const std::string & propName,cmGeneratorTarget const * target,ImportPropertyMap & properties)124 void cmExportFileGenerator::PopulateInterfaceProperty(
125   const std::string& propName, cmGeneratorTarget const* target,
126   ImportPropertyMap& properties)
127 {
128   cmValue input = target->GetProperty(propName);
129   if (input) {
130     properties[propName] = *input;
131   }
132 }
133 
PopulateInterfaceProperty(const std::string & propName,const std::string & outputName,cmGeneratorTarget const * target,cmGeneratorExpression::PreprocessContext preprocessRule,ImportPropertyMap & properties,std::vector<std::string> & missingTargets)134 void cmExportFileGenerator::PopulateInterfaceProperty(
135   const std::string& propName, const std::string& outputName,
136   cmGeneratorTarget const* target,
137   cmGeneratorExpression::PreprocessContext preprocessRule,
138   ImportPropertyMap& properties, std::vector<std::string>& missingTargets)
139 {
140   cmValue input = target->GetProperty(propName);
141   if (input) {
142     if (input->empty()) {
143       // Set to empty
144       properties[outputName].clear();
145       return;
146     }
147 
148     std::string prepro =
149       cmGeneratorExpression::Preprocess(*input, preprocessRule);
150     if (!prepro.empty()) {
151       this->ResolveTargetsInGeneratorExpressions(prepro, target,
152                                                  missingTargets);
153       properties[outputName] = prepro;
154     }
155   }
156 }
157 
GenerateRequiredCMakeVersion(std::ostream & os,const char * versionString)158 void cmExportFileGenerator::GenerateRequiredCMakeVersion(
159   std::ostream& os, const char* versionString)
160 {
161   /* clang-format off */
162   os << "if(CMAKE_VERSION VERSION_LESS " << versionString << ")\n"
163         "  message(FATAL_ERROR \"This file relies on consumers using "
164         "CMake " << versionString << " or greater.\")\n"
165         "endif()\n\n";
166   /* clang-format on */
167 }
168 
PopulateInterfaceLinkLibrariesProperty(cmGeneratorTarget const * target,cmGeneratorExpression::PreprocessContext preprocessRule,ImportPropertyMap & properties,std::vector<std::string> & missingTargets)169 bool cmExportFileGenerator::PopulateInterfaceLinkLibrariesProperty(
170   cmGeneratorTarget const* target,
171   cmGeneratorExpression::PreprocessContext preprocessRule,
172   ImportPropertyMap& properties, std::vector<std::string>& missingTargets)
173 {
174   if (!target->IsLinkable()) {
175     return false;
176   }
177   cmValue input = target->GetProperty("INTERFACE_LINK_LIBRARIES");
178   if (input) {
179     std::string prepro =
180       cmGeneratorExpression::Preprocess(*input, preprocessRule);
181     if (!prepro.empty()) {
182       this->ResolveTargetsInGeneratorExpressions(
183         prepro, target, missingTargets, ReplaceFreeTargets);
184       properties["INTERFACE_LINK_LIBRARIES"] = prepro;
185       return true;
186     }
187   }
188   return false;
189 }
190 
isSubDirectory(std::string const & a,std::string const & b)191 static bool isSubDirectory(std::string const& a, std::string const& b)
192 {
193   return (cmSystemTools::ComparePath(a, b) ||
194           cmSystemTools::IsSubDirectory(a, b));
195 }
196 
checkInterfaceDirs(const std::string & prepro,cmGeneratorTarget const * target,const std::string & prop)197 static bool checkInterfaceDirs(const std::string& prepro,
198                                cmGeneratorTarget const* target,
199                                const std::string& prop)
200 {
201   std::string const& installDir =
202     target->Makefile->GetSafeDefinition("CMAKE_INSTALL_PREFIX");
203   std::string const& topSourceDir =
204     target->GetLocalGenerator()->GetSourceDirectory();
205   std::string const& topBinaryDir =
206     target->GetLocalGenerator()->GetBinaryDirectory();
207 
208   std::vector<std::string> parts;
209   cmGeneratorExpression::Split(prepro, parts);
210 
211   const bool inSourceBuild = topSourceDir == topBinaryDir;
212 
213   bool hadFatalError = false;
214 
215   for (std::string const& li : parts) {
216     size_t genexPos = cmGeneratorExpression::Find(li);
217     if (genexPos == 0) {
218       continue;
219     }
220     if (cmHasLiteralPrefix(li, "${_IMPORT_PREFIX}")) {
221       continue;
222     }
223     MessageType messageType = MessageType::FATAL_ERROR;
224     std::ostringstream e;
225     if (genexPos != std::string::npos) {
226       if (prop == "INTERFACE_INCLUDE_DIRECTORIES") {
227         switch (target->GetPolicyStatusCMP0041()) {
228           case cmPolicies::WARN:
229             messageType = MessageType::WARNING;
230             e << cmPolicies::GetPolicyWarning(cmPolicies::CMP0041) << "\n";
231             break;
232           case cmPolicies::OLD:
233             continue;
234           case cmPolicies::REQUIRED_IF_USED:
235           case cmPolicies::REQUIRED_ALWAYS:
236           case cmPolicies::NEW:
237             hadFatalError = true;
238             break; // Issue fatal message.
239         }
240       } else {
241         hadFatalError = true;
242       }
243     }
244     if (!cmSystemTools::FileIsFullPath(li)) {
245       /* clang-format off */
246       e << "Target \"" << target->GetName() << "\" " << prop <<
247            " property contains relative path:\n"
248            "  \"" << li << "\"";
249       /* clang-format on */
250       target->GetLocalGenerator()->IssueMessage(messageType, e.str());
251     }
252     bool inBinary = isSubDirectory(li, topBinaryDir);
253     bool inSource = isSubDirectory(li, topSourceDir);
254     if (isSubDirectory(li, installDir)) {
255       // The include directory is inside the install tree.  If the
256       // install tree is not inside the source tree or build tree then
257       // fall through to the checks below that the include directory is not
258       // also inside the source tree or build tree.
259       bool shouldContinue =
260         (!inBinary || isSubDirectory(installDir, topBinaryDir)) &&
261         (!inSource || isSubDirectory(installDir, topSourceDir));
262 
263       if (prop == "INTERFACE_INCLUDE_DIRECTORIES") {
264         if (!shouldContinue) {
265           switch (target->GetPolicyStatusCMP0052()) {
266             case cmPolicies::WARN: {
267               std::ostringstream s;
268               s << cmPolicies::GetPolicyWarning(cmPolicies::CMP0052) << "\n";
269               s << "Directory:\n    \"" << li
270                 << "\"\nin "
271                    "INTERFACE_INCLUDE_DIRECTORIES of target \""
272                 << target->GetName()
273                 << "\" is a subdirectory of the install "
274                    "directory:\n    \""
275                 << installDir
276                 << "\"\nhowever it is also "
277                    "a subdirectory of the "
278                 << (inBinary ? "build" : "source") << " tree:\n    \""
279                 << (inBinary ? topBinaryDir : topSourceDir) << "\"\n";
280               target->GetLocalGenerator()->IssueMessage(
281                 MessageType::AUTHOR_WARNING, s.str());
282               CM_FALLTHROUGH;
283             }
284             case cmPolicies::OLD:
285               shouldContinue = true;
286               break;
287             case cmPolicies::REQUIRED_ALWAYS:
288             case cmPolicies::REQUIRED_IF_USED:
289             case cmPolicies::NEW:
290               break;
291           }
292         }
293       }
294       if (shouldContinue) {
295         continue;
296       }
297     }
298     if (inBinary) {
299       /* clang-format off */
300       e << "Target \"" << target->GetName() << "\" " << prop <<
301            " property contains path:\n"
302            "  \"" << li << "\"\nwhich is prefixed in the build directory.";
303       /* clang-format on */
304       target->GetLocalGenerator()->IssueMessage(messageType, e.str());
305     }
306     if (!inSourceBuild) {
307       if (inSource) {
308         e << "Target \"" << target->GetName() << "\" " << prop
309           << " property contains path:\n"
310              "  \""
311           << li << "\"\nwhich is prefixed in the source directory.";
312         target->GetLocalGenerator()->IssueMessage(messageType, e.str());
313       }
314     }
315   }
316   return !hadFatalError;
317 }
318 
prefixItems(std::string & exportDirs)319 static void prefixItems(std::string& exportDirs)
320 {
321   std::vector<std::string> entries;
322   cmGeneratorExpression::Split(exportDirs, entries);
323   exportDirs.clear();
324   const char* sep = "";
325   for (std::string const& e : entries) {
326     exportDirs += sep;
327     sep = ";";
328     if (!cmSystemTools::FileIsFullPath(e) &&
329         e.find("${_IMPORT_PREFIX}") == std::string::npos) {
330       exportDirs += "${_IMPORT_PREFIX}/";
331     }
332     exportDirs += e;
333   }
334 }
335 
PopulateSourcesInterface(cmGeneratorTarget const * gt,cmGeneratorExpression::PreprocessContext preprocessRule,ImportPropertyMap & properties,std::vector<std::string> & missingTargets)336 void cmExportFileGenerator::PopulateSourcesInterface(
337   cmGeneratorTarget const* gt,
338   cmGeneratorExpression::PreprocessContext preprocessRule,
339   ImportPropertyMap& properties, std::vector<std::string>& missingTargets)
340 {
341   assert(preprocessRule == cmGeneratorExpression::InstallInterface);
342 
343   const char* propName = "INTERFACE_SOURCES";
344   cmValue input = gt->GetProperty(propName);
345 
346   if (!input) {
347     return;
348   }
349 
350   if (input->empty()) {
351     properties[propName].clear();
352     return;
353   }
354 
355   std::string prepro =
356     cmGeneratorExpression::Preprocess(*input, preprocessRule, true);
357   if (!prepro.empty()) {
358     this->ResolveTargetsInGeneratorExpressions(prepro, gt, missingTargets);
359 
360     if (!checkInterfaceDirs(prepro, gt, propName)) {
361       return;
362     }
363     properties[propName] = prepro;
364   }
365 }
366 
PopulateIncludeDirectoriesInterface(cmGeneratorTarget const * target,cmGeneratorExpression::PreprocessContext preprocessRule,ImportPropertyMap & properties,std::vector<std::string> & missingTargets)367 void cmExportFileGenerator::PopulateIncludeDirectoriesInterface(
368   cmGeneratorTarget const* target,
369   cmGeneratorExpression::PreprocessContext preprocessRule,
370   ImportPropertyMap& properties, std::vector<std::string>& missingTargets)
371 {
372   assert(preprocessRule == cmGeneratorExpression::InstallInterface);
373 
374   const char* propName = "INTERFACE_INCLUDE_DIRECTORIES";
375   cmValue input = target->GetProperty(propName);
376 
377   cmGeneratorExpression ge;
378 
379   std::string dirs = cmGeneratorExpression::Preprocess(
380     cmJoin(target->Target->GetInstallIncludeDirectoriesEntries(), ";"),
381     preprocessRule, true);
382   this->ReplaceInstallPrefix(dirs);
383   std::unique_ptr<cmCompiledGeneratorExpression> cge = ge.Parse(dirs);
384   std::string exportDirs =
385     cge->Evaluate(target->GetLocalGenerator(), "", target);
386 
387   if (cge->GetHadContextSensitiveCondition()) {
388     cmLocalGenerator* lg = target->GetLocalGenerator();
389     std::ostringstream e;
390     e << "Target \"" << target->GetName()
391       << "\" is installed with "
392          "INCLUDES DESTINATION set to a context sensitive path.  Paths which "
393          "depend on the configuration, policy values or the link interface "
394          "are "
395          "not supported.  Consider using target_include_directories instead.";
396     lg->IssueMessage(MessageType::FATAL_ERROR, e.str());
397     return;
398   }
399 
400   if (!input && exportDirs.empty()) {
401     return;
402   }
403   if ((input && input->empty()) && exportDirs.empty()) {
404     // Set to empty
405     properties[propName].clear();
406     return;
407   }
408 
409   prefixItems(exportDirs);
410 
411   std::string includes = (input ? *input : "");
412   const char* sep = input ? ";" : "";
413   includes += sep + exportDirs;
414   std::string prepro =
415     cmGeneratorExpression::Preprocess(includes, preprocessRule, true);
416   if (!prepro.empty()) {
417     this->ResolveTargetsInGeneratorExpressions(prepro, target, missingTargets);
418 
419     if (!checkInterfaceDirs(prepro, target, propName)) {
420       return;
421     }
422     properties[propName] = prepro;
423   }
424 }
425 
PopulateLinkDependsInterface(cmGeneratorTarget const * gt,cmGeneratorExpression::PreprocessContext preprocessRule,ImportPropertyMap & properties,std::vector<std::string> & missingTargets)426 void cmExportFileGenerator::PopulateLinkDependsInterface(
427   cmGeneratorTarget const* gt,
428   cmGeneratorExpression::PreprocessContext preprocessRule,
429   ImportPropertyMap& properties, std::vector<std::string>& missingTargets)
430 {
431   assert(preprocessRule == cmGeneratorExpression::InstallInterface);
432 
433   const char* propName = "INTERFACE_LINK_DEPENDS";
434   cmValue input = gt->GetProperty(propName);
435 
436   if (!input) {
437     return;
438   }
439 
440   if (input->empty()) {
441     properties[propName].clear();
442     return;
443   }
444 
445   std::string prepro =
446     cmGeneratorExpression::Preprocess(*input, preprocessRule, true);
447   if (!prepro.empty()) {
448     this->ResolveTargetsInGeneratorExpressions(prepro, gt, missingTargets);
449 
450     if (!checkInterfaceDirs(prepro, gt, propName)) {
451       return;
452     }
453     properties[propName] = prepro;
454   }
455 }
456 
PopulateLinkDirectoriesInterface(cmGeneratorTarget const * gt,cmGeneratorExpression::PreprocessContext preprocessRule,ImportPropertyMap & properties,std::vector<std::string> & missingTargets)457 void cmExportFileGenerator::PopulateLinkDirectoriesInterface(
458   cmGeneratorTarget const* gt,
459   cmGeneratorExpression::PreprocessContext preprocessRule,
460   ImportPropertyMap& properties, std::vector<std::string>& missingTargets)
461 {
462   assert(preprocessRule == cmGeneratorExpression::InstallInterface);
463 
464   const char* propName = "INTERFACE_LINK_DIRECTORIES";
465   cmValue input = gt->GetProperty(propName);
466 
467   if (!input) {
468     return;
469   }
470 
471   if (input->empty()) {
472     properties[propName].clear();
473     return;
474   }
475 
476   std::string prepro =
477     cmGeneratorExpression::Preprocess(*input, preprocessRule, true);
478   if (!prepro.empty()) {
479     this->ResolveTargetsInGeneratorExpressions(prepro, gt, missingTargets);
480 
481     if (!checkInterfaceDirs(prepro, gt, propName)) {
482       return;
483     }
484     properties[propName] = prepro;
485   }
486 }
487 
PopulateInterfaceProperty(const std::string & propName,cmGeneratorTarget const * target,cmGeneratorExpression::PreprocessContext preprocessRule,ImportPropertyMap & properties,std::vector<std::string> & missingTargets)488 void cmExportFileGenerator::PopulateInterfaceProperty(
489   const std::string& propName, cmGeneratorTarget const* target,
490   cmGeneratorExpression::PreprocessContext preprocessRule,
491   ImportPropertyMap& properties, std::vector<std::string>& missingTargets)
492 {
493   this->PopulateInterfaceProperty(propName, propName, target, preprocessRule,
494                                   properties, missingTargets);
495 }
496 
getPropertyContents(cmGeneratorTarget const * tgt,const std::string & prop,std::set<std::string> & ifaceProperties)497 void getPropertyContents(cmGeneratorTarget const* tgt, const std::string& prop,
498                          std::set<std::string>& ifaceProperties)
499 {
500   cmValue p = tgt->GetProperty(prop);
501   if (!p) {
502     return;
503   }
504   std::vector<std::string> content = cmExpandedList(*p);
505   ifaceProperties.insert(content.begin(), content.end());
506 }
507 
getCompatibleInterfaceProperties(cmGeneratorTarget const * target,std::set<std::string> & ifaceProperties,const std::string & config)508 void getCompatibleInterfaceProperties(cmGeneratorTarget const* target,
509                                       std::set<std::string>& ifaceProperties,
510                                       const std::string& config)
511 {
512   if (target->GetType() == cmStateEnums::OBJECT_LIBRARY) {
513     // object libraries have no link information, so nothing to compute
514     return;
515   }
516 
517   cmComputeLinkInformation* info = target->GetLinkInformation(config);
518 
519   if (!info) {
520     cmLocalGenerator* lg = target->GetLocalGenerator();
521     std::ostringstream e;
522     e << "Exporting the target \"" << target->GetName()
523       << "\" is not "
524          "allowed since its linker language cannot be determined";
525     lg->IssueMessage(MessageType::FATAL_ERROR, e.str());
526     return;
527   }
528 
529   const cmComputeLinkInformation::ItemVector& deps = info->GetItems();
530 
531   for (auto const& dep : deps) {
532     if (!dep.Target) {
533       continue;
534     }
535     getPropertyContents(dep.Target, "COMPATIBLE_INTERFACE_BOOL",
536                         ifaceProperties);
537     getPropertyContents(dep.Target, "COMPATIBLE_INTERFACE_STRING",
538                         ifaceProperties);
539     getPropertyContents(dep.Target, "COMPATIBLE_INTERFACE_NUMBER_MIN",
540                         ifaceProperties);
541     getPropertyContents(dep.Target, "COMPATIBLE_INTERFACE_NUMBER_MAX",
542                         ifaceProperties);
543   }
544 }
545 
PopulateCompatibleInterfaceProperties(cmGeneratorTarget const * gtarget,ImportPropertyMap & properties)546 void cmExportFileGenerator::PopulateCompatibleInterfaceProperties(
547   cmGeneratorTarget const* gtarget, ImportPropertyMap& properties)
548 {
549   this->PopulateInterfaceProperty("COMPATIBLE_INTERFACE_BOOL", gtarget,
550                                   properties);
551   this->PopulateInterfaceProperty("COMPATIBLE_INTERFACE_STRING", gtarget,
552                                   properties);
553   this->PopulateInterfaceProperty("COMPATIBLE_INTERFACE_NUMBER_MIN", gtarget,
554                                   properties);
555   this->PopulateInterfaceProperty("COMPATIBLE_INTERFACE_NUMBER_MAX", gtarget,
556                                   properties);
557 
558   std::set<std::string> ifaceProperties;
559 
560   getPropertyContents(gtarget, "COMPATIBLE_INTERFACE_BOOL", ifaceProperties);
561   getPropertyContents(gtarget, "COMPATIBLE_INTERFACE_STRING", ifaceProperties);
562   getPropertyContents(gtarget, "COMPATIBLE_INTERFACE_NUMBER_MIN",
563                       ifaceProperties);
564   getPropertyContents(gtarget, "COMPATIBLE_INTERFACE_NUMBER_MAX",
565                       ifaceProperties);
566 
567   if (gtarget->GetType() != cmStateEnums::INTERFACE_LIBRARY) {
568     std::vector<std::string> configNames =
569       gtarget->Target->GetMakefile()->GetGeneratorConfigs(
570         cmMakefile::IncludeEmptyConfig);
571 
572     for (std::string const& cn : configNames) {
573       getCompatibleInterfaceProperties(gtarget, ifaceProperties, cn);
574     }
575   }
576 
577   for (std::string const& ip : ifaceProperties) {
578     this->PopulateInterfaceProperty("INTERFACE_" + ip, gtarget, properties);
579   }
580 }
581 
GenerateInterfaceProperties(const cmGeneratorTarget * target,std::ostream & os,const ImportPropertyMap & properties)582 void cmExportFileGenerator::GenerateInterfaceProperties(
583   const cmGeneratorTarget* target, std::ostream& os,
584   const ImportPropertyMap& properties)
585 {
586   if (!properties.empty()) {
587     std::string targetName =
588       cmStrCat(this->Namespace, target->GetExportName());
589     os << "set_target_properties(" << targetName << " PROPERTIES\n";
590     for (auto const& property : properties) {
591       os << "  " << property.first << " "
592          << cmExportFileGeneratorEscape(property.second) << "\n";
593     }
594     os << ")\n\n";
595   }
596 }
597 
AddTargetNamespace(std::string & input,cmGeneratorTarget const * target,std::vector<std::string> & missingTargets)598 bool cmExportFileGenerator::AddTargetNamespace(
599   std::string& input, cmGeneratorTarget const* target,
600   std::vector<std::string>& missingTargets)
601 {
602   cmGeneratorTarget::TargetOrString resolved =
603     target->ResolveTargetReference(input);
604 
605   cmGeneratorTarget* tgt = resolved.Target;
606   if (!tgt) {
607     input = resolved.String;
608     return false;
609   }
610 
611   if (tgt->IsImported()) {
612     input = tgt->GetName();
613     return true;
614   }
615   if (this->ExportedTargets.find(tgt) != this->ExportedTargets.end()) {
616     input = this->Namespace + tgt->GetExportName();
617   } else {
618     std::string namespacedTarget;
619     this->HandleMissingTarget(namespacedTarget, missingTargets, target, tgt);
620     if (!namespacedTarget.empty()) {
621       input = namespacedTarget;
622     } else {
623       input = tgt->GetName();
624     }
625   }
626   return true;
627 }
628 
ResolveTargetsInGeneratorExpressions(std::string & input,cmGeneratorTarget const * target,std::vector<std::string> & missingTargets,FreeTargetsReplace replace)629 void cmExportFileGenerator::ResolveTargetsInGeneratorExpressions(
630   std::string& input, cmGeneratorTarget const* target,
631   std::vector<std::string>& missingTargets, FreeTargetsReplace replace)
632 {
633   if (replace == NoReplaceFreeTargets) {
634     this->ResolveTargetsInGeneratorExpression(input, target, missingTargets);
635     return;
636   }
637   std::vector<std::string> parts;
638   cmGeneratorExpression::Split(input, parts);
639 
640   std::string sep;
641   input.clear();
642   for (std::string& li : parts) {
643     if (cmHasLiteralPrefix(li, CMAKE_DIRECTORY_ID_SEP)) {
644       continue;
645     }
646     if (cmGeneratorExpression::Find(li) == std::string::npos) {
647       this->AddTargetNamespace(li, target, missingTargets);
648     } else {
649       this->ResolveTargetsInGeneratorExpression(li, target, missingTargets);
650     }
651     input += sep + li;
652     sep = ";";
653   }
654 }
655 
ResolveTargetsInGeneratorExpression(std::string & input,cmGeneratorTarget const * target,std::vector<std::string> & missingTargets)656 void cmExportFileGenerator::ResolveTargetsInGeneratorExpression(
657   std::string& input, cmGeneratorTarget const* target,
658   std::vector<std::string>& missingTargets)
659 {
660   std::string::size_type pos = 0;
661   std::string::size_type lastPos = pos;
662 
663   while ((pos = input.find("$<TARGET_PROPERTY:", lastPos)) !=
664          std::string::npos) {
665     std::string::size_type nameStartPos =
666       pos + sizeof("$<TARGET_PROPERTY:") - 1;
667     std::string::size_type closePos = input.find('>', nameStartPos);
668     std::string::size_type commaPos = input.find(',', nameStartPos);
669     std::string::size_type nextOpenPos = input.find("$<", nameStartPos);
670     if (commaPos == std::string::npos    // Implied 'this' target
671         || closePos == std::string::npos // Incomplete expression.
672         || closePos < commaPos           // Implied 'this' target
673         || nextOpenPos < commaPos)       // Non-literal
674     {
675       lastPos = nameStartPos;
676       continue;
677     }
678 
679     std::string targetName =
680       input.substr(nameStartPos, commaPos - nameStartPos);
681 
682     if (this->AddTargetNamespace(targetName, target, missingTargets)) {
683       input.replace(nameStartPos, commaPos - nameStartPos, targetName);
684     }
685     lastPos = nameStartPos + targetName.size() + 1;
686   }
687 
688   std::string errorString;
689   pos = 0;
690   lastPos = pos;
691   while ((pos = input.find("$<TARGET_NAME:", lastPos)) != std::string::npos) {
692     std::string::size_type nameStartPos = pos + sizeof("$<TARGET_NAME:") - 1;
693     std::string::size_type endPos = input.find('>', nameStartPos);
694     if (endPos == std::string::npos) {
695       errorString = "$<TARGET_NAME:...> expression incomplete";
696       break;
697     }
698     std::string targetName = input.substr(nameStartPos, endPos - nameStartPos);
699     if (targetName.find("$<") != std::string::npos) {
700       errorString = "$<TARGET_NAME:...> requires its parameter to be a "
701                     "literal.";
702       break;
703     }
704     if (!this->AddTargetNamespace(targetName, target, missingTargets)) {
705       errorString = "$<TARGET_NAME:...> requires its parameter to be a "
706                     "reachable target.";
707       break;
708     }
709     input.replace(pos, endPos - pos + 1, targetName);
710     lastPos = pos + targetName.size();
711   }
712 
713   pos = 0;
714   lastPos = pos;
715   while (errorString.empty() &&
716          (pos = input.find("$<LINK_ONLY:", lastPos)) != std::string::npos) {
717     std::string::size_type nameStartPos = pos + sizeof("$<LINK_ONLY:") - 1;
718     std::string::size_type endPos = input.find('>', nameStartPos);
719     if (endPos == std::string::npos) {
720       errorString = "$<LINK_ONLY:...> expression incomplete";
721       break;
722     }
723     std::string libName = input.substr(nameStartPos, endPos - nameStartPos);
724     if (cmGeneratorExpression::IsValidTargetName(libName) &&
725         this->AddTargetNamespace(libName, target, missingTargets)) {
726       input.replace(nameStartPos, endPos - nameStartPos, libName);
727     }
728     lastPos = nameStartPos + libName.size() + 1;
729   }
730 
731   this->ReplaceInstallPrefix(input);
732 
733   if (!errorString.empty()) {
734     target->GetLocalGenerator()->IssueMessage(MessageType::FATAL_ERROR,
735                                               errorString);
736   }
737 }
738 
ReplaceInstallPrefix(std::string &)739 void cmExportFileGenerator::ReplaceInstallPrefix(std::string& /*unused*/)
740 {
741   // Do nothing
742 }
743 
SetImportLinkInterface(const std::string & config,std::string const & suffix,cmGeneratorExpression::PreprocessContext preprocessRule,cmGeneratorTarget const * target,ImportPropertyMap & properties,std::vector<std::string> & missingTargets)744 void cmExportFileGenerator::SetImportLinkInterface(
745   const std::string& config, std::string const& suffix,
746   cmGeneratorExpression::PreprocessContext preprocessRule,
747   cmGeneratorTarget const* target, ImportPropertyMap& properties,
748   std::vector<std::string>& missingTargets)
749 {
750   // Add the transitive link dependencies for this configuration.
751   cmLinkInterface const* iface = target->GetLinkInterface(config, target);
752   if (!iface) {
753     return;
754   }
755 
756   if (iface->ImplementationIsInterface) {
757     // Policy CMP0022 must not be NEW.
758     this->SetImportLinkProperty(
759       suffix, target, "IMPORTED_LINK_INTERFACE_LIBRARIES", iface->Libraries,
760       properties, missingTargets, ImportLinkPropertyTargetNames::Yes);
761     return;
762   }
763 
764   cmValue propContent;
765 
766   if (cmValue prop_suffixed =
767         target->GetProperty("LINK_INTERFACE_LIBRARIES" + suffix)) {
768     propContent = prop_suffixed;
769   } else if (cmValue prop = target->GetProperty("LINK_INTERFACE_LIBRARIES")) {
770     propContent = prop;
771   } else {
772     return;
773   }
774 
775   const bool newCMP0022Behavior =
776     target->GetPolicyStatusCMP0022() != cmPolicies::WARN &&
777     target->GetPolicyStatusCMP0022() != cmPolicies::OLD;
778 
779   if (newCMP0022Behavior && !this->ExportOld) {
780     cmLocalGenerator* lg = target->GetLocalGenerator();
781     std::ostringstream e;
782     e << "Target \"" << target->GetName()
783       << "\" has policy CMP0022 enabled, "
784          "but also has old-style LINK_INTERFACE_LIBRARIES properties "
785          "populated, but it was exported without the "
786          "EXPORT_LINK_INTERFACE_LIBRARIES to export the old-style properties";
787     lg->IssueMessage(MessageType::FATAL_ERROR, e.str());
788     return;
789   }
790 
791   if (propContent->empty()) {
792     properties["IMPORTED_LINK_INTERFACE_LIBRARIES" + suffix].clear();
793     return;
794   }
795 
796   std::string prepro =
797     cmGeneratorExpression::Preprocess(*propContent, preprocessRule);
798   if (!prepro.empty()) {
799     this->ResolveTargetsInGeneratorExpressions(prepro, target, missingTargets,
800                                                ReplaceFreeTargets);
801     properties["IMPORTED_LINK_INTERFACE_LIBRARIES" + suffix] = prepro;
802   }
803 }
804 
SetImportDetailProperties(const std::string & config,std::string const & suffix,cmGeneratorTarget * target,ImportPropertyMap & properties,std::vector<std::string> & missingTargets)805 void cmExportFileGenerator::SetImportDetailProperties(
806   const std::string& config, std::string const& suffix,
807   cmGeneratorTarget* target, ImportPropertyMap& properties,
808   std::vector<std::string>& missingTargets)
809 {
810   // Get the makefile in which to lookup target information.
811   cmMakefile* mf = target->Makefile;
812 
813   // Add the soname for unix shared libraries.
814   if (target->GetType() == cmStateEnums::SHARED_LIBRARY ||
815       target->GetType() == cmStateEnums::MODULE_LIBRARY) {
816     if (!target->IsDLLPlatform()) {
817       std::string prop;
818       std::string value;
819       if (target->HasSOName(config)) {
820         if (mf->IsOn("CMAKE_PLATFORM_HAS_INSTALLNAME")) {
821           value = this->InstallNameDir(target, config);
822         }
823         prop = "IMPORTED_SONAME";
824         value += target->GetSOName(config);
825       } else {
826         prop = "IMPORTED_NO_SONAME";
827         value = "TRUE";
828       }
829       prop += suffix;
830       properties[prop] = value;
831     }
832   }
833 
834   // Add the transitive link dependencies for this configuration.
835   if (cmLinkInterface const* iface =
836         target->GetLinkInterface(config, target)) {
837     this->SetImportLinkProperty(
838       suffix, target, "IMPORTED_LINK_INTERFACE_LANGUAGES", iface->Languages,
839       properties, missingTargets, ImportLinkPropertyTargetNames::No);
840 
841     std::vector<std::string> dummy;
842     this->SetImportLinkProperty(
843       suffix, target, "IMPORTED_LINK_DEPENDENT_LIBRARIES", iface->SharedDeps,
844       properties, dummy, ImportLinkPropertyTargetNames::Yes);
845     if (iface->Multiplicity > 0) {
846       std::string prop =
847         cmStrCat("IMPORTED_LINK_INTERFACE_MULTIPLICITY", suffix);
848       properties[prop] = std::to_string(iface->Multiplicity);
849     }
850   }
851 
852   // Add information if this target is a managed target
853   if (target->GetManagedType(config) !=
854       cmGeneratorTarget::ManagedType::Native) {
855     std::string prop = cmStrCat("IMPORTED_COMMON_LANGUAGE_RUNTIME", suffix);
856     std::string propval;
857     if (cmValue p = target->GetProperty("COMMON_LANGUAGE_RUNTIME")) {
858       propval = *p;
859     } else if (target->IsCSharpOnly()) {
860       // C# projects do not have the /clr flag, so we set the property
861       // here to mark the target as (only) managed (i.e. no .lib file
862       // to link to). Otherwise the  COMMON_LANGUAGE_RUNTIME target
863       // property would have to be set manually for C# targets to make
864       // exporting/importing work.
865       propval = "CSharp";
866     }
867     properties[prop] = propval;
868   }
869 }
870 
asString(std::string const & l)871 static std::string const& asString(std::string const& l)
872 {
873   return l;
874 }
875 
asString(cmLinkItem const & l)876 static std::string const& asString(cmLinkItem const& l)
877 {
878   return l.AsStr();
879 }
880 
881 template <typename T>
SetImportLinkProperty(std::string const & suffix,cmGeneratorTarget const * target,const std::string & propName,std::vector<T> const & entries,ImportPropertyMap & properties,std::vector<std::string> & missingTargets,ImportLinkPropertyTargetNames targetNames)882 void cmExportFileGenerator::SetImportLinkProperty(
883   std::string const& suffix, cmGeneratorTarget const* target,
884   const std::string& propName, std::vector<T> const& entries,
885   ImportPropertyMap& properties, std::vector<std::string>& missingTargets,
886   ImportLinkPropertyTargetNames targetNames)
887 {
888   // Skip the property if there are no entries.
889   if (entries.empty()) {
890     return;
891   }
892 
893   // Construct the property value.
894   std::string link_entries;
895   const char* sep = "";
896   for (T const& l : entries) {
897     // Separate this from the previous entry.
898     link_entries += sep;
899     sep = ";";
900 
901     if (targetNames == ImportLinkPropertyTargetNames::Yes) {
902       std::string temp = asString(l);
903       this->AddTargetNamespace(temp, target, missingTargets);
904       link_entries += temp;
905     } else {
906       link_entries += asString(l);
907     }
908   }
909 
910   // Store the property.
911   std::string prop = cmStrCat(propName, suffix);
912   properties[prop] = link_entries;
913 }
914 
GeneratePolicyHeaderCode(std::ostream & os)915 void cmExportFileGenerator::GeneratePolicyHeaderCode(std::ostream& os)
916 {
917   // Protect that file against use with older CMake versions.
918   /* clang-format off */
919   os << "# Generated by CMake\n\n";
920   os << "if(\"${CMAKE_MAJOR_VERSION}.${CMAKE_MINOR_VERSION}\" LESS 2.6)\n"
921      << "   message(FATAL_ERROR \"CMake >= 2.6.0 required\")\n"
922      << "endif()\n";
923   /* clang-format on */
924 
925   // Isolate the file policy level.
926   // Support CMake versions as far back as 2.6 but also support using NEW
927   // policy settings for up to CMake 3.20 (this upper limit may be reviewed
928   // and increased from time to time). This reduces the opportunity for CMake
929   // warnings when an older export file is later used with newer CMake
930   // versions.
931   /* clang-format off */
932   os << "cmake_policy(PUSH)\n"
933      << "cmake_policy(VERSION 2.6...3.20)\n";
934   /* clang-format on */
935 }
936 
GeneratePolicyFooterCode(std::ostream & os)937 void cmExportFileGenerator::GeneratePolicyFooterCode(std::ostream& os)
938 {
939   os << "cmake_policy(POP)\n";
940 }
941 
GenerateImportHeaderCode(std::ostream & os,const std::string & config)942 void cmExportFileGenerator::GenerateImportHeaderCode(std::ostream& os,
943                                                      const std::string& config)
944 {
945   os << "#----------------------------------------------------------------\n"
946      << "# Generated CMake target import file";
947   if (!config.empty()) {
948     os << " for configuration \"" << config << "\".\n";
949   } else {
950     os << ".\n";
951   }
952   os << "#----------------------------------------------------------------\n"
953      << "\n";
954   this->GenerateImportVersionCode(os);
955 }
956 
GenerateImportFooterCode(std::ostream & os)957 void cmExportFileGenerator::GenerateImportFooterCode(std::ostream& os)
958 {
959   os << "# Commands beyond this point should not need to know the version.\n"
960      << "set(CMAKE_IMPORT_FILE_VERSION)\n";
961 }
962 
GenerateImportVersionCode(std::ostream & os)963 void cmExportFileGenerator::GenerateImportVersionCode(std::ostream& os)
964 {
965   // Store an import file format version.  This will let us change the
966   // format later while still allowing old import files to work.
967   /* clang-format off */
968   os << "# Commands may need to know the format version.\n"
969      << "set(CMAKE_IMPORT_FILE_VERSION 1)\n"
970      << "\n";
971   /* clang-format on */
972 }
973 
GenerateExpectedTargetsCode(std::ostream & os,const std::string & expectedTargets)974 void cmExportFileGenerator::GenerateExpectedTargetsCode(
975   std::ostream& os, const std::string& expectedTargets)
976 {
977   /* clang-format off */
978   os << "# Protect against multiple inclusion, which would fail when already "
979         "imported targets are added once more.\n"
980         "set(_targetsDefined)\n"
981         "set(_targetsNotDefined)\n"
982         "set(_expectedTargets)\n"
983         "foreach(_expectedTarget " << expectedTargets << ")\n"
984         "  list(APPEND _expectedTargets ${_expectedTarget})\n"
985         "  if(NOT TARGET ${_expectedTarget})\n"
986         "    list(APPEND _targetsNotDefined ${_expectedTarget})\n"
987         "  endif()\n"
988         "  if(TARGET ${_expectedTarget})\n"
989         "    list(APPEND _targetsDefined ${_expectedTarget})\n"
990         "  endif()\n"
991         "endforeach()\n"
992         "if(\"${_targetsDefined}\" STREQUAL \"${_expectedTargets}\")\n"
993         "  unset(_targetsDefined)\n"
994         "  unset(_targetsNotDefined)\n"
995         "  unset(_expectedTargets)\n"
996         "  set(CMAKE_IMPORT_FILE_VERSION)\n"
997         "  cmake_policy(POP)\n"
998         "  return()\n"
999         "endif()\n"
1000         "if(NOT \"${_targetsDefined}\" STREQUAL \"\")\n"
1001         "  message(FATAL_ERROR \"Some (but not all) targets in this export "
1002         "set were already defined.\\nTargets Defined: ${_targetsDefined}\\n"
1003         "Targets not yet defined: ${_targetsNotDefined}\\n\")\n"
1004         "endif()\n"
1005         "unset(_targetsDefined)\n"
1006         "unset(_targetsNotDefined)\n"
1007         "unset(_expectedTargets)\n"
1008         "\n\n";
1009   /* clang-format on */
1010 }
1011 
GenerateImportTargetCode(std::ostream & os,cmGeneratorTarget const * target,cmStateEnums::TargetType targetType)1012 void cmExportFileGenerator::GenerateImportTargetCode(
1013   std::ostream& os, cmGeneratorTarget const* target,
1014   cmStateEnums::TargetType targetType)
1015 {
1016   // Construct the imported target name.
1017   std::string targetName = this->Namespace;
1018 
1019   targetName += target->GetExportName();
1020 
1021   // Create the imported target.
1022   os << "# Create imported target " << targetName << "\n";
1023   switch (targetType) {
1024     case cmStateEnums::EXECUTABLE:
1025       os << "add_executable(" << targetName << " IMPORTED)\n";
1026       break;
1027     case cmStateEnums::STATIC_LIBRARY:
1028       os << "add_library(" << targetName << " STATIC IMPORTED)\n";
1029       break;
1030     case cmStateEnums::SHARED_LIBRARY:
1031       os << "add_library(" << targetName << " SHARED IMPORTED)\n";
1032       break;
1033     case cmStateEnums::MODULE_LIBRARY:
1034       os << "add_library(" << targetName << " MODULE IMPORTED)\n";
1035       break;
1036     case cmStateEnums::UNKNOWN_LIBRARY:
1037       os << "add_library(" << targetName << " UNKNOWN IMPORTED)\n";
1038       break;
1039     case cmStateEnums::OBJECT_LIBRARY:
1040       os << "add_library(" << targetName << " OBJECT IMPORTED)\n";
1041       break;
1042     case cmStateEnums::INTERFACE_LIBRARY:
1043       os << "add_library(" << targetName << " INTERFACE IMPORTED)\n";
1044       break;
1045     default: // should never happen
1046       break;
1047   }
1048 
1049   // Mark the imported executable if it has exports.
1050   if (target->IsExecutableWithExports()) {
1051     os << "set_property(TARGET " << targetName
1052        << " PROPERTY ENABLE_EXPORTS 1)\n";
1053   }
1054 
1055   // Mark the imported library if it is a framework.
1056   if (target->IsFrameworkOnApple()) {
1057     os << "set_property(TARGET " << targetName << " PROPERTY FRAMEWORK 1)\n";
1058   }
1059 
1060   // Mark the imported executable if it is an application bundle.
1061   if (target->IsAppBundleOnApple()) {
1062     os << "set_property(TARGET " << targetName
1063        << " PROPERTY MACOSX_BUNDLE 1)\n";
1064   }
1065 
1066   if (target->IsCFBundleOnApple()) {
1067     os << "set_property(TARGET " << targetName << " PROPERTY BUNDLE 1)\n";
1068   }
1069 
1070   // generate DEPRECATION
1071   if (target->IsDeprecated()) {
1072     os << "set_property(TARGET " << targetName << " PROPERTY DEPRECATION "
1073        << cmExportFileGeneratorEscape(target->GetDeprecation()) << ")\n";
1074   }
1075   os << "\n";
1076 }
1077 
GenerateImportPropertyCode(std::ostream & os,const std::string & config,cmGeneratorTarget const * target,ImportPropertyMap const & properties)1078 void cmExportFileGenerator::GenerateImportPropertyCode(
1079   std::ostream& os, const std::string& config, cmGeneratorTarget const* target,
1080   ImportPropertyMap const& properties)
1081 {
1082   // Construct the imported target name.
1083   std::string targetName = this->Namespace;
1084 
1085   targetName += target->GetExportName();
1086 
1087   // Set the import properties.
1088   os << "# Import target \"" << targetName << "\" for configuration \""
1089      << config << "\"\n";
1090   os << "set_property(TARGET " << targetName
1091      << " APPEND PROPERTY IMPORTED_CONFIGURATIONS ";
1092   if (!config.empty()) {
1093     os << cmSystemTools::UpperCase(config);
1094   } else {
1095     os << "NOCONFIG";
1096   }
1097   os << ")\n";
1098   os << "set_target_properties(" << targetName << " PROPERTIES\n";
1099   for (auto const& property : properties) {
1100     os << "  " << property.first << " "
1101        << cmExportFileGeneratorEscape(property.second) << "\n";
1102   }
1103   os << "  )\n"
1104      << "\n";
1105 }
1106 
GenerateMissingTargetsCheckCode(std::ostream & os,const std::vector<std::string> & missingTargets)1107 void cmExportFileGenerator::GenerateMissingTargetsCheckCode(
1108   std::ostream& os, const std::vector<std::string>& missingTargets)
1109 {
1110   if (missingTargets.empty()) {
1111     /* clang-format off */
1112     os << "# This file does not depend on other imported targets which have\n"
1113           "# been exported from the same project but in a separate "
1114             "export set.\n\n";
1115     /* clang-format on */
1116     return;
1117   }
1118   /* clang-format off */
1119   os << "# Make sure the targets which have been exported in some other\n"
1120         "# export set exist.\n"
1121         "unset(${CMAKE_FIND_PACKAGE_NAME}_NOT_FOUND_MESSAGE_targets)\n"
1122         "foreach(_target ";
1123   /* clang-format on */
1124   std::set<std::string> emitted;
1125   for (std::string const& missingTarget : missingTargets) {
1126     if (emitted.insert(missingTarget).second) {
1127       os << "\"" << missingTarget << "\" ";
1128     }
1129   }
1130   /* clang-format off */
1131   os << ")\n"
1132         "  if(NOT TARGET \"${_target}\" )\n"
1133         "    set(${CMAKE_FIND_PACKAGE_NAME}_NOT_FOUND_MESSAGE_targets \""
1134         "${${CMAKE_FIND_PACKAGE_NAME}_NOT_FOUND_MESSAGE_targets} ${_target}\")"
1135         "\n"
1136         "  endif()\n"
1137         "endforeach()\n"
1138         "\n"
1139         "if(DEFINED ${CMAKE_FIND_PACKAGE_NAME}_NOT_FOUND_MESSAGE_targets)\n"
1140         "  if(CMAKE_FIND_PACKAGE_NAME)\n"
1141         "    set( ${CMAKE_FIND_PACKAGE_NAME}_FOUND FALSE)\n"
1142         "    set( ${CMAKE_FIND_PACKAGE_NAME}_NOT_FOUND_MESSAGE "
1143         "\"The following imported targets are "
1144         "referenced, but are missing: "
1145                  "${${CMAKE_FIND_PACKAGE_NAME}_NOT_FOUND_MESSAGE_targets}\")\n"
1146         "  else()\n"
1147         "    message(FATAL_ERROR \"The following imported targets are "
1148         "referenced, but are missing: "
1149                 "${${CMAKE_FIND_PACKAGE_NAME}_NOT_FOUND_MESSAGE_targets}\")\n"
1150         "  endif()\n"
1151         "endif()\n"
1152         "unset(${CMAKE_FIND_PACKAGE_NAME}_NOT_FOUND_MESSAGE_targets)\n"
1153         "\n";
1154   /* clang-format on */
1155 }
1156 
GenerateImportedFileCheckLoop(std::ostream & os)1157 void cmExportFileGenerator::GenerateImportedFileCheckLoop(std::ostream& os)
1158 {
1159   // Add code which verifies at cmake time that the file which is being
1160   // imported actually exists on disk. This should in theory always be theory
1161   // case, but still when packages are split into normal and development
1162   // packages this might get broken (e.g. the Config.cmake could be part of
1163   // the non-development package, something similar happened to me without
1164   // on SUSE with a mysql pkg-config file, which claimed everything is fine,
1165   // but the development package was not installed.).
1166   /* clang-format off */
1167   os << "# Loop over all imported files and verify that they actually exist\n"
1168         "foreach(target ${_IMPORT_CHECK_TARGETS} )\n"
1169         "  foreach(file ${_IMPORT_CHECK_FILES_FOR_${target}} )\n"
1170         "    if(NOT EXISTS \"${file}\" )\n"
1171         "      message(FATAL_ERROR \"The imported target \\\"${target}\\\""
1172         " references the file\n"
1173         "   \\\"${file}\\\"\n"
1174         "but this file does not exist.  Possible reasons include:\n"
1175         "* The file was deleted, renamed, or moved to another location.\n"
1176         "* An install or uninstall procedure did not complete successfully.\n"
1177         "* The installation package was faulty and contained\n"
1178         "   \\\"${CMAKE_CURRENT_LIST_FILE}\\\"\n"
1179         "but not all the files it references.\n"
1180         "\")\n"
1181         "    endif()\n"
1182         "  endforeach()\n"
1183         "  unset(_IMPORT_CHECK_FILES_FOR_${target})\n"
1184         "endforeach()\n"
1185         "unset(_IMPORT_CHECK_TARGETS)\n"
1186         "\n";
1187   /* clang-format on */
1188 }
1189 
GenerateImportedFileChecksCode(std::ostream & os,cmGeneratorTarget * target,ImportPropertyMap const & properties,const std::set<std::string> & importedLocations)1190 void cmExportFileGenerator::GenerateImportedFileChecksCode(
1191   std::ostream& os, cmGeneratorTarget* target,
1192   ImportPropertyMap const& properties,
1193   const std::set<std::string>& importedLocations)
1194 {
1195   // Construct the imported target name.
1196   std::string targetName = cmStrCat(this->Namespace, target->GetExportName());
1197 
1198   os << "list(APPEND _IMPORT_CHECK_TARGETS " << targetName
1199      << " )\n"
1200         "list(APPEND _IMPORT_CHECK_FILES_FOR_"
1201      << targetName << " ";
1202 
1203   for (std::string const& li : importedLocations) {
1204     auto pi = properties.find(li);
1205     if (pi != properties.end()) {
1206       os << cmExportFileGeneratorEscape(pi->second) << " ";
1207     }
1208   }
1209 
1210   os << ")\n\n";
1211 }
1212 
PopulateExportProperties(cmGeneratorTarget const * gte,ImportPropertyMap & properties,std::string & errorMessage)1213 bool cmExportFileGenerator::PopulateExportProperties(
1214   cmGeneratorTarget const* gte, ImportPropertyMap& properties,
1215   std::string& errorMessage)
1216 {
1217   const auto& targetProperties = gte->Target->GetProperties();
1218   if (cmValue exportProperties =
1219         targetProperties.GetPropertyValue("EXPORT_PROPERTIES")) {
1220     for (auto& prop : cmExpandedList(*exportProperties)) {
1221       /* Black list reserved properties */
1222       if (cmHasLiteralPrefix(prop, "IMPORTED_") ||
1223           cmHasLiteralPrefix(prop, "INTERFACE_")) {
1224         std::ostringstream e;
1225         e << "Target \"" << gte->Target->GetName() << "\" contains property \""
1226           << prop << "\" in EXPORT_PROPERTIES but IMPORTED_* and INTERFACE_* "
1227           << "properties are reserved.";
1228         errorMessage = e.str();
1229         return false;
1230       }
1231       cmValue propertyValue = targetProperties.GetPropertyValue(prop);
1232       if (!propertyValue) {
1233         // Asked to export a property that isn't defined on the target. Do not
1234         // consider this an error, there's just nothing to export.
1235         continue;
1236       }
1237       std::string evaluatedValue = cmGeneratorExpression::Preprocess(
1238         *propertyValue, cmGeneratorExpression::StripAllGeneratorExpressions);
1239       if (evaluatedValue != *propertyValue) {
1240         std::ostringstream e;
1241         e << "Target \"" << gte->Target->GetName() << "\" contains property \""
1242           << prop << "\" in EXPORT_PROPERTIES but this property contains a "
1243           << "generator expression. This is not allowed.";
1244         errorMessage = e.str();
1245         return false;
1246       }
1247       properties[prop] = *propertyValue;
1248     }
1249   }
1250   return true;
1251 }
1252