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