cmExportBuildFileGenerator.cxx 19 KB

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