cmMakefileLibraryTargetGenerator.cxx 36 KB

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