cmExportFileGenerator.cxx 48 KB

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