cmExportBuildFileGenerator.cxx 19 KB

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