cmExportBuildFileGenerator.cxx 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579
  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 "cmExportBuildFileGenerator.h"
  4. #include <algorithm>
  5. #include <cstddef>
  6. #include <map>
  7. #include <memory>
  8. #include <set>
  9. #include <sstream>
  10. #include <utility>
  11. #include <cm/string_view>
  12. #include <cmext/algorithm>
  13. #include <cmext/string_view>
  14. #include "cmCryptoHash.h"
  15. #include "cmExportSet.h"
  16. #include "cmFileSet.h"
  17. #include "cmGeneratedFileStream.h"
  18. #include "cmGeneratorExpression.h"
  19. #include "cmGeneratorTarget.h"
  20. #include "cmGlobalGenerator.h"
  21. #include "cmList.h"
  22. #include "cmLocalGenerator.h"
  23. #include "cmMakefile.h"
  24. #include "cmMessageType.h"
  25. #include "cmOutputConverter.h"
  26. #include "cmPolicies.h"
  27. #include "cmStateTypes.h"
  28. #include "cmStringAlgorithms.h"
  29. #include "cmSystemTools.h"
  30. #include "cmTarget.h"
  31. #include "cmTargetExport.h"
  32. #include "cmValue.h"
  33. #include "cmake.h"
  34. class cmSourceFile;
  35. cmExportBuildFileGenerator::cmExportBuildFileGenerator()
  36. {
  37. this->LG = nullptr;
  38. this->ExportSet = nullptr;
  39. }
  40. void cmExportBuildFileGenerator::Compute(cmLocalGenerator* lg)
  41. {
  42. this->LG = lg;
  43. if (this->ExportSet) {
  44. this->ExportSet->Compute(lg);
  45. }
  46. }
  47. bool cmExportBuildFileGenerator::GenerateMainFile(std::ostream& os)
  48. {
  49. {
  50. std::string expectedTargets;
  51. std::string sep;
  52. std::vector<std::string> targets;
  53. bool generatedInterfaceRequired = false;
  54. this->GetTargets(targets);
  55. for (std::string const& tei : targets) {
  56. cmGeneratorTarget* te = this->LG->FindGeneratorTargetToUse(tei);
  57. expectedTargets += sep + this->Namespace + te->GetExportName();
  58. sep = " ";
  59. if (this->ExportedTargets.insert(te).second) {
  60. this->Exports.push_back(te);
  61. } else {
  62. std::ostringstream e;
  63. e << "given target \"" << te->GetName() << "\" more than once.";
  64. this->LG->GetGlobalGenerator()->GetCMakeInstance()->IssueMessage(
  65. MessageType::FATAL_ERROR, e.str(),
  66. this->LG->GetMakefile()->GetBacktrace());
  67. return false;
  68. }
  69. generatedInterfaceRequired |=
  70. this->GetExportTargetType(te) == cmStateEnums::INTERFACE_LIBRARY;
  71. }
  72. if (generatedInterfaceRequired) {
  73. this->GenerateRequiredCMakeVersion(os, "3.0.0");
  74. }
  75. this->GenerateExpectedTargetsCode(os, expectedTargets);
  76. }
  77. // Create all the imported targets.
  78. for (cmGeneratorTarget* gte : this->Exports) {
  79. this->GenerateImportTargetCode(os, gte, this->GetExportTargetType(gte));
  80. gte->Target->AppendBuildInterfaceIncludes();
  81. ImportPropertyMap properties;
  82. this->PopulateInterfaceProperty("INTERFACE_INCLUDE_DIRECTORIES", gte,
  83. cmGeneratorExpression::BuildInterface,
  84. properties);
  85. this->PopulateInterfaceProperty("INTERFACE_SOURCES", gte,
  86. cmGeneratorExpression::BuildInterface,
  87. properties);
  88. this->PopulateInterfaceProperty("INTERFACE_COMPILE_DEFINITIONS", gte,
  89. cmGeneratorExpression::BuildInterface,
  90. properties);
  91. this->PopulateInterfaceProperty("INTERFACE_COMPILE_OPTIONS", gte,
  92. cmGeneratorExpression::BuildInterface,
  93. properties);
  94. this->PopulateInterfaceProperty("INTERFACE_PRECOMPILE_HEADERS", gte,
  95. cmGeneratorExpression::BuildInterface,
  96. properties);
  97. this->PopulateInterfaceProperty("INTERFACE_AUTOUIC_OPTIONS", gte,
  98. cmGeneratorExpression::BuildInterface,
  99. properties);
  100. this->PopulateInterfaceProperty("INTERFACE_AUTOMOC_MACRO_NAMES", gte,
  101. cmGeneratorExpression::BuildInterface,
  102. properties);
  103. this->PopulateInterfaceProperty("INTERFACE_COMPILE_FEATURES", gte,
  104. cmGeneratorExpression::BuildInterface,
  105. properties);
  106. this->PopulateInterfaceProperty("INTERFACE_LINK_OPTIONS", gte,
  107. cmGeneratorExpression::BuildInterface,
  108. properties);
  109. this->PopulateInterfaceProperty("INTERFACE_LINK_DIRECTORIES", gte,
  110. cmGeneratorExpression::BuildInterface,
  111. properties);
  112. this->PopulateInterfaceProperty("INTERFACE_LINK_DEPENDS", gte,
  113. cmGeneratorExpression::BuildInterface,
  114. properties);
  115. this->PopulateInterfaceProperty("INTERFACE_POSITION_INDEPENDENT_CODE", gte,
  116. properties);
  117. std::string errorMessage;
  118. if (!this->PopulateCxxModuleExportProperties(
  119. gte, properties, cmGeneratorExpression::BuildInterface, {},
  120. errorMessage)) {
  121. this->LG->GetGlobalGenerator()->GetCMakeInstance()->IssueMessage(
  122. MessageType::FATAL_ERROR, errorMessage,
  123. this->LG->GetMakefile()->GetBacktrace());
  124. return false;
  125. }
  126. if (!this->PopulateExportProperties(gte, properties, errorMessage)) {
  127. this->LG->GetGlobalGenerator()->GetCMakeInstance()->IssueMessage(
  128. MessageType::FATAL_ERROR, errorMessage,
  129. this->LG->GetMakefile()->GetBacktrace());
  130. return false;
  131. }
  132. const bool newCMP0022Behavior =
  133. gte->GetPolicyStatusCMP0022() != cmPolicies::WARN &&
  134. gte->GetPolicyStatusCMP0022() != cmPolicies::OLD;
  135. if (newCMP0022Behavior) {
  136. this->PopulateInterfaceLinkLibrariesProperty(
  137. gte, cmGeneratorExpression::BuildInterface, properties);
  138. }
  139. this->PopulateCompatibleInterfaceProperties(gte, properties);
  140. this->GenerateInterfaceProperties(gte, os, properties);
  141. this->GenerateTargetFileSets(gte, os);
  142. }
  143. std::string cxx_modules_name;
  144. if (this->ExportSet) {
  145. cxx_modules_name = this->ExportSet->GetName();
  146. } else {
  147. cmCryptoHash hasher(cmCryptoHash::AlgoSHA3_512);
  148. constexpr std::size_t HASH_TRUNCATION = 12;
  149. for (auto const& target : this->Targets) {
  150. hasher.Append(target);
  151. }
  152. cxx_modules_name = hasher.FinalizeHex().substr(0, HASH_TRUNCATION);
  153. }
  154. this->GenerateCxxModuleInformation(cxx_modules_name, os);
  155. // Generate import file content for each configuration.
  156. for (std::string const& c : this->Configurations) {
  157. this->GenerateImportConfig(os, c);
  158. }
  159. // Generate import file content for each configuration.
  160. for (std::string const& c : this->Configurations) {
  161. this->GenerateImportCxxModuleConfigTargetInclusion(cxx_modules_name, c);
  162. }
  163. this->GenerateMissingTargetsCheckCode(os);
  164. return true;
  165. }
  166. void cmExportBuildFileGenerator::GenerateImportTargetsConfig(
  167. std::ostream& os, const std::string& config, std::string const& suffix)
  168. {
  169. for (cmGeneratorTarget* target : this->Exports) {
  170. // Collect import properties for this target.
  171. ImportPropertyMap properties;
  172. if (this->GetExportTargetType(target) != cmStateEnums::INTERFACE_LIBRARY) {
  173. this->SetImportLocationProperty(config, suffix, target, properties);
  174. }
  175. if (!properties.empty()) {
  176. // Get the rest of the target details.
  177. if (this->GetExportTargetType(target) !=
  178. cmStateEnums::INTERFACE_LIBRARY) {
  179. this->SetImportDetailProperties(config, suffix, target, properties);
  180. this->SetImportLinkInterface(config, suffix,
  181. cmGeneratorExpression::BuildInterface,
  182. target, properties);
  183. }
  184. // TODO: PUBLIC_HEADER_LOCATION
  185. // This should wait until the build feature propagation stuff
  186. // is done. Then this can be a propagated include directory.
  187. // this->GenerateImportProperty(config, te->HeaderGenerator,
  188. // properties);
  189. // Generate code in the export file.
  190. this->GenerateImportPropertyCode(os, config, target, properties);
  191. }
  192. }
  193. }
  194. cmStateEnums::TargetType cmExportBuildFileGenerator::GetExportTargetType(
  195. cmGeneratorTarget const* target) const
  196. {
  197. cmStateEnums::TargetType targetType = target->GetType();
  198. // An object library exports as an interface library if we cannot
  199. // tell clients where to find the objects. This is sufficient
  200. // to support transitive usage requirements on other targets that
  201. // use the object library.
  202. if (targetType == cmStateEnums::OBJECT_LIBRARY &&
  203. !target->Target->HasKnownObjectFileLocation(nullptr)) {
  204. targetType = cmStateEnums::INTERFACE_LIBRARY;
  205. }
  206. return targetType;
  207. }
  208. void cmExportBuildFileGenerator::SetExportSet(cmExportSet* exportSet)
  209. {
  210. this->ExportSet = exportSet;
  211. }
  212. void cmExportBuildFileGenerator::SetImportLocationProperty(
  213. const std::string& config, std::string const& suffix,
  214. cmGeneratorTarget* target, ImportPropertyMap& properties)
  215. {
  216. // Get the makefile in which to lookup target information.
  217. cmMakefile* mf = target->Makefile;
  218. if (target->GetType() == cmStateEnums::OBJECT_LIBRARY) {
  219. std::string prop = cmStrCat("IMPORTED_OBJECTS", suffix);
  220. // Compute all the object files inside this target and setup
  221. // IMPORTED_OBJECTS as a list of object files
  222. std::vector<cmSourceFile const*> objectSources;
  223. target->GetObjectSources(objectSources, config);
  224. std::string const obj_dir = target->GetObjectDirectory(config);
  225. std::vector<std::string> objects;
  226. for (cmSourceFile const* sf : objectSources) {
  227. const std::string& obj = target->GetObjectName(sf);
  228. objects.push_back(obj_dir + obj);
  229. }
  230. // Store the property.
  231. properties[prop] = cmList::to_string(objects);
  232. } else {
  233. // Add the main target file.
  234. {
  235. std::string prop = cmStrCat("IMPORTED_LOCATION", suffix);
  236. std::string value;
  237. if (target->IsAppBundleOnApple()) {
  238. value =
  239. target->GetFullPath(config, cmStateEnums::RuntimeBinaryArtifact);
  240. } else {
  241. value = target->GetFullPath(config,
  242. cmStateEnums::RuntimeBinaryArtifact, true);
  243. }
  244. properties[prop] = value;
  245. }
  246. // Add the import library for windows DLLs.
  247. if (target->HasImportLibrary(config)) {
  248. std::string prop = cmStrCat("IMPORTED_IMPLIB", suffix);
  249. std::string value =
  250. target->GetFullPath(config, cmStateEnums::ImportLibraryArtifact, true);
  251. if (mf->GetDefinition("CMAKE_IMPORT_LIBRARY_SUFFIX")) {
  252. target->GetImplibGNUtoMS(config, value, value,
  253. "${CMAKE_IMPORT_LIBRARY_SUFFIX}");
  254. }
  255. properties[prop] = value;
  256. }
  257. }
  258. }
  259. void cmExportBuildFileGenerator::HandleMissingTarget(
  260. std::string& link_libs, cmGeneratorTarget const* depender,
  261. cmGeneratorTarget* dependee)
  262. {
  263. // The target is not in the export.
  264. if (!this->AppendMode) {
  265. const std::string name = dependee->GetName();
  266. cmGlobalGenerator* gg =
  267. dependee->GetLocalGenerator()->GetGlobalGenerator();
  268. auto exportInfo = this->FindBuildExportInfo(gg, name);
  269. std::vector<std::string> const& exportFiles = exportInfo.first;
  270. if (exportFiles.size() == 1) {
  271. std::string missingTarget = exportInfo.second;
  272. missingTarget += dependee->GetExportName();
  273. link_libs += missingTarget;
  274. this->MissingTargets.emplace_back(std::move(missingTarget));
  275. return;
  276. }
  277. // We are not appending, so all exported targets should be
  278. // known here. This is probably user-error.
  279. this->ComplainAboutMissingTarget(depender, dependee, exportFiles);
  280. }
  281. // Assume the target will be exported by another command.
  282. // Append it with the export namespace.
  283. link_libs += this->Namespace;
  284. link_libs += dependee->GetExportName();
  285. }
  286. void cmExportBuildFileGenerator::GetTargets(
  287. std::vector<std::string>& targets) const
  288. {
  289. if (this->ExportSet) {
  290. for (std::unique_ptr<cmTargetExport> const& te :
  291. this->ExportSet->GetTargetExports()) {
  292. if (te->NamelinkOnly) {
  293. continue;
  294. }
  295. targets.push_back(te->TargetName);
  296. }
  297. return;
  298. }
  299. targets = this->Targets;
  300. }
  301. std::pair<std::vector<std::string>, std::string>
  302. cmExportBuildFileGenerator::FindBuildExportInfo(cmGlobalGenerator* gg,
  303. const std::string& name)
  304. {
  305. std::vector<std::string> exportFiles;
  306. std::string ns;
  307. auto& exportSets = gg->GetBuildExportSets();
  308. for (auto const& exp : exportSets) {
  309. const auto& exportSet = exp.second;
  310. std::vector<std::string> targets;
  311. exportSet->GetTargets(targets);
  312. if (cm::contains(targets, name)) {
  313. exportFiles.push_back(exp.first);
  314. ns = exportSet->GetNamespace();
  315. }
  316. }
  317. return { exportFiles, ns };
  318. }
  319. void cmExportBuildFileGenerator::ComplainAboutMissingTarget(
  320. cmGeneratorTarget const* depender, cmGeneratorTarget const* dependee,
  321. std::vector<std::string> const& exportFiles)
  322. {
  323. std::ostringstream e;
  324. e << "export called with target \"" << depender->GetName()
  325. << "\" which requires target \"" << dependee->GetName() << "\" ";
  326. if (exportFiles.empty()) {
  327. e << "that is not in any export set.";
  328. } else {
  329. e << "that is not in this export set, but in multiple other export sets: "
  330. << cmJoin(exportFiles, ", ") << ".\n";
  331. e << "An exported target cannot depend upon another target which is "
  332. "exported multiple times. Consider consolidating the exports of the "
  333. "\""
  334. << dependee->GetName() << "\" target to a single export.";
  335. }
  336. this->LG->GetGlobalGenerator()->GetCMakeInstance()->IssueMessage(
  337. MessageType::FATAL_ERROR, e.str(),
  338. this->LG->GetMakefile()->GetBacktrace());
  339. }
  340. std::string cmExportBuildFileGenerator::InstallNameDir(
  341. cmGeneratorTarget const* target, const std::string& config)
  342. {
  343. std::string install_name_dir;
  344. cmMakefile* mf = target->Target->GetMakefile();
  345. if (mf->IsOn("CMAKE_PLATFORM_HAS_INSTALLNAME")) {
  346. install_name_dir = target->GetInstallNameDirForBuildTree(config);
  347. }
  348. return install_name_dir;
  349. }
  350. namespace {
  351. bool EntryIsContextSensitive(
  352. const std::unique_ptr<cmCompiledGeneratorExpression>& cge)
  353. {
  354. return cge->GetHadContextSensitiveCondition();
  355. }
  356. }
  357. std::string cmExportBuildFileGenerator::GetFileSetDirectories(
  358. cmGeneratorTarget* gte, cmFileSet* fileSet, cmTargetExport* /*te*/)
  359. {
  360. std::vector<std::string> resultVector;
  361. auto configs =
  362. gte->Makefile->GetGeneratorConfigs(cmMakefile::IncludeEmptyConfig);
  363. auto directoryEntries = fileSet->CompileDirectoryEntries();
  364. for (auto const& config : configs) {
  365. auto directories = fileSet->EvaluateDirectoryEntries(
  366. directoryEntries, gte->LocalGenerator, config, gte);
  367. bool const contextSensitive =
  368. std::any_of(directoryEntries.begin(), directoryEntries.end(),
  369. EntryIsContextSensitive);
  370. auto const& type = fileSet->GetType();
  371. // C++ modules do not support interface file sets which are dependent upon
  372. // the configuration.
  373. if (contextSensitive && type == "CXX_MODULES"_s) {
  374. auto* mf = this->LG->GetMakefile();
  375. std::ostringstream e;
  376. e << "The \"" << gte->GetName() << "\" target's interface file set \""
  377. << fileSet->GetName() << "\" of type \"" << type
  378. << "\" contains context-sensitive base directory entries which is not "
  379. "supported.";
  380. mf->IssueMessage(MessageType::FATAL_ERROR, e.str());
  381. return std::string{};
  382. }
  383. for (auto const& directory : directories) {
  384. auto dest = cmOutputConverter::EscapeForCMake(
  385. directory, cmOutputConverter::WrapQuotes::NoWrap);
  386. if (contextSensitive && configs.size() != 1) {
  387. resultVector.push_back(
  388. cmStrCat("\"$<$<CONFIG:", config, ">:", dest, ">\""));
  389. } else {
  390. resultVector.emplace_back(cmStrCat('"', dest, '"'));
  391. break;
  392. }
  393. }
  394. }
  395. return cmJoin(resultVector, " ");
  396. }
  397. std::string cmExportBuildFileGenerator::GetFileSetFiles(cmGeneratorTarget* gte,
  398. cmFileSet* fileSet,
  399. cmTargetExport* /*te*/)
  400. {
  401. std::vector<std::string> resultVector;
  402. auto configs =
  403. gte->Makefile->GetGeneratorConfigs(cmMakefile::IncludeEmptyConfig);
  404. auto fileEntries = fileSet->CompileFileEntries();
  405. auto directoryEntries = fileSet->CompileDirectoryEntries();
  406. for (auto const& config : configs) {
  407. auto directories = fileSet->EvaluateDirectoryEntries(
  408. directoryEntries, gte->LocalGenerator, config, gte);
  409. std::map<std::string, std::vector<std::string>> files;
  410. for (auto const& entry : fileEntries) {
  411. fileSet->EvaluateFileEntry(directories, files, entry,
  412. gte->LocalGenerator, config, gte);
  413. }
  414. bool const contextSensitive =
  415. std::any_of(directoryEntries.begin(), directoryEntries.end(),
  416. EntryIsContextSensitive) ||
  417. std::any_of(fileEntries.begin(), fileEntries.end(),
  418. EntryIsContextSensitive);
  419. auto const& type = fileSet->GetType();
  420. // C++ modules do not support interface file sets which are dependent upon
  421. // the configuration.
  422. if (contextSensitive && type == "CXX_MODULES"_s) {
  423. auto* mf = this->LG->GetMakefile();
  424. std::ostringstream e;
  425. e << "The \"" << gte->GetName() << "\" target's interface file set \""
  426. << fileSet->GetName() << "\" of type \"" << type
  427. << "\" contains context-sensitive file entries which is not "
  428. "supported.";
  429. mf->IssueMessage(MessageType::FATAL_ERROR, e.str());
  430. return std::string{};
  431. }
  432. for (auto const& it : files) {
  433. for (auto const& filename : it.second) {
  434. auto escapedFile = cmOutputConverter::EscapeForCMake(
  435. filename, cmOutputConverter::WrapQuotes::NoWrap);
  436. if (contextSensitive && configs.size() != 1) {
  437. resultVector.push_back(
  438. cmStrCat("\"$<$<CONFIG:", config, ">:", escapedFile, ">\""));
  439. } else {
  440. resultVector.emplace_back(cmStrCat('"', escapedFile, '"'));
  441. }
  442. }
  443. }
  444. if (!(contextSensitive && configs.size() != 1)) {
  445. break;
  446. }
  447. }
  448. return cmJoin(resultVector, " ");
  449. }
  450. std::string cmExportBuildFileGenerator::GetCxxModulesDirectory() const
  451. {
  452. return this->CxxModulesDirectory;
  453. }
  454. void cmExportBuildFileGenerator::GenerateCxxModuleConfigInformation(
  455. std::string const& name, std::ostream& os) const
  456. {
  457. const char* opt = "";
  458. if (this->Configurations.size() > 1) {
  459. // With more than one configuration, each individual file is optional.
  460. opt = " OPTIONAL";
  461. }
  462. // Generate import file content for each configuration.
  463. for (std::string c : this->Configurations) {
  464. if (c.empty()) {
  465. c = "noconfig";
  466. }
  467. os << "include(\"${CMAKE_CURRENT_LIST_DIR}/cxx-modules-" << name << '-'
  468. << c << ".cmake\"" << opt << ")\n";
  469. }
  470. }
  471. bool cmExportBuildFileGenerator::GenerateImportCxxModuleConfigTargetInclusion(
  472. std::string const& name, std::string config) const
  473. {
  474. auto cxx_modules_dirname = this->GetCxxModulesDirectory();
  475. if (cxx_modules_dirname.empty()) {
  476. return true;
  477. }
  478. if (config.empty()) {
  479. config = "noconfig";
  480. }
  481. std::string fileName =
  482. cmStrCat(this->FileDir, '/', cxx_modules_dirname, "/cxx-modules-", name,
  483. '-', config, ".cmake");
  484. cmGeneratedFileStream os(fileName, true);
  485. if (!os) {
  486. std::string se = cmSystemTools::GetLastSystemError();
  487. std::ostringstream e;
  488. e << "cannot write to file \"" << fileName << "\": " << se;
  489. cmSystemTools::Error(e.str());
  490. return false;
  491. }
  492. os.SetCopyIfDifferent(true);
  493. for (auto const* tgt : this->ExportedTargets) {
  494. // Only targets with C++ module sources will have a
  495. // collator-generated install script.
  496. if (!tgt->HaveCxx20ModuleSources()) {
  497. continue;
  498. }
  499. os << "include(\"${CMAKE_CURRENT_LIST_DIR}/target-" << tgt->GetExportName()
  500. << '-' << config << ".cmake\")\n";
  501. }
  502. return true;
  503. }