cmExportFileGenerator.cxx 37 KB

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