cmExportFileGenerator.cxx 45 KB

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