cmExportFileGenerator.cxx 37 KB

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