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