cmExportFileGenerator.cxx 37 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105
  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 "cm_auto_ptr.hxx"
  19. #include "cmsys/FStream.hxx"
  20. #include <assert.h>
  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. if (target->GetType() == cmStateEnums::OBJECT_LIBRARY) {
  400. // object libraries have no link information, so nothing to compute
  401. return;
  402. }
  403. cmComputeLinkInformation* info = target->GetLinkInformation(config);
  404. if (!info) {
  405. cmLocalGenerator* lg = target->GetLocalGenerator();
  406. std::ostringstream e;
  407. e << "Exporting the target \"" << target->GetName()
  408. << "\" is not "
  409. "allowed since its linker language cannot be determined";
  410. lg->IssueMessage(cmake::FATAL_ERROR, e.str());
  411. return;
  412. }
  413. const cmComputeLinkInformation::ItemVector& deps = info->GetItems();
  414. for (cmComputeLinkInformation::ItemVector::const_iterator li = deps.begin();
  415. li != deps.end(); ++li) {
  416. if (!li->Target) {
  417. continue;
  418. }
  419. getPropertyContents(li->Target, "COMPATIBLE_INTERFACE_BOOL",
  420. ifaceProperties);
  421. getPropertyContents(li->Target, "COMPATIBLE_INTERFACE_STRING",
  422. ifaceProperties);
  423. getPropertyContents(li->Target, "COMPATIBLE_INTERFACE_NUMBER_MIN",
  424. ifaceProperties);
  425. getPropertyContents(li->Target, "COMPATIBLE_INTERFACE_NUMBER_MAX",
  426. ifaceProperties);
  427. }
  428. }
  429. void cmExportFileGenerator::PopulateCompatibleInterfaceProperties(
  430. cmGeneratorTarget* gtarget, ImportPropertyMap& properties)
  431. {
  432. this->PopulateInterfaceProperty("COMPATIBLE_INTERFACE_BOOL", gtarget,
  433. properties);
  434. this->PopulateInterfaceProperty("COMPATIBLE_INTERFACE_STRING", gtarget,
  435. properties);
  436. this->PopulateInterfaceProperty("COMPATIBLE_INTERFACE_NUMBER_MIN", gtarget,
  437. properties);
  438. this->PopulateInterfaceProperty("COMPATIBLE_INTERFACE_NUMBER_MAX", gtarget,
  439. properties);
  440. std::set<std::string> ifaceProperties;
  441. getPropertyContents(gtarget, "COMPATIBLE_INTERFACE_BOOL", ifaceProperties);
  442. getPropertyContents(gtarget, "COMPATIBLE_INTERFACE_STRING", ifaceProperties);
  443. getPropertyContents(gtarget, "COMPATIBLE_INTERFACE_NUMBER_MIN",
  444. ifaceProperties);
  445. getPropertyContents(gtarget, "COMPATIBLE_INTERFACE_NUMBER_MAX",
  446. ifaceProperties);
  447. if (gtarget->GetType() != cmStateEnums::INTERFACE_LIBRARY) {
  448. getCompatibleInterfaceProperties(gtarget, ifaceProperties, "");
  449. std::vector<std::string> configNames;
  450. gtarget->Target->GetMakefile()->GetConfigurations(configNames);
  451. for (std::vector<std::string>::const_iterator ci = configNames.begin();
  452. ci != configNames.end(); ++ci) {
  453. getCompatibleInterfaceProperties(gtarget, ifaceProperties, *ci);
  454. }
  455. }
  456. for (std::set<std::string>::const_iterator it = ifaceProperties.begin();
  457. it != ifaceProperties.end(); ++it) {
  458. this->PopulateInterfaceProperty("INTERFACE_" + *it, gtarget, properties);
  459. }
  460. }
  461. void cmExportFileGenerator::GenerateInterfaceProperties(
  462. const cmGeneratorTarget* target, std::ostream& os,
  463. const ImportPropertyMap& properties)
  464. {
  465. if (!properties.empty()) {
  466. std::string targetName = this->Namespace;
  467. targetName += target->GetExportName();
  468. os << "set_target_properties(" << targetName << " PROPERTIES\n";
  469. for (ImportPropertyMap::const_iterator pi = properties.begin();
  470. pi != properties.end(); ++pi) {
  471. os << " " << pi->first << " " << cmExportFileGeneratorEscape(pi->second)
  472. << "\n";
  473. }
  474. os << ")\n\n";
  475. }
  476. }
  477. bool cmExportFileGenerator::AddTargetNamespace(
  478. std::string& input, cmGeneratorTarget* target,
  479. std::vector<std::string>& missingTargets)
  480. {
  481. cmLocalGenerator* lg = target->GetLocalGenerator();
  482. cmGeneratorTarget* tgt = lg->FindGeneratorTargetToUse(input);
  483. if (!tgt) {
  484. return false;
  485. }
  486. if (tgt->IsImported()) {
  487. return true;
  488. }
  489. if (this->ExportedTargets.find(tgt) != this->ExportedTargets.end()) {
  490. input = this->Namespace + tgt->GetExportName();
  491. } else {
  492. std::string namespacedTarget;
  493. this->HandleMissingTarget(namespacedTarget, missingTargets, target, tgt);
  494. if (!namespacedTarget.empty()) {
  495. input = namespacedTarget;
  496. }
  497. }
  498. return true;
  499. }
  500. void cmExportFileGenerator::ResolveTargetsInGeneratorExpressions(
  501. std::string& input, cmGeneratorTarget* target,
  502. std::vector<std::string>& missingTargets, FreeTargetsReplace replace)
  503. {
  504. if (replace == NoReplaceFreeTargets) {
  505. this->ResolveTargetsInGeneratorExpression(input, target, missingTargets);
  506. return;
  507. }
  508. std::vector<std::string> parts;
  509. cmGeneratorExpression::Split(input, parts);
  510. std::string sep;
  511. input = "";
  512. for (std::vector<std::string>::iterator li = parts.begin();
  513. li != parts.end(); ++li) {
  514. if (cmGeneratorExpression::Find(*li) == std::string::npos) {
  515. this->AddTargetNamespace(*li, target, missingTargets);
  516. } else {
  517. this->ResolveTargetsInGeneratorExpression(*li, target, missingTargets);
  518. }
  519. input += sep + *li;
  520. sep = ";";
  521. }
  522. }
  523. void cmExportFileGenerator::ResolveTargetsInGeneratorExpression(
  524. std::string& input, cmGeneratorTarget* target,
  525. std::vector<std::string>& missingTargets)
  526. {
  527. std::string::size_type pos = 0;
  528. std::string::size_type lastPos = pos;
  529. while ((pos = input.find("$<TARGET_PROPERTY:", lastPos)) !=
  530. std::string::npos) {
  531. std::string::size_type nameStartPos =
  532. pos + sizeof("$<TARGET_PROPERTY:") - 1;
  533. std::string::size_type closePos = input.find('>', nameStartPos);
  534. std::string::size_type commaPos = input.find(',', nameStartPos);
  535. std::string::size_type nextOpenPos = input.find("$<", nameStartPos);
  536. if (commaPos == std::string::npos // Implied 'this' target
  537. || closePos == std::string::npos // Imcomplete expression.
  538. || closePos < commaPos // Implied 'this' target
  539. || nextOpenPos < commaPos) // Non-literal
  540. {
  541. lastPos = nameStartPos;
  542. continue;
  543. }
  544. std::string targetName =
  545. input.substr(nameStartPos, commaPos - nameStartPos);
  546. if (this->AddTargetNamespace(targetName, target, missingTargets)) {
  547. input.replace(nameStartPos, commaPos - nameStartPos, targetName);
  548. }
  549. lastPos = nameStartPos + targetName.size() + 1;
  550. }
  551. std::string errorString;
  552. pos = 0;
  553. lastPos = pos;
  554. while ((pos = input.find("$<TARGET_NAME:", lastPos)) != std::string::npos) {
  555. std::string::size_type nameStartPos = pos + sizeof("$<TARGET_NAME:") - 1;
  556. std::string::size_type endPos = input.find('>', nameStartPos);
  557. if (endPos == std::string::npos) {
  558. errorString = "$<TARGET_NAME:...> expression incomplete";
  559. break;
  560. }
  561. std::string targetName = input.substr(nameStartPos, endPos - nameStartPos);
  562. if (targetName.find("$<") != std::string::npos) {
  563. errorString = "$<TARGET_NAME:...> requires its parameter to be a "
  564. "literal.";
  565. break;
  566. }
  567. if (!this->AddTargetNamespace(targetName, target, missingTargets)) {
  568. errorString = "$<TARGET_NAME:...> requires its parameter to be a "
  569. "reachable target.";
  570. break;
  571. }
  572. input.replace(pos, endPos - pos + 1, targetName);
  573. lastPos = endPos;
  574. }
  575. pos = 0;
  576. lastPos = pos;
  577. while (errorString.empty() &&
  578. (pos = input.find("$<LINK_ONLY:", lastPos)) != std::string::npos) {
  579. std::string::size_type nameStartPos = pos + sizeof("$<LINK_ONLY:") - 1;
  580. std::string::size_type endPos = input.find('>', nameStartPos);
  581. if (endPos == std::string::npos) {
  582. errorString = "$<LINK_ONLY:...> expression incomplete";
  583. break;
  584. }
  585. std::string libName = input.substr(nameStartPos, endPos - nameStartPos);
  586. if (cmGeneratorExpression::IsValidTargetName(libName) &&
  587. this->AddTargetNamespace(libName, target, missingTargets)) {
  588. input.replace(nameStartPos, endPos - nameStartPos, libName);
  589. }
  590. lastPos = nameStartPos + libName.size() + 1;
  591. }
  592. this->ReplaceInstallPrefix(input);
  593. if (!errorString.empty()) {
  594. target->GetLocalGenerator()->IssueMessage(cmake::FATAL_ERROR, errorString);
  595. }
  596. }
  597. void cmExportFileGenerator::ReplaceInstallPrefix(std::string& /*unused*/)
  598. {
  599. // Do nothing
  600. }
  601. void cmExportFileGenerator::SetImportLinkInterface(
  602. const std::string& config, std::string const& suffix,
  603. cmGeneratorExpression::PreprocessContext preprocessRule,
  604. cmGeneratorTarget* target, ImportPropertyMap& properties,
  605. std::vector<std::string>& missingTargets)
  606. {
  607. // Add the transitive link dependencies for this configuration.
  608. cmLinkInterface const* iface = target->GetLinkInterface(config, target);
  609. if (!iface) {
  610. return;
  611. }
  612. if (iface->ImplementationIsInterface) {
  613. // Policy CMP0022 must not be NEW.
  614. this->SetImportLinkProperty(suffix, target,
  615. "IMPORTED_LINK_INTERFACE_LIBRARIES",
  616. iface->Libraries, properties, missingTargets);
  617. return;
  618. }
  619. const char* propContent;
  620. if (const char* prop_suffixed =
  621. target->GetProperty("LINK_INTERFACE_LIBRARIES" + suffix)) {
  622. propContent = prop_suffixed;
  623. } else if (const char* prop =
  624. target->GetProperty("LINK_INTERFACE_LIBRARIES")) {
  625. propContent = prop;
  626. } else {
  627. return;
  628. }
  629. const bool newCMP0022Behavior =
  630. target->GetPolicyStatusCMP0022() != cmPolicies::WARN &&
  631. target->GetPolicyStatusCMP0022() != cmPolicies::OLD;
  632. if (newCMP0022Behavior && !this->ExportOld) {
  633. cmLocalGenerator* lg = target->GetLocalGenerator();
  634. std::ostringstream e;
  635. e << "Target \"" << target->GetName()
  636. << "\" has policy CMP0022 enabled, "
  637. "but also has old-style LINK_INTERFACE_LIBRARIES properties "
  638. "populated, but it was exported without the "
  639. "EXPORT_LINK_INTERFACE_LIBRARIES to export the old-style properties";
  640. lg->IssueMessage(cmake::FATAL_ERROR, e.str());
  641. return;
  642. }
  643. if (!*propContent) {
  644. properties["IMPORTED_LINK_INTERFACE_LIBRARIES" + suffix] = "";
  645. return;
  646. }
  647. std::string prepro =
  648. cmGeneratorExpression::Preprocess(propContent, preprocessRule);
  649. if (!prepro.empty()) {
  650. this->ResolveTargetsInGeneratorExpressions(prepro, target, missingTargets,
  651. ReplaceFreeTargets);
  652. properties["IMPORTED_LINK_INTERFACE_LIBRARIES" + suffix] = prepro;
  653. }
  654. }
  655. void cmExportFileGenerator::SetImportDetailProperties(
  656. const std::string& config, std::string const& suffix,
  657. cmGeneratorTarget* target, ImportPropertyMap& properties,
  658. std::vector<std::string>& missingTargets)
  659. {
  660. // Get the makefile in which to lookup target information.
  661. cmMakefile* mf = target->Makefile;
  662. // Add the soname for unix shared libraries.
  663. if (target->GetType() == cmStateEnums::SHARED_LIBRARY ||
  664. target->GetType() == cmStateEnums::MODULE_LIBRARY) {
  665. if (!target->IsDLLPlatform()) {
  666. std::string prop;
  667. std::string value;
  668. if (target->HasSOName(config)) {
  669. if (mf->IsOn("CMAKE_PLATFORM_HAS_INSTALLNAME")) {
  670. value = this->InstallNameDir(target, config);
  671. }
  672. prop = "IMPORTED_SONAME";
  673. value += target->GetSOName(config);
  674. } else {
  675. prop = "IMPORTED_NO_SONAME";
  676. value = "TRUE";
  677. }
  678. prop += suffix;
  679. properties[prop] = value;
  680. }
  681. }
  682. // Add the transitive link dependencies for this configuration.
  683. if (cmLinkInterface const* iface =
  684. target->GetLinkInterface(config, target)) {
  685. this->SetImportLinkProperty(suffix, target,
  686. "IMPORTED_LINK_INTERFACE_LANGUAGES",
  687. iface->Languages, properties, missingTargets);
  688. std::vector<std::string> dummy;
  689. this->SetImportLinkProperty(suffix, target,
  690. "IMPORTED_LINK_DEPENDENT_LIBRARIES",
  691. iface->SharedDeps, properties, dummy);
  692. if (iface->Multiplicity > 0) {
  693. std::string prop = "IMPORTED_LINK_INTERFACE_MULTIPLICITY";
  694. prop += suffix;
  695. std::ostringstream m;
  696. m << iface->Multiplicity;
  697. properties[prop] = m.str();
  698. }
  699. }
  700. }
  701. template <typename T>
  702. void cmExportFileGenerator::SetImportLinkProperty(
  703. std::string const& suffix, cmGeneratorTarget* target,
  704. const std::string& propName, std::vector<T> const& entries,
  705. ImportPropertyMap& properties, std::vector<std::string>& missingTargets)
  706. {
  707. // Skip the property if there are no entries.
  708. if (entries.empty()) {
  709. return;
  710. }
  711. // Construct the property value.
  712. std::string link_entries;
  713. const char* sep = "";
  714. for (typename std::vector<T>::const_iterator li = entries.begin();
  715. li != entries.end(); ++li) {
  716. // Separate this from the previous entry.
  717. link_entries += sep;
  718. sep = ";";
  719. std::string temp = *li;
  720. this->AddTargetNamespace(temp, target, missingTargets);
  721. link_entries += temp;
  722. }
  723. // Store the property.
  724. std::string prop = propName;
  725. prop += suffix;
  726. properties[prop] = link_entries;
  727. }
  728. void cmExportFileGenerator::GeneratePolicyHeaderCode(std::ostream& os)
  729. {
  730. // Protect that file against use with older CMake versions.
  731. /* clang-format off */
  732. os << "# Generated by CMake\n\n";
  733. os << "if(\"${CMAKE_MAJOR_VERSION}.${CMAKE_MINOR_VERSION}\" LESS 2.5)\n"
  734. << " message(FATAL_ERROR \"CMake >= 2.6.0 required\")\n"
  735. << "endif()\n";
  736. /* clang-format on */
  737. // Isolate the file policy level.
  738. // We use 2.6 here instead of the current version because newer
  739. // versions of CMake should be able to export files imported by 2.6
  740. // until the import format changes.
  741. /* clang-format off */
  742. os << "cmake_policy(PUSH)\n"
  743. << "cmake_policy(VERSION 2.6)\n";
  744. /* clang-format on */
  745. }
  746. void cmExportFileGenerator::GeneratePolicyFooterCode(std::ostream& os)
  747. {
  748. os << "cmake_policy(POP)\n";
  749. }
  750. void cmExportFileGenerator::GenerateImportHeaderCode(std::ostream& os,
  751. const std::string& config)
  752. {
  753. os << "#----------------------------------------------------------------\n"
  754. << "# Generated CMake target import file";
  755. if (!config.empty()) {
  756. os << " for configuration \"" << config << "\".\n";
  757. } else {
  758. os << ".\n";
  759. }
  760. os << "#----------------------------------------------------------------\n"
  761. << "\n";
  762. this->GenerateImportVersionCode(os);
  763. }
  764. void cmExportFileGenerator::GenerateImportFooterCode(std::ostream& os)
  765. {
  766. os << "# Commands beyond this point should not need to know the version.\n"
  767. << "set(CMAKE_IMPORT_FILE_VERSION)\n";
  768. }
  769. void cmExportFileGenerator::GenerateImportVersionCode(std::ostream& os)
  770. {
  771. // Store an import file format version. This will let us change the
  772. // format later while still allowing old import files to work.
  773. /* clang-format off */
  774. os << "# Commands may need to know the format version.\n"
  775. << "set(CMAKE_IMPORT_FILE_VERSION 1)\n"
  776. << "\n";
  777. /* clang-format on */
  778. }
  779. void cmExportFileGenerator::GenerateExpectedTargetsCode(
  780. std::ostream& os, const std::string& expectedTargets)
  781. {
  782. /* clang-format off */
  783. os << "# Protect against multiple inclusion, which would fail when already "
  784. "imported targets are added once more.\n"
  785. "set(_targetsDefined)\n"
  786. "set(_targetsNotDefined)\n"
  787. "set(_expectedTargets)\n"
  788. "foreach(_expectedTarget " << expectedTargets << ")\n"
  789. " list(APPEND _expectedTargets ${_expectedTarget})\n"
  790. " if(NOT TARGET ${_expectedTarget})\n"
  791. " list(APPEND _targetsNotDefined ${_expectedTarget})\n"
  792. " endif()\n"
  793. " if(TARGET ${_expectedTarget})\n"
  794. " list(APPEND _targetsDefined ${_expectedTarget})\n"
  795. " endif()\n"
  796. "endforeach()\n"
  797. "if(\"${_targetsDefined}\" STREQUAL \"${_expectedTargets}\")\n"
  798. " unset(_targetsDefined)\n"
  799. " unset(_targetsNotDefined)\n"
  800. " unset(_expectedTargets)\n"
  801. " set(CMAKE_IMPORT_FILE_VERSION)\n"
  802. " cmake_policy(POP)\n"
  803. " return()\n"
  804. "endif()\n"
  805. "if(NOT \"${_targetsDefined}\" STREQUAL \"\")\n"
  806. " message(FATAL_ERROR \"Some (but not all) targets in this export "
  807. "set were already defined.\\nTargets Defined: ${_targetsDefined}\\n"
  808. "Targets not yet defined: ${_targetsNotDefined}\\n\")\n"
  809. "endif()\n"
  810. "unset(_targetsDefined)\n"
  811. "unset(_targetsNotDefined)\n"
  812. "unset(_expectedTargets)\n"
  813. "\n\n";
  814. /* clang-format on */
  815. }
  816. void cmExportFileGenerator::GenerateImportTargetCode(
  817. std::ostream& os, const cmGeneratorTarget* target)
  818. {
  819. // Construct the imported target name.
  820. std::string targetName = this->Namespace;
  821. targetName += target->GetExportName();
  822. // Create the imported target.
  823. os << "# Create imported target " << targetName << "\n";
  824. switch (target->GetType()) {
  825. case cmStateEnums::EXECUTABLE:
  826. os << "add_executable(" << targetName << " IMPORTED)\n";
  827. break;
  828. case cmStateEnums::STATIC_LIBRARY:
  829. os << "add_library(" << targetName << " STATIC IMPORTED)\n";
  830. break;
  831. case cmStateEnums::SHARED_LIBRARY:
  832. os << "add_library(" << targetName << " SHARED IMPORTED)\n";
  833. break;
  834. case cmStateEnums::MODULE_LIBRARY:
  835. os << "add_library(" << targetName << " MODULE IMPORTED)\n";
  836. break;
  837. case cmStateEnums::UNKNOWN_LIBRARY:
  838. os << "add_library(" << targetName << " UNKNOWN IMPORTED)\n";
  839. break;
  840. case cmStateEnums::OBJECT_LIBRARY:
  841. os << "add_library(" << targetName << " OBJECT IMPORTED)\n";
  842. break;
  843. case cmStateEnums::INTERFACE_LIBRARY:
  844. os << "add_library(" << targetName << " INTERFACE IMPORTED)\n";
  845. break;
  846. default: // should never happen
  847. break;
  848. }
  849. // Mark the imported executable if it has exports.
  850. if (target->IsExecutableWithExports()) {
  851. os << "set_property(TARGET " << targetName
  852. << " PROPERTY ENABLE_EXPORTS 1)\n";
  853. }
  854. // Mark the imported library if it is a framework.
  855. if (target->IsFrameworkOnApple()) {
  856. os << "set_property(TARGET " << targetName << " PROPERTY FRAMEWORK 1)\n";
  857. }
  858. // Mark the imported executable if it is an application bundle.
  859. if (target->IsAppBundleOnApple()) {
  860. os << "set_property(TARGET " << targetName
  861. << " PROPERTY MACOSX_BUNDLE 1)\n";
  862. }
  863. if (target->IsCFBundleOnApple()) {
  864. os << "set_property(TARGET " << targetName << " PROPERTY BUNDLE 1)\n";
  865. }
  866. os << "\n";
  867. }
  868. void cmExportFileGenerator::GenerateImportPropertyCode(
  869. std::ostream& os, const std::string& config, cmGeneratorTarget const* target,
  870. ImportPropertyMap const& properties)
  871. {
  872. // Construct the imported target name.
  873. std::string targetName = this->Namespace;
  874. targetName += target->GetExportName();
  875. // Set the import properties.
  876. os << "# Import target \"" << targetName << "\" for configuration \""
  877. << config << "\"\n";
  878. os << "set_property(TARGET " << targetName
  879. << " APPEND PROPERTY IMPORTED_CONFIGURATIONS ";
  880. if (!config.empty()) {
  881. os << cmSystemTools::UpperCase(config);
  882. } else {
  883. os << "NOCONFIG";
  884. }
  885. os << ")\n";
  886. os << "set_target_properties(" << targetName << " PROPERTIES\n";
  887. for (ImportPropertyMap::const_iterator pi = properties.begin();
  888. pi != properties.end(); ++pi) {
  889. os << " " << pi->first << " " << cmExportFileGeneratorEscape(pi->second)
  890. << "\n";
  891. }
  892. os << " )\n"
  893. << "\n";
  894. }
  895. void cmExportFileGenerator::GenerateMissingTargetsCheckCode(
  896. std::ostream& os, const std::vector<std::string>& missingTargets)
  897. {
  898. if (missingTargets.empty()) {
  899. /* clang-format off */
  900. os << "# This file does not depend on other imported targets which have\n"
  901. "# been exported from the same project but in a separate "
  902. "export set.\n\n";
  903. /* clang-format on */
  904. return;
  905. }
  906. /* clang-format off */
  907. os << "# Make sure the targets which have been exported in some other \n"
  908. "# export set exist.\n"
  909. "unset(${CMAKE_FIND_PACKAGE_NAME}_NOT_FOUND_MESSAGE_targets)\n"
  910. "foreach(_target ";
  911. /* clang-format on */
  912. std::set<std::string> emitted;
  913. for (unsigned int i = 0; i < missingTargets.size(); ++i) {
  914. if (emitted.insert(missingTargets[i]).second) {
  915. os << "\"" << missingTargets[i] << "\" ";
  916. }
  917. }
  918. /* clang-format off */
  919. os << ")\n"
  920. " if(NOT TARGET \"${_target}\" )\n"
  921. " set(${CMAKE_FIND_PACKAGE_NAME}_NOT_FOUND_MESSAGE_targets \""
  922. "${${CMAKE_FIND_PACKAGE_NAME}_NOT_FOUND_MESSAGE_targets} ${_target}\")"
  923. "\n"
  924. " endif()\n"
  925. "endforeach()\n"
  926. "\n"
  927. "if(DEFINED ${CMAKE_FIND_PACKAGE_NAME}_NOT_FOUND_MESSAGE_targets)\n"
  928. " if(CMAKE_FIND_PACKAGE_NAME)\n"
  929. " set( ${CMAKE_FIND_PACKAGE_NAME}_FOUND FALSE)\n"
  930. " set( ${CMAKE_FIND_PACKAGE_NAME}_NOT_FOUND_MESSAGE "
  931. "\"The following imported targets are "
  932. "referenced, but are missing: "
  933. "${${CMAKE_FIND_PACKAGE_NAME}_NOT_FOUND_MESSAGE_targets}\")\n"
  934. " else()\n"
  935. " message(FATAL_ERROR \"The following imported targets are "
  936. "referenced, but are missing: "
  937. "${${CMAKE_FIND_PACKAGE_NAME}_NOT_FOUND_MESSAGE_targets}\")\n"
  938. " endif()\n"
  939. "endif()\n"
  940. "unset(${CMAKE_FIND_PACKAGE_NAME}_NOT_FOUND_MESSAGE_targets)\n"
  941. "\n";
  942. /* clang-format on */
  943. }
  944. void cmExportFileGenerator::GenerateImportedFileCheckLoop(std::ostream& os)
  945. {
  946. // Add code which verifies at cmake time that the file which is being
  947. // imported actually exists on disk. This should in theory always be theory
  948. // case, but still when packages are split into normal and development
  949. // packages this might get broken (e.g. the Config.cmake could be part of
  950. // the non-development package, something similar happened to me without
  951. // on SUSE with a mysql pkg-config file, which claimed everything is fine,
  952. // but the development package was not installed.).
  953. /* clang-format off */
  954. os << "# Loop over all imported files and verify that they actually exist\n"
  955. "foreach(target ${_IMPORT_CHECK_TARGETS} )\n"
  956. " foreach(file ${_IMPORT_CHECK_FILES_FOR_${target}} )\n"
  957. " if(NOT EXISTS \"${file}\" )\n"
  958. " message(FATAL_ERROR \"The imported target \\\"${target}\\\""
  959. " references the file\n"
  960. " \\\"${file}\\\"\n"
  961. "but this file does not exist. Possible reasons include:\n"
  962. "* The file was deleted, renamed, or moved to another location.\n"
  963. "* An install or uninstall procedure did not complete successfully.\n"
  964. "* The installation package was faulty and contained\n"
  965. " \\\"${CMAKE_CURRENT_LIST_FILE}\\\"\n"
  966. "but not all the files it references.\n"
  967. "\")\n"
  968. " endif()\n"
  969. " endforeach()\n"
  970. " unset(_IMPORT_CHECK_FILES_FOR_${target})\n"
  971. "endforeach()\n"
  972. "unset(_IMPORT_CHECK_TARGETS)\n"
  973. "\n";
  974. /* clang-format on */
  975. }
  976. void cmExportFileGenerator::GenerateImportedFileChecksCode(
  977. std::ostream& os, cmGeneratorTarget* target,
  978. ImportPropertyMap const& properties,
  979. const std::set<std::string>& importedLocations)
  980. {
  981. // Construct the imported target name.
  982. std::string targetName = this->Namespace;
  983. targetName += target->GetExportName();
  984. os << "list(APPEND _IMPORT_CHECK_TARGETS " << targetName
  985. << " )\n"
  986. "list(APPEND _IMPORT_CHECK_FILES_FOR_"
  987. << targetName << " ";
  988. for (std::set<std::string>::const_iterator li = importedLocations.begin();
  989. li != importedLocations.end(); ++li) {
  990. ImportPropertyMap::const_iterator pi = properties.find(*li);
  991. if (pi != properties.end()) {
  992. os << cmExportFileGeneratorEscape(pi->second) << " ";
  993. }
  994. }
  995. os << ")\n\n";
  996. }