cmExportFileGenerator.cxx 37 KB

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