cmExportFileGenerator.cxx 55 KB

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