cmExportFileGenerator.cxx 37 KB

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