cmMakefileLibraryTargetGenerator.cxx 36 KB

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