cmExportFileGenerator.cxx 37 KB

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