cmMakefileLibraryTargetGenerator.cxx 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954
  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 "cmMakefileLibraryTargetGenerator.h"
  4. #include <cstddef>
  5. #include <set>
  6. #include <sstream>
  7. #include <utility>
  8. #include <vector>
  9. #include <cm/memory>
  10. #include <cmext/algorithm>
  11. #include "cmGeneratedFileStream.h"
  12. #include "cmGeneratorTarget.h"
  13. #include "cmGlobalUnixMakefileGenerator3.h"
  14. #include "cmLinkLineComputer.h"
  15. #include "cmLinkLineDeviceComputer.h"
  16. #include "cmLocalGenerator.h"
  17. #include "cmLocalUnixMakefileGenerator3.h"
  18. #include "cmMakefile.h"
  19. #include "cmOSXBundleGenerator.h"
  20. #include "cmOutputConverter.h"
  21. #include "cmRulePlaceholderExpander.h"
  22. #include "cmState.h"
  23. #include "cmStateDirectory.h"
  24. #include "cmStateSnapshot.h"
  25. #include "cmStateTypes.h"
  26. #include "cmStringAlgorithms.h"
  27. #include "cmSystemTools.h"
  28. #include "cmValue.h"
  29. cmMakefileLibraryTargetGenerator::cmMakefileLibraryTargetGenerator(
  30. cmGeneratorTarget* target)
  31. : cmMakefileTargetGenerator(target)
  32. {
  33. this->CustomCommandDriver = OnDepends;
  34. if (this->GeneratorTarget->GetType() != cmStateEnums::INTERFACE_LIBRARY) {
  35. this->TargetNames =
  36. this->GeneratorTarget->GetLibraryNames(this->GetConfigName());
  37. }
  38. this->OSXBundleGenerator = cm::make_unique<cmOSXBundleGenerator>(target);
  39. this->OSXBundleGenerator->SetMacContentFolders(&this->MacContentFolders);
  40. }
  41. cmMakefileLibraryTargetGenerator::~cmMakefileLibraryTargetGenerator() =
  42. default;
  43. void cmMakefileLibraryTargetGenerator::WriteRuleFiles()
  44. {
  45. // create the build.make file and directory, put in the common blocks
  46. this->CreateRuleFile();
  47. // write rules used to help build object files
  48. this->WriteCommonCodeRules();
  49. // write the per-target per-language flags
  50. this->WriteTargetLanguageFlags();
  51. // write in rules for object files and custom commands
  52. this->WriteTargetBuildRules();
  53. // write the link rules
  54. // Write the rule for this target type.
  55. switch (this->GeneratorTarget->GetType()) {
  56. case cmStateEnums::STATIC_LIBRARY:
  57. this->WriteStaticLibraryRules();
  58. break;
  59. case cmStateEnums::SHARED_LIBRARY:
  60. this->WriteSharedLibraryRules(false);
  61. if (this->GeneratorTarget->NeedRelinkBeforeInstall(
  62. this->GetConfigName())) {
  63. // Write rules to link an installable version of the target.
  64. this->WriteSharedLibraryRules(true);
  65. }
  66. break;
  67. case cmStateEnums::MODULE_LIBRARY:
  68. this->WriteModuleLibraryRules(false);
  69. if (this->GeneratorTarget->NeedRelinkBeforeInstall(
  70. this->GetConfigName())) {
  71. // Write rules to link an installable version of the target.
  72. this->WriteModuleLibraryRules(true);
  73. }
  74. break;
  75. case cmStateEnums::OBJECT_LIBRARY:
  76. this->WriteObjectLibraryRules();
  77. break;
  78. default:
  79. // If language is not known, this is an error.
  80. cmSystemTools::Error("Unknown Library Type");
  81. break;
  82. }
  83. // Write clean target
  84. this->WriteTargetCleanRules();
  85. // Write the dependency generation rule. This must be done last so
  86. // that multiple output pair information is available.
  87. this->WriteTargetDependRules();
  88. // close the streams
  89. this->CloseFileStreams();
  90. }
  91. void cmMakefileLibraryTargetGenerator::WriteObjectLibraryRules()
  92. {
  93. std::vector<std::string> commands;
  94. std::vector<std::string> depends;
  95. // Add post-build rules.
  96. this->LocalGenerator->AppendCustomCommands(
  97. commands, this->GeneratorTarget->GetPostBuildCommands(),
  98. this->GeneratorTarget, this->LocalGenerator->GetBinaryDirectory());
  99. // Depend on the object files.
  100. this->AppendObjectDepends(depends);
  101. // Write the rule.
  102. this->LocalGenerator->WriteMakeRule(*this->BuildFileStream, nullptr,
  103. this->GeneratorTarget->GetName(),
  104. depends, commands, true);
  105. // Write the main driver rule to build everything in this target.
  106. this->WriteTargetDriverRule(this->GeneratorTarget->GetName(), false);
  107. }
  108. void cmMakefileLibraryTargetGenerator::WriteStaticLibraryRules()
  109. {
  110. const bool requiresDeviceLinking = requireDeviceLinking(
  111. *this->GeneratorTarget, *this->LocalGenerator, this->GetConfigName());
  112. if (requiresDeviceLinking) {
  113. this->WriteDeviceLibraryRules("CMAKE_CUDA_DEVICE_LINK_LIBRARY", false);
  114. }
  115. std::string linkLanguage =
  116. this->GeneratorTarget->GetLinkerLanguage(this->GetConfigName());
  117. std::string linkRuleVar = this->GeneratorTarget->GetCreateRuleVariable(
  118. linkLanguage, this->GetConfigName());
  119. std::string extraFlags;
  120. this->LocalGenerator->GetStaticLibraryFlags(
  121. extraFlags, this->GetConfigName(), linkLanguage, this->GeneratorTarget);
  122. this->WriteLibraryRules(linkRuleVar, extraFlags, false);
  123. }
  124. void cmMakefileLibraryTargetGenerator::WriteSharedLibraryRules(bool relink)
  125. {
  126. if (this->GeneratorTarget->IsFrameworkOnApple()) {
  127. this->WriteFrameworkRules(relink);
  128. return;
  129. }
  130. if (!relink) {
  131. const bool requiresDeviceLinking = requireDeviceLinking(
  132. *this->GeneratorTarget, *this->LocalGenerator, this->GetConfigName());
  133. if (requiresDeviceLinking) {
  134. this->WriteDeviceLibraryRules("CMAKE_CUDA_DEVICE_LINK_LIBRARY", relink);
  135. }
  136. }
  137. std::string linkLanguage =
  138. this->GeneratorTarget->GetLinkerLanguage(this->GetConfigName());
  139. std::string linkRuleVar =
  140. cmStrCat("CMAKE_", linkLanguage, "_CREATE_SHARED_LIBRARY");
  141. std::string extraFlags;
  142. this->GetTargetLinkFlags(extraFlags, linkLanguage);
  143. this->LocalGenerator->AddConfigVariableFlags(
  144. extraFlags, "CMAKE_SHARED_LINKER_FLAGS", this->GetConfigName());
  145. std::unique_ptr<cmLinkLineComputer> linkLineComputer =
  146. this->CreateLinkLineComputer(
  147. this->LocalGenerator,
  148. this->LocalGenerator->GetStateSnapshot().GetDirectory());
  149. this->LocalGenerator->AppendModuleDefinitionFlag(
  150. extraFlags, this->GeneratorTarget, linkLineComputer.get(),
  151. this->GetConfigName());
  152. this->UseLWYU = this->LocalGenerator->AppendLWYUFlags(
  153. extraFlags, this->GeneratorTarget, linkLanguage);
  154. this->WriteLibraryRules(linkRuleVar, extraFlags, relink);
  155. }
  156. void cmMakefileLibraryTargetGenerator::WriteModuleLibraryRules(bool relink)
  157. {
  158. if (!relink) {
  159. const bool requiresDeviceLinking = requireDeviceLinking(
  160. *this->GeneratorTarget, *this->LocalGenerator, this->GetConfigName());
  161. if (requiresDeviceLinking) {
  162. this->WriteDeviceLibraryRules("CMAKE_CUDA_DEVICE_LINK_LIBRARY", relink);
  163. }
  164. }
  165. std::string linkLanguage =
  166. this->GeneratorTarget->GetLinkerLanguage(this->GetConfigName());
  167. std::string linkRuleVar =
  168. cmStrCat("CMAKE_", linkLanguage, "_CREATE_SHARED_MODULE");
  169. std::string extraFlags;
  170. this->GetTargetLinkFlags(extraFlags, linkLanguage);
  171. this->LocalGenerator->AddConfigVariableFlags(
  172. extraFlags, "CMAKE_MODULE_LINKER_FLAGS", this->GetConfigName());
  173. std::unique_ptr<cmLinkLineComputer> linkLineComputer =
  174. this->CreateLinkLineComputer(
  175. this->LocalGenerator,
  176. this->LocalGenerator->GetStateSnapshot().GetDirectory());
  177. this->LocalGenerator->AppendModuleDefinitionFlag(
  178. extraFlags, this->GeneratorTarget, linkLineComputer.get(),
  179. this->GetConfigName());
  180. this->WriteLibraryRules(linkRuleVar, extraFlags, relink);
  181. }
  182. void cmMakefileLibraryTargetGenerator::WriteFrameworkRules(bool relink)
  183. {
  184. std::string linkLanguage =
  185. this->GeneratorTarget->GetLinkerLanguage(this->GetConfigName());
  186. std::string linkRuleVar =
  187. cmStrCat("CMAKE_", linkLanguage, "_CREATE_MACOSX_FRAMEWORK");
  188. std::string extraFlags;
  189. this->GetTargetLinkFlags(extraFlags, linkLanguage);
  190. this->LocalGenerator->AddConfigVariableFlags(
  191. extraFlags, "CMAKE_MACOSX_FRAMEWORK_LINKER_FLAGS", this->GetConfigName());
  192. this->WriteLibraryRules(linkRuleVar, extraFlags, relink);
  193. }
  194. void cmMakefileLibraryTargetGenerator::WriteDeviceLibraryRules(
  195. const std::string& linkRuleVar, bool relink)
  196. {
  197. #ifndef CMAKE_BOOTSTRAP
  198. // TODO: Merge the methods that call this method to avoid
  199. // code duplication.
  200. std::vector<std::string> commands;
  201. std::string const objExt =
  202. this->Makefile->GetSafeDefinition("CMAKE_CUDA_OUTPUT_EXTENSION");
  203. // Get the name of the device object to generate.
  204. std::string const targetOutput =
  205. this->GeneratorTarget->ObjectDirectory + "cmake_device_link" + objExt;
  206. this->DeviceLinkObject = targetOutput;
  207. this->NumberOfProgressActions++;
  208. if (!this->NoRuleMessages) {
  209. cmLocalUnixMakefileGenerator3::EchoProgress progress;
  210. this->MakeEchoProgress(progress);
  211. // Add the link message.
  212. std::string buildEcho = cmStrCat(
  213. "Linking CUDA device code ",
  214. this->LocalGenerator->ConvertToOutputFormat(
  215. this->LocalGenerator->MaybeRelativeToCurBinDir(this->DeviceLinkObject),
  216. cmOutputConverter::SHELL));
  217. this->LocalGenerator->AppendEcho(
  218. commands, buildEcho, cmLocalUnixMakefileGenerator3::EchoLink, &progress);
  219. }
  220. if (this->Makefile->GetSafeDefinition("CMAKE_CUDA_COMPILER_ID") == "Clang") {
  221. this->WriteDeviceLinkRule(commands, targetOutput);
  222. } else {
  223. this->WriteNvidiaDeviceLibraryRules(linkRuleVar, relink, commands,
  224. targetOutput);
  225. }
  226. // Write the main driver rule to build everything in this target.
  227. this->WriteTargetDriverRule(targetOutput, relink);
  228. }
  229. void cmMakefileLibraryTargetGenerator::WriteNvidiaDeviceLibraryRules(
  230. const std::string& linkRuleVar, bool relink,
  231. std::vector<std::string>& commands, const std::string& targetOutput)
  232. {
  233. std::string linkLanguage = "CUDA";
  234. // Build list of dependencies.
  235. std::vector<std::string> depends;
  236. this->AppendLinkDepends(depends, linkLanguage);
  237. // Add language-specific flags.
  238. std::string langFlags;
  239. this->LocalGenerator->AddLanguageFlagsForLinking(
  240. langFlags, this->GeneratorTarget, linkLanguage, this->GetConfigName());
  241. // Create set of linking flags.
  242. std::string linkFlags;
  243. this->GetDeviceLinkFlags(linkFlags, linkLanguage);
  244. // Clean files associated with this library.
  245. std::set<std::string> libCleanFiles;
  246. libCleanFiles.insert(
  247. this->LocalGenerator->MaybeRelativeToCurBinDir(targetOutput));
  248. // Determine whether a link script will be used.
  249. bool useLinkScript = this->GlobalGenerator->GetUseLinkScript();
  250. bool useResponseFileForObjects =
  251. this->CheckUseResponseFileForObjects(linkLanguage);
  252. bool const useResponseFileForLibs =
  253. this->CheckUseResponseFileForLibraries(linkLanguage);
  254. cmRulePlaceholderExpander::RuleVariables vars;
  255. vars.Language = linkLanguage.c_str();
  256. // Expand the rule variables.
  257. std::vector<std::string> real_link_commands;
  258. {
  259. // Set path conversion for link script shells.
  260. this->LocalGenerator->SetLinkScriptShell(useLinkScript);
  261. // Collect up flags to link in needed libraries.
  262. std::string linkLibs;
  263. std::unique_ptr<cmLinkLineComputer> linkLineComputer(
  264. new cmLinkLineDeviceComputer(
  265. this->LocalGenerator,
  266. this->LocalGenerator->GetStateSnapshot().GetDirectory()));
  267. linkLineComputer->SetForResponse(useResponseFileForLibs);
  268. linkLineComputer->SetRelink(relink);
  269. this->CreateLinkLibs(linkLineComputer.get(), linkLibs,
  270. useResponseFileForLibs, depends);
  271. // Construct object file lists that may be needed to expand the
  272. // rule.
  273. std::string buildObjs;
  274. this->CreateObjectLists(useLinkScript, false, // useArchiveRules
  275. useResponseFileForObjects, buildObjs, depends,
  276. false);
  277. std::string objectDir = this->GeneratorTarget->GetSupportDirectory();
  278. objectDir = this->LocalGenerator->ConvertToOutputFormat(
  279. this->LocalGenerator->MaybeRelativeToCurBinDir(objectDir),
  280. cmOutputConverter::SHELL);
  281. std::string target = this->LocalGenerator->ConvertToOutputFormat(
  282. this->LocalGenerator->MaybeRelativeToCurBinDir(targetOutput),
  283. cmOutputConverter::SHELL);
  284. std::string targetFullPathCompilePDB =
  285. this->ComputeTargetCompilePDB(this->GetConfigName());
  286. std::string targetOutPathCompilePDB =
  287. this->LocalGenerator->ConvertToOutputFormat(targetFullPathCompilePDB,
  288. cmOutputConverter::SHELL);
  289. vars.Objects = buildObjs.c_str();
  290. vars.ObjectDir = objectDir.c_str();
  291. vars.Target = target.c_str();
  292. vars.LinkLibraries = linkLibs.c_str();
  293. vars.ObjectsQuoted = buildObjs.c_str();
  294. vars.LanguageCompileFlags = langFlags.c_str();
  295. vars.LinkFlags = linkFlags.c_str();
  296. vars.TargetCompilePDB = targetOutPathCompilePDB.c_str();
  297. std::string launcher;
  298. cmValue val = this->LocalGenerator->GetRuleLauncher(this->GeneratorTarget,
  299. "RULE_LAUNCH_LINK");
  300. if (cmNonempty(val)) {
  301. launcher = cmStrCat(*val, ' ');
  302. }
  303. std::unique_ptr<cmRulePlaceholderExpander> rulePlaceholderExpander(
  304. this->LocalGenerator->CreateRulePlaceholderExpander());
  305. // Construct the main link rule and expand placeholders.
  306. rulePlaceholderExpander->SetTargetImpLib(targetOutput);
  307. std::string linkRule = this->GetLinkRule(linkRuleVar);
  308. cmExpandList(linkRule, real_link_commands);
  309. // Expand placeholders.
  310. for (std::string& real_link_command : real_link_commands) {
  311. real_link_command = cmStrCat(launcher, real_link_command);
  312. rulePlaceholderExpander->ExpandRuleVariables(this->LocalGenerator,
  313. real_link_command, vars);
  314. }
  315. // Restore path conversion to normal shells.
  316. this->LocalGenerator->SetLinkScriptShell(false);
  317. // Clean all the possible library names and symlinks.
  318. this->CleanFiles.insert(libCleanFiles.begin(), libCleanFiles.end());
  319. }
  320. std::vector<std::string> commands1;
  321. // Optionally convert the build rule to use a script to avoid long
  322. // command lines in the make shell.
  323. if (useLinkScript) {
  324. // Use a link script.
  325. const char* name = (relink ? "drelink.txt" : "dlink.txt");
  326. this->CreateLinkScript(name, real_link_commands, commands1, depends);
  327. } else {
  328. // No link script. Just use the link rule directly.
  329. commands1 = real_link_commands;
  330. }
  331. this->LocalGenerator->CreateCDCommand(
  332. commands1, this->Makefile->GetCurrentBinaryDirectory(),
  333. this->LocalGenerator->GetBinaryDirectory());
  334. cm::append(commands, commands1);
  335. commands1.clear();
  336. // Compute the list of outputs.
  337. std::vector<std::string> outputs(1, targetOutput);
  338. // Write the build rule.
  339. this->WriteMakeRule(*this->BuildFileStream, nullptr, outputs, depends,
  340. commands, false);
  341. #else
  342. static_cast<void>(linkRuleVar);
  343. static_cast<void>(relink);
  344. #endif
  345. }
  346. void cmMakefileLibraryTargetGenerator::WriteLibraryRules(
  347. const std::string& linkRuleVar, const std::string& extraFlags, bool relink)
  348. {
  349. // TODO: Merge the methods that call this method to avoid
  350. // code duplication.
  351. std::vector<std::string> commands;
  352. // Get the language to use for linking this library.
  353. std::string linkLanguage =
  354. this->GeneratorTarget->GetLinkerLanguage(this->GetConfigName());
  355. // Make sure we have a link language.
  356. if (linkLanguage.empty()) {
  357. cmSystemTools::Error("Cannot determine link language for target \"" +
  358. this->GeneratorTarget->GetName() + "\".");
  359. return;
  360. }
  361. // Build list of dependencies.
  362. std::vector<std::string> depends;
  363. this->AppendLinkDepends(depends, linkLanguage);
  364. if (!this->DeviceLinkObject.empty()) {
  365. depends.push_back(this->DeviceLinkObject);
  366. }
  367. // Create set of linking flags.
  368. std::string linkFlags;
  369. this->LocalGenerator->AppendFlags(linkFlags, extraFlags);
  370. this->LocalGenerator->AppendIPOLinkerFlags(
  371. linkFlags, this->GeneratorTarget, this->GetConfigName(), linkLanguage);
  372. // Add OSX version flags, if any.
  373. if (this->GeneratorTarget->GetType() == cmStateEnums::SHARED_LIBRARY ||
  374. this->GeneratorTarget->GetType() == cmStateEnums::MODULE_LIBRARY) {
  375. this->AppendOSXVerFlag(linkFlags, linkLanguage, "COMPATIBILITY", true);
  376. this->AppendOSXVerFlag(linkFlags, linkLanguage, "CURRENT", false);
  377. }
  378. // Construct the name of the library.
  379. this->GeneratorTarget->GetLibraryNames(this->GetConfigName());
  380. // Construct the full path version of the names.
  381. std::string outpath;
  382. std::string outpathImp;
  383. if (this->GeneratorTarget->IsFrameworkOnApple()) {
  384. outpath = this->GeneratorTarget->GetDirectory(this->GetConfigName());
  385. this->OSXBundleGenerator->CreateFramework(this->TargetNames.Output,
  386. outpath, this->GetConfigName());
  387. outpath += '/';
  388. } else if (this->GeneratorTarget->IsCFBundleOnApple()) {
  389. outpath = this->GeneratorTarget->GetDirectory(this->GetConfigName());
  390. this->OSXBundleGenerator->CreateCFBundle(this->TargetNames.Output, outpath,
  391. this->GetConfigName());
  392. outpath += '/';
  393. } else if (relink) {
  394. outpath = cmStrCat(this->Makefile->GetCurrentBinaryDirectory(),
  395. "/CMakeFiles/CMakeRelink.dir");
  396. cmSystemTools::MakeDirectory(outpath);
  397. outpath += '/';
  398. if (!this->TargetNames.ImportLibrary.empty()) {
  399. outpathImp = outpath;
  400. }
  401. } else {
  402. outpath = this->GeneratorTarget->GetDirectory(this->GetConfigName());
  403. cmSystemTools::MakeDirectory(outpath);
  404. outpath += '/';
  405. if (!this->TargetNames.ImportLibrary.empty()) {
  406. outpathImp = this->GeneratorTarget->GetDirectory(
  407. this->GetConfigName(), cmStateEnums::ImportLibraryArtifact);
  408. cmSystemTools::MakeDirectory(outpathImp);
  409. outpathImp += '/';
  410. }
  411. }
  412. std::string compilePdbOutputPath =
  413. this->GeneratorTarget->GetCompilePDBDirectory(this->GetConfigName());
  414. cmSystemTools::MakeDirectory(compilePdbOutputPath);
  415. std::string pdbOutputPath =
  416. this->GeneratorTarget->GetPDBDirectory(this->GetConfigName());
  417. cmSystemTools::MakeDirectory(pdbOutputPath);
  418. pdbOutputPath += "/";
  419. std::string targetFullPath = outpath + this->TargetNames.Output;
  420. std::string targetFullPathPDB = pdbOutputPath + this->TargetNames.PDB;
  421. std::string targetFullPathSO = outpath + this->TargetNames.SharedObject;
  422. std::string targetFullPathReal = outpath + this->TargetNames.Real;
  423. std::string targetFullPathImport =
  424. outpathImp + this->TargetNames.ImportLibrary;
  425. // Construct the output path version of the names for use in command
  426. // arguments.
  427. std::string targetOutPathPDB = this->LocalGenerator->ConvertToOutputFormat(
  428. targetFullPathPDB, cmOutputConverter::SHELL);
  429. std::string targetOutPath = this->LocalGenerator->ConvertToOutputFormat(
  430. this->LocalGenerator->MaybeRelativeToCurBinDir(targetFullPath),
  431. cmOutputConverter::SHELL);
  432. std::string targetOutPathSO = this->LocalGenerator->ConvertToOutputFormat(
  433. this->LocalGenerator->MaybeRelativeToCurBinDir(targetFullPathSO),
  434. cmOutputConverter::SHELL);
  435. std::string targetOutPathReal = this->LocalGenerator->ConvertToOutputFormat(
  436. this->LocalGenerator->MaybeRelativeToCurBinDir(targetFullPathReal),
  437. cmOutputConverter::SHELL);
  438. std::string targetOutPathImport =
  439. this->LocalGenerator->ConvertToOutputFormat(
  440. this->LocalGenerator->MaybeRelativeToCurBinDir(targetFullPathImport),
  441. cmOutputConverter::SHELL);
  442. this->NumberOfProgressActions++;
  443. if (!this->NoRuleMessages) {
  444. cmLocalUnixMakefileGenerator3::EchoProgress progress;
  445. this->MakeEchoProgress(progress);
  446. // Add the link message.
  447. std::string buildEcho = cmStrCat("Linking ", linkLanguage);
  448. switch (this->GeneratorTarget->GetType()) {
  449. case cmStateEnums::STATIC_LIBRARY:
  450. buildEcho += " static library ";
  451. break;
  452. case cmStateEnums::SHARED_LIBRARY:
  453. buildEcho += " shared library ";
  454. break;
  455. case cmStateEnums::MODULE_LIBRARY:
  456. if (this->GeneratorTarget->IsCFBundleOnApple()) {
  457. buildEcho += " CFBundle";
  458. }
  459. buildEcho += " shared module ";
  460. break;
  461. default:
  462. buildEcho += " library ";
  463. break;
  464. }
  465. buildEcho += targetOutPath;
  466. this->LocalGenerator->AppendEcho(
  467. commands, buildEcho, cmLocalUnixMakefileGenerator3::EchoLink, &progress);
  468. }
  469. // Clean files associated with this library.
  470. std::set<std::string> libCleanFiles;
  471. libCleanFiles.insert(
  472. this->LocalGenerator->MaybeRelativeToCurBinDir(targetFullPathReal));
  473. std::vector<std::string> commands1;
  474. // Add a command to remove any existing files for this library.
  475. // for static libs only
  476. if (this->GeneratorTarget->GetType() == cmStateEnums::STATIC_LIBRARY) {
  477. this->LocalGenerator->AppendCleanCommand(commands1, libCleanFiles,
  478. this->GeneratorTarget, "target");
  479. this->LocalGenerator->CreateCDCommand(
  480. commands1, this->Makefile->GetCurrentBinaryDirectory(),
  481. this->LocalGenerator->GetBinaryDirectory());
  482. cm::append(commands, commands1);
  483. commands1.clear();
  484. }
  485. if (this->TargetNames.Output != this->TargetNames.Real) {
  486. libCleanFiles.insert(
  487. this->LocalGenerator->MaybeRelativeToCurBinDir(targetFullPath));
  488. }
  489. if (this->TargetNames.SharedObject != this->TargetNames.Real &&
  490. this->TargetNames.SharedObject != this->TargetNames.Output) {
  491. libCleanFiles.insert(
  492. this->LocalGenerator->MaybeRelativeToCurBinDir(targetFullPathSO));
  493. }
  494. if (!this->TargetNames.ImportLibrary.empty()) {
  495. libCleanFiles.insert(
  496. this->LocalGenerator->MaybeRelativeToCurBinDir(targetFullPathImport));
  497. std::string implib;
  498. if (this->GeneratorTarget->GetImplibGNUtoMS(
  499. this->GetConfigName(), targetFullPathImport, implib)) {
  500. libCleanFiles.insert(
  501. this->LocalGenerator->MaybeRelativeToCurBinDir(implib));
  502. }
  503. }
  504. // List the PDB for cleaning only when the whole target is
  505. // cleaned. We do not want to delete the .pdb file just before
  506. // linking the target.
  507. this->CleanFiles.insert(
  508. this->LocalGenerator->MaybeRelativeToCurBinDir(targetFullPathPDB));
  509. #ifdef _WIN32
  510. // There may be a manifest file for this target. Add it to the
  511. // clean set just in case.
  512. if (this->GeneratorTarget->GetType() != cmStateEnums::STATIC_LIBRARY) {
  513. libCleanFiles.insert(this->LocalGenerator->MaybeRelativeToCurBinDir(
  514. targetFullPath + ".manifest"));
  515. }
  516. #endif
  517. // Add the pre-build and pre-link rules building but not when relinking.
  518. if (!relink) {
  519. this->LocalGenerator->AppendCustomCommands(
  520. commands, this->GeneratorTarget->GetPreBuildCommands(),
  521. this->GeneratorTarget, this->LocalGenerator->GetBinaryDirectory());
  522. this->LocalGenerator->AppendCustomCommands(
  523. commands, this->GeneratorTarget->GetPreLinkCommands(),
  524. this->GeneratorTarget, this->LocalGenerator->GetBinaryDirectory());
  525. }
  526. // Determine whether a link script will be used.
  527. bool useLinkScript = this->GlobalGenerator->GetUseLinkScript();
  528. bool useResponseFileForObjects =
  529. this->CheckUseResponseFileForObjects(linkLanguage);
  530. bool const useResponseFileForLibs =
  531. this->CheckUseResponseFileForLibraries(linkLanguage);
  532. // For static libraries there might be archiving rules.
  533. bool haveStaticLibraryRule = false;
  534. std::vector<std::string> archiveCreateCommands;
  535. std::vector<std::string> archiveAppendCommands;
  536. std::vector<std::string> archiveFinishCommands;
  537. std::string::size_type archiveCommandLimit = std::string::npos;
  538. if (this->GeneratorTarget->GetType() == cmStateEnums::STATIC_LIBRARY) {
  539. haveStaticLibraryRule = this->Makefile->IsDefinitionSet(linkRuleVar);
  540. std::string arCreateVar =
  541. cmStrCat("CMAKE_", linkLanguage, "_ARCHIVE_CREATE");
  542. arCreateVar = this->GeneratorTarget->GetFeatureSpecificLinkRuleVariable(
  543. arCreateVar, linkLanguage, this->GetConfigName());
  544. this->Makefile->GetDefExpandList(arCreateVar, archiveCreateCommands);
  545. std::string arAppendVar =
  546. cmStrCat("CMAKE_", linkLanguage, "_ARCHIVE_APPEND");
  547. arAppendVar = this->GeneratorTarget->GetFeatureSpecificLinkRuleVariable(
  548. arAppendVar, linkLanguage, this->GetConfigName());
  549. this->Makefile->GetDefExpandList(arAppendVar, archiveAppendCommands);
  550. std::string arFinishVar =
  551. cmStrCat("CMAKE_", linkLanguage, "_ARCHIVE_FINISH");
  552. arFinishVar = this->GeneratorTarget->GetFeatureSpecificLinkRuleVariable(
  553. arFinishVar, linkLanguage, this->GetConfigName());
  554. this->Makefile->GetDefExpandList(arFinishVar, archiveFinishCommands);
  555. }
  556. // Decide whether to use archiving rules.
  557. bool useArchiveRules = !haveStaticLibraryRule &&
  558. !archiveCreateCommands.empty() && !archiveAppendCommands.empty();
  559. if (useArchiveRules) {
  560. // Archiving rules are always run with a link script.
  561. useLinkScript = true;
  562. // Archiving rules never use a response file.
  563. useResponseFileForObjects = false;
  564. // Limit the length of individual object lists to less than half of
  565. // the command line length limit (leaving half for other flags).
  566. // This may result in several calls to the archiver.
  567. if (size_t limit = cmSystemTools::CalculateCommandLineLengthLimit()) {
  568. archiveCommandLimit = limit / 2;
  569. } else {
  570. archiveCommandLimit = 8000;
  571. }
  572. }
  573. // Expand the rule variables.
  574. std::vector<std::string> real_link_commands;
  575. {
  576. bool useWatcomQuote =
  577. this->Makefile->IsOn(linkRuleVar + "_USE_WATCOM_QUOTE");
  578. // Set path conversion for link script shells.
  579. this->LocalGenerator->SetLinkScriptShell(useLinkScript);
  580. // Collect up flags to link in needed libraries.
  581. std::string linkLibs;
  582. if (this->GeneratorTarget->GetType() != cmStateEnums::STATIC_LIBRARY) {
  583. std::unique_ptr<cmLinkLineComputer> linkLineComputer =
  584. this->CreateLinkLineComputer(
  585. this->LocalGenerator,
  586. this->LocalGenerator->GetStateSnapshot().GetDirectory());
  587. linkLineComputer->SetForResponse(useResponseFileForLibs);
  588. linkLineComputer->SetUseWatcomQuote(useWatcomQuote);
  589. linkLineComputer->SetRelink(relink);
  590. this->CreateLinkLibs(linkLineComputer.get(), linkLibs,
  591. useResponseFileForLibs, depends);
  592. }
  593. // Construct object file lists that may be needed to expand the
  594. // rule.
  595. std::string buildObjs;
  596. this->CreateObjectLists(useLinkScript, useArchiveRules,
  597. useResponseFileForObjects, buildObjs, depends,
  598. useWatcomQuote);
  599. if (!this->DeviceLinkObject.empty()) {
  600. buildObjs += " " +
  601. this->LocalGenerator->ConvertToOutputFormat(
  602. this->LocalGenerator->MaybeRelativeToCurBinDir(
  603. this->DeviceLinkObject),
  604. cmOutputConverter::SHELL);
  605. }
  606. std::string const& aixExports = this->GetAIXExports(this->GetConfigName());
  607. // maybe create .def file from list of objects
  608. this->GenDefFile(real_link_commands);
  609. std::string manifests = this->GetManifests(this->GetConfigName());
  610. cmRulePlaceholderExpander::RuleVariables vars;
  611. vars.TargetPDB = targetOutPathPDB.c_str();
  612. // Setup the target version.
  613. std::string targetVersionMajor;
  614. std::string targetVersionMinor;
  615. {
  616. std::ostringstream majorStream;
  617. std::ostringstream minorStream;
  618. int major;
  619. int minor;
  620. this->GeneratorTarget->GetTargetVersion(major, minor);
  621. majorStream << major;
  622. minorStream << minor;
  623. targetVersionMajor = majorStream.str();
  624. targetVersionMinor = minorStream.str();
  625. }
  626. vars.TargetVersionMajor = targetVersionMajor.c_str();
  627. vars.TargetVersionMinor = targetVersionMinor.c_str();
  628. vars.CMTargetName = this->GeneratorTarget->GetName().c_str();
  629. vars.CMTargetType =
  630. cmState::GetTargetTypeName(this->GeneratorTarget->GetType()).c_str();
  631. vars.Language = linkLanguage.c_str();
  632. vars.AIXExports = aixExports.c_str();
  633. vars.Objects = buildObjs.c_str();
  634. std::string objectDir = this->GeneratorTarget->GetSupportDirectory();
  635. objectDir = this->LocalGenerator->ConvertToOutputFormat(
  636. this->LocalGenerator->MaybeRelativeToCurBinDir(objectDir),
  637. cmOutputConverter::SHELL);
  638. vars.ObjectDir = objectDir.c_str();
  639. cmOutputConverter::OutputFormat output = (useWatcomQuote)
  640. ? cmOutputConverter::WATCOMQUOTE
  641. : cmOutputConverter::SHELL;
  642. std::string target = this->LocalGenerator->ConvertToOutputFormat(
  643. this->LocalGenerator->MaybeRelativeToCurBinDir(targetFullPathReal),
  644. output);
  645. vars.Target = target.c_str();
  646. vars.LinkLibraries = linkLibs.c_str();
  647. vars.ObjectsQuoted = buildObjs.c_str();
  648. std::string targetOutSOName;
  649. if (this->GeneratorTarget->HasSOName(this->GetConfigName())) {
  650. vars.SONameFlag = this->Makefile->GetSONameFlag(linkLanguage);
  651. targetOutSOName = this->LocalGenerator->ConvertToOutputFormat(
  652. this->TargetNames.SharedObject.c_str(), cmOutputConverter::SHELL);
  653. vars.TargetSOName = targetOutSOName.c_str();
  654. }
  655. vars.LinkFlags = linkFlags.c_str();
  656. vars.Manifests = manifests.c_str();
  657. // Compute the directory portion of the install_name setting.
  658. std::string install_name_dir;
  659. if (this->GeneratorTarget->GetType() == cmStateEnums::SHARED_LIBRARY) {
  660. // Get the install_name directory for the build tree.
  661. install_name_dir = this->GeneratorTarget->GetInstallNameDirForBuildTree(
  662. this->GetConfigName());
  663. // Set the rule variable replacement value.
  664. if (install_name_dir.empty()) {
  665. vars.TargetInstallNameDir = "";
  666. } else {
  667. // Convert to a path for the native build tool.
  668. install_name_dir = this->LocalGenerator->ConvertToOutputFormat(
  669. install_name_dir, cmOutputConverter::SHELL);
  670. vars.TargetInstallNameDir = install_name_dir.c_str();
  671. }
  672. }
  673. // Add language-specific flags.
  674. std::string langFlags;
  675. this->LocalGenerator->AddLanguageFlagsForLinking(
  676. langFlags, this->GeneratorTarget, linkLanguage, this->GetConfigName());
  677. this->LocalGenerator->AddArchitectureFlags(
  678. langFlags, this->GeneratorTarget, linkLanguage, this->GetConfigName());
  679. vars.LanguageCompileFlags = langFlags.c_str();
  680. std::string linkerLauncher =
  681. this->GetLinkerLauncher(this->GetConfigName());
  682. if (cmNonempty(linkerLauncher)) {
  683. vars.Launcher = linkerLauncher.c_str();
  684. }
  685. std::string launcher;
  686. cmValue val = this->LocalGenerator->GetRuleLauncher(this->GeneratorTarget,
  687. "RULE_LAUNCH_LINK");
  688. if (cmNonempty(val)) {
  689. launcher = cmStrCat(*val, ' ');
  690. }
  691. std::unique_ptr<cmRulePlaceholderExpander> rulePlaceholderExpander(
  692. this->LocalGenerator->CreateRulePlaceholderExpander());
  693. // Construct the main link rule and expand placeholders.
  694. rulePlaceholderExpander->SetTargetImpLib(targetOutPathImport);
  695. if (useArchiveRules) {
  696. // Construct the individual object list strings.
  697. std::vector<std::string> object_strings;
  698. this->WriteObjectsStrings(object_strings, archiveCommandLimit);
  699. // Add the cuda device object to the list of archive files. This will
  700. // only occur on archives which have CUDA_RESOLVE_DEVICE_SYMBOLS enabled
  701. if (!this->DeviceLinkObject.empty()) {
  702. object_strings.push_back(this->LocalGenerator->ConvertToOutputFormat(
  703. this->LocalGenerator->MaybeRelativeToCurBinDir(
  704. this->DeviceLinkObject),
  705. cmOutputConverter::SHELL));
  706. }
  707. // Create the archive with the first set of objects.
  708. auto osi = object_strings.begin();
  709. {
  710. vars.Objects = osi->c_str();
  711. for (std::string const& acc : archiveCreateCommands) {
  712. std::string cmd = launcher + acc;
  713. rulePlaceholderExpander->ExpandRuleVariables(this->LocalGenerator,
  714. cmd, vars);
  715. real_link_commands.push_back(std::move(cmd));
  716. }
  717. }
  718. // Append to the archive with the other object sets.
  719. for (++osi; osi != object_strings.end(); ++osi) {
  720. vars.Objects = osi->c_str();
  721. for (std::string const& aac : archiveAppendCommands) {
  722. std::string cmd = launcher + aac;
  723. rulePlaceholderExpander->ExpandRuleVariables(this->LocalGenerator,
  724. cmd, vars);
  725. real_link_commands.push_back(std::move(cmd));
  726. }
  727. }
  728. // Finish the archive.
  729. vars.Objects = "";
  730. for (std::string const& afc : archiveFinishCommands) {
  731. std::string cmd = launcher + afc;
  732. rulePlaceholderExpander->ExpandRuleVariables(this->LocalGenerator, cmd,
  733. vars);
  734. // If there is no ranlib the command will be ":". Skip it.
  735. if (!cmd.empty() && cmd[0] != ':') {
  736. real_link_commands.push_back(std::move(cmd));
  737. }
  738. }
  739. } else {
  740. // Get the set of commands.
  741. std::string linkRule = this->GetLinkRule(linkRuleVar);
  742. cmExpandList(linkRule, real_link_commands);
  743. if (this->UseLWYU) {
  744. cmValue lwyuCheck =
  745. this->Makefile->GetDefinition("CMAKE_LINK_WHAT_YOU_USE_CHECK");
  746. if (lwyuCheck) {
  747. std::string cmakeCommand = cmStrCat(
  748. this->LocalGenerator->ConvertToOutputFormat(
  749. cmSystemTools::GetCMakeCommand(), cmLocalGenerator::SHELL),
  750. " -E __run_co_compile --lwyu=");
  751. cmakeCommand += this->LocalGenerator->EscapeForShell(*lwyuCheck);
  752. cmakeCommand += cmStrCat(" --source=", targetOutPathReal);
  753. real_link_commands.push_back(std::move(cmakeCommand));
  754. }
  755. }
  756. // Expand placeholders.
  757. for (std::string& real_link_command : real_link_commands) {
  758. real_link_command = cmStrCat(launcher, real_link_command);
  759. rulePlaceholderExpander->ExpandRuleVariables(this->LocalGenerator,
  760. real_link_command, vars);
  761. }
  762. }
  763. // Restore path conversion to normal shells.
  764. this->LocalGenerator->SetLinkScriptShell(false);
  765. }
  766. // Optionally convert the build rule to use a script to avoid long
  767. // command lines in the make shell.
  768. if (useLinkScript) {
  769. // Use a link script.
  770. const char* name = (relink ? "relink.txt" : "link.txt");
  771. this->CreateLinkScript(name, real_link_commands, commands1, depends);
  772. } else {
  773. // No link script. Just use the link rule directly.
  774. commands1 = real_link_commands;
  775. }
  776. this->LocalGenerator->CreateCDCommand(
  777. commands1, this->Makefile->GetCurrentBinaryDirectory(),
  778. this->LocalGenerator->GetBinaryDirectory());
  779. cm::append(commands, commands1);
  780. commands1.clear();
  781. // Add a rule to create necessary symlinks for the library.
  782. // Frameworks are handled by cmOSXBundleGenerator.
  783. if (targetOutPath != targetOutPathReal &&
  784. !this->GeneratorTarget->IsFrameworkOnApple()) {
  785. std::string symlink =
  786. cmStrCat("$(CMAKE_COMMAND) -E cmake_symlink_library ", targetOutPathReal,
  787. ' ', targetOutPathSO, ' ', targetOutPath);
  788. commands1.push_back(std::move(symlink));
  789. this->LocalGenerator->CreateCDCommand(
  790. commands1, this->Makefile->GetCurrentBinaryDirectory(),
  791. this->LocalGenerator->GetBinaryDirectory());
  792. cm::append(commands, commands1);
  793. commands1.clear();
  794. }
  795. // Add the post-build rules when building but not when relinking.
  796. if (!relink) {
  797. this->LocalGenerator->AppendCustomCommands(
  798. commands, this->GeneratorTarget->GetPostBuildCommands(),
  799. this->GeneratorTarget, this->LocalGenerator->GetBinaryDirectory());
  800. }
  801. // Compute the list of outputs.
  802. std::vector<std::string> outputs;
  803. outputs.reserve(3);
  804. outputs.push_back(targetFullPathReal);
  805. if (this->TargetNames.SharedObject != this->TargetNames.Real) {
  806. outputs.push_back(targetFullPathSO);
  807. }
  808. if (this->TargetNames.Output != this->TargetNames.SharedObject &&
  809. this->TargetNames.Output != this->TargetNames.Real) {
  810. outputs.push_back(targetFullPath);
  811. }
  812. // Write the build rule.
  813. this->WriteMakeRule(*this->BuildFileStream, nullptr, outputs, depends,
  814. commands, false);
  815. // Write the main driver rule to build everything in this target.
  816. this->WriteTargetDriverRule(targetFullPath, relink);
  817. // Clean all the possible library names and symlinks.
  818. this->CleanFiles.insert(libCleanFiles.begin(), libCleanFiles.end());
  819. }