cmExportBuildFileGenerator.cxx 19 KB

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