cmExportFileGenerator.cxx 50 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488
  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. std::string& includesDestinationDirs)
  343. {
  344. assert(preprocessRule == cmGeneratorExpression::InstallInterface);
  345. includesDestinationDirs.clear();
  346. const char* propName = "INTERFACE_INCLUDE_DIRECTORIES";
  347. cmValue input = target->GetProperty(propName);
  348. cmGeneratorExpression ge(*target->Makefile->GetCMakeInstance());
  349. std::string dirs = cmGeneratorExpression::Preprocess(
  350. cmList::to_string(target->Target->GetInstallIncludeDirectoriesEntries(te)),
  351. preprocessRule, true);
  352. this->ReplaceInstallPrefix(dirs);
  353. std::unique_ptr<cmCompiledGeneratorExpression> cge = ge.Parse(dirs);
  354. std::string exportDirs =
  355. cge->Evaluate(target->GetLocalGenerator(), "", target);
  356. if (cge->GetHadContextSensitiveCondition()) {
  357. cmLocalGenerator* lg = target->GetLocalGenerator();
  358. std::ostringstream e;
  359. e << "Target \"" << target->GetName()
  360. << "\" is installed with "
  361. "INCLUDES DESTINATION set to a context sensitive path. Paths which "
  362. "depend on the configuration, policy values or the link interface "
  363. "are "
  364. "not supported. Consider using target_include_directories instead.";
  365. lg->IssueMessage(MessageType::FATAL_ERROR, e.str());
  366. return;
  367. }
  368. if (!input && exportDirs.empty()) {
  369. return;
  370. }
  371. if ((input && input->empty()) && exportDirs.empty()) {
  372. // Set to empty
  373. properties[propName].clear();
  374. return;
  375. }
  376. prefixItems(exportDirs);
  377. includesDestinationDirs = exportDirs;
  378. std::string includes = (input ? *input : "");
  379. const char* sep = input ? ";" : "";
  380. includes += sep + exportDirs;
  381. std::string prepro =
  382. cmGeneratorExpression::Preprocess(includes, preprocessRule, true);
  383. if (!prepro.empty()) {
  384. this->ResolveTargetsInGeneratorExpressions(prepro, target);
  385. if (!checkInterfaceDirs(prepro, target, propName)) {
  386. return;
  387. }
  388. properties[propName] = prepro;
  389. }
  390. }
  391. void cmExportFileGenerator::PopulateLinkDependsInterface(
  392. cmGeneratorTarget const* gt,
  393. cmGeneratorExpression::PreprocessContext preprocessRule,
  394. ImportPropertyMap& properties)
  395. {
  396. assert(preprocessRule == cmGeneratorExpression::InstallInterface);
  397. const char* propName = "INTERFACE_LINK_DEPENDS";
  398. cmValue input = gt->GetProperty(propName);
  399. if (!input) {
  400. return;
  401. }
  402. if (input->empty()) {
  403. properties[propName].clear();
  404. return;
  405. }
  406. std::string prepro =
  407. cmGeneratorExpression::Preprocess(*input, preprocessRule, true);
  408. if (!prepro.empty()) {
  409. this->ResolveTargetsInGeneratorExpressions(prepro, gt);
  410. if (!checkInterfaceDirs(prepro, gt, propName)) {
  411. return;
  412. }
  413. properties[propName] = prepro;
  414. }
  415. }
  416. void cmExportFileGenerator::PopulateLinkDirectoriesInterface(
  417. cmGeneratorTarget const* gt,
  418. cmGeneratorExpression::PreprocessContext preprocessRule,
  419. ImportPropertyMap& properties)
  420. {
  421. assert(preprocessRule == cmGeneratorExpression::InstallInterface);
  422. const char* propName = "INTERFACE_LINK_DIRECTORIES";
  423. cmValue input = gt->GetProperty(propName);
  424. if (!input) {
  425. return;
  426. }
  427. if (input->empty()) {
  428. properties[propName].clear();
  429. return;
  430. }
  431. std::string prepro =
  432. cmGeneratorExpression::Preprocess(*input, preprocessRule, true);
  433. if (!prepro.empty()) {
  434. this->ResolveTargetsInGeneratorExpressions(prepro, gt);
  435. if (!checkInterfaceDirs(prepro, gt, propName)) {
  436. return;
  437. }
  438. properties[propName] = prepro;
  439. }
  440. }
  441. void cmExportFileGenerator::PopulateInterfaceProperty(
  442. const std::string& propName, cmGeneratorTarget const* target,
  443. cmGeneratorExpression::PreprocessContext preprocessRule,
  444. ImportPropertyMap& properties)
  445. {
  446. this->PopulateInterfaceProperty(propName, propName, target, preprocessRule,
  447. properties);
  448. }
  449. static void getPropertyContents(cmGeneratorTarget const* tgt,
  450. const std::string& prop,
  451. std::set<std::string>& ifaceProperties)
  452. {
  453. cmValue p = tgt->GetProperty(prop);
  454. if (!p) {
  455. return;
  456. }
  457. cmList content{ *p };
  458. ifaceProperties.insert(content.begin(), content.end());
  459. }
  460. static void getCompatibleInterfaceProperties(
  461. cmGeneratorTarget const* target, std::set<std::string>& ifaceProperties,
  462. const std::string& config)
  463. {
  464. if (target->GetType() == cmStateEnums::OBJECT_LIBRARY) {
  465. // object libraries have no link information, so nothing to compute
  466. return;
  467. }
  468. cmComputeLinkInformation* info = target->GetLinkInformation(config);
  469. if (!info) {
  470. cmLocalGenerator* lg = target->GetLocalGenerator();
  471. std::ostringstream e;
  472. e << "Exporting the target \"" << target->GetName()
  473. << "\" is not "
  474. "allowed since its linker language cannot be determined";
  475. lg->IssueMessage(MessageType::FATAL_ERROR, e.str());
  476. return;
  477. }
  478. const cmComputeLinkInformation::ItemVector& deps = info->GetItems();
  479. for (auto const& dep : deps) {
  480. if (!dep.Target || dep.Target->GetType() == cmStateEnums::OBJECT_LIBRARY) {
  481. continue;
  482. }
  483. getPropertyContents(dep.Target, "COMPATIBLE_INTERFACE_BOOL",
  484. ifaceProperties);
  485. getPropertyContents(dep.Target, "COMPATIBLE_INTERFACE_STRING",
  486. ifaceProperties);
  487. getPropertyContents(dep.Target, "COMPATIBLE_INTERFACE_NUMBER_MIN",
  488. ifaceProperties);
  489. getPropertyContents(dep.Target, "COMPATIBLE_INTERFACE_NUMBER_MAX",
  490. ifaceProperties);
  491. }
  492. }
  493. void cmExportFileGenerator::PopulateCompatibleInterfaceProperties(
  494. cmGeneratorTarget const* gtarget, ImportPropertyMap& properties)
  495. {
  496. this->PopulateInterfaceProperty("COMPATIBLE_INTERFACE_BOOL", gtarget,
  497. properties);
  498. this->PopulateInterfaceProperty("COMPATIBLE_INTERFACE_STRING", gtarget,
  499. properties);
  500. this->PopulateInterfaceProperty("COMPATIBLE_INTERFACE_NUMBER_MIN", gtarget,
  501. properties);
  502. this->PopulateInterfaceProperty("COMPATIBLE_INTERFACE_NUMBER_MAX", gtarget,
  503. properties);
  504. std::set<std::string> ifaceProperties;
  505. getPropertyContents(gtarget, "COMPATIBLE_INTERFACE_BOOL", ifaceProperties);
  506. getPropertyContents(gtarget, "COMPATIBLE_INTERFACE_STRING", ifaceProperties);
  507. getPropertyContents(gtarget, "COMPATIBLE_INTERFACE_NUMBER_MIN",
  508. ifaceProperties);
  509. getPropertyContents(gtarget, "COMPATIBLE_INTERFACE_NUMBER_MAX",
  510. ifaceProperties);
  511. if (gtarget->GetType() != cmStateEnums::INTERFACE_LIBRARY) {
  512. std::vector<std::string> configNames =
  513. gtarget->Target->GetMakefile()->GetGeneratorConfigs(
  514. cmMakefile::IncludeEmptyConfig);
  515. for (std::string const& cn : configNames) {
  516. getCompatibleInterfaceProperties(gtarget, ifaceProperties, cn);
  517. }
  518. }
  519. for (std::string const& ip : ifaceProperties) {
  520. this->PopulateInterfaceProperty("INTERFACE_" + ip, gtarget, properties);
  521. }
  522. }
  523. void cmExportFileGenerator::GenerateInterfaceProperties(
  524. const cmGeneratorTarget* target, std::ostream& os,
  525. const ImportPropertyMap& properties)
  526. {
  527. if (!properties.empty()) {
  528. std::string targetName =
  529. cmStrCat(this->Namespace, target->GetExportName());
  530. os << "set_target_properties(" << targetName << " PROPERTIES\n";
  531. for (auto const& property : properties) {
  532. os << " " << property.first << " "
  533. << cmExportFileGeneratorEscape(property.second) << "\n";
  534. }
  535. os << ")\n\n";
  536. }
  537. }
  538. bool cmExportFileGenerator::AddTargetNamespace(std::string& input,
  539. cmGeneratorTarget const* target,
  540. cmLocalGenerator const* lg)
  541. {
  542. cmGeneratorTarget::TargetOrString resolved =
  543. target->ResolveTargetReference(input, lg);
  544. cmGeneratorTarget* tgt = resolved.Target;
  545. if (!tgt) {
  546. input = resolved.String;
  547. return false;
  548. }
  549. if (tgt->IsImported()) {
  550. input = tgt->GetName();
  551. return true;
  552. }
  553. if (this->ExportedTargets.find(tgt) != this->ExportedTargets.end()) {
  554. input = this->Namespace + tgt->GetExportName();
  555. } else {
  556. std::string namespacedTarget;
  557. this->HandleMissingTarget(namespacedTarget, target, tgt);
  558. if (!namespacedTarget.empty()) {
  559. input = namespacedTarget;
  560. } else {
  561. input = tgt->GetName();
  562. }
  563. }
  564. return true;
  565. }
  566. void cmExportFileGenerator::ResolveTargetsInGeneratorExpressions(
  567. std::string& input, cmGeneratorTarget const* target,
  568. FreeTargetsReplace replace)
  569. {
  570. cmLocalGenerator const* lg = target->GetLocalGenerator();
  571. if (replace == NoReplaceFreeTargets) {
  572. this->ResolveTargetsInGeneratorExpression(input, target, lg);
  573. return;
  574. }
  575. std::vector<std::string> parts;
  576. cmGeneratorExpression::Split(input, parts);
  577. std::string sep;
  578. input.clear();
  579. for (std::string& li : parts) {
  580. if (target->IsLinkLookupScope(li, lg)) {
  581. continue;
  582. }
  583. if (cmGeneratorExpression::Find(li) == std::string::npos) {
  584. this->AddTargetNamespace(li, target, lg);
  585. } else {
  586. this->ResolveTargetsInGeneratorExpression(li, target, lg);
  587. }
  588. input += sep + li;
  589. sep = ";";
  590. }
  591. }
  592. void cmExportFileGenerator::ResolveTargetsInGeneratorExpression(
  593. std::string& input, cmGeneratorTarget const* target,
  594. cmLocalGenerator const* lg)
  595. {
  596. std::string::size_type pos = 0;
  597. std::string::size_type lastPos = pos;
  598. while ((pos = input.find("$<TARGET_PROPERTY:", lastPos)) !=
  599. std::string::npos) {
  600. std::string::size_type nameStartPos = pos + cmStrLen("$<TARGET_PROPERTY:");
  601. std::string::size_type closePos = input.find('>', nameStartPos);
  602. std::string::size_type commaPos = input.find(',', nameStartPos);
  603. std::string::size_type nextOpenPos = input.find("$<", nameStartPos);
  604. if (commaPos == std::string::npos // Implied 'this' target
  605. || closePos == std::string::npos // Incomplete expression.
  606. || closePos < commaPos // Implied 'this' target
  607. || nextOpenPos < commaPos) // Non-literal
  608. {
  609. lastPos = nameStartPos;
  610. continue;
  611. }
  612. std::string targetName =
  613. input.substr(nameStartPos, commaPos - nameStartPos);
  614. if (this->AddTargetNamespace(targetName, target, lg)) {
  615. input.replace(nameStartPos, commaPos - nameStartPos, targetName);
  616. }
  617. lastPos = nameStartPos + targetName.size() + 1;
  618. }
  619. std::string errorString;
  620. pos = 0;
  621. lastPos = pos;
  622. while ((pos = input.find("$<TARGET_NAME:", lastPos)) != std::string::npos) {
  623. std::string::size_type nameStartPos = pos + cmStrLen("$<TARGET_NAME:");
  624. std::string::size_type endPos = input.find('>', nameStartPos);
  625. if (endPos == std::string::npos) {
  626. errorString = "$<TARGET_NAME:...> expression incomplete";
  627. break;
  628. }
  629. std::string targetName = input.substr(nameStartPos, endPos - nameStartPos);
  630. if (targetName.find("$<") != std::string::npos) {
  631. errorString = "$<TARGET_NAME:...> requires its parameter to be a "
  632. "literal.";
  633. break;
  634. }
  635. if (!this->AddTargetNamespace(targetName, target, lg)) {
  636. errorString = "$<TARGET_NAME:...> requires its parameter to be a "
  637. "reachable target.";
  638. break;
  639. }
  640. input.replace(pos, endPos - pos + 1, targetName);
  641. lastPos = pos + targetName.size();
  642. }
  643. pos = 0;
  644. lastPos = pos;
  645. while (errorString.empty() &&
  646. (pos = input.find("$<LINK_ONLY:", lastPos)) != std::string::npos) {
  647. std::string::size_type nameStartPos = pos + cmStrLen("$<LINK_ONLY:");
  648. std::string::size_type endPos = input.find('>', nameStartPos);
  649. if (endPos == std::string::npos) {
  650. errorString = "$<LINK_ONLY:...> expression incomplete";
  651. break;
  652. }
  653. std::string libName = input.substr(nameStartPos, endPos - nameStartPos);
  654. if (cmGeneratorExpression::IsValidTargetName(libName) &&
  655. this->AddTargetNamespace(libName, target, lg)) {
  656. input.replace(nameStartPos, endPos - nameStartPos, libName);
  657. }
  658. lastPos = nameStartPos + libName.size() + 1;
  659. }
  660. while (errorString.empty() &&
  661. (pos = input.find("$<COMPILE_ONLY:", lastPos)) != std::string::npos) {
  662. std::string::size_type nameStartPos = pos + cmStrLen("$<COMPILE_ONLY:");
  663. std::string::size_type endPos = input.find('>', nameStartPos);
  664. if (endPos == std::string::npos) {
  665. errorString = "$<COMPILE_ONLY:...> expression incomplete";
  666. break;
  667. }
  668. std::string libName = input.substr(nameStartPos, endPos - nameStartPos);
  669. if (cmGeneratorExpression::IsValidTargetName(libName) &&
  670. this->AddTargetNamespace(libName, target, lg)) {
  671. input.replace(nameStartPos, endPos - nameStartPos, libName);
  672. }
  673. lastPos = nameStartPos + libName.size() + 1;
  674. }
  675. this->ReplaceInstallPrefix(input);
  676. if (!errorString.empty()) {
  677. target->GetLocalGenerator()->IssueMessage(MessageType::FATAL_ERROR,
  678. errorString);
  679. }
  680. }
  681. void cmExportFileGenerator::ReplaceInstallPrefix(std::string& /*unused*/)
  682. {
  683. // Do nothing
  684. }
  685. void cmExportFileGenerator::SetImportLinkInterface(
  686. const std::string& config, std::string const& suffix,
  687. cmGeneratorExpression::PreprocessContext preprocessRule,
  688. cmGeneratorTarget const* target, ImportPropertyMap& properties)
  689. {
  690. // Add the transitive link dependencies for this configuration.
  691. cmLinkInterface const* iface = target->GetLinkInterface(config, target);
  692. if (!iface) {
  693. return;
  694. }
  695. if (iface->ImplementationIsInterface) {
  696. // Policy CMP0022 must not be NEW.
  697. this->SetImportLinkProperty(
  698. suffix, target, "IMPORTED_LINK_INTERFACE_LIBRARIES", iface->Libraries,
  699. properties, ImportLinkPropertyTargetNames::Yes);
  700. return;
  701. }
  702. cmValue propContent;
  703. if (cmValue prop_suffixed =
  704. target->GetProperty("LINK_INTERFACE_LIBRARIES" + suffix)) {
  705. propContent = prop_suffixed;
  706. } else if (cmValue prop = target->GetProperty("LINK_INTERFACE_LIBRARIES")) {
  707. propContent = prop;
  708. } else {
  709. return;
  710. }
  711. const bool newCMP0022Behavior =
  712. target->GetPolicyStatusCMP0022() != cmPolicies::WARN &&
  713. target->GetPolicyStatusCMP0022() != cmPolicies::OLD;
  714. if (newCMP0022Behavior && !this->ExportOld) {
  715. cmLocalGenerator* lg = target->GetLocalGenerator();
  716. std::ostringstream e;
  717. e << "Target \"" << target->GetName()
  718. << "\" has policy CMP0022 enabled, "
  719. "but also has old-style LINK_INTERFACE_LIBRARIES properties "
  720. "populated, but it was exported without the "
  721. "EXPORT_LINK_INTERFACE_LIBRARIES to export the old-style properties";
  722. lg->IssueMessage(MessageType::FATAL_ERROR, e.str());
  723. return;
  724. }
  725. if (propContent->empty()) {
  726. properties["IMPORTED_LINK_INTERFACE_LIBRARIES" + suffix].clear();
  727. return;
  728. }
  729. std::string prepro =
  730. cmGeneratorExpression::Preprocess(*propContent, preprocessRule);
  731. if (!prepro.empty()) {
  732. this->ResolveTargetsInGeneratorExpressions(prepro, target,
  733. ReplaceFreeTargets);
  734. properties["IMPORTED_LINK_INTERFACE_LIBRARIES" + suffix] = prepro;
  735. }
  736. }
  737. void cmExportFileGenerator::SetImportDetailProperties(
  738. const std::string& config, std::string const& suffix,
  739. cmGeneratorTarget* target, ImportPropertyMap& properties)
  740. {
  741. // Get the makefile in which to lookup target information.
  742. cmMakefile* mf = target->Makefile;
  743. // Add the soname for unix shared libraries.
  744. if (target->GetType() == cmStateEnums::SHARED_LIBRARY ||
  745. target->GetType() == cmStateEnums::MODULE_LIBRARY) {
  746. if (!target->IsDLLPlatform()) {
  747. std::string prop;
  748. std::string value;
  749. if (target->HasSOName(config)) {
  750. if (mf->IsOn("CMAKE_PLATFORM_HAS_INSTALLNAME")) {
  751. value = this->InstallNameDir(target, config);
  752. }
  753. prop = "IMPORTED_SONAME";
  754. value += target->GetSOName(config);
  755. } else {
  756. prop = "IMPORTED_NO_SONAME";
  757. value = "TRUE";
  758. }
  759. prop += suffix;
  760. properties[prop] = value;
  761. }
  762. }
  763. // Add the transitive link dependencies for this configuration.
  764. if (cmLinkInterface const* iface =
  765. target->GetLinkInterface(config, target)) {
  766. this->SetImportLinkProperty(
  767. suffix, target, "IMPORTED_LINK_INTERFACE_LANGUAGES", iface->Languages,
  768. properties, ImportLinkPropertyTargetNames::No);
  769. // Export IMPORTED_LINK_DEPENDENT_LIBRARIES to help consuming linkers
  770. // find private dependencies of shared libraries.
  771. std::size_t oldMissingTargetsSize = this->MissingTargets.size();
  772. this->SetImportLinkProperty(
  773. suffix, target, "IMPORTED_LINK_DEPENDENT_LIBRARIES", iface->SharedDeps,
  774. properties, ImportLinkPropertyTargetNames::Yes);
  775. // Avoid enforcing shared library private dependencies as public package
  776. // dependencies by ignoring missing targets added for them.
  777. this->MissingTargets.resize(oldMissingTargetsSize);
  778. if (iface->Multiplicity > 0) {
  779. std::string prop =
  780. cmStrCat("IMPORTED_LINK_INTERFACE_MULTIPLICITY", suffix);
  781. properties[prop] = std::to_string(iface->Multiplicity);
  782. }
  783. }
  784. // Add information if this target is a managed target
  785. if (target->GetManagedType(config) !=
  786. cmGeneratorTarget::ManagedType::Native) {
  787. std::string prop = cmStrCat("IMPORTED_COMMON_LANGUAGE_RUNTIME", suffix);
  788. std::string propval;
  789. if (cmValue p = target->GetProperty("COMMON_LANGUAGE_RUNTIME")) {
  790. propval = *p;
  791. } else if (target->IsCSharpOnly()) {
  792. // C# projects do not have the /clr flag, so we set the property
  793. // here to mark the target as (only) managed (i.e. no .lib file
  794. // to link to). Otherwise the COMMON_LANGUAGE_RUNTIME target
  795. // property would have to be set manually for C# targets to make
  796. // exporting/importing work.
  797. propval = "CSharp";
  798. }
  799. properties[prop] = propval;
  800. }
  801. }
  802. static std::string const& asString(std::string const& l)
  803. {
  804. return l;
  805. }
  806. static std::string const& asString(cmLinkItem const& l)
  807. {
  808. return l.AsStr();
  809. }
  810. template <typename T>
  811. void cmExportFileGenerator::SetImportLinkProperty(
  812. std::string const& suffix, cmGeneratorTarget const* target,
  813. const std::string& propName, std::vector<T> const& entries,
  814. ImportPropertyMap& properties, ImportLinkPropertyTargetNames targetNames)
  815. {
  816. // Skip the property if there are no entries.
  817. if (entries.empty()) {
  818. return;
  819. }
  820. cmLocalGenerator const* lg = target->GetLocalGenerator();
  821. // Construct the property value.
  822. std::string link_entries;
  823. const char* sep = "";
  824. for (T const& l : entries) {
  825. // Separate this from the previous entry.
  826. link_entries += sep;
  827. sep = ";";
  828. if (targetNames == ImportLinkPropertyTargetNames::Yes) {
  829. std::string temp = asString(l);
  830. this->AddTargetNamespace(temp, target, lg);
  831. link_entries += temp;
  832. } else {
  833. link_entries += asString(l);
  834. }
  835. }
  836. // Store the property.
  837. std::string prop = cmStrCat(propName, suffix);
  838. properties[prop] = link_entries;
  839. }
  840. void cmExportFileGenerator::GeneratePolicyHeaderCode(std::ostream& os)
  841. {
  842. // Protect that file against use with older CMake versions.
  843. /* clang-format off */
  844. os << "# Generated by CMake\n\n";
  845. os << "if(\"${CMAKE_MAJOR_VERSION}.${CMAKE_MINOR_VERSION}\" LESS 2.8)\n"
  846. << " message(FATAL_ERROR \"CMake >= 2.8.0 required\")\n"
  847. << "endif()\n"
  848. << "if(CMAKE_VERSION VERSION_LESS \"2.8.3\")\n"
  849. << " message(FATAL_ERROR \"CMake >= 2.8.3 required\")\n"
  850. << "endif()\n";
  851. /* clang-format on */
  852. // Isolate the file policy level.
  853. // Support CMake versions as far back as 2.6 but also support using NEW
  854. // policy settings for up to CMake 3.26 (this upper limit may be reviewed
  855. // and increased from time to time). This reduces the opportunity for CMake
  856. // warnings when an older export file is later used with newer CMake
  857. // versions.
  858. /* clang-format off */
  859. os << "cmake_policy(PUSH)\n"
  860. << "cmake_policy(VERSION 2.8.3...3.26)\n";
  861. /* clang-format on */
  862. }
  863. void cmExportFileGenerator::GeneratePolicyFooterCode(std::ostream& os)
  864. {
  865. os << "cmake_policy(POP)\n";
  866. }
  867. void cmExportFileGenerator::GenerateImportHeaderCode(std::ostream& os,
  868. const std::string& config)
  869. {
  870. os << "#----------------------------------------------------------------\n"
  871. << "# Generated CMake target import file";
  872. if (!config.empty()) {
  873. os << " for configuration \"" << config << "\".\n";
  874. } else {
  875. os << ".\n";
  876. }
  877. os << "#----------------------------------------------------------------\n"
  878. << "\n";
  879. this->GenerateImportVersionCode(os);
  880. }
  881. void cmExportFileGenerator::GenerateImportFooterCode(std::ostream& os)
  882. {
  883. os << "# Commands beyond this point should not need to know the version.\n"
  884. << "set(CMAKE_IMPORT_FILE_VERSION)\n";
  885. }
  886. void cmExportFileGenerator::GenerateImportVersionCode(std::ostream& os)
  887. {
  888. // Store an import file format version. This will let us change the
  889. // format later while still allowing old import files to work.
  890. /* clang-format off */
  891. os << "# Commands may need to know the format version.\n"
  892. << "set(CMAKE_IMPORT_FILE_VERSION 1)\n"
  893. << "\n";
  894. /* clang-format on */
  895. }
  896. void cmExportFileGenerator::GenerateExpectedTargetsCode(
  897. std::ostream& os, const std::string& expectedTargets)
  898. {
  899. /* clang-format off */
  900. os << "# Protect against multiple inclusion, which would fail when already "
  901. "imported targets are added once more.\n"
  902. "set(_cmake_targets_defined \"\")\n"
  903. "set(_cmake_targets_not_defined \"\")\n"
  904. "set(_cmake_expected_targets \"\")\n"
  905. "foreach(_cmake_expected_target IN ITEMS " << expectedTargets << ")\n"
  906. " list(APPEND _cmake_expected_targets \"${_cmake_expected_target}\")\n"
  907. " if(TARGET \"${_cmake_expected_target}\")\n"
  908. " list(APPEND _cmake_targets_defined \"${_cmake_expected_target}\")\n"
  909. " else()\n"
  910. " list(APPEND _cmake_targets_not_defined \"${_cmake_expected_target}\")\n"
  911. " endif()\n"
  912. "endforeach()\n"
  913. "unset(_cmake_expected_target)\n"
  914. "if(_cmake_targets_defined STREQUAL _cmake_expected_targets)\n"
  915. " unset(_cmake_targets_defined)\n"
  916. " unset(_cmake_targets_not_defined)\n"
  917. " unset(_cmake_expected_targets)\n"
  918. " unset(CMAKE_IMPORT_FILE_VERSION)\n"
  919. " cmake_policy(POP)\n"
  920. " return()\n"
  921. "endif()\n"
  922. "if(NOT _cmake_targets_defined STREQUAL \"\")\n"
  923. " string(REPLACE \";\" \", \" _cmake_targets_defined_text \"${_cmake_targets_defined}\")\n"
  924. " string(REPLACE \";\" \", \" _cmake_targets_not_defined_text \"${_cmake_targets_not_defined}\")\n"
  925. " message(FATAL_ERROR \"Some (but not all) targets in this export "
  926. "set were already defined.\\nTargets Defined: ${_cmake_targets_defined_text}\\n"
  927. "Targets not yet defined: ${_cmake_targets_not_defined_text}\\n\")\n"
  928. "endif()\n"
  929. "unset(_cmake_targets_defined)\n"
  930. "unset(_cmake_targets_not_defined)\n"
  931. "unset(_cmake_expected_targets)\n"
  932. "\n\n";
  933. /* clang-format on */
  934. }
  935. void cmExportFileGenerator::GenerateImportTargetCode(
  936. std::ostream& os, cmGeneratorTarget const* target,
  937. cmStateEnums::TargetType targetType)
  938. {
  939. // Construct the imported target name.
  940. std::string targetName = this->Namespace;
  941. targetName += target->GetExportName();
  942. // Create the imported target.
  943. os << "# Create imported target " << targetName << "\n";
  944. switch (targetType) {
  945. case cmStateEnums::EXECUTABLE:
  946. os << "add_executable(" << targetName << " IMPORTED)\n";
  947. break;
  948. case cmStateEnums::STATIC_LIBRARY:
  949. os << "add_library(" << targetName << " STATIC IMPORTED)\n";
  950. break;
  951. case cmStateEnums::SHARED_LIBRARY:
  952. os << "add_library(" << targetName << " SHARED IMPORTED)\n";
  953. break;
  954. case cmStateEnums::MODULE_LIBRARY:
  955. os << "add_library(" << targetName << " MODULE IMPORTED)\n";
  956. break;
  957. case cmStateEnums::UNKNOWN_LIBRARY:
  958. os << "add_library(" << targetName << " UNKNOWN IMPORTED)\n";
  959. break;
  960. case cmStateEnums::OBJECT_LIBRARY:
  961. os << "add_library(" << targetName << " OBJECT IMPORTED)\n";
  962. break;
  963. case cmStateEnums::INTERFACE_LIBRARY:
  964. os << "add_library(" << targetName << " INTERFACE IMPORTED)\n";
  965. break;
  966. default: // should never happen
  967. break;
  968. }
  969. // Mark the imported executable if it has exports.
  970. if (target->IsExecutableWithExports() ||
  971. (target->IsSharedLibraryWithExports() && target->HasImportLibrary(""))) {
  972. os << "set_property(TARGET " << targetName
  973. << " PROPERTY ENABLE_EXPORTS 1)\n";
  974. }
  975. // Mark the imported library if it is a framework.
  976. if (target->IsFrameworkOnApple()) {
  977. os << "set_property(TARGET " << targetName << " PROPERTY FRAMEWORK 1)\n";
  978. }
  979. // Mark the imported executable if it is an application bundle.
  980. if (target->IsAppBundleOnApple()) {
  981. os << "set_property(TARGET " << targetName
  982. << " PROPERTY MACOSX_BUNDLE 1)\n";
  983. }
  984. if (target->IsCFBundleOnApple()) {
  985. os << "set_property(TARGET " << targetName << " PROPERTY BUNDLE 1)\n";
  986. }
  987. // generate DEPRECATION
  988. if (target->IsDeprecated()) {
  989. os << "set_property(TARGET " << targetName << " PROPERTY DEPRECATION "
  990. << cmExportFileGeneratorEscape(target->GetDeprecation()) << ")\n";
  991. }
  992. if (target->GetPropertyAsBool("IMPORTED_NO_SYSTEM")) {
  993. os << "set_property(TARGET " << targetName
  994. << " PROPERTY IMPORTED_NO_SYSTEM 1)\n";
  995. }
  996. if (target->GetPropertyAsBool("EXPORT_NO_SYSTEM")) {
  997. os << "set_property(TARGET " << targetName << " PROPERTY SYSTEM 0)\n";
  998. }
  999. os << "\n";
  1000. }
  1001. void cmExportFileGenerator::GenerateImportPropertyCode(
  1002. std::ostream& os, const std::string& config, cmGeneratorTarget const* target,
  1003. ImportPropertyMap const& properties)
  1004. {
  1005. // Construct the imported target name.
  1006. std::string targetName = this->Namespace;
  1007. targetName += target->GetExportName();
  1008. // Set the import properties.
  1009. os << "# Import target \"" << targetName << "\" for configuration \""
  1010. << config << "\"\n";
  1011. os << "set_property(TARGET " << targetName
  1012. << " APPEND PROPERTY IMPORTED_CONFIGURATIONS ";
  1013. if (!config.empty()) {
  1014. os << cmSystemTools::UpperCase(config);
  1015. } else {
  1016. os << "NOCONFIG";
  1017. }
  1018. os << ")\n";
  1019. os << "set_target_properties(" << targetName << " PROPERTIES\n";
  1020. for (auto const& property : properties) {
  1021. os << " " << property.first << " "
  1022. << cmExportFileGeneratorEscape(property.second) << "\n";
  1023. }
  1024. os << " )\n"
  1025. << "\n";
  1026. }
  1027. void cmExportFileGenerator::GenerateMissingTargetsCheckCode(std::ostream& os)
  1028. {
  1029. if (this->MissingTargets.empty()) {
  1030. /* clang-format off */
  1031. os << "# This file does not depend on other imported targets which have\n"
  1032. "# been exported from the same project but in a separate "
  1033. "export set.\n\n";
  1034. /* clang-format on */
  1035. return;
  1036. }
  1037. /* clang-format off */
  1038. os << "# Make sure the targets which have been exported in some other\n"
  1039. "# export set exist.\n"
  1040. "unset(${CMAKE_FIND_PACKAGE_NAME}_NOT_FOUND_MESSAGE_targets)\n"
  1041. "foreach(_target ";
  1042. /* clang-format on */
  1043. std::set<std::string> emitted;
  1044. for (std::string const& missingTarget : this->MissingTargets) {
  1045. if (emitted.insert(missingTarget).second) {
  1046. os << "\"" << missingTarget << "\" ";
  1047. }
  1048. }
  1049. /* clang-format off */
  1050. os << ")\n"
  1051. " if(NOT TARGET \"${_target}\" )\n"
  1052. " set(${CMAKE_FIND_PACKAGE_NAME}_NOT_FOUND_MESSAGE_targets \""
  1053. "${${CMAKE_FIND_PACKAGE_NAME}_NOT_FOUND_MESSAGE_targets} ${_target}\")"
  1054. "\n"
  1055. " endif()\n"
  1056. "endforeach()\n"
  1057. "\n"
  1058. "if(DEFINED ${CMAKE_FIND_PACKAGE_NAME}_NOT_FOUND_MESSAGE_targets)\n"
  1059. " if(CMAKE_FIND_PACKAGE_NAME)\n"
  1060. " set( ${CMAKE_FIND_PACKAGE_NAME}_FOUND FALSE)\n"
  1061. " set( ${CMAKE_FIND_PACKAGE_NAME}_NOT_FOUND_MESSAGE "
  1062. "\"The following imported targets are "
  1063. "referenced, but are missing: "
  1064. "${${CMAKE_FIND_PACKAGE_NAME}_NOT_FOUND_MESSAGE_targets}\")\n"
  1065. " else()\n"
  1066. " message(FATAL_ERROR \"The following imported targets are "
  1067. "referenced, but are missing: "
  1068. "${${CMAKE_FIND_PACKAGE_NAME}_NOT_FOUND_MESSAGE_targets}\")\n"
  1069. " endif()\n"
  1070. "endif()\n"
  1071. "unset(${CMAKE_FIND_PACKAGE_NAME}_NOT_FOUND_MESSAGE_targets)\n"
  1072. "\n";
  1073. /* clang-format on */
  1074. }
  1075. void cmExportFileGenerator::GenerateImportedFileCheckLoop(std::ostream& os)
  1076. {
  1077. // Add code which verifies at cmake time that the file which is being
  1078. // imported actually exists on disk. This should in theory always be theory
  1079. // case, but still when packages are split into normal and development
  1080. // packages this might get broken (e.g. the Config.cmake could be part of
  1081. // the non-development package, something similar happened to me without
  1082. // on SUSE with a mysql pkg-config file, which claimed everything is fine,
  1083. // but the development package was not installed.).
  1084. /* clang-format off */
  1085. os << "# Loop over all imported files and verify that they actually exist\n"
  1086. "foreach(_cmake_target IN LISTS _cmake_import_check_targets)\n"
  1087. " foreach(_cmake_file IN LISTS \"_cmake_import_check_files_for_${_cmake_target}\")\n"
  1088. " if(NOT EXISTS \"${_cmake_file}\")\n"
  1089. " message(FATAL_ERROR \"The imported target \\\"${_cmake_target}\\\""
  1090. " references the file\n"
  1091. " \\\"${_cmake_file}\\\"\n"
  1092. "but this file does not exist. Possible reasons include:\n"
  1093. "* The file was deleted, renamed, or moved to another location.\n"
  1094. "* An install or uninstall procedure did not complete successfully.\n"
  1095. "* The installation package was faulty and contained\n"
  1096. " \\\"${CMAKE_CURRENT_LIST_FILE}\\\"\n"
  1097. "but not all the files it references.\n"
  1098. "\")\n"
  1099. " endif()\n"
  1100. " endforeach()\n"
  1101. " unset(_cmake_file)\n"
  1102. " unset(\"_cmake_import_check_files_for_${_cmake_target}\")\n"
  1103. "endforeach()\n"
  1104. "unset(_cmake_target)\n"
  1105. "unset(_cmake_import_check_targets)\n"
  1106. "\n";
  1107. /* clang-format on */
  1108. }
  1109. void cmExportFileGenerator::GenerateImportedFileChecksCode(
  1110. std::ostream& os, cmGeneratorTarget* target,
  1111. ImportPropertyMap const& properties,
  1112. const std::set<std::string>& importedLocations)
  1113. {
  1114. // Construct the imported target name.
  1115. std::string targetName = cmStrCat(this->Namespace, target->GetExportName());
  1116. os << "list(APPEND _cmake_import_check_targets " << targetName
  1117. << " )\n"
  1118. "list(APPEND _cmake_import_check_files_for_"
  1119. << targetName << " ";
  1120. for (std::string const& li : importedLocations) {
  1121. auto pi = properties.find(li);
  1122. if (pi != properties.end()) {
  1123. os << cmExportFileGeneratorEscape(pi->second) << " ";
  1124. }
  1125. }
  1126. os << ")\n\n";
  1127. }
  1128. enum class PropertyType
  1129. {
  1130. Strings,
  1131. Paths,
  1132. IncludePaths,
  1133. };
  1134. namespace {
  1135. bool PropertyTypeIsForPaths(PropertyType pt)
  1136. {
  1137. switch (pt) {
  1138. case PropertyType::Strings:
  1139. return false;
  1140. case PropertyType::Paths:
  1141. case PropertyType::IncludePaths:
  1142. return true;
  1143. }
  1144. return false;
  1145. }
  1146. }
  1147. struct ModulePropertyTable
  1148. {
  1149. cm::static_string_view Name;
  1150. PropertyType Type;
  1151. };
  1152. bool cmExportFileGenerator::PopulateCxxModuleExportProperties(
  1153. cmGeneratorTarget const* gte, ImportPropertyMap& properties,
  1154. cmGeneratorExpression::PreprocessContext ctx,
  1155. std::string const& includesDestinationDirs, std::string& errorMessage)
  1156. {
  1157. if (!gte->HaveCxx20ModuleSources(&errorMessage)) {
  1158. return true;
  1159. }
  1160. const cm::static_string_view exportedDirectModuleProperties[] = {
  1161. "CXX_EXTENSIONS"_s,
  1162. };
  1163. for (auto const& propName : exportedDirectModuleProperties) {
  1164. auto const propNameStr = std::string(propName);
  1165. cmValue prop = gte->Target->GetComputedProperty(
  1166. propNameStr, *gte->Target->GetMakefile());
  1167. if (!prop) {
  1168. prop = gte->Target->GetProperty(propNameStr);
  1169. }
  1170. if (prop) {
  1171. properties[propNameStr] = cmGeneratorExpression::Preprocess(*prop, ctx);
  1172. }
  1173. }
  1174. const ModulePropertyTable exportedModuleProperties[] = {
  1175. { "INCLUDE_DIRECTORIES"_s, PropertyType::IncludePaths },
  1176. { "COMPILE_DEFINITIONS"_s, PropertyType::Strings },
  1177. { "COMPILE_OPTIONS"_s, PropertyType::Strings },
  1178. { "COMPILE_FEATURES"_s, PropertyType::Strings },
  1179. };
  1180. for (auto const& propEntry : exportedModuleProperties) {
  1181. auto const propNameStr = std::string(propEntry.Name);
  1182. cmValue prop = gte->Target->GetComputedProperty(
  1183. propNameStr, *gte->Target->GetMakefile());
  1184. if (!prop) {
  1185. prop = gte->Target->GetProperty(propNameStr);
  1186. }
  1187. if (prop) {
  1188. auto const exportedPropName =
  1189. cmStrCat("IMPORTED_CXX_MODULES_", propEntry.Name);
  1190. properties[exportedPropName] =
  1191. cmGeneratorExpression::Preprocess(*prop, ctx);
  1192. if (ctx == cmGeneratorExpression::InstallInterface &&
  1193. PropertyTypeIsForPaths(propEntry.Type)) {
  1194. this->ReplaceInstallPrefix(properties[exportedPropName]);
  1195. prefixItems(properties[exportedPropName]);
  1196. if (propEntry.Type == PropertyType::IncludePaths &&
  1197. !includesDestinationDirs.empty()) {
  1198. if (!properties[exportedPropName].empty()) {
  1199. properties[exportedPropName] += ';';
  1200. }
  1201. properties[exportedPropName] += includesDestinationDirs;
  1202. }
  1203. }
  1204. }
  1205. }
  1206. const cm::static_string_view exportedLinkModuleProperties[] = {
  1207. "LINK_LIBRARIES"_s,
  1208. };
  1209. for (auto const& propName : exportedLinkModuleProperties) {
  1210. auto const propNameStr = std::string(propName);
  1211. cmValue prop = gte->Target->GetComputedProperty(
  1212. propNameStr, *gte->Target->GetMakefile());
  1213. if (!prop) {
  1214. prop = gte->Target->GetProperty(propNameStr);
  1215. }
  1216. if (prop) {
  1217. auto const exportedPropName =
  1218. cmStrCat("IMPORTED_CXX_MODULES_", propName);
  1219. auto value = cmGeneratorExpression::Preprocess(*prop, ctx);
  1220. this->ResolveTargetsInGeneratorExpressions(
  1221. value, gte, cmExportFileGenerator::ReplaceFreeTargets);
  1222. std::vector<std::string> wrappedValues;
  1223. for (auto& item : cmList{ value }) {
  1224. wrappedValues.push_back(cmStrCat("$<COMPILE_ONLY:", item, '>'));
  1225. }
  1226. properties[exportedPropName] = cmJoin(wrappedValues, ";");
  1227. }
  1228. }
  1229. return true;
  1230. }
  1231. bool cmExportFileGenerator::PopulateExportProperties(
  1232. cmGeneratorTarget const* gte, ImportPropertyMap& properties,
  1233. std::string& errorMessage)
  1234. {
  1235. const auto& targetProperties = gte->Target->GetProperties();
  1236. if (cmValue exportProperties =
  1237. targetProperties.GetPropertyValue("EXPORT_PROPERTIES")) {
  1238. for (auto& prop : cmList{ *exportProperties }) {
  1239. /* Black list reserved properties */
  1240. if (cmHasLiteralPrefix(prop, "IMPORTED_") ||
  1241. cmHasLiteralPrefix(prop, "INTERFACE_")) {
  1242. std::ostringstream e;
  1243. e << "Target \"" << gte->Target->GetName() << "\" contains property \""
  1244. << prop << "\" in EXPORT_PROPERTIES but IMPORTED_* and INTERFACE_* "
  1245. << "properties are reserved.";
  1246. errorMessage = e.str();
  1247. return false;
  1248. }
  1249. cmValue propertyValue = targetProperties.GetPropertyValue(prop);
  1250. if (!propertyValue) {
  1251. // Asked to export a property that isn't defined on the target. Do not
  1252. // consider this an error, there's just nothing to export.
  1253. continue;
  1254. }
  1255. std::string evaluatedValue = cmGeneratorExpression::Preprocess(
  1256. *propertyValue, cmGeneratorExpression::StripAllGeneratorExpressions);
  1257. if (evaluatedValue != *propertyValue) {
  1258. std::ostringstream e;
  1259. e << "Target \"" << gte->Target->GetName() << "\" contains property \""
  1260. << prop << "\" in EXPORT_PROPERTIES but this property contains a "
  1261. << "generator expression. This is not allowed.";
  1262. errorMessage = e.str();
  1263. return false;
  1264. }
  1265. properties[prop] = *propertyValue;
  1266. }
  1267. }
  1268. return true;
  1269. }
  1270. void cmExportFileGenerator::GenerateTargetFileSets(cmGeneratorTarget* gte,
  1271. std::ostream& os,
  1272. cmTargetExport* te)
  1273. {
  1274. auto interfaceFileSets = gte->Target->GetAllInterfaceFileSets();
  1275. if (!interfaceFileSets.empty()) {
  1276. std::string targetName = cmStrCat(this->Namespace, gte->GetExportName());
  1277. os << "if(NOT CMAKE_VERSION VERSION_LESS \"3.23.0\")\n"
  1278. " target_sources("
  1279. << targetName << "\n";
  1280. for (auto const& name : interfaceFileSets) {
  1281. auto* fileSet = gte->Target->GetFileSet(name);
  1282. if (!fileSet) {
  1283. gte->Makefile->IssueMessage(
  1284. MessageType::FATAL_ERROR,
  1285. cmStrCat("File set \"", name,
  1286. "\" is listed in interface file sets of ", gte->GetName(),
  1287. " but has not been created"));
  1288. return;
  1289. }
  1290. os << " INTERFACE"
  1291. << "\n FILE_SET " << cmOutputConverter::EscapeForCMake(name)
  1292. << "\n TYPE "
  1293. << cmOutputConverter::EscapeForCMake(fileSet->GetType())
  1294. << "\n BASE_DIRS "
  1295. << this->GetFileSetDirectories(gte, fileSet, te) << "\n FILES "
  1296. << this->GetFileSetFiles(gte, fileSet, te) << "\n";
  1297. }
  1298. os << " )\nelse()\n set_property(TARGET " << targetName
  1299. << "\n APPEND PROPERTY INTERFACE_INCLUDE_DIRECTORIES";
  1300. for (auto const& name : interfaceFileSets) {
  1301. auto* fileSet = gte->Target->GetFileSet(name);
  1302. if (!fileSet) {
  1303. gte->Makefile->IssueMessage(
  1304. MessageType::FATAL_ERROR,
  1305. cmStrCat("File set \"", name,
  1306. "\" is listed in interface file sets of ", gte->GetName(),
  1307. " but has not been created"));
  1308. return;
  1309. }
  1310. os << "\n " << this->GetFileSetDirectories(gte, fileSet, te);
  1311. }
  1312. os << "\n )\nendif()\n\n";
  1313. }
  1314. }
  1315. void cmExportFileGenerator::GenerateCxxModuleInformation(
  1316. std::string const& name, std::ostream& os)
  1317. {
  1318. auto const cxx_module_dirname = this->GetCxxModulesDirectory();
  1319. if (cxx_module_dirname.empty()) {
  1320. return;
  1321. }
  1322. // Write the include.
  1323. os << "# Include C++ module properties\n"
  1324. << "include(\"${CMAKE_CURRENT_LIST_DIR}/" << cxx_module_dirname
  1325. << "/cxx-modules-" << name << ".cmake\")\n\n";
  1326. // Get the path to the file we're going to write.
  1327. std::string path = this->MainImportFile;
  1328. path = cmSystemTools::GetFilenamePath(path);
  1329. auto trampoline_path =
  1330. cmStrCat(path, '/', cxx_module_dirname, "/cxx-modules-", name, ".cmake");
  1331. // Include all configuration-specific include files.
  1332. cmGeneratedFileStream ap(trampoline_path, true);
  1333. ap.SetCopyIfDifferent(true);
  1334. this->GenerateCxxModuleConfigInformation(name, ap);
  1335. }