cmExportBuildFileGenerator.cxx 19 KB

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