cmExportFileGenerator.cxx 37 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096
  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 "cmAlgorithms.h"
  5. #include "cmComputeLinkInformation.h"
  6. #include "cmGeneratedFileStream.h"
  7. #include "cmGeneratorTarget.h"
  8. #include "cmLinkItem.h"
  9. #include "cmLocalGenerator.h"
  10. #include "cmMakefile.h"
  11. #include "cmOutputConverter.h"
  12. #include "cmPolicies.h"
  13. #include "cmStateTypes.h"
  14. #include "cmSystemTools.h"
  15. #include "cmTarget.h"
  16. #include "cmTargetExport.h"
  17. #include "cmake.h"
  18. #include <assert.h>
  19. #include <cm_auto_ptr.hxx>
  20. #include <cmsys/FStream.hxx>
  21. #include <sstream>
  22. #include <string.h>
  23. #include <utility>
  24. static std::string cmExportFileGeneratorEscape(std::string const& str)
  25. {
  26. // Escape a property value for writing into a .cmake file.
  27. std::string result = cmOutputConverter::EscapeForCMake(str);
  28. // Un-escape variable references generated by our own export code.
  29. cmSystemTools::ReplaceString(result, "\\${_IMPORT_PREFIX}",
  30. "${_IMPORT_PREFIX}");
  31. cmSystemTools::ReplaceString(result, "\\${CMAKE_IMPORT_LIBRARY_SUFFIX}",
  32. "${CMAKE_IMPORT_LIBRARY_SUFFIX}");
  33. return result;
  34. }
  35. cmExportFileGenerator::cmExportFileGenerator()
  36. {
  37. this->AppendMode = false;
  38. this->ExportOld = false;
  39. }
  40. void cmExportFileGenerator::AddConfiguration(const std::string& config)
  41. {
  42. this->Configurations.push_back(config);
  43. }
  44. void cmExportFileGenerator::SetExportFile(const char* mainFile)
  45. {
  46. this->MainImportFile = mainFile;
  47. this->FileDir = cmSystemTools::GetFilenamePath(this->MainImportFile);
  48. this->FileBase =
  49. cmSystemTools::GetFilenameWithoutLastExtension(this->MainImportFile);
  50. this->FileExt =
  51. cmSystemTools::GetFilenameLastExtension(this->MainImportFile);
  52. }
  53. const char* cmExportFileGenerator::GetMainExportFileName() const
  54. {
  55. return this->MainImportFile.c_str();
  56. }
  57. bool cmExportFileGenerator::GenerateImportFile()
  58. {
  59. // Open the output file to generate it.
  60. CM_AUTO_PTR<cmsys::ofstream> foutPtr;
  61. if (this->AppendMode) {
  62. // Open for append.
  63. CM_AUTO_PTR<cmsys::ofstream> ap(
  64. new cmsys::ofstream(this->MainImportFile.c_str(), std::ios::app));
  65. foutPtr = ap;
  66. } else {
  67. // Generate atomically and with copy-if-different.
  68. CM_AUTO_PTR<cmGeneratedFileStream> ap(
  69. new cmGeneratedFileStream(this->MainImportFile.c_str(), true));
  70. ap->SetCopyIfDifferent(true);
  71. foutPtr = ap;
  72. }
  73. if (!foutPtr.get() || !*foutPtr) {
  74. std::string se = cmSystemTools::GetLastSystemError();
  75. std::ostringstream e;
  76. e << "cannot write to file \"" << this->MainImportFile << "\": " << se;
  77. cmSystemTools::Error(e.str().c_str());
  78. return false;
  79. }
  80. std::ostream& os = *foutPtr;
  81. // Start with the import file header.
  82. this->GeneratePolicyHeaderCode(os);
  83. this->GenerateImportHeaderCode(os);
  84. // Create all the imported targets.
  85. bool result = this->GenerateMainFile(os);
  86. // End with the import file footer.
  87. this->GenerateImportFooterCode(os);
  88. this->GeneratePolicyFooterCode(os);
  89. return result;
  90. }
  91. void cmExportFileGenerator::GenerateImportConfig(
  92. std::ostream& os, const std::string& config,
  93. std::vector<std::string>& missingTargets)
  94. {
  95. // Construct the property configuration suffix.
  96. std::string suffix = "_";
  97. if (!config.empty()) {
  98. suffix += cmSystemTools::UpperCase(config);
  99. } else {
  100. suffix += "NOCONFIG";
  101. }
  102. // Generate the per-config target information.
  103. this->GenerateImportTargetsConfig(os, config, suffix, missingTargets);
  104. }
  105. void cmExportFileGenerator::PopulateInterfaceProperty(
  106. const std::string& propName, cmGeneratorTarget* target,
  107. ImportPropertyMap& properties)
  108. {
  109. const char* input = target->GetProperty(propName);
  110. if (input) {
  111. properties[propName] = input;
  112. }
  113. }
  114. void cmExportFileGenerator::PopulateInterfaceProperty(
  115. const std::string& propName, const std::string& outputName,
  116. cmGeneratorTarget* target,
  117. cmGeneratorExpression::PreprocessContext preprocessRule,
  118. ImportPropertyMap& properties, std::vector<std::string>& missingTargets)
  119. {
  120. const char* input = target->GetProperty(propName);
  121. if (input) {
  122. if (!*input) {
  123. // Set to empty
  124. properties[outputName] = "";
  125. return;
  126. }
  127. std::string prepro =
  128. cmGeneratorExpression::Preprocess(input, preprocessRule);
  129. if (!prepro.empty()) {
  130. this->ResolveTargetsInGeneratorExpressions(prepro, target,
  131. missingTargets);
  132. properties[outputName] = prepro;
  133. }
  134. }
  135. }
  136. void cmExportFileGenerator::GenerateRequiredCMakeVersion(
  137. std::ostream& os, const char* versionString)
  138. {
  139. /* clang-format off */
  140. os << "if(CMAKE_VERSION VERSION_LESS " << versionString << ")\n"
  141. " message(FATAL_ERROR \"This file relies on consumers using "
  142. "CMake " << versionString << " or greater.\")\n"
  143. "endif()\n\n";
  144. /* clang-format on */
  145. }
  146. bool cmExportFileGenerator::PopulateInterfaceLinkLibrariesProperty(
  147. cmGeneratorTarget* target,
  148. cmGeneratorExpression::PreprocessContext preprocessRule,
  149. ImportPropertyMap& properties, std::vector<std::string>& missingTargets)
  150. {
  151. if (!target->IsLinkable()) {
  152. return false;
  153. }
  154. const char* input = target->GetProperty("INTERFACE_LINK_LIBRARIES");
  155. if (input) {
  156. std::string prepro =
  157. cmGeneratorExpression::Preprocess(input, preprocessRule);
  158. if (!prepro.empty()) {
  159. this->ResolveTargetsInGeneratorExpressions(
  160. prepro, target, missingTargets, ReplaceFreeTargets);
  161. properties["INTERFACE_LINK_LIBRARIES"] = prepro;
  162. return true;
  163. }
  164. }
  165. return false;
  166. }
  167. static bool isSubDirectory(const char* a, const char* b)
  168. {
  169. return (cmSystemTools::ComparePath(a, b) ||
  170. cmSystemTools::IsSubDirectory(a, b));
  171. }
  172. static bool checkInterfaceDirs(const std::string& prepro,
  173. cmGeneratorTarget* target,
  174. const std::string& prop)
  175. {
  176. const char* installDir =
  177. target->Makefile->GetSafeDefinition("CMAKE_INSTALL_PREFIX");
  178. const char* topSourceDir = target->GetLocalGenerator()->GetSourceDirectory();
  179. const char* topBinaryDir = target->GetLocalGenerator()->GetBinaryDirectory();
  180. std::vector<std::string> parts;
  181. cmGeneratorExpression::Split(prepro, parts);
  182. const bool inSourceBuild = strcmp(topSourceDir, topBinaryDir) == 0;
  183. bool hadFatalError = false;
  184. for (std::vector<std::string>::iterator li = parts.begin();
  185. li != parts.end(); ++li) {
  186. size_t genexPos = cmGeneratorExpression::Find(*li);
  187. if (genexPos == 0) {
  188. continue;
  189. }
  190. cmake::MessageType messageType = cmake::FATAL_ERROR;
  191. std::ostringstream e;
  192. if (genexPos != std::string::npos) {
  193. if (prop == "INTERFACE_INCLUDE_DIRECTORIES") {
  194. switch (target->GetPolicyStatusCMP0041()) {
  195. case cmPolicies::WARN:
  196. messageType = cmake::WARNING;
  197. e << cmPolicies::GetPolicyWarning(cmPolicies::CMP0041) << "\n";
  198. break;
  199. case cmPolicies::OLD:
  200. continue;
  201. case cmPolicies::REQUIRED_IF_USED:
  202. case cmPolicies::REQUIRED_ALWAYS:
  203. case cmPolicies::NEW:
  204. hadFatalError = true;
  205. break; // Issue fatal message.
  206. }
  207. } else {
  208. hadFatalError = true;
  209. }
  210. }
  211. if (cmHasLiteralPrefix(li->c_str(), "${_IMPORT_PREFIX}")) {
  212. continue;
  213. }
  214. if (!cmSystemTools::FileIsFullPath(li->c_str())) {
  215. /* clang-format off */
  216. e << "Target \"" << target->GetName() << "\" " << prop <<
  217. " property contains relative path:\n"
  218. " \"" << *li << "\"";
  219. /* clang-format on */
  220. target->GetLocalGenerator()->IssueMessage(messageType, e.str());
  221. }
  222. bool inBinary = isSubDirectory(li->c_str(), topBinaryDir);
  223. bool inSource = isSubDirectory(li->c_str(), topSourceDir);
  224. if (isSubDirectory(li->c_str(), installDir)) {
  225. // The include directory is inside the install tree. If the
  226. // install tree is not inside the source tree or build tree then
  227. // fall through to the checks below that the include directory is not
  228. // also inside the source tree or build tree.
  229. bool shouldContinue =
  230. (!inBinary || isSubDirectory(installDir, topBinaryDir)) &&
  231. (!inSource || isSubDirectory(installDir, topSourceDir));
  232. if (prop == "INTERFACE_INCLUDE_DIRECTORIES") {
  233. if (!shouldContinue) {
  234. switch (target->GetPolicyStatusCMP0052()) {
  235. case cmPolicies::WARN: {
  236. std::ostringstream s;
  237. s << cmPolicies::GetPolicyWarning(cmPolicies::CMP0052) << "\n";
  238. s << "Directory:\n \"" << *li
  239. << "\"\nin "
  240. "INTERFACE_INCLUDE_DIRECTORIES of target \""
  241. << target->GetName() << "\" is a subdirectory of the install "
  242. "directory:\n \""
  243. << installDir << "\"\nhowever it is also "
  244. "a subdirectory of the "
  245. << (inBinary ? "build" : "source") << " tree:\n \""
  246. << (inBinary ? topBinaryDir : topSourceDir) << "\""
  247. << std::endl;
  248. target->GetLocalGenerator()->IssueMessage(cmake::AUTHOR_WARNING,
  249. s.str());
  250. }
  251. case cmPolicies::OLD:
  252. shouldContinue = true;
  253. break;
  254. case cmPolicies::REQUIRED_ALWAYS:
  255. case cmPolicies::REQUIRED_IF_USED:
  256. case cmPolicies::NEW:
  257. break;
  258. }
  259. }
  260. }
  261. if (shouldContinue) {
  262. continue;
  263. }
  264. }
  265. if (inBinary) {
  266. /* clang-format off */
  267. e << "Target \"" << target->GetName() << "\" " << prop <<
  268. " property contains path:\n"
  269. " \"" << *li << "\"\nwhich is prefixed in the build directory.";
  270. /* clang-format on */
  271. target->GetLocalGenerator()->IssueMessage(messageType, e.str());
  272. }
  273. if (!inSourceBuild) {
  274. if (inSource) {
  275. e << "Target \"" << target->GetName() << "\" " << prop
  276. << " property contains path:\n"
  277. " \""
  278. << *li << "\"\nwhich is prefixed in the source directory.";
  279. target->GetLocalGenerator()->IssueMessage(messageType, e.str());
  280. }
  281. }
  282. }
  283. return !hadFatalError;
  284. }
  285. static void prefixItems(std::string& exportDirs)
  286. {
  287. std::vector<std::string> entries;
  288. cmGeneratorExpression::Split(exportDirs, entries);
  289. exportDirs = "";
  290. const char* sep = "";
  291. for (std::vector<std::string>::const_iterator ei = entries.begin();
  292. ei != entries.end(); ++ei) {
  293. exportDirs += sep;
  294. sep = ";";
  295. if (!cmSystemTools::FileIsFullPath(ei->c_str()) &&
  296. ei->find("${_IMPORT_PREFIX}") == std::string::npos) {
  297. exportDirs += "${_IMPORT_PREFIX}/";
  298. }
  299. exportDirs += *ei;
  300. }
  301. }
  302. void cmExportFileGenerator::PopulateSourcesInterface(
  303. cmTargetExport* tei, cmGeneratorExpression::PreprocessContext preprocessRule,
  304. ImportPropertyMap& properties, std::vector<std::string>& missingTargets)
  305. {
  306. cmGeneratorTarget* gt = tei->Target;
  307. assert(preprocessRule == cmGeneratorExpression::InstallInterface);
  308. const char* propName = "INTERFACE_SOURCES";
  309. const char* input = gt->GetProperty(propName);
  310. if (!input) {
  311. return;
  312. }
  313. if (!*input) {
  314. properties[propName] = "";
  315. return;
  316. }
  317. std::string prepro =
  318. cmGeneratorExpression::Preprocess(input, preprocessRule, true);
  319. if (!prepro.empty()) {
  320. this->ResolveTargetsInGeneratorExpressions(prepro, gt, missingTargets);
  321. if (!checkInterfaceDirs(prepro, gt, propName)) {
  322. return;
  323. }
  324. properties[propName] = prepro;
  325. }
  326. }
  327. void cmExportFileGenerator::PopulateIncludeDirectoriesInterface(
  328. cmTargetExport* tei, cmGeneratorExpression::PreprocessContext preprocessRule,
  329. ImportPropertyMap& properties, std::vector<std::string>& missingTargets)
  330. {
  331. cmGeneratorTarget* target = tei->Target;
  332. assert(preprocessRule == cmGeneratorExpression::InstallInterface);
  333. const char* propName = "INTERFACE_INCLUDE_DIRECTORIES";
  334. const char* input = target->GetProperty(propName);
  335. cmGeneratorExpression ge;
  336. std::string dirs = cmGeneratorExpression::Preprocess(
  337. tei->InterfaceIncludeDirectories, preprocessRule, true);
  338. this->ReplaceInstallPrefix(dirs);
  339. CM_AUTO_PTR<cmCompiledGeneratorExpression> cge = ge.Parse(dirs);
  340. std::string exportDirs =
  341. cge->Evaluate(target->GetLocalGenerator(), "", false, target);
  342. if (cge->GetHadContextSensitiveCondition()) {
  343. cmLocalGenerator* lg = target->GetLocalGenerator();
  344. std::ostringstream e;
  345. e << "Target \"" << target->GetName()
  346. << "\" is installed with "
  347. "INCLUDES DESTINATION set to a context sensitive path. Paths which "
  348. "depend on the configuration, policy values or the link interface "
  349. "are "
  350. "not supported. Consider using target_include_directories instead.";
  351. lg->IssueMessage(cmake::FATAL_ERROR, e.str());
  352. return;
  353. }
  354. if (!input && exportDirs.empty()) {
  355. return;
  356. }
  357. if ((input && !*input) && exportDirs.empty()) {
  358. // Set to empty
  359. properties[propName] = "";
  360. return;
  361. }
  362. prefixItems(exportDirs);
  363. std::string includes = (input ? input : "");
  364. const char* sep = input ? ";" : "";
  365. includes += sep + exportDirs;
  366. std::string prepro =
  367. cmGeneratorExpression::Preprocess(includes, preprocessRule, true);
  368. if (!prepro.empty()) {
  369. this->ResolveTargetsInGeneratorExpressions(prepro, target, missingTargets);
  370. if (!checkInterfaceDirs(prepro, target, propName)) {
  371. return;
  372. }
  373. properties[propName] = prepro;
  374. }
  375. }
  376. void cmExportFileGenerator::PopulateInterfaceProperty(
  377. const std::string& propName, cmGeneratorTarget* target,
  378. cmGeneratorExpression::PreprocessContext preprocessRule,
  379. ImportPropertyMap& properties, std::vector<std::string>& missingTargets)
  380. {
  381. this->PopulateInterfaceProperty(propName, propName, target, preprocessRule,
  382. properties, missingTargets);
  383. }
  384. void getPropertyContents(cmGeneratorTarget const* tgt, const std::string& prop,
  385. std::set<std::string>& ifaceProperties)
  386. {
  387. const char* p = tgt->GetProperty(prop);
  388. if (!p) {
  389. return;
  390. }
  391. std::vector<std::string> content;
  392. cmSystemTools::ExpandListArgument(p, content);
  393. ifaceProperties.insert(content.begin(), content.end());
  394. }
  395. void getCompatibleInterfaceProperties(cmGeneratorTarget* target,
  396. std::set<std::string>& ifaceProperties,
  397. const std::string& config)
  398. {
  399. cmComputeLinkInformation* info = target->GetLinkInformation(config);
  400. if (!info) {
  401. cmLocalGenerator* lg = target->GetLocalGenerator();
  402. std::ostringstream e;
  403. e << "Exporting the target \"" << target->GetName()
  404. << "\" is not "
  405. "allowed since its linker language cannot be determined";
  406. lg->IssueMessage(cmake::FATAL_ERROR, e.str());
  407. return;
  408. }
  409. const cmComputeLinkInformation::ItemVector& deps = info->GetItems();
  410. for (cmComputeLinkInformation::ItemVector::const_iterator li = deps.begin();
  411. li != deps.end(); ++li) {
  412. if (!li->Target) {
  413. continue;
  414. }
  415. getPropertyContents(li->Target, "COMPATIBLE_INTERFACE_BOOL",
  416. ifaceProperties);
  417. getPropertyContents(li->Target, "COMPATIBLE_INTERFACE_STRING",
  418. ifaceProperties);
  419. getPropertyContents(li->Target, "COMPATIBLE_INTERFACE_NUMBER_MIN",
  420. ifaceProperties);
  421. getPropertyContents(li->Target, "COMPATIBLE_INTERFACE_NUMBER_MAX",
  422. ifaceProperties);
  423. }
  424. }
  425. void cmExportFileGenerator::PopulateCompatibleInterfaceProperties(
  426. cmGeneratorTarget* gtarget, ImportPropertyMap& properties)
  427. {
  428. this->PopulateInterfaceProperty("COMPATIBLE_INTERFACE_BOOL", gtarget,
  429. properties);
  430. this->PopulateInterfaceProperty("COMPATIBLE_INTERFACE_STRING", gtarget,
  431. properties);
  432. this->PopulateInterfaceProperty("COMPATIBLE_INTERFACE_NUMBER_MIN", gtarget,
  433. properties);
  434. this->PopulateInterfaceProperty("COMPATIBLE_INTERFACE_NUMBER_MAX", gtarget,
  435. properties);
  436. std::set<std::string> ifaceProperties;
  437. getPropertyContents(gtarget, "COMPATIBLE_INTERFACE_BOOL", ifaceProperties);
  438. getPropertyContents(gtarget, "COMPATIBLE_INTERFACE_STRING", ifaceProperties);
  439. getPropertyContents(gtarget, "COMPATIBLE_INTERFACE_NUMBER_MIN",
  440. ifaceProperties);
  441. getPropertyContents(gtarget, "COMPATIBLE_INTERFACE_NUMBER_MAX",
  442. ifaceProperties);
  443. if (gtarget->GetType() != cmStateEnums::INTERFACE_LIBRARY) {
  444. getCompatibleInterfaceProperties(gtarget, ifaceProperties, "");
  445. std::vector<std::string> configNames;
  446. gtarget->Target->GetMakefile()->GetConfigurations(configNames);
  447. for (std::vector<std::string>::const_iterator ci = configNames.begin();
  448. ci != configNames.end(); ++ci) {
  449. getCompatibleInterfaceProperties(gtarget, ifaceProperties, *ci);
  450. }
  451. }
  452. for (std::set<std::string>::const_iterator it = ifaceProperties.begin();
  453. it != ifaceProperties.end(); ++it) {
  454. this->PopulateInterfaceProperty("INTERFACE_" + *it, gtarget, properties);
  455. }
  456. }
  457. void cmExportFileGenerator::GenerateInterfaceProperties(
  458. const cmGeneratorTarget* target, std::ostream& os,
  459. const ImportPropertyMap& properties)
  460. {
  461. if (!properties.empty()) {
  462. std::string targetName = this->Namespace;
  463. targetName += target->GetExportName();
  464. os << "set_target_properties(" << targetName << " PROPERTIES\n";
  465. for (ImportPropertyMap::const_iterator pi = properties.begin();
  466. pi != properties.end(); ++pi) {
  467. os << " " << pi->first << " " << cmExportFileGeneratorEscape(pi->second)
  468. << "\n";
  469. }
  470. os << ")\n\n";
  471. }
  472. }
  473. bool cmExportFileGenerator::AddTargetNamespace(
  474. std::string& input, cmGeneratorTarget* target,
  475. std::vector<std::string>& missingTargets)
  476. {
  477. cmLocalGenerator* lg = target->GetLocalGenerator();
  478. cmGeneratorTarget* tgt = lg->FindGeneratorTargetToUse(input);
  479. if (!tgt) {
  480. return false;
  481. }
  482. if (tgt->IsImported()) {
  483. return true;
  484. }
  485. if (this->ExportedTargets.find(tgt) != this->ExportedTargets.end()) {
  486. input = this->Namespace + tgt->GetExportName();
  487. } else {
  488. std::string namespacedTarget;
  489. this->HandleMissingTarget(namespacedTarget, missingTargets, target, tgt);
  490. if (!namespacedTarget.empty()) {
  491. input = namespacedTarget;
  492. }
  493. }
  494. return true;
  495. }
  496. void cmExportFileGenerator::ResolveTargetsInGeneratorExpressions(
  497. std::string& input, cmGeneratorTarget* target,
  498. std::vector<std::string>& missingTargets, FreeTargetsReplace replace)
  499. {
  500. if (replace == NoReplaceFreeTargets) {
  501. this->ResolveTargetsInGeneratorExpression(input, target, missingTargets);
  502. return;
  503. }
  504. std::vector<std::string> parts;
  505. cmGeneratorExpression::Split(input, parts);
  506. std::string sep;
  507. input = "";
  508. for (std::vector<std::string>::iterator li = parts.begin();
  509. li != parts.end(); ++li) {
  510. if (cmGeneratorExpression::Find(*li) == std::string::npos) {
  511. this->AddTargetNamespace(*li, target, missingTargets);
  512. } else {
  513. this->ResolveTargetsInGeneratorExpression(*li, target, missingTargets);
  514. }
  515. input += sep + *li;
  516. sep = ";";
  517. }
  518. }
  519. void cmExportFileGenerator::ResolveTargetsInGeneratorExpression(
  520. std::string& input, cmGeneratorTarget* target,
  521. std::vector<std::string>& missingTargets)
  522. {
  523. std::string::size_type pos = 0;
  524. std::string::size_type lastPos = pos;
  525. while ((pos = input.find("$<TARGET_PROPERTY:", lastPos)) != input.npos) {
  526. std::string::size_type nameStartPos =
  527. pos + sizeof("$<TARGET_PROPERTY:") - 1;
  528. std::string::size_type closePos = input.find('>', nameStartPos);
  529. std::string::size_type commaPos = input.find(',', nameStartPos);
  530. std::string::size_type nextOpenPos = input.find("$<", nameStartPos);
  531. if (commaPos == input.npos // Implied 'this' target
  532. || closePos == input.npos // Imcomplete expression.
  533. || closePos < commaPos // Implied 'this' target
  534. || nextOpenPos < commaPos) // Non-literal
  535. {
  536. lastPos = nameStartPos;
  537. continue;
  538. }
  539. std::string targetName =
  540. input.substr(nameStartPos, commaPos - nameStartPos);
  541. if (this->AddTargetNamespace(targetName, target, missingTargets)) {
  542. input.replace(nameStartPos, commaPos - nameStartPos, targetName);
  543. }
  544. lastPos = nameStartPos + targetName.size() + 1;
  545. }
  546. std::string errorString;
  547. pos = 0;
  548. lastPos = pos;
  549. while ((pos = input.find("$<TARGET_NAME:", lastPos)) != input.npos) {
  550. std::string::size_type nameStartPos = pos + sizeof("$<TARGET_NAME:") - 1;
  551. std::string::size_type endPos = input.find('>', nameStartPos);
  552. if (endPos == input.npos) {
  553. errorString = "$<TARGET_NAME:...> expression incomplete";
  554. break;
  555. }
  556. std::string targetName = input.substr(nameStartPos, endPos - nameStartPos);
  557. if (targetName.find("$<") != input.npos) {
  558. errorString = "$<TARGET_NAME:...> requires its parameter to be a "
  559. "literal.";
  560. break;
  561. }
  562. if (!this->AddTargetNamespace(targetName, target, missingTargets)) {
  563. errorString = "$<TARGET_NAME:...> requires its parameter to be a "
  564. "reachable target.";
  565. break;
  566. }
  567. input.replace(pos, endPos - pos + 1, targetName);
  568. lastPos = endPos;
  569. }
  570. pos = 0;
  571. lastPos = pos;
  572. while (errorString.empty() &&
  573. (pos = input.find("$<LINK_ONLY:", lastPos)) != input.npos) {
  574. std::string::size_type nameStartPos = pos + sizeof("$<LINK_ONLY:") - 1;
  575. std::string::size_type endPos = input.find('>', nameStartPos);
  576. if (endPos == input.npos) {
  577. errorString = "$<LINK_ONLY:...> expression incomplete";
  578. break;
  579. }
  580. std::string libName = input.substr(nameStartPos, endPos - nameStartPos);
  581. if (cmGeneratorExpression::IsValidTargetName(libName) &&
  582. this->AddTargetNamespace(libName, target, missingTargets)) {
  583. input.replace(nameStartPos, endPos - nameStartPos, libName);
  584. }
  585. lastPos = nameStartPos + libName.size() + 1;
  586. }
  587. this->ReplaceInstallPrefix(input);
  588. if (!errorString.empty()) {
  589. target->GetLocalGenerator()->IssueMessage(cmake::FATAL_ERROR, errorString);
  590. }
  591. }
  592. void cmExportFileGenerator::ReplaceInstallPrefix(std::string& /*unused*/)
  593. {
  594. // Do nothing
  595. }
  596. void cmExportFileGenerator::SetImportLinkInterface(
  597. const std::string& config, std::string const& suffix,
  598. cmGeneratorExpression::PreprocessContext preprocessRule,
  599. cmGeneratorTarget* target, ImportPropertyMap& properties,
  600. std::vector<std::string>& missingTargets)
  601. {
  602. // Add the transitive link dependencies for this configuration.
  603. cmLinkInterface const* iface = target->GetLinkInterface(config, target);
  604. if (!iface) {
  605. return;
  606. }
  607. if (iface->ImplementationIsInterface) {
  608. // Policy CMP0022 must not be NEW.
  609. this->SetImportLinkProperty(suffix, target,
  610. "IMPORTED_LINK_INTERFACE_LIBRARIES",
  611. iface->Libraries, properties, missingTargets);
  612. return;
  613. }
  614. const char* propContent;
  615. if (const char* prop_suffixed =
  616. target->GetProperty("LINK_INTERFACE_LIBRARIES" + suffix)) {
  617. propContent = prop_suffixed;
  618. } else if (const char* prop =
  619. target->GetProperty("LINK_INTERFACE_LIBRARIES")) {
  620. propContent = prop;
  621. } else {
  622. return;
  623. }
  624. const bool newCMP0022Behavior =
  625. target->GetPolicyStatusCMP0022() != cmPolicies::WARN &&
  626. target->GetPolicyStatusCMP0022() != cmPolicies::OLD;
  627. if (newCMP0022Behavior && !this->ExportOld) {
  628. cmLocalGenerator* lg = target->GetLocalGenerator();
  629. std::ostringstream e;
  630. e << "Target \"" << target->GetName()
  631. << "\" has policy CMP0022 enabled, "
  632. "but also has old-style LINK_INTERFACE_LIBRARIES properties "
  633. "populated, but it was exported without the "
  634. "EXPORT_LINK_INTERFACE_LIBRARIES to export the old-style properties";
  635. lg->IssueMessage(cmake::FATAL_ERROR, e.str());
  636. return;
  637. }
  638. if (!*propContent) {
  639. properties["IMPORTED_LINK_INTERFACE_LIBRARIES" + suffix] = "";
  640. return;
  641. }
  642. std::string prepro =
  643. cmGeneratorExpression::Preprocess(propContent, preprocessRule);
  644. if (!prepro.empty()) {
  645. this->ResolveTargetsInGeneratorExpressions(prepro, target, missingTargets,
  646. ReplaceFreeTargets);
  647. properties["IMPORTED_LINK_INTERFACE_LIBRARIES" + suffix] = prepro;
  648. }
  649. }
  650. void cmExportFileGenerator::SetImportDetailProperties(
  651. const std::string& config, std::string const& suffix,
  652. cmGeneratorTarget* target, ImportPropertyMap& properties,
  653. std::vector<std::string>& missingTargets)
  654. {
  655. // Get the makefile in which to lookup target information.
  656. cmMakefile* mf = target->Makefile;
  657. // Add the soname for unix shared libraries.
  658. if (target->GetType() == cmStateEnums::SHARED_LIBRARY ||
  659. target->GetType() == cmStateEnums::MODULE_LIBRARY) {
  660. if (!target->IsDLLPlatform()) {
  661. std::string prop;
  662. std::string value;
  663. if (target->HasSOName(config)) {
  664. if (mf->IsOn("CMAKE_PLATFORM_HAS_INSTALLNAME")) {
  665. value = this->InstallNameDir(target, config);
  666. }
  667. prop = "IMPORTED_SONAME";
  668. value += target->GetSOName(config);
  669. } else {
  670. prop = "IMPORTED_NO_SONAME";
  671. value = "TRUE";
  672. }
  673. prop += suffix;
  674. properties[prop] = value;
  675. }
  676. }
  677. // Add the transitive link dependencies for this configuration.
  678. if (cmLinkInterface const* iface =
  679. target->GetLinkInterface(config, target)) {
  680. this->SetImportLinkProperty(suffix, target,
  681. "IMPORTED_LINK_INTERFACE_LANGUAGES",
  682. iface->Languages, properties, missingTargets);
  683. std::vector<std::string> dummy;
  684. this->SetImportLinkProperty(suffix, target,
  685. "IMPORTED_LINK_DEPENDENT_LIBRARIES",
  686. iface->SharedDeps, properties, dummy);
  687. if (iface->Multiplicity > 0) {
  688. std::string prop = "IMPORTED_LINK_INTERFACE_MULTIPLICITY";
  689. prop += suffix;
  690. std::ostringstream m;
  691. m << iface->Multiplicity;
  692. properties[prop] = m.str();
  693. }
  694. }
  695. }
  696. template <typename T>
  697. void cmExportFileGenerator::SetImportLinkProperty(
  698. std::string const& suffix, cmGeneratorTarget* target,
  699. const std::string& propName, std::vector<T> const& entries,
  700. ImportPropertyMap& properties, std::vector<std::string>& missingTargets)
  701. {
  702. // Skip the property if there are no entries.
  703. if (entries.empty()) {
  704. return;
  705. }
  706. // Construct the property value.
  707. std::string link_entries;
  708. const char* sep = "";
  709. for (typename std::vector<T>::const_iterator li = entries.begin();
  710. li != entries.end(); ++li) {
  711. // Separate this from the previous entry.
  712. link_entries += sep;
  713. sep = ";";
  714. std::string temp = *li;
  715. this->AddTargetNamespace(temp, target, missingTargets);
  716. link_entries += temp;
  717. }
  718. // Store the property.
  719. std::string prop = propName;
  720. prop += suffix;
  721. properties[prop] = link_entries;
  722. }
  723. void cmExportFileGenerator::GeneratePolicyHeaderCode(std::ostream& os)
  724. {
  725. // Protect that file against use with older CMake versions.
  726. /* clang-format off */
  727. os << "# Generated by CMake\n\n";
  728. os << "if(\"${CMAKE_MAJOR_VERSION}.${CMAKE_MINOR_VERSION}\" LESS 2.5)\n"
  729. << " message(FATAL_ERROR \"CMake >= 2.6.0 required\")\n"
  730. << "endif()\n";
  731. /* clang-format on */
  732. // Isolate the file policy level.
  733. // We use 2.6 here instead of the current version because newer
  734. // versions of CMake should be able to export files imported by 2.6
  735. // until the import format changes.
  736. /* clang-format off */
  737. os << "cmake_policy(PUSH)\n"
  738. << "cmake_policy(VERSION 2.6)\n";
  739. /* clang-format on */
  740. }
  741. void cmExportFileGenerator::GeneratePolicyFooterCode(std::ostream& os)
  742. {
  743. os << "cmake_policy(POP)\n";
  744. }
  745. void cmExportFileGenerator::GenerateImportHeaderCode(std::ostream& os,
  746. const std::string& config)
  747. {
  748. os << "#----------------------------------------------------------------\n"
  749. << "# Generated CMake target import file";
  750. if (!config.empty()) {
  751. os << " for configuration \"" << config << "\".\n";
  752. } else {
  753. os << ".\n";
  754. }
  755. os << "#----------------------------------------------------------------\n"
  756. << "\n";
  757. this->GenerateImportVersionCode(os);
  758. }
  759. void cmExportFileGenerator::GenerateImportFooterCode(std::ostream& os)
  760. {
  761. os << "# Commands beyond this point should not need to know the version.\n"
  762. << "set(CMAKE_IMPORT_FILE_VERSION)\n";
  763. }
  764. void cmExportFileGenerator::GenerateImportVersionCode(std::ostream& os)
  765. {
  766. // Store an import file format version. This will let us change the
  767. // format later while still allowing old import files to work.
  768. /* clang-format off */
  769. os << "# Commands may need to know the format version.\n"
  770. << "set(CMAKE_IMPORT_FILE_VERSION 1)\n"
  771. << "\n";
  772. /* clang-format on */
  773. }
  774. void cmExportFileGenerator::GenerateExpectedTargetsCode(
  775. std::ostream& os, const std::string& expectedTargets)
  776. {
  777. /* clang-format off */
  778. os << "# Protect against multiple inclusion, which would fail when already "
  779. "imported targets are added once more.\n"
  780. "set(_targetsDefined)\n"
  781. "set(_targetsNotDefined)\n"
  782. "set(_expectedTargets)\n"
  783. "foreach(_expectedTarget " << expectedTargets << ")\n"
  784. " list(APPEND _expectedTargets ${_expectedTarget})\n"
  785. " if(NOT TARGET ${_expectedTarget})\n"
  786. " list(APPEND _targetsNotDefined ${_expectedTarget})\n"
  787. " endif()\n"
  788. " if(TARGET ${_expectedTarget})\n"
  789. " list(APPEND _targetsDefined ${_expectedTarget})\n"
  790. " endif()\n"
  791. "endforeach()\n"
  792. "if(\"${_targetsDefined}\" STREQUAL \"${_expectedTargets}\")\n"
  793. " unset(_targetsDefined)\n"
  794. " unset(_targetsNotDefined)\n"
  795. " unset(_expectedTargets)\n"
  796. " set(CMAKE_IMPORT_FILE_VERSION)\n"
  797. " cmake_policy(POP)\n"
  798. " return()\n"
  799. "endif()\n"
  800. "if(NOT \"${_targetsDefined}\" STREQUAL \"\")\n"
  801. " message(FATAL_ERROR \"Some (but not all) targets in this export "
  802. "set were already defined.\\nTargets Defined: ${_targetsDefined}\\n"
  803. "Targets not yet defined: ${_targetsNotDefined}\\n\")\n"
  804. "endif()\n"
  805. "unset(_targetsDefined)\n"
  806. "unset(_targetsNotDefined)\n"
  807. "unset(_expectedTargets)\n"
  808. "\n\n";
  809. /* clang-format on */
  810. }
  811. void cmExportFileGenerator::GenerateImportTargetCode(
  812. std::ostream& os, const cmGeneratorTarget* target)
  813. {
  814. // Construct the imported target name.
  815. std::string targetName = this->Namespace;
  816. targetName += target->GetExportName();
  817. // Create the imported target.
  818. os << "# Create imported target " << targetName << "\n";
  819. switch (target->GetType()) {
  820. case cmStateEnums::EXECUTABLE:
  821. os << "add_executable(" << targetName << " IMPORTED)\n";
  822. break;
  823. case cmStateEnums::STATIC_LIBRARY:
  824. os << "add_library(" << targetName << " STATIC IMPORTED)\n";
  825. break;
  826. case cmStateEnums::SHARED_LIBRARY:
  827. os << "add_library(" << targetName << " SHARED IMPORTED)\n";
  828. break;
  829. case cmStateEnums::MODULE_LIBRARY:
  830. os << "add_library(" << targetName << " MODULE IMPORTED)\n";
  831. break;
  832. case cmStateEnums::UNKNOWN_LIBRARY:
  833. os << "add_library(" << targetName << " UNKNOWN IMPORTED)\n";
  834. break;
  835. case cmStateEnums::INTERFACE_LIBRARY:
  836. os << "add_library(" << targetName << " INTERFACE IMPORTED)\n";
  837. break;
  838. default: // should never happen
  839. break;
  840. }
  841. // Mark the imported executable if it has exports.
  842. if (target->IsExecutableWithExports()) {
  843. os << "set_property(TARGET " << targetName
  844. << " PROPERTY ENABLE_EXPORTS 1)\n";
  845. }
  846. // Mark the imported library if it is a framework.
  847. if (target->IsFrameworkOnApple()) {
  848. os << "set_property(TARGET " << targetName << " PROPERTY FRAMEWORK 1)\n";
  849. }
  850. // Mark the imported executable if it is an application bundle.
  851. if (target->IsAppBundleOnApple()) {
  852. os << "set_property(TARGET " << targetName
  853. << " PROPERTY MACOSX_BUNDLE 1)\n";
  854. }
  855. if (target->IsCFBundleOnApple()) {
  856. os << "set_property(TARGET " << targetName << " PROPERTY BUNDLE 1)\n";
  857. }
  858. os << "\n";
  859. }
  860. void cmExportFileGenerator::GenerateImportPropertyCode(
  861. std::ostream& os, const std::string& config, cmGeneratorTarget const* target,
  862. ImportPropertyMap const& properties)
  863. {
  864. // Construct the imported target name.
  865. std::string targetName = this->Namespace;
  866. targetName += target->GetExportName();
  867. // Set the import properties.
  868. os << "# Import target \"" << targetName << "\" for configuration \""
  869. << config << "\"\n";
  870. os << "set_property(TARGET " << targetName
  871. << " APPEND PROPERTY IMPORTED_CONFIGURATIONS ";
  872. if (!config.empty()) {
  873. os << cmSystemTools::UpperCase(config);
  874. } else {
  875. os << "NOCONFIG";
  876. }
  877. os << ")\n";
  878. os << "set_target_properties(" << targetName << " PROPERTIES\n";
  879. for (ImportPropertyMap::const_iterator pi = properties.begin();
  880. pi != properties.end(); ++pi) {
  881. os << " " << pi->first << " " << cmExportFileGeneratorEscape(pi->second)
  882. << "\n";
  883. }
  884. os << " )\n"
  885. << "\n";
  886. }
  887. void cmExportFileGenerator::GenerateMissingTargetsCheckCode(
  888. std::ostream& os, const std::vector<std::string>& missingTargets)
  889. {
  890. if (missingTargets.empty()) {
  891. /* clang-format off */
  892. os << "# This file does not depend on other imported targets which have\n"
  893. "# been exported from the same project but in a separate "
  894. "export set.\n\n";
  895. /* clang-format on */
  896. return;
  897. }
  898. /* clang-format off */
  899. os << "# Make sure the targets which have been exported in some other \n"
  900. "# export set exist.\n"
  901. "unset(${CMAKE_FIND_PACKAGE_NAME}_NOT_FOUND_MESSAGE_targets)\n"
  902. "foreach(_target ";
  903. /* clang-format on */
  904. std::set<std::string> emitted;
  905. for (unsigned int i = 0; i < missingTargets.size(); ++i) {
  906. if (emitted.insert(missingTargets[i]).second) {
  907. os << "\"" << missingTargets[i] << "\" ";
  908. }
  909. }
  910. /* clang-format off */
  911. os << ")\n"
  912. " if(NOT TARGET \"${_target}\" )\n"
  913. " set(${CMAKE_FIND_PACKAGE_NAME}_NOT_FOUND_MESSAGE_targets \""
  914. "${${CMAKE_FIND_PACKAGE_NAME}_NOT_FOUND_MESSAGE_targets} ${_target}\")"
  915. "\n"
  916. " endif()\n"
  917. "endforeach()\n"
  918. "\n"
  919. "if(DEFINED ${CMAKE_FIND_PACKAGE_NAME}_NOT_FOUND_MESSAGE_targets)\n"
  920. " if(CMAKE_FIND_PACKAGE_NAME)\n"
  921. " set( ${CMAKE_FIND_PACKAGE_NAME}_FOUND FALSE)\n"
  922. " set( ${CMAKE_FIND_PACKAGE_NAME}_NOT_FOUND_MESSAGE "
  923. "\"The following imported targets are "
  924. "referenced, but are missing: "
  925. "${${CMAKE_FIND_PACKAGE_NAME}_NOT_FOUND_MESSAGE_targets}\")\n"
  926. " else()\n"
  927. " message(FATAL_ERROR \"The following imported targets are "
  928. "referenced, but are missing: "
  929. "${${CMAKE_FIND_PACKAGE_NAME}_NOT_FOUND_MESSAGE_targets}\")\n"
  930. " endif()\n"
  931. "endif()\n"
  932. "unset(${CMAKE_FIND_PACKAGE_NAME}_NOT_FOUND_MESSAGE_targets)\n"
  933. "\n";
  934. /* clang-format on */
  935. }
  936. void cmExportFileGenerator::GenerateImportedFileCheckLoop(std::ostream& os)
  937. {
  938. // Add code which verifies at cmake time that the file which is being
  939. // imported actually exists on disk. This should in theory always be theory
  940. // case, but still when packages are split into normal and development
  941. // packages this might get broken (e.g. the Config.cmake could be part of
  942. // the non-development package, something similar happened to me without
  943. // on SUSE with a mysql pkg-config file, which claimed everything is fine,
  944. // but the development package was not installed.).
  945. /* clang-format off */
  946. os << "# Loop over all imported files and verify that they actually exist\n"
  947. "foreach(target ${_IMPORT_CHECK_TARGETS} )\n"
  948. " foreach(file ${_IMPORT_CHECK_FILES_FOR_${target}} )\n"
  949. " if(NOT EXISTS \"${file}\" )\n"
  950. " message(FATAL_ERROR \"The imported target \\\"${target}\\\""
  951. " references the file\n"
  952. " \\\"${file}\\\"\n"
  953. "but this file does not exist. Possible reasons include:\n"
  954. "* The file was deleted, renamed, or moved to another location.\n"
  955. "* An install or uninstall procedure did not complete successfully.\n"
  956. "* The installation package was faulty and contained\n"
  957. " \\\"${CMAKE_CURRENT_LIST_FILE}\\\"\n"
  958. "but not all the files it references.\n"
  959. "\")\n"
  960. " endif()\n"
  961. " endforeach()\n"
  962. " unset(_IMPORT_CHECK_FILES_FOR_${target})\n"
  963. "endforeach()\n"
  964. "unset(_IMPORT_CHECK_TARGETS)\n"
  965. "\n";
  966. /* clang-format on */
  967. }
  968. void cmExportFileGenerator::GenerateImportedFileChecksCode(
  969. std::ostream& os, cmGeneratorTarget* target,
  970. ImportPropertyMap const& properties,
  971. const std::set<std::string>& importedLocations)
  972. {
  973. // Construct the imported target name.
  974. std::string targetName = this->Namespace;
  975. targetName += target->GetExportName();
  976. os << "list(APPEND _IMPORT_CHECK_TARGETS " << targetName
  977. << " )\n"
  978. "list(APPEND _IMPORT_CHECK_FILES_FOR_"
  979. << targetName << " ";
  980. for (std::set<std::string>::const_iterator li = importedLocations.begin();
  981. li != importedLocations.end(); ++li) {
  982. ImportPropertyMap::const_iterator pi = properties.find(*li);
  983. if (pi != properties.end()) {
  984. os << cmExportFileGeneratorEscape(pi->second) << " ";
  985. }
  986. }
  987. os << ")\n\n";
  988. }