cmExportFileGenerator.cxx 55 KB

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