cmExportFileGenerator.cxx 45 KB

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