cmExportFileGenerator.cxx 46 KB

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