resolve cyclic dependency with zstd
[platform/upstream/cmake.git] / Source / cmLocalUnixMakefileGenerator3.cxx
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 "cmLocalUnixMakefileGenerator3.h"
4
5 #include <algorithm>
6 #include <cassert>
7 #include <cstdio>
8 #include <functional>
9 #include <sstream>
10 #include <utility>
11
12 #include <cm/memory>
13 #include <cm/string_view>
14 #include <cm/vector>
15 #include <cmext/algorithm>
16 #include <cmext/string_view>
17
18 #include "cmsys/FStream.hxx"
19 #include "cmsys/Terminal.h"
20
21 #include "cmCMakePath.h"
22 #include "cmCustomCommand.h" // IWYU pragma: keep
23 #include "cmCustomCommandGenerator.h"
24 #include "cmDependsCompiler.h"
25 #include "cmFileTimeCache.h"
26 #include "cmGeneratedFileStream.h"
27 #include "cmGeneratorExpression.h"
28 #include "cmGeneratorTarget.h"
29 #include "cmGlobalGenerator.h"
30 #include "cmGlobalUnixMakefileGenerator3.h"
31 #include "cmListFileCache.h"
32 #include "cmLocalGenerator.h"
33 #include "cmMakefile.h"
34 #include "cmMakefileTargetGenerator.h"
35 #include "cmOutputConverter.h"
36 #include "cmRange.h"
37 #include "cmRulePlaceholderExpander.h"
38 #include "cmSourceFile.h"
39 #include "cmState.h"
40 #include "cmStateSnapshot.h"
41 #include "cmStateTypes.h"
42 #include "cmStringAlgorithms.h"
43 #include "cmSystemTools.h"
44 #include "cmTargetDepend.h"
45 #include "cmValue.h"
46 #include "cmVersion.h"
47 #include "cmake.h"
48
49 // Include dependency scanners for supported languages.  Only the
50 // C/C++ scanner is needed for bootstrapping CMake.
51 #include "cmDependsC.h"
52 #ifndef CMAKE_BOOTSTRAP
53 #  include "cmDependsFortran.h"
54 #  include "cmDependsJava.h"
55 #endif
56
57 namespace {
58 // Helper function used below.
59 std::string cmSplitExtension(std::string const& in, std::string& base)
60 {
61   std::string ext;
62   std::string::size_type dot_pos = in.rfind('.');
63   if (dot_pos != std::string::npos) {
64     // Remove the extension first in case &base == &in.
65     ext = in.substr(dot_pos);
66     base = in.substr(0, dot_pos);
67   } else {
68     base = in;
69   }
70   return ext;
71 }
72
73 // Helper predicate for removing absolute paths that don't point to the
74 // source or binary directory. It is used when CMAKE_DEPENDS_IN_PROJECT_ONLY
75 // is set ON, to only consider in-project dependencies during the build.
76 class NotInProjectDir
77 {
78 public:
79   // Constructor with the source and binary directory's path
80   NotInProjectDir(cm::string_view sourceDir, cm::string_view binaryDir)
81     : SourceDir(sourceDir)
82     , BinaryDir(binaryDir)
83   {
84   }
85
86   // Operator evaluating the predicate
87   bool operator()(const std::string& p) const
88   {
89     auto path = cmCMakePath(p).Normal();
90
91     // Keep all relative paths:
92     if (path.IsRelative()) {
93       return false;
94     }
95
96     // If it's an absolute path, check if it starts with the source
97     // directory:
98     return !(cmCMakePath(this->SourceDir).IsPrefix(path) ||
99              cmCMakePath(this->BinaryDir).IsPrefix(path));
100   }
101
102 private:
103   // The path to the source directory
104   cm::string_view SourceDir;
105   // The path to the binary directory
106   cm::string_view BinaryDir;
107 };
108 }
109
110 cmLocalUnixMakefileGenerator3::cmLocalUnixMakefileGenerator3(
111   cmGlobalGenerator* gg, cmMakefile* mf)
112   : cmLocalCommonGenerator(gg, mf, WorkDir::CurBin)
113 {
114   this->MakefileVariableSize = 0;
115   this->ColorMakefile = false;
116   this->SkipPreprocessedSourceRules = false;
117   this->SkipAssemblySourceRules = false;
118   this->MakeCommandEscapeTargetTwice = false;
119   this->BorlandMakeCurlyHack = false;
120 }
121
122 cmLocalUnixMakefileGenerator3::~cmLocalUnixMakefileGenerator3() = default;
123
124 std::string cmLocalUnixMakefileGenerator3::GetConfigName() const
125 {
126   auto const& configNames = this->GetConfigNames();
127   assert(configNames.size() == 1);
128   return configNames.front();
129 }
130
131 void cmLocalUnixMakefileGenerator3::Generate()
132 {
133   // Record whether some options are enabled to avoid checking many
134   // times later.
135   if (!this->GetGlobalGenerator()->GetCMakeInstance()->GetIsInTryCompile()) {
136     if (this->Makefile->IsSet("CMAKE_COLOR_MAKEFILE")) {
137       this->ColorMakefile = this->Makefile->IsOn("CMAKE_COLOR_MAKEFILE");
138     } else {
139       this->ColorMakefile = this->Makefile->IsOn("CMAKE_COLOR_DIAGNOSTICS");
140     }
141   }
142   this->SkipPreprocessedSourceRules =
143     this->Makefile->IsOn("CMAKE_SKIP_PREPROCESSED_SOURCE_RULES");
144   this->SkipAssemblySourceRules =
145     this->Makefile->IsOn("CMAKE_SKIP_ASSEMBLY_SOURCE_RULES");
146
147   // Generate the rule files for each target.
148   cmGlobalUnixMakefileGenerator3* gg =
149     static_cast<cmGlobalUnixMakefileGenerator3*>(this->GlobalGenerator);
150   for (cmGeneratorTarget* gt :
151        this->GlobalGenerator->GetLocalGeneratorTargetsInOrder(this)) {
152     if (!gt->IsInBuildSystem()) {
153       continue;
154     }
155
156     auto& gtVisited = this->GetCommandsVisited(gt);
157     const auto& deps = this->GlobalGenerator->GetTargetDirectDepends(gt);
158     for (const auto& d : deps) {
159       // Take the union of visited source files of custom commands
160       auto depVisited = this->GetCommandsVisited(d);
161       gtVisited.insert(depVisited.begin(), depVisited.end());
162     }
163
164     std::unique_ptr<cmMakefileTargetGenerator> tg(
165       cmMakefileTargetGenerator::New(gt));
166     if (tg) {
167       tg->WriteRuleFiles();
168       gg->RecordTargetProgress(tg.get());
169     }
170   }
171
172   // write the local Makefile
173   this->WriteLocalMakefile();
174
175   // Write the cmake file with information for this directory.
176   this->WriteDirectoryInformationFile();
177 }
178
179 void cmLocalUnixMakefileGenerator3::ComputeHomeRelativeOutputPath()
180 {
181   // Compute the path to use when referencing the current output
182   // directory from the top output directory.
183   this->HomeRelativeOutputPath =
184     this->MaybeRelativeToTopBinDir(this->GetCurrentBinaryDirectory());
185   if (this->HomeRelativeOutputPath == ".") {
186     this->HomeRelativeOutputPath.clear();
187   }
188   if (!this->HomeRelativeOutputPath.empty()) {
189     this->HomeRelativeOutputPath += "/";
190   }
191 }
192
193 void cmLocalUnixMakefileGenerator3::GetLocalObjectFiles(
194   std::map<std::string, LocalObjectInfo>& localObjectFiles)
195 {
196   for (const auto& gt : this->GetGeneratorTargets()) {
197     if (!gt->CanCompileSources()) {
198       continue;
199     }
200     std::vector<cmSourceFile const*> objectSources;
201     gt->GetObjectSources(objectSources, this->GetConfigName());
202     // Compute full path to object file directory for this target.
203     std::string dir = cmStrCat(gt->LocalGenerator->GetCurrentBinaryDirectory(),
204                                '/', this->GetTargetDirectory(gt.get()), '/');
205     // Compute the name of each object file.
206     for (cmSourceFile const* sf : objectSources) {
207       bool hasSourceExtension = true;
208       std::string objectName =
209         this->GetObjectFileNameWithoutTarget(*sf, dir, &hasSourceExtension);
210       if (cmSystemTools::FileIsFullPath(objectName)) {
211         objectName = cmSystemTools::GetFilenameName(objectName);
212       }
213       LocalObjectInfo& info = localObjectFiles[objectName];
214       info.HasSourceExtension = hasSourceExtension;
215       info.emplace_back(gt.get(), sf->GetLanguage());
216     }
217   }
218 }
219
220 void cmLocalUnixMakefileGenerator3::GetIndividualFileTargets(
221   std::vector<std::string>& targets)
222 {
223   std::map<std::string, LocalObjectInfo> localObjectFiles;
224   this->GetLocalObjectFiles(localObjectFiles);
225   for (auto const& localObjectFile : localObjectFiles) {
226     targets.push_back(localObjectFile.first);
227
228     std::string::size_type dot_pos = localObjectFile.first.rfind(".");
229     std::string base = localObjectFile.first.substr(0, dot_pos);
230     if (localObjectFile.second.HasPreprocessRule) {
231       targets.push_back(base + ".i");
232     }
233
234     if (localObjectFile.second.HasAssembleRule) {
235       targets.push_back(base + ".s");
236     }
237   }
238 }
239
240 void cmLocalUnixMakefileGenerator3::WriteLocalMakefile()
241 {
242   // generate the includes
243   std::string ruleFileName = "Makefile";
244
245   // Open the rule file.  This should be copy-if-different because the
246   // rules may depend on this file itself.
247   std::string ruleFileNameFull = this->ConvertToFullPath(ruleFileName);
248   cmGeneratedFileStream ruleFileStream(
249     ruleFileNameFull, false, this->GlobalGenerator->GetMakefileEncoding());
250   if (!ruleFileStream) {
251     return;
252   }
253   // always write the top makefile
254   if (!this->IsRootMakefile()) {
255     ruleFileStream.SetCopyIfDifferent(true);
256   }
257
258   // write the all rules
259   this->WriteLocalAllRules(ruleFileStream);
260
261   // only write local targets unless at the top Keep track of targets already
262   // listed.
263   std::set<std::string> emittedTargets;
264   if (!this->IsRootMakefile()) {
265     // write our targets, and while doing it collect up the object
266     // file rules
267     this->WriteLocalMakefileTargets(ruleFileStream, emittedTargets);
268   } else {
269     cmGlobalUnixMakefileGenerator3* gg =
270       static_cast<cmGlobalUnixMakefileGenerator3*>(this->GlobalGenerator);
271     gg->WriteConvenienceRules(ruleFileStream, emittedTargets);
272   }
273
274   bool do_preprocess_rules = this->GetCreatePreprocessedSourceRules();
275   bool do_assembly_rules = this->GetCreateAssemblySourceRules();
276
277   std::map<std::string, LocalObjectInfo> localObjectFiles;
278   this->GetLocalObjectFiles(localObjectFiles);
279
280   // now write out the object rules
281   // for each object file name
282   for (auto& localObjectFile : localObjectFiles) {
283     // Add a convenience rule for building the object file.
284     this->WriteObjectConvenienceRule(
285       ruleFileStream, "target to build an object file", localObjectFile.first,
286       localObjectFile.second);
287
288     // Check whether preprocessing and assembly rules make sense.
289     // They make sense only for C and C++ sources.
290     bool lang_has_preprocessor = false;
291     bool lang_has_assembly = false;
292
293     for (LocalObjectEntry const& entry : localObjectFile.second) {
294       if (entry.Language == "C" || entry.Language == "CXX" ||
295           entry.Language == "CUDA" || entry.Language == "Fortran" ||
296           entry.Language == "HIP" || entry.Language == "ISPC") {
297         // Right now, C, C++, CUDA, Fortran, HIP and ISPC have both a
298         // preprocessor and the ability to generate assembly code
299         lang_has_preprocessor = true;
300         lang_has_assembly = true;
301         break;
302       }
303     }
304
305     // Add convenience rules for preprocessed and assembly files.
306     if (lang_has_preprocessor && do_preprocess_rules) {
307       std::string::size_type dot_pos = localObjectFile.first.rfind(".");
308       std::string base = localObjectFile.first.substr(0, dot_pos);
309       this->WriteObjectConvenienceRule(ruleFileStream,
310                                        "target to preprocess a source file",
311                                        (base + ".i"), localObjectFile.second);
312       localObjectFile.second.HasPreprocessRule = true;
313     }
314
315     if (lang_has_assembly && do_assembly_rules) {
316       std::string::size_type dot_pos = localObjectFile.first.rfind(".");
317       std::string base = localObjectFile.first.substr(0, dot_pos);
318       this->WriteObjectConvenienceRule(
319         ruleFileStream, "target to generate assembly for a file",
320         (base + ".s"), localObjectFile.second);
321       localObjectFile.second.HasAssembleRule = true;
322     }
323   }
324
325   // add a help target as long as there isn;t a real target named help
326   if (emittedTargets.insert("help").second) {
327     cmGlobalUnixMakefileGenerator3* gg =
328       static_cast<cmGlobalUnixMakefileGenerator3*>(this->GlobalGenerator);
329     gg->WriteHelpRule(ruleFileStream, this);
330   }
331
332   this->WriteSpecialTargetsBottom(ruleFileStream);
333 }
334
335 void cmLocalUnixMakefileGenerator3::WriteObjectConvenienceRule(
336   std::ostream& ruleFileStream, const char* comment, const std::string& output,
337   LocalObjectInfo const& info)
338 {
339   // If the rule includes the source file extension then create a
340   // version that has the extension removed.  The help should include
341   // only the version without source extension.
342   bool inHelp = true;
343   if (info.HasSourceExtension) {
344     // Remove the last extension.  This should be kept.
345     std::string outBase1 = output;
346     std::string outExt1 = cmSplitExtension(outBase1, outBase1);
347
348     // Now remove the source extension and put back the last
349     // extension.
350     std::string outNoExt;
351     cmSplitExtension(outBase1, outNoExt);
352     outNoExt += outExt1;
353
354     // Add a rule to drive the rule below.
355     std::vector<std::string> depends;
356     depends.emplace_back(output);
357     std::vector<std::string> no_commands;
358     this->WriteMakeRule(ruleFileStream, nullptr, outNoExt, depends,
359                         no_commands, true, true);
360     inHelp = false;
361   }
362
363   // Recursively make the rule for each target using the object file.
364   std::vector<std::string> commands;
365   for (LocalObjectEntry const& t : info) {
366     std::string tgtMakefileName = this->GetRelativeTargetDirectory(t.Target);
367     std::string targetName = tgtMakefileName;
368     tgtMakefileName += "/build.make";
369     targetName += "/";
370     targetName += output;
371     commands.push_back(
372       this->GetRecursiveMakeCall(tgtMakefileName, targetName));
373   }
374   this->CreateCDCommand(commands, this->GetBinaryDirectory(),
375                         this->GetCurrentBinaryDirectory());
376
377   // Write the rule to the makefile.
378   std::vector<std::string> no_depends;
379   this->WriteMakeRule(ruleFileStream, comment, output, no_depends, commands,
380                       true, inHelp);
381 }
382
383 void cmLocalUnixMakefileGenerator3::WriteLocalMakefileTargets(
384   std::ostream& ruleFileStream, std::set<std::string>& emitted)
385 {
386   std::vector<std::string> depends;
387   std::vector<std::string> commands;
388
389   // for each target we just provide a rule to cd up to the top and do a make
390   // on the target
391   std::string localName;
392   for (const auto& target : this->GetGeneratorTargets()) {
393     if ((target->GetType() == cmStateEnums::EXECUTABLE) ||
394         (target->GetType() == cmStateEnums::STATIC_LIBRARY) ||
395         (target->GetType() == cmStateEnums::SHARED_LIBRARY) ||
396         (target->GetType() == cmStateEnums::MODULE_LIBRARY) ||
397         (target->GetType() == cmStateEnums::OBJECT_LIBRARY) ||
398         (target->GetType() == cmStateEnums::UTILITY)) {
399       emitted.insert(target->GetName());
400
401       // for subdirs add a rule to build this specific target by name.
402       localName =
403         cmStrCat(this->GetRelativeTargetDirectory(target.get()), "/rule");
404       commands.clear();
405       depends.clear();
406
407       // Build the target for this pass.
408       std::string makefile2 = "CMakeFiles/Makefile2";
409       commands.push_back(this->GetRecursiveMakeCall(makefile2, localName));
410       this->CreateCDCommand(commands, this->GetBinaryDirectory(),
411                             this->GetCurrentBinaryDirectory());
412       this->WriteMakeRule(ruleFileStream, "Convenience name for target.",
413                           localName, depends, commands, true);
414
415       // Add a target with the canonical name (no prefix, suffix or path).
416       if (localName != target->GetName()) {
417         commands.clear();
418         depends.push_back(localName);
419         this->WriteMakeRule(ruleFileStream, "Convenience name for target.",
420                             target->GetName(), depends, commands, true);
421       }
422
423       // Add a fast rule to build the target
424       std::string makefileName = cmStrCat(
425         this->GetRelativeTargetDirectory(target.get()), "/build.make");
426       // make sure the makefile name is suitable for a makefile
427       std::string makeTargetName =
428         cmStrCat(this->GetRelativeTargetDirectory(target.get()), "/build");
429       localName = cmStrCat(target->GetName(), "/fast");
430       depends.clear();
431       commands.clear();
432       commands.push_back(
433         this->GetRecursiveMakeCall(makefileName, makeTargetName));
434       this->CreateCDCommand(commands, this->GetBinaryDirectory(),
435                             this->GetCurrentBinaryDirectory());
436       this->WriteMakeRule(ruleFileStream, "fast build rule for target.",
437                           localName, depends, commands, true);
438
439       // Add a local name for the rule to relink the target before
440       // installation.
441       if (target->NeedRelinkBeforeInstall(this->GetConfigName())) {
442         makeTargetName = cmStrCat(
443           this->GetRelativeTargetDirectory(target.get()), "/preinstall");
444         localName = cmStrCat(target->GetName(), "/preinstall");
445         depends.clear();
446         commands.clear();
447         commands.push_back(
448           this->GetRecursiveMakeCall(makefile2, makeTargetName));
449         this->CreateCDCommand(commands, this->GetBinaryDirectory(),
450                               this->GetCurrentBinaryDirectory());
451         this->WriteMakeRule(ruleFileStream,
452                             "Manual pre-install relink rule for target.",
453                             localName, depends, commands, true);
454       }
455     }
456   }
457 }
458
459 void cmLocalUnixMakefileGenerator3::WriteDirectoryInformationFile()
460 {
461   std::string infoFileName =
462     cmStrCat(this->GetCurrentBinaryDirectory(),
463              "/CMakeFiles/CMakeDirectoryInformation.cmake");
464
465   // Open the output file.
466   cmGeneratedFileStream infoFileStream(infoFileName);
467   if (!infoFileStream) {
468     return;
469   }
470
471   infoFileStream.SetCopyIfDifferent(true);
472   // Write the do not edit header.
473   this->WriteDisclaimer(infoFileStream);
474
475   // Setup relative path conversion tops.
476   /* clang-format off */
477   infoFileStream
478     << "# Relative path conversion top directories.\n"
479     << "set(CMAKE_RELATIVE_PATH_TOP_SOURCE \""
480     << this->GetRelativePathTopSource() << "\")\n"
481     << "set(CMAKE_RELATIVE_PATH_TOP_BINARY \""
482     << this->GetRelativePathTopBinary() << "\")\n"
483     << "\n";
484   /* clang-format on */
485
486   // Tell the dependency scanner to use unix paths if necessary.
487   if (cmSystemTools::GetForceUnixPaths()) {
488     /* clang-format off */
489     infoFileStream
490       << "# Force unix paths in dependencies.\n"
491       << "set(CMAKE_FORCE_UNIX_PATHS 1)\n"
492       << "\n";
493     /* clang-format on */
494   }
495
496   // Store the include regular expressions for this directory.
497   infoFileStream << "\n"
498                  << "# The C and CXX include file regular expressions for "
499                  << "this directory.\n";
500   infoFileStream << "set(CMAKE_C_INCLUDE_REGEX_SCAN ";
501   cmLocalUnixMakefileGenerator3::WriteCMakeArgument(
502     infoFileStream, this->Makefile->GetIncludeRegularExpression());
503   infoFileStream << ")\n";
504   infoFileStream << "set(CMAKE_C_INCLUDE_REGEX_COMPLAIN ";
505   cmLocalUnixMakefileGenerator3::WriteCMakeArgument(
506     infoFileStream, this->Makefile->GetComplainRegularExpression());
507   infoFileStream << ")\n";
508   infoFileStream
509     << "set(CMAKE_CXX_INCLUDE_REGEX_SCAN ${CMAKE_C_INCLUDE_REGEX_SCAN})\n";
510   infoFileStream << "set(CMAKE_CXX_INCLUDE_REGEX_COMPLAIN "
511                     "${CMAKE_C_INCLUDE_REGEX_COMPLAIN})\n";
512 }
513
514 std::string cmLocalUnixMakefileGenerator3::ConvertToFullPath(
515   const std::string& localPath)
516 {
517   std::string dir =
518     cmStrCat(this->GetCurrentBinaryDirectory(), '/', localPath);
519   return dir;
520 }
521
522 const std::string& cmLocalUnixMakefileGenerator3::GetHomeRelativeOutputPath()
523 {
524   return this->HomeRelativeOutputPath;
525 }
526
527 std::string cmLocalUnixMakefileGenerator3::ConvertToMakefilePath(
528   std::string const& path) const
529 {
530   cmGlobalUnixMakefileGenerator3* gg =
531     static_cast<cmGlobalUnixMakefileGenerator3*>(this->GlobalGenerator);
532   return gg->ConvertToMakefilePath(path);
533 }
534
535 void cmLocalUnixMakefileGenerator3::WriteMakeRule(
536   std::ostream& os, const char* comment, const std::string& target,
537   const std::vector<std::string>& depends,
538   const std::vector<std::string>& commands, bool symbolic, bool in_help)
539 {
540   // Make sure there is a target.
541   if (target.empty()) {
542     std::string err("No target for WriteMakeRule! called with comment: ");
543     if (comment) {
544       err += comment;
545     }
546     cmSystemTools::Error(err);
547     return;
548   }
549
550   std::string replace;
551
552   // Write the comment describing the rule in the makefile.
553   if (comment) {
554     replace = comment;
555     std::string::size_type lpos = 0;
556     std::string::size_type rpos;
557     while ((rpos = replace.find('\n', lpos)) != std::string::npos) {
558       os << "# " << replace.substr(lpos, rpos - lpos) << "\n";
559       lpos = rpos + 1;
560     }
561     os << "# " << replace.substr(lpos) << "\n";
562   }
563
564   // Construct the left hand side of the rule.
565   std::string tgt =
566     this->ConvertToMakefilePath(this->MaybeRelativeToTopBinDir(target));
567
568   const char* space = "";
569   if (tgt.size() == 1) {
570     // Add a space before the ":" to avoid drive letter confusion on
571     // Windows.
572     space = " ";
573   }
574
575   // Mark the rule as symbolic if requested.
576   if (symbolic) {
577     if (cmValue sym =
578           this->Makefile->GetDefinition("CMAKE_MAKE_SYMBOLIC_RULE")) {
579       os << tgt << space << ": " << *sym << "\n";
580     }
581   }
582
583   // Write the rule.
584   if (depends.empty()) {
585     // No dependencies.  The commands will always run.
586     os << tgt << space << ":\n";
587   } else {
588     // Split dependencies into multiple rule lines.  This allows for
589     // very long dependency lists even on older make implementations.
590     for (std::string const& depend : depends) {
591       os << tgt << space << ": "
592          << this->ConvertToMakefilePath(this->MaybeRelativeToTopBinDir(depend))
593          << '\n';
594     }
595   }
596
597   if (!commands.empty()) {
598     // Write the list of commands.
599     os << cmWrap("\t", commands, "", "\n") << "\n";
600   }
601   if (symbolic && !this->IsWatcomWMake()) {
602     os << ".PHONY : " << tgt << "\n";
603   }
604   os << "\n";
605   // Add the output to the local help if requested.
606   if (in_help) {
607     this->LocalHelp.push_back(target);
608   }
609 }
610
611 std::string cmLocalUnixMakefileGenerator3::MaybeConvertWatcomShellCommand(
612   std::string const& cmd)
613 {
614   if (this->IsWatcomWMake() && cmSystemTools::FileIsFullPath(cmd) &&
615       cmd.find_first_of("( )") != std::string::npos) {
616     // On Watcom WMake use the windows short path for the command
617     // name.  This is needed to avoid funny quoting problems on
618     // lines with shell redirection operators.
619     std::string scmd;
620     if (cmSystemTools::GetShortPath(cmd, scmd)) {
621       return this->ConvertToOutputFormat(scmd, cmOutputConverter::SHELL);
622     }
623   }
624   return std::string();
625 }
626
627 void cmLocalUnixMakefileGenerator3::WriteMakeVariables(
628   std::ostream& makefileStream)
629 {
630   this->WriteDivider(makefileStream);
631   makefileStream << "# Set environment variables for the build.\n"
632                  << "\n";
633   cmGlobalUnixMakefileGenerator3* gg =
634     static_cast<cmGlobalUnixMakefileGenerator3*>(this->GlobalGenerator);
635   if (gg->DefineWindowsNULL) {
636     makefileStream << "!IF \"$(OS)\" == \"Windows_NT\"\n"
637                    << "NULL=\n"
638                    << "!ELSE\n"
639                    << "NULL=nul\n"
640                    << "!ENDIF\n";
641   }
642   if (this->IsWindowsShell()) {
643     makefileStream << "SHELL = cmd.exe\n"
644                    << "\n";
645   } else {
646 #if !defined(__VMS)
647     /* clang-format off */
648       makefileStream
649         << "# The shell in which to execute make rules.\n"
650         << "SHELL = /bin/sh\n"
651         << "\n";
652 /* clang-format on */
653 #endif
654   }
655
656   std::string cmakeShellCommand =
657     this->MaybeConvertWatcomShellCommand(cmSystemTools::GetCMakeCommand());
658   if (cmakeShellCommand.empty()) {
659     cmakeShellCommand = this->ConvertToOutputFormat(
660       cmSystemTools::GetCMakeCommand(), cmOutputConverter::SHELL);
661   }
662
663   /* clang-format off */
664   makefileStream
665     << "# The CMake executable.\n"
666     << "CMAKE_COMMAND = "
667     << cmakeShellCommand
668     << "\n"
669     << "\n";
670   makefileStream
671     << "# The command to remove a file.\n"
672     << "RM = "
673     << cmakeShellCommand
674     << " -E rm -f\n"
675     << "\n";
676   makefileStream
677     << "# Escaping for special characters.\n"
678     << "EQUALS = =\n"
679     << "\n";
680   makefileStream
681     << "# The top-level source directory on which CMake was run.\n"
682     << "CMAKE_SOURCE_DIR = "
683     << this->ConvertToOutputFormat(
684       this->GetSourceDirectory(), cmOutputConverter::SHELL)
685     << "\n"
686     << "\n";
687   makefileStream
688     << "# The top-level build directory on which CMake was run.\n"
689     << "CMAKE_BINARY_DIR = "
690     << this->ConvertToOutputFormat(
691       this->GetBinaryDirectory(), cmOutputConverter::SHELL)
692     << "\n"
693     << "\n";
694   /* clang-format on */
695 }
696
697 void cmLocalUnixMakefileGenerator3::WriteSpecialTargetsTop(
698   std::ostream& makefileStream)
699 {
700   this->WriteDivider(makefileStream);
701   makefileStream << "# Special targets provided by cmake.\n"
702                  << "\n";
703
704   std::vector<std::string> no_commands;
705   std::vector<std::string> no_depends;
706
707   // Special target to cleanup operation of make tool.
708   // This should be the first target except for the default_target in
709   // the interface Makefile.
710   this->WriteMakeRule(makefileStream,
711                       "Disable implicit rules so canonical targets will work.",
712                       ".SUFFIXES", no_depends, no_commands, false);
713
714   if (!this->IsNMake() && !this->IsWatcomWMake() &&
715       !this->BorlandMakeCurlyHack) {
716     // turn off RCS and SCCS automatic stuff from gmake
717     constexpr const char* vcs_rules[] = {
718       "%,v", "RCS/%", "RCS/%,v", "SCCS/s.%", "s.%",
719     };
720     for (const auto* vcs_rule : vcs_rules) {
721       std::vector<std::string> vcs_depend;
722       vcs_depend.emplace_back(vcs_rule);
723       this->WriteMakeRule(makefileStream, "Disable VCS-based implicit rules.",
724                           "%", vcs_depend, no_commands, false);
725     }
726   }
727   // Add a fake suffix to keep HP happy.  Must be max 32 chars for SGI make.
728   std::vector<std::string> depends;
729   depends.emplace_back(".hpux_make_needs_suffix_list");
730   this->WriteMakeRule(makefileStream, nullptr, ".SUFFIXES", depends,
731                       no_commands, false);
732   if (this->IsWatcomWMake()) {
733     // Switch on WMake feature, if an error or interrupt occurs during
734     // makefile processing, the current target being made may be deleted
735     // without prompting (the same as command line -e option).
736     /* clang-format off */
737     makefileStream <<
738       "\n"
739       ".ERASE\n"
740       "\n"
741       ;
742     /* clang-format on */
743   }
744   if (this->Makefile->IsOn("CMAKE_VERBOSE_MAKEFILE")) {
745     /* clang-format off */
746     makefileStream
747       << "# Produce verbose output by default.\n"
748       << "VERBOSE = 1\n"
749       << "\n";
750     /* clang-format on */
751   }
752   if (this->IsWatcomWMake()) {
753     /* clang-format off */
754     makefileStream <<
755       "!ifndef VERBOSE\n"
756       ".SILENT\n"
757       "!endif\n"
758       "\n"
759       ;
760     /* clang-format on */
761   } else {
762     makefileStream << "# Command-line flag to silence nested $(MAKE).\n"
763                       "$(VERBOSE)MAKESILENT = -s\n"
764                       "\n";
765
766     // Write special target to silence make output.  This must be after
767     // the default target in case VERBOSE is set (which changes the
768     // name).  The setting of CMAKE_VERBOSE_MAKEFILE to ON will cause a
769     // "VERBOSE=1" to be added as a make variable which will change the
770     // name of this special target.  This gives a make-time choice to
771     // the user.
772     // Write directly to the stream since WriteMakeRule escapes '$'.
773     makefileStream << "#Suppress display of executed commands.\n"
774                       "$(VERBOSE).SILENT:\n"
775                       "\n";
776   }
777
778   // Work-around for makes that drop rules that have no dependencies
779   // or commands.
780   cmGlobalUnixMakefileGenerator3* gg =
781     static_cast<cmGlobalUnixMakefileGenerator3*>(this->GlobalGenerator);
782   std::string hack = gg->GetEmptyRuleHackDepends();
783   if (!hack.empty()) {
784     no_depends.push_back(std::move(hack));
785   }
786   std::string hack_cmd = gg->GetEmptyRuleHackCommand();
787   if (!hack_cmd.empty()) {
788     no_commands.push_back(std::move(hack_cmd));
789   }
790
791   // Special symbolic target that never exists to force dependers to
792   // run their rules.
793   this->WriteMakeRule(makefileStream, "A target that is always out of date.",
794                       "cmake_force", no_depends, no_commands, true);
795
796   // Variables for reference by other rules.
797   this->WriteMakeVariables(makefileStream);
798 }
799
800 void cmLocalUnixMakefileGenerator3::WriteSpecialTargetsBottom(
801   std::ostream& makefileStream)
802 {
803   this->WriteDivider(makefileStream);
804   makefileStream << "# Special targets to cleanup operation of make.\n"
805                  << "\n";
806
807   // Write special "cmake_check_build_system" target to run cmake with
808   // the --check-build-system flag.
809   if (!this->GlobalGenerator->GlobalSettingIsOn(
810         "CMAKE_SUPPRESS_REGENERATION")) {
811     // Build command to run CMake to check if anything needs regenerating.
812     std::vector<std::string> commands;
813     cmake* cm = this->GlobalGenerator->GetCMakeInstance();
814     if (cm->DoWriteGlobVerifyTarget()) {
815       std::string rescanRule =
816         cmStrCat("$(CMAKE_COMMAND) -P ",
817                  this->ConvertToOutputFormat(cm->GetGlobVerifyScript(),
818                                              cmOutputConverter::SHELL));
819       commands.push_back(rescanRule);
820     }
821     std::string cmakefileName = "CMakeFiles/Makefile.cmake";
822     std::string runRule = cmStrCat(
823       "$(CMAKE_COMMAND) -S$(CMAKE_SOURCE_DIR) -B$(CMAKE_BINARY_DIR) "
824       "--check-build-system ",
825       this->ConvertToOutputFormat(cmakefileName, cmOutputConverter::SHELL),
826       " 0");
827
828     std::vector<std::string> no_depends;
829     commands.push_back(std::move(runRule));
830     if (!this->IsRootMakefile()) {
831       this->CreateCDCommand(commands, this->GetBinaryDirectory(),
832                             this->GetCurrentBinaryDirectory());
833     }
834     this->WriteMakeRule(makefileStream,
835                         "Special rule to run CMake to check the build system "
836                         "integrity.\n"
837                         "No rule that depends on this can have "
838                         "commands that come from listfiles\n"
839                         "because they might be regenerated.",
840                         "cmake_check_build_system", no_depends, commands,
841                         true);
842   }
843 }
844
845 void cmLocalUnixMakefileGenerator3::WriteConvenienceRule(
846   std::ostream& ruleFileStream, const std::string& realTarget,
847   const std::string& helpTarget)
848 {
849   // A rule is only needed if the names are different.
850   if (realTarget != helpTarget) {
851     // The helper target depends on the real target.
852     std::vector<std::string> depends;
853     depends.push_back(realTarget);
854
855     // There are no commands.
856     std::vector<std::string> no_commands;
857
858     // Write the rule.
859     this->WriteMakeRule(ruleFileStream, "Convenience name for target.",
860                         helpTarget, depends, no_commands, true);
861   }
862 }
863
864 std::string cmLocalUnixMakefileGenerator3::GetRelativeTargetDirectory(
865   cmGeneratorTarget const* target) const
866 {
867   std::string dir =
868     cmStrCat(this->HomeRelativeOutputPath, this->GetTargetDirectory(target));
869   return dir;
870 }
871
872 void cmLocalUnixMakefileGenerator3::AppendFlags(
873   std::string& flags, const std::string& newFlags) const
874 {
875   if (this->IsWatcomWMake() && !newFlags.empty()) {
876     std::string newf = newFlags;
877     if (newf.find("\\\"") != std::string::npos) {
878       cmSystemTools::ReplaceString(newf, "\\\"", "\"");
879       this->cmLocalGenerator::AppendFlags(flags, newf);
880       return;
881     }
882   }
883   this->cmLocalGenerator::AppendFlags(flags, newFlags);
884 }
885
886 void cmLocalUnixMakefileGenerator3::AppendRuleDepend(
887   std::vector<std::string>& depends, const char* ruleFileName)
888 {
889   // Add a dependency on the rule file itself unless an option to skip
890   // it is specifically enabled by the user or project.
891   cmValue nodep = this->Makefile->GetDefinition("CMAKE_SKIP_RULE_DEPENDENCY");
892   if (cmIsOff(nodep)) {
893     depends.emplace_back(ruleFileName);
894   }
895 }
896
897 void cmLocalUnixMakefileGenerator3::AppendRuleDepends(
898   std::vector<std::string>& depends, std::vector<std::string> const& ruleFiles)
899 {
900   // Add a dependency on the rule file itself unless an option to skip
901   // it is specifically enabled by the user or project.
902   if (!this->Makefile->IsOn("CMAKE_SKIP_RULE_DEPENDENCY")) {
903     cm::append(depends, ruleFiles);
904   }
905 }
906
907 void cmLocalUnixMakefileGenerator3::AppendCustomDepends(
908   std::vector<std::string>& depends, const std::vector<cmCustomCommand>& ccs)
909 {
910   for (cmCustomCommand const& cc : ccs) {
911     cmCustomCommandGenerator ccg(cc, this->GetConfigName(), this);
912     this->AppendCustomDepend(depends, ccg);
913   }
914 }
915
916 void cmLocalUnixMakefileGenerator3::AppendCustomDepend(
917   std::vector<std::string>& depends, cmCustomCommandGenerator const& ccg)
918 {
919   for (std::string const& d : ccg.GetDepends()) {
920     // Lookup the real name of the dependency in case it is a CMake target.
921     std::string dep;
922     if (this->GetRealDependency(d, this->GetConfigName(), dep)) {
923       depends.push_back(std::move(dep));
924     }
925   }
926 }
927
928 void cmLocalUnixMakefileGenerator3::AppendCustomCommands(
929   std::vector<std::string>& commands, const std::vector<cmCustomCommand>& ccs,
930   cmGeneratorTarget* target, std::string const& relative)
931 {
932   for (cmCustomCommand const& cc : ccs) {
933     cmCustomCommandGenerator ccg(cc, this->GetConfigName(), this);
934     this->AppendCustomCommand(commands, ccg, target, relative, true);
935   }
936 }
937
938 void cmLocalUnixMakefileGenerator3::AppendCustomCommand(
939   std::vector<std::string>& commands, cmCustomCommandGenerator const& ccg,
940   cmGeneratorTarget* target, std::string const& relative, bool echo_comment,
941   std::ostream* content)
942 {
943   // Optionally create a command to display the custom command's
944   // comment text.  This is used for pre-build, pre-link, and
945   // post-build command comments.  Custom build step commands have
946   // their comments generated elsewhere.
947   if (echo_comment) {
948     const char* comment = ccg.GetComment();
949     if (comment && *comment) {
950       this->AppendEcho(commands, comment,
951                        cmLocalUnixMakefileGenerator3::EchoGenerate);
952     }
953   }
954
955   // if the command specified a working directory use it.
956   std::string dir = this->GetCurrentBinaryDirectory();
957   std::string workingDir = ccg.GetWorkingDirectory();
958   if (!workingDir.empty()) {
959     dir = workingDir;
960   }
961   if (content) {
962     *content << dir;
963   }
964
965   std::unique_ptr<cmRulePlaceholderExpander> rulePlaceholderExpander(
966     this->CreateRulePlaceholderExpander());
967
968   // Add each command line to the set of commands.
969   std::vector<std::string> commands1;
970   for (unsigned int c = 0; c < ccg.GetNumberOfCommands(); ++c) {
971     // Build the command line in a single string.
972     std::string cmd = ccg.GetCommand(c);
973     if (!cmd.empty()) {
974       // Use "call " before any invocations of .bat or .cmd files
975       // invoked as custom commands in the WindowsShell.
976       //
977       bool useCall = false;
978
979       if (this->IsWindowsShell()) {
980         std::string suffix;
981         if (cmd.size() > 4) {
982           suffix = cmSystemTools::LowerCase(cmd.substr(cmd.size() - 4));
983           if (suffix == ".bat" || suffix == ".cmd") {
984             useCall = true;
985           }
986         }
987       }
988
989       cmSystemTools::ReplaceString(cmd, "/./", "/");
990       // Convert the command to a relative path only if the current
991       // working directory will be the start-output directory.
992       bool had_slash = cmd.find('/') != std::string::npos;
993       if (workingDir.empty()) {
994         cmd = this->MaybeRelativeToCurBinDir(cmd);
995       }
996       bool has_slash = cmd.find('/') != std::string::npos;
997       if (had_slash && !has_slash) {
998         // This command was specified as a path to a file in the
999         // current directory.  Add a leading "./" so it can run
1000         // without the current directory being in the search path.
1001         cmd = cmStrCat("./", cmd);
1002       }
1003
1004       std::string launcher;
1005       // Short-circuit if there is no launcher.
1006       cmValue val = this->GetRuleLauncher(target, "RULE_LAUNCH_CUSTOM");
1007       if (cmNonempty(val)) {
1008         // Expand rule variables referenced in the given launcher command.
1009         cmRulePlaceholderExpander::RuleVariables vars;
1010         vars.CMTargetName = target->GetName().c_str();
1011         vars.CMTargetType =
1012           cmState::GetTargetTypeName(target->GetType()).c_str();
1013         std::string output;
1014         const std::vector<std::string>& outputs = ccg.GetOutputs();
1015         if (!outputs.empty()) {
1016           output = outputs[0];
1017           if (workingDir.empty()) {
1018             output = this->MaybeRelativeToCurBinDir(output);
1019           }
1020           output =
1021             this->ConvertToOutputFormat(output, cmOutputConverter::SHELL);
1022         }
1023         vars.Output = output.c_str();
1024
1025         launcher = *val;
1026         rulePlaceholderExpander->ExpandRuleVariables(this, launcher, vars);
1027         if (!launcher.empty()) {
1028           launcher += " ";
1029         }
1030       }
1031
1032       std::string shellCommand = this->MaybeConvertWatcomShellCommand(cmd);
1033       if (shellCommand.empty()) {
1034         shellCommand =
1035           this->ConvertToOutputFormat(cmd, cmOutputConverter::SHELL);
1036       }
1037       cmd = launcher + shellCommand;
1038
1039       ccg.AppendArguments(c, cmd);
1040       if (content) {
1041         // Rule content does not include the launcher.
1042         *content << (cmd.c_str() + launcher.size());
1043       }
1044       if (this->BorlandMakeCurlyHack) {
1045         // Borland Make has a very strange bug.  If the first curly
1046         // brace anywhere in the command string is a left curly, it
1047         // must be written {{} instead of just {.  Otherwise some
1048         // curly braces are removed.  The hack can be skipped if the
1049         // first curly brace is the last character.
1050         std::string::size_type lcurly = cmd.find('{');
1051         if (lcurly != std::string::npos && lcurly < (cmd.size() - 1)) {
1052           std::string::size_type rcurly = cmd.find('}');
1053           if (rcurly == std::string::npos || rcurly > lcurly) {
1054             // The first curly is a left curly.  Use the hack.
1055             cmd =
1056               cmStrCat(cmd.substr(0, lcurly), "{{}", cmd.substr(lcurly + 1));
1057           }
1058         }
1059       }
1060       if (launcher.empty()) {
1061         if (useCall) {
1062           cmd = cmStrCat("call ", cmd);
1063         } else if (this->IsNMake() && cmd[0] == '"') {
1064           cmd = cmStrCat("echo >nul && ", cmd);
1065         }
1066       }
1067       commands1.push_back(std::move(cmd));
1068     }
1069   }
1070
1071   // Setup the proper working directory for the commands.
1072   this->CreateCDCommand(commands1, dir, relative);
1073
1074   // push back the custom commands
1075   cm::append(commands, commands1);
1076 }
1077
1078 void cmLocalUnixMakefileGenerator3::AppendCleanCommand(
1079   std::vector<std::string>& commands, const std::set<std::string>& files,
1080   cmGeneratorTarget* target, const char* filename)
1081 {
1082   std::string currentBinDir = this->GetCurrentBinaryDirectory();
1083   std::string cleanfile = cmStrCat(
1084     currentBinDir, '/', this->GetTargetDirectory(target), "/cmake_clean");
1085   if (filename) {
1086     cleanfile += "_";
1087     cleanfile += filename;
1088   }
1089   cleanfile += ".cmake";
1090   cmsys::ofstream fout(cleanfile.c_str());
1091   if (!fout) {
1092     cmSystemTools::Error("Could not create " + cleanfile);
1093   }
1094   if (!files.empty()) {
1095     fout << "file(REMOVE_RECURSE\n";
1096     for (std::string const& file : files) {
1097       std::string fc = this->MaybeRelativeToCurBinDir(file);
1098       fout << "  " << cmOutputConverter::EscapeForCMake(fc) << "\n";
1099     }
1100     fout << ")\n";
1101   }
1102   {
1103     std::string remove = cmStrCat(
1104       "$(CMAKE_COMMAND) -P ",
1105       this->ConvertToOutputFormat(this->MaybeRelativeToCurBinDir(cleanfile),
1106                                   cmOutputConverter::SHELL));
1107     commands.push_back(std::move(remove));
1108   }
1109
1110   // For the main clean rule add per-language cleaning.
1111   if (!filename) {
1112     // Get the set of source languages in the target.
1113     std::set<std::string> languages;
1114     target->GetLanguages(
1115       languages, this->Makefile->GetSafeDefinition("CMAKE_BUILD_TYPE"));
1116     /* clang-format off */
1117     fout << "\n"
1118          << "# Per-language clean rules from dependency scanning.\n"
1119          << "foreach(lang " << cmJoin(languages, " ") << ")\n"
1120          << "  include(" << this->GetTargetDirectory(target)
1121          << "/cmake_clean_${lang}.cmake OPTIONAL)\n"
1122          << "endforeach()\n";
1123     /* clang-format on */
1124   }
1125 }
1126
1127 void cmLocalUnixMakefileGenerator3::AppendDirectoryCleanCommand(
1128   std::vector<std::string>& commands)
1129 {
1130   std::vector<std::string> cleanFiles;
1131   // Look for additional files registered for cleaning in this directory.
1132   if (cmValue prop_value =
1133         this->Makefile->GetProperty("ADDITIONAL_CLEAN_FILES")) {
1134     cmExpandList(cmGeneratorExpression::Evaluate(
1135                    *prop_value, this,
1136                    this->Makefile->GetSafeDefinition("CMAKE_BUILD_TYPE")),
1137                  cleanFiles);
1138   }
1139   if (cleanFiles.empty()) {
1140     return;
1141   }
1142
1143   const auto& rootLG = this->GetGlobalGenerator()->GetLocalGenerators().at(0);
1144   std::string const& currentBinaryDir = this->GetCurrentBinaryDirectory();
1145   std::string cleanfile =
1146     cmStrCat(currentBinaryDir, "/CMakeFiles/cmake_directory_clean.cmake");
1147   // Write clean script
1148   {
1149     cmsys::ofstream fout(cleanfile.c_str());
1150     if (!fout) {
1151       cmSystemTools::Error("Could not create " + cleanfile);
1152       return;
1153     }
1154     fout << "file(REMOVE_RECURSE\n";
1155     for (std::string const& cfl : cleanFiles) {
1156       std::string fc = rootLG->MaybeRelativeToCurBinDir(
1157         cmSystemTools::CollapseFullPath(cfl, currentBinaryDir));
1158       fout << "  " << cmOutputConverter::EscapeForCMake(fc) << "\n";
1159     }
1160     fout << ")\n";
1161   }
1162   // Create command
1163   {
1164     std::string remove = cmStrCat(
1165       "$(CMAKE_COMMAND) -P ",
1166       this->ConvertToOutputFormat(rootLG->MaybeRelativeToCurBinDir(cleanfile),
1167                                   cmOutputConverter::SHELL));
1168     commands.push_back(std::move(remove));
1169   }
1170 }
1171
1172 void cmLocalUnixMakefileGenerator3::AppendEcho(
1173   std::vector<std::string>& commands, std::string const& text, EchoColor color,
1174   EchoProgress const* progress)
1175 {
1176   // Choose the color for the text.
1177   std::string color_name;
1178   if (this->GlobalGenerator->GetToolSupportsColor() && this->ColorMakefile) {
1179     // See cmake::ExecuteEchoColor in cmake.cxx for these options.
1180     // This color set is readable on both black and white backgrounds.
1181     switch (color) {
1182       case EchoNormal:
1183         break;
1184       case EchoDepend:
1185         color_name = "--magenta --bold ";
1186         break;
1187       case EchoBuild:
1188         color_name = "--green ";
1189         break;
1190       case EchoLink:
1191         color_name = "--green --bold ";
1192         break;
1193       case EchoGenerate:
1194         color_name = "--blue --bold ";
1195         break;
1196       case EchoGlobal:
1197         color_name = "--cyan ";
1198         break;
1199     }
1200   }
1201
1202   // Echo one line at a time.
1203   std::string line;
1204   line.reserve(200);
1205   for (const char* c = text.c_str();; ++c) {
1206     if (*c == '\n' || *c == '\0') {
1207       // Avoid writing a blank last line on end-of-string.
1208       if (*c != '\0' || !line.empty()) {
1209         // Add a command to echo this line.
1210         std::string cmd;
1211         if (color_name.empty() && !progress) {
1212           // Use the native echo command.
1213           cmd = cmStrCat("@echo ", this->EscapeForShell(line, false, true));
1214         } else {
1215           // Use cmake to echo the text in color.
1216           cmd = cmStrCat(
1217             "@$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) ",
1218             color_name);
1219           if (progress) {
1220             cmd += "--progress-dir=";
1221             cmd += this->ConvertToOutputFormat(progress->Dir,
1222                                                cmOutputConverter::SHELL);
1223             cmd += " ";
1224             cmd += "--progress-num=";
1225             cmd += progress->Arg;
1226             cmd += " ";
1227           }
1228           cmd += this->EscapeForShell(line);
1229         }
1230         commands.push_back(std::move(cmd));
1231       }
1232
1233       // Reset the line to empty.
1234       line.clear();
1235
1236       // Progress appears only on first line.
1237       progress = nullptr;
1238
1239       // Terminate on end-of-string.
1240       if (*c == '\0') {
1241         return;
1242       }
1243     } else if (*c != '\r') {
1244       // Append this character to the current line.
1245       line += *c;
1246     }
1247   }
1248 }
1249
1250 std::string cmLocalUnixMakefileGenerator3::CreateMakeVariable(
1251   std::string const& s, std::string const& s2)
1252 {
1253   std::string unmodified = cmStrCat(s, s2);
1254   // if there is no restriction on the length of make variables
1255   // and there are no "." characters in the string, then return the
1256   // unmodified combination.
1257   if ((!this->MakefileVariableSize &&
1258        unmodified.find('.') == std::string::npos) &&
1259       (!this->MakefileVariableSize &&
1260        unmodified.find('+') == std::string::npos) &&
1261       (!this->MakefileVariableSize &&
1262        unmodified.find('-') == std::string::npos)) {
1263     return unmodified;
1264   }
1265
1266   // see if the variable has been defined before and return
1267   // the modified version of the variable
1268   auto i = this->MakeVariableMap.find(unmodified);
1269   if (i != this->MakeVariableMap.end()) {
1270     return i->second;
1271   }
1272   // start with the unmodified variable
1273   std::string ret = unmodified;
1274   // if this there is no value for this->MakefileVariableSize then
1275   // the string must have bad characters in it
1276   if (!this->MakefileVariableSize) {
1277     std::replace(ret.begin(), ret.end(), '.', '_');
1278     cmSystemTools::ReplaceString(ret, "-", "__");
1279     cmSystemTools::ReplaceString(ret, "+", "___");
1280     int ni = 0;
1281     char buffer[12];
1282     // make sure the _ version is not already used, if
1283     // it is used then add number to the end of the variable
1284     while (this->ShortMakeVariableMap.count(ret) && ni < 1000) {
1285       ++ni;
1286       snprintf(buffer, sizeof(buffer), "%04d", ni);
1287       ret = unmodified + buffer;
1288     }
1289     this->ShortMakeVariableMap[ret] = "1";
1290     this->MakeVariableMap[unmodified] = ret;
1291     return ret;
1292   }
1293
1294   // if the string is greater than 32 chars it is an invalid variable name
1295   // for borland make
1296   if (static_cast<int>(ret.size()) > this->MakefileVariableSize) {
1297     int keep = this->MakefileVariableSize - 8;
1298     int size = keep + 3;
1299     std::string str1 = s;
1300     std::string str2 = s2;
1301     // we must shorten the combined string by 4 characters
1302     // keep no more than 24 characters from the second string
1303     if (static_cast<int>(str2.size()) > keep) {
1304       str2 = str2.substr(0, keep);
1305     }
1306     if (static_cast<int>(str1.size()) + static_cast<int>(str2.size()) > size) {
1307       str1 = str1.substr(0, size - str2.size());
1308     }
1309     char buffer[12];
1310     int ni = 0;
1311     snprintf(buffer, sizeof(buffer), "%04d", ni);
1312     ret = str1 + str2 + buffer;
1313     while (this->ShortMakeVariableMap.count(ret) && ni < 1000) {
1314       ++ni;
1315       snprintf(buffer, sizeof(buffer), "%04d", ni);
1316       ret = str1 + str2 + buffer;
1317     }
1318     if (ni == 1000) {
1319       cmSystemTools::Error("Borland makefile variable length too long");
1320       return unmodified;
1321     }
1322     // once an unused variable is found
1323     this->ShortMakeVariableMap[ret] = "1";
1324   }
1325   // always make an entry into the unmodified to variable map
1326   this->MakeVariableMap[unmodified] = ret;
1327   return ret;
1328 }
1329
1330 bool cmLocalUnixMakefileGenerator3::UpdateDependencies(
1331   const std::string& tgtInfo, bool verbose, bool color)
1332 {
1333   // read in the target info file
1334   if (!this->Makefile->ReadListFile(tgtInfo) ||
1335       cmSystemTools::GetErrorOccurredFlag()) {
1336     cmSystemTools::Error("Target DependInfo.cmake file not found");
1337   }
1338
1339   bool status = true;
1340
1341   // Check if any multiple output pairs have a missing file.
1342   this->CheckMultipleOutputs(verbose);
1343
1344   std::string const targetDir = cmSystemTools::GetFilenamePath(tgtInfo);
1345   if (!this->Makefile->GetSafeDefinition("CMAKE_DEPENDS_LANGUAGES").empty()) {
1346     // dependencies are managed by CMake itself
1347
1348     std::string const internalDependFile = targetDir + "/depend.internal";
1349     std::string const dependFile = targetDir + "/depend.make";
1350
1351     // If the target DependInfo.cmake file has changed since the last
1352     // time dependencies were scanned then force rescanning.  This may
1353     // happen when a new source file is added and CMake regenerates the
1354     // project but no other sources were touched.
1355     bool needRescanDependInfo = false;
1356     cmFileTimeCache* ftc =
1357       this->GlobalGenerator->GetCMakeInstance()->GetFileTimeCache();
1358     {
1359       int result;
1360       if (!ftc->Compare(internalDependFile, tgtInfo, &result) || result < 0) {
1361         if (verbose) {
1362           cmSystemTools::Stdout(cmStrCat("Dependee \"", tgtInfo,
1363                                          "\" is newer than depender \"",
1364                                          internalDependFile, "\".\n"));
1365         }
1366         needRescanDependInfo = true;
1367       }
1368     }
1369
1370     // If the directory information is newer than depend.internal, include
1371     // dirs may have changed. In this case discard all old dependencies.
1372     bool needRescanDirInfo = false;
1373     {
1374       std::string dirInfoFile =
1375         cmStrCat(this->GetCurrentBinaryDirectory(),
1376                  "/CMakeFiles/CMakeDirectoryInformation.cmake");
1377       int result;
1378       if (!ftc->Compare(internalDependFile, dirInfoFile, &result) ||
1379           result < 0) {
1380         if (verbose) {
1381           cmSystemTools::Stdout(cmStrCat("Dependee \"", dirInfoFile,
1382                                          "\" is newer than depender \"",
1383                                          internalDependFile, "\".\n"));
1384         }
1385         needRescanDirInfo = true;
1386       }
1387     }
1388
1389     // Check the implicit dependencies to see if they are up to date.
1390     // The build.make file may have explicit dependencies for the object
1391     // files but these will not affect the scanning process so they need
1392     // not be considered.
1393     cmDepends::DependencyMap validDependencies;
1394     bool needRescanDependencies = false;
1395     if (!needRescanDirInfo) {
1396       cmDependsC checker;
1397       checker.SetVerbose(verbose);
1398       checker.SetFileTimeCache(ftc);
1399       // cmDependsC::Check() fills the vector validDependencies() with the
1400       // dependencies for those files where they are still valid, i.e.
1401       // neither the files themselves nor any files they depend on have
1402       // changed. We don't do that if the CMakeDirectoryInformation.cmake
1403       // file has changed, because then potentially all dependencies have
1404       // changed. This information is given later on to cmDependsC, which
1405       // then only rescans the files where it did not get valid dependencies
1406       // via this dependency vector. This means that in the normal case, when
1407       // only few or one file have been edited, then also only this one file
1408       // is actually scanned again, instead of all files for this target.
1409       needRescanDependencies =
1410         !checker.Check(dependFile, internalDependFile, validDependencies);
1411     }
1412
1413     if (needRescanDependInfo || needRescanDirInfo || needRescanDependencies) {
1414       // The dependencies must be regenerated.
1415       if (verbose) {
1416         std::string targetName = cmSystemTools::GetFilenameName(targetDir);
1417         targetName = targetName.substr(0, targetName.length() - 4);
1418         std::string message =
1419           cmStrCat("Scanning dependencies of target ", targetName);
1420         cmSystemTools::MakefileColorEcho(
1421           cmsysTerminal_Color_ForegroundMagenta |
1422             cmsysTerminal_Color_ForegroundBold,
1423           message.c_str(), true, color);
1424       }
1425
1426       status = this->ScanDependencies(targetDir, dependFile,
1427                                       internalDependFile, validDependencies);
1428     }
1429   }
1430
1431   auto depends =
1432     this->Makefile->GetSafeDefinition("CMAKE_DEPENDS_DEPENDENCY_FILES");
1433   if (!depends.empty()) {
1434     // dependencies are managed by compiler
1435     auto depFiles = cmExpandedList(depends, true);
1436     std::string const internalDepFile =
1437       targetDir + "/compiler_depend.internal";
1438     std::string const depFile = targetDir + "/compiler_depend.make";
1439     cmDepends::DependencyMap dependencies;
1440     cmDependsCompiler depsManager;
1441     bool projectOnly = cmIsOn(
1442       this->Makefile->GetSafeDefinition("CMAKE_DEPENDS_IN_PROJECT_ONLY"));
1443
1444     depsManager.SetVerbose(verbose);
1445     depsManager.SetLocalGenerator(this);
1446
1447     if (!depsManager.CheckDependencies(
1448           internalDepFile, depFiles, dependencies,
1449           projectOnly ? NotInProjectDir(this->GetSourceDirectory(),
1450                                         this->GetBinaryDirectory())
1451                       : std::function<bool(const std::string&)>())) {
1452       // regenerate dependencies files
1453       if (verbose) {
1454         std::string targetName = cmCMakePath(targetDir)
1455                                    .GetFileName()
1456                                    .RemoveExtension()
1457                                    .GenericString();
1458         auto message =
1459           cmStrCat("Consolidate compiler generated dependencies of target ",
1460                    targetName);
1461         cmSystemTools::MakefileColorEcho(
1462           cmsysTerminal_Color_ForegroundMagenta |
1463             cmsysTerminal_Color_ForegroundBold,
1464           message.c_str(), true, color);
1465       }
1466
1467       // Open the make depends file.  This should be copy-if-different
1468       // because the make tool may try to reload it needlessly otherwise.
1469       cmGeneratedFileStream ruleFileStream(
1470         depFile, false, this->GlobalGenerator->GetMakefileEncoding());
1471       ruleFileStream.SetCopyIfDifferent(true);
1472       if (!ruleFileStream) {
1473         return false;
1474       }
1475
1476       // Open the cmake dependency tracking file.  This should not be
1477       // copy-if-different because dependencies are re-scanned when it is
1478       // older than the DependInfo.cmake.
1479       cmGeneratedFileStream internalRuleFileStream(
1480         internalDepFile, false, this->GlobalGenerator->GetMakefileEncoding());
1481       if (!internalRuleFileStream) {
1482         return false;
1483       }
1484
1485       this->WriteDisclaimer(ruleFileStream);
1486       this->WriteDisclaimer(internalRuleFileStream);
1487
1488       depsManager.WriteDependencies(dependencies, ruleFileStream,
1489                                     internalRuleFileStream);
1490     }
1491   }
1492
1493   // The dependencies are already up-to-date.
1494   return status;
1495 }
1496
1497 bool cmLocalUnixMakefileGenerator3::ScanDependencies(
1498   std::string const& targetDir, std::string const& dependFile,
1499   std::string const& internalDependFile, cmDepends::DependencyMap& validDeps)
1500 {
1501   // Read the directory information file.
1502   cmMakefile* mf = this->Makefile;
1503   bool haveDirectoryInfo = false;
1504   {
1505     std::string dirInfoFile =
1506       cmStrCat(this->GetCurrentBinaryDirectory(),
1507                "/CMakeFiles/CMakeDirectoryInformation.cmake");
1508     if (mf->ReadListFile(dirInfoFile) &&
1509         !cmSystemTools::GetErrorOccurredFlag()) {
1510       haveDirectoryInfo = true;
1511     }
1512   }
1513
1514   // Lookup useful directory information.
1515   if (haveDirectoryInfo) {
1516     // Test whether we need to force Unix paths.
1517     if (cmValue force = mf->GetDefinition("CMAKE_FORCE_UNIX_PATHS")) {
1518       if (!cmIsOff(force)) {
1519         cmSystemTools::SetForceUnixPaths(true);
1520       }
1521     }
1522
1523     // Setup relative path top directories.
1524     cmValue relativePathTopSource =
1525       mf->GetDefinition("CMAKE_RELATIVE_PATH_TOP_SOURCE");
1526     cmValue relativePathTopBinary =
1527       mf->GetDefinition("CMAKE_RELATIVE_PATH_TOP_BINARY");
1528     if (relativePathTopSource && relativePathTopBinary) {
1529       this->SetRelativePathTop(*relativePathTopSource, *relativePathTopBinary);
1530     }
1531   } else {
1532     cmSystemTools::Error("Directory Information file not found");
1533   }
1534
1535   // Open the make depends file.  This should be copy-if-different
1536   // because the make tool may try to reload it needlessly otherwise.
1537   cmGeneratedFileStream ruleFileStream(
1538     dependFile, false, this->GlobalGenerator->GetMakefileEncoding());
1539   ruleFileStream.SetCopyIfDifferent(true);
1540   if (!ruleFileStream) {
1541     return false;
1542   }
1543
1544   // Open the cmake dependency tracking file.  This should not be
1545   // copy-if-different because dependencies are re-scanned when it is
1546   // older than the DependInfo.cmake.
1547   cmGeneratedFileStream internalRuleFileStream(
1548     internalDependFile, false, this->GlobalGenerator->GetMakefileEncoding());
1549   if (!internalRuleFileStream) {
1550     return false;
1551   }
1552
1553   this->WriteDisclaimer(ruleFileStream);
1554   this->WriteDisclaimer(internalRuleFileStream);
1555
1556   // for each language we need to scan, scan it
1557   std::vector<std::string> langs =
1558     cmExpandedList(mf->GetSafeDefinition("CMAKE_DEPENDS_LANGUAGES"));
1559   for (std::string const& lang : langs) {
1560     // construct the checker
1561     // Create the scanner for this language
1562     std::unique_ptr<cmDepends> scanner;
1563     if (lang == "C" || lang == "CXX" || lang == "RC" || lang == "ASM" ||
1564         lang == "OBJC" || lang == "OBJCXX" || lang == "CUDA" ||
1565         lang == "HIP" || lang == "ISPC") {
1566       // TODO: Handle RC (resource files) dependencies correctly.
1567       scanner = cm::make_unique<cmDependsC>(this, targetDir, lang, &validDeps);
1568     }
1569 #ifndef CMAKE_BOOTSTRAP
1570     else if (lang == "Fortran") {
1571       ruleFileStream << "# Note that incremental build could trigger "
1572                      << "a call to cmake_copy_f90_mod on each re-build\n";
1573       scanner = cm::make_unique<cmDependsFortran>(this);
1574     } else if (lang == "Java") {
1575       scanner = cm::make_unique<cmDependsJava>();
1576     }
1577 #endif
1578
1579     if (scanner) {
1580       scanner->SetLocalGenerator(this);
1581       scanner->SetFileTimeCache(
1582         this->GlobalGenerator->GetCMakeInstance()->GetFileTimeCache());
1583       scanner->SetLanguage(lang);
1584       scanner->SetTargetDirectory(targetDir);
1585       scanner->Write(ruleFileStream, internalRuleFileStream);
1586     }
1587   }
1588
1589   return true;
1590 }
1591
1592 void cmLocalUnixMakefileGenerator3::CheckMultipleOutputs(bool verbose)
1593 {
1594   cmMakefile* mf = this->Makefile;
1595
1596   // Get the string listing the multiple output pairs.
1597   cmValue pairs_string = mf->GetDefinition("CMAKE_MULTIPLE_OUTPUT_PAIRS");
1598   if (!pairs_string) {
1599     return;
1600   }
1601
1602   // Convert the string to a list and preserve empty entries.
1603   std::vector<std::string> pairs = cmExpandedList(*pairs_string, true);
1604   for (auto i = pairs.begin(); i != pairs.end() && (i + 1) != pairs.end();) {
1605     const std::string& depender = *i++;
1606     const std::string& dependee = *i++;
1607
1608     // If the depender is missing then delete the dependee to make
1609     // sure both will be regenerated.
1610     if (cmSystemTools::FileExists(dependee) &&
1611         !cmSystemTools::FileExists(depender)) {
1612       if (verbose) {
1613         cmSystemTools::Stdout(cmStrCat(
1614           "Deleting primary custom command output \"", dependee,
1615           "\" because another output \"", depender, "\" does not exist.\n"));
1616       }
1617       cmSystemTools::RemoveFile(dependee);
1618     }
1619   }
1620 }
1621
1622 void cmLocalUnixMakefileGenerator3::WriteLocalAllRules(
1623   std::ostream& ruleFileStream)
1624 {
1625   this->WriteDisclaimer(ruleFileStream);
1626
1627   // Write the main entry point target.  This must be the VERY first
1628   // target so that make with no arguments will run it.
1629   {
1630     // Just depend on the all target to drive the build.
1631     std::vector<std::string> depends;
1632     std::vector<std::string> no_commands;
1633     depends.emplace_back("all");
1634
1635     // Write the rule.
1636     this->WriteMakeRule(ruleFileStream,
1637                         "Default target executed when no arguments are "
1638                         "given to make.",
1639                         "default_target", depends, no_commands, true);
1640
1641     // Help out users that try "gmake target1 target2 -j".
1642     cmGlobalUnixMakefileGenerator3* gg =
1643       static_cast<cmGlobalUnixMakefileGenerator3*>(this->GlobalGenerator);
1644     if (gg->AllowNotParallel()) {
1645       std::vector<std::string> no_depends;
1646       this->WriteMakeRule(ruleFileStream,
1647                           "Allow only one \"make -f "
1648                           "Makefile2\" at a time, but pass "
1649                           "parallelism.",
1650                           ".NOTPARALLEL", no_depends, no_commands, false);
1651     }
1652   }
1653
1654   this->WriteSpecialTargetsTop(ruleFileStream);
1655
1656   // Include the progress variables for the target.
1657   // Write all global targets
1658   this->WriteDivider(ruleFileStream);
1659   ruleFileStream << "# Targets provided globally by CMake.\n"
1660                  << "\n";
1661   const auto& targets = this->GetGeneratorTargets();
1662   for (const auto& gt : targets) {
1663     if (gt->GetType() == cmStateEnums::GLOBAL_TARGET) {
1664       std::string targetString =
1665         "Special rule for the target " + gt->GetName();
1666       std::vector<std::string> commands;
1667       std::vector<std::string> depends;
1668
1669       cmValue p = gt->GetProperty("EchoString");
1670       const char* text = p ? p->c_str() : "Running external command ...";
1671       depends.reserve(gt->GetUtilities().size());
1672       for (BT<std::pair<std::string, bool>> const& u : gt->GetUtilities()) {
1673         depends.push_back(u.Value.first);
1674       }
1675       this->AppendEcho(commands, text,
1676                        cmLocalUnixMakefileGenerator3::EchoGlobal);
1677
1678       // Global targets store their rules in pre- and post-build commands.
1679       this->AppendCustomDepends(depends, gt->GetPreBuildCommands());
1680       this->AppendCustomDepends(depends, gt->GetPostBuildCommands());
1681       this->AppendCustomCommands(commands, gt->GetPreBuildCommands(), gt.get(),
1682                                  this->GetCurrentBinaryDirectory());
1683       this->AppendCustomCommands(commands, gt->GetPostBuildCommands(),
1684                                  gt.get(), this->GetCurrentBinaryDirectory());
1685       std::string targetName = gt->GetName();
1686       this->WriteMakeRule(ruleFileStream, targetString.c_str(), targetName,
1687                           depends, commands, true);
1688
1689       // Provide a "/fast" version of the target.
1690       depends.clear();
1691       if ((targetName == "install") || (targetName == "install/local") ||
1692           (targetName == "install/strip")) {
1693         // Provide a fast install target that does not depend on all
1694         // but has the same command.
1695         depends.emplace_back("preinstall/fast");
1696       } else {
1697         // Just forward to the real target so at least it will work.
1698         depends.push_back(targetName);
1699         commands.clear();
1700       }
1701       targetName += "/fast";
1702       this->WriteMakeRule(ruleFileStream, targetString.c_str(), targetName,
1703                           depends, commands, true);
1704     }
1705   }
1706
1707   std::vector<std::string> depends;
1708   std::vector<std::string> commands;
1709
1710   // Write the all rule.
1711   std::string recursiveTarget =
1712     cmStrCat(this->GetCurrentBinaryDirectory(), "/all");
1713
1714   bool regenerate =
1715     !this->GlobalGenerator->GlobalSettingIsOn("CMAKE_SUPPRESS_REGENERATION");
1716   if (regenerate) {
1717     depends.emplace_back("cmake_check_build_system");
1718   }
1719
1720   std::string progressDir =
1721     cmStrCat(this->GetBinaryDirectory(), "/CMakeFiles");
1722   {
1723     std::ostringstream progCmd;
1724     progCmd << "$(CMAKE_COMMAND) -E cmake_progress_start ";
1725     progCmd << this->ConvertToOutputFormat(progressDir,
1726                                            cmOutputConverter::SHELL);
1727
1728     std::string progressFile = "/CMakeFiles/progress.marks";
1729     std::string progressFileNameFull = this->ConvertToFullPath(progressFile);
1730     progCmd << " "
1731             << this->ConvertToOutputFormat(progressFileNameFull,
1732                                            cmOutputConverter::SHELL);
1733     commands.push_back(progCmd.str());
1734   }
1735   std::string mf2Dir = "CMakeFiles/Makefile2";
1736   commands.push_back(this->GetRecursiveMakeCall(mf2Dir, recursiveTarget));
1737   this->CreateCDCommand(commands, this->GetBinaryDirectory(),
1738                         this->GetCurrentBinaryDirectory());
1739   {
1740     std::ostringstream progCmd;
1741     progCmd << "$(CMAKE_COMMAND) -E cmake_progress_start "; // # 0
1742     progCmd << this->ConvertToOutputFormat(progressDir,
1743                                            cmOutputConverter::SHELL);
1744     progCmd << " 0";
1745     commands.push_back(progCmd.str());
1746   }
1747   this->WriteMakeRule(ruleFileStream, "The main all target", "all", depends,
1748                       commands, true);
1749
1750   // Write the clean rule.
1751   recursiveTarget = cmStrCat(this->GetCurrentBinaryDirectory(), "/clean");
1752   commands.clear();
1753   depends.clear();
1754   commands.push_back(this->GetRecursiveMakeCall(mf2Dir, recursiveTarget));
1755   this->CreateCDCommand(commands, this->GetBinaryDirectory(),
1756                         this->GetCurrentBinaryDirectory());
1757   this->WriteMakeRule(ruleFileStream, "The main clean target", "clean",
1758                       depends, commands, true);
1759   commands.clear();
1760   depends.clear();
1761   depends.emplace_back("clean");
1762   this->WriteMakeRule(ruleFileStream, "The main clean target", "clean/fast",
1763                       depends, commands, true);
1764
1765   // Write the preinstall rule.
1766   recursiveTarget = cmStrCat(this->GetCurrentBinaryDirectory(), "/preinstall");
1767   commands.clear();
1768   depends.clear();
1769   cmValue noall =
1770     this->Makefile->GetDefinition("CMAKE_SKIP_INSTALL_ALL_DEPENDENCY");
1771   if (cmIsOff(noall)) {
1772     // Drive the build before installing.
1773     depends.emplace_back("all");
1774   } else if (regenerate) {
1775     // At least make sure the build system is up to date.
1776     depends.emplace_back("cmake_check_build_system");
1777   }
1778   commands.push_back(this->GetRecursiveMakeCall(mf2Dir, recursiveTarget));
1779   this->CreateCDCommand(commands, this->GetBinaryDirectory(),
1780                         this->GetCurrentBinaryDirectory());
1781   this->WriteMakeRule(ruleFileStream, "Prepare targets for installation.",
1782                       "preinstall", depends, commands, true);
1783   depends.clear();
1784   this->WriteMakeRule(ruleFileStream, "Prepare targets for installation.",
1785                       "preinstall/fast", depends, commands, true);
1786
1787   if (regenerate) {
1788     // write the depend rule, really a recompute depends rule
1789     depends.clear();
1790     commands.clear();
1791     cmake* cm = this->GlobalGenerator->GetCMakeInstance();
1792     if (cm->DoWriteGlobVerifyTarget()) {
1793       std::string rescanRule =
1794         cmStrCat("$(CMAKE_COMMAND) -P ",
1795                  this->ConvertToOutputFormat(cm->GetGlobVerifyScript(),
1796                                              cmOutputConverter::SHELL));
1797       commands.push_back(rescanRule);
1798     }
1799     std::string cmakefileName = "CMakeFiles/Makefile.cmake";
1800     {
1801       std::string runRule = cmStrCat(
1802         "$(CMAKE_COMMAND) -S$(CMAKE_SOURCE_DIR) -B$(CMAKE_BINARY_DIR) "
1803         "--check-build-system ",
1804         this->ConvertToOutputFormat(cmakefileName, cmOutputConverter::SHELL),
1805         " 1");
1806       commands.push_back(std::move(runRule));
1807     }
1808     this->CreateCDCommand(commands, this->GetBinaryDirectory(),
1809                           this->GetCurrentBinaryDirectory());
1810     this->WriteMakeRule(ruleFileStream, "clear depends", "depend", depends,
1811                         commands, true);
1812   }
1813 }
1814
1815 void cmLocalUnixMakefileGenerator3::ClearDependencies(cmMakefile* mf,
1816                                                       bool verbose)
1817 {
1818   // Get the list of target files to check
1819   cmValue infoDef = mf->GetDefinition("CMAKE_DEPEND_INFO_FILES");
1820   if (!infoDef) {
1821     return;
1822   }
1823   std::vector<std::string> files = cmExpandedList(*infoDef);
1824
1825   // Each depend information file corresponds to a target.  Clear the
1826   // dependencies for that target.
1827   cmDepends clearer;
1828   clearer.SetVerbose(verbose);
1829   for (std::string const& file : files) {
1830     auto snapshot = mf->GetState()->CreateBaseSnapshot();
1831     cmMakefile lmf(mf->GetGlobalGenerator(), snapshot);
1832     lmf.ReadListFile(file);
1833
1834     if (!lmf.GetSafeDefinition("CMAKE_DEPENDS_LANGUAGES").empty()) {
1835       std::string dir = cmSystemTools::GetFilenamePath(file);
1836
1837       // Clear the implicit dependency makefile.
1838       std::string dependFile = dir + "/depend.make";
1839       clearer.Clear(dependFile);
1840
1841       // Remove the internal dependency check file to force
1842       // regeneration.
1843       std::string internalDependFile = dir + "/depend.internal";
1844       cmSystemTools::RemoveFile(internalDependFile);
1845     }
1846
1847     auto depsFiles = lmf.GetSafeDefinition("CMAKE_DEPENDS_DEPENDENCY_FILES");
1848     if (!depsFiles.empty()) {
1849       auto dir = cmCMakePath(file).GetParentPath();
1850       // Clear the implicit dependency makefile.
1851       auto depFile = cmCMakePath(dir).Append("compiler_depend.make");
1852       clearer.Clear(depFile.GenericString());
1853
1854       // Remove the internal dependency check file
1855       auto internalDepFile =
1856         cmCMakePath(dir).Append("compiler_depend.internal");
1857       cmSystemTools::RemoveFile(internalDepFile.GenericString());
1858
1859       // Touch timestamp file to force dependencies regeneration
1860       auto DepTimestamp = cmCMakePath(dir).Append("compiler_depend.ts");
1861       cmSystemTools::Touch(DepTimestamp.GenericString(), true);
1862
1863       // clear the dependencies files generated by the compiler
1864       std::vector<std::string> dependencies = cmExpandedList(depsFiles, true);
1865       cmDependsCompiler depsManager;
1866       depsManager.SetVerbose(verbose);
1867       depsManager.ClearDependencies(dependencies);
1868     }
1869   }
1870 }
1871
1872 void cmLocalUnixMakefileGenerator3::WriteDependLanguageInfo(
1873   std::ostream& cmakefileStream, cmGeneratorTarget* target)
1874 {
1875   // To enable dependencies filtering
1876   cmakefileStream << "\n"
1877                   << "# Consider dependencies only in project.\n"
1878                   << "set(CMAKE_DEPENDS_IN_PROJECT_ONLY "
1879                   << (cmIsOn(this->Makefile->GetSafeDefinition(
1880                         "CMAKE_DEPENDS_IN_PROJECT_ONLY"))
1881                         ? "ON"
1882                         : "OFF")
1883                   << ")\n\n";
1884
1885   auto const& implicitLangs =
1886     this->GetImplicitDepends(target, cmDependencyScannerKind::CMake);
1887
1888   // list the languages
1889   cmakefileStream << "# The set of languages for which implicit "
1890                      "dependencies are needed:\n";
1891   cmakefileStream << "set(CMAKE_DEPENDS_LANGUAGES\n";
1892   for (auto const& implicitLang : implicitLangs) {
1893     cmakefileStream << "  \"" << implicitLang.first << "\"\n";
1894   }
1895   cmakefileStream << "  )\n";
1896
1897   if (!implicitLangs.empty()) {
1898     // now list the files for each language
1899     cmakefileStream
1900       << "# The set of files for implicit dependencies of each language:\n";
1901     for (auto const& implicitLang : implicitLangs) {
1902       const auto& lang = implicitLang.first;
1903
1904       cmakefileStream << "set(CMAKE_DEPENDS_CHECK_" << lang << "\n";
1905       auto const& implicitPairs = implicitLang.second;
1906
1907       // for each file pair
1908       for (auto const& implicitPair : implicitPairs) {
1909         for (auto const& di : implicitPair.second) {
1910           cmakefileStream << "  \"" << di << "\" ";
1911           cmakefileStream << "\"" << implicitPair.first << "\"\n";
1912         }
1913       }
1914       cmakefileStream << "  )\n";
1915
1916       // Tell the dependency scanner what compiler is used.
1917       std::string cidVar = cmStrCat("CMAKE_", lang, "_COMPILER_ID");
1918       cmValue cid = this->Makefile->GetDefinition(cidVar);
1919       if (cmNonempty(cid)) {
1920         cmakefileStream << "set(CMAKE_" << lang << "_COMPILER_ID \"" << *cid
1921                         << "\")\n";
1922       }
1923
1924       if (lang == "Fortran") {
1925         std::string smodSep =
1926           this->Makefile->GetSafeDefinition("CMAKE_Fortran_SUBMODULE_SEP");
1927         std::string smodExt =
1928           this->Makefile->GetSafeDefinition("CMAKE_Fortran_SUBMODULE_EXT");
1929         cmakefileStream << "set(CMAKE_Fortran_SUBMODULE_SEP \"" << smodSep
1930                         << "\")\n";
1931         cmakefileStream << "set(CMAKE_Fortran_SUBMODULE_EXT \"" << smodExt
1932                         << "\")\n";
1933       }
1934
1935       // Build a list of preprocessor definitions for the target.
1936       std::set<std::string> defines;
1937       this->GetTargetDefines(target, this->GetConfigName(), lang, defines);
1938       if (!defines.empty()) {
1939         /* clang-format off */
1940       cmakefileStream
1941         << "\n"
1942         << "# Preprocessor definitions for this target.\n"
1943         << "set(CMAKE_TARGET_DEFINITIONS_" << lang << "\n";
1944         /* clang-format on */
1945         for (std::string const& define : defines) {
1946           cmakefileStream << "  " << cmOutputConverter::EscapeForCMake(define)
1947                           << "\n";
1948         }
1949         cmakefileStream << "  )\n";
1950       }
1951
1952       // Target-specific include directories:
1953       cmakefileStream << "\n"
1954                       << "# The include file search paths:\n";
1955       cmakefileStream << "set(CMAKE_" << lang << "_TARGET_INCLUDE_PATH\n";
1956       std::vector<std::string> includes;
1957
1958       this->GetIncludeDirectories(includes, target, lang,
1959                                   this->GetConfigName());
1960       std::string const& binaryDir = this->GetState()->GetBinaryDirectory();
1961       if (this->Makefile->IsOn("CMAKE_DEPENDS_IN_PROJECT_ONLY")) {
1962         std::string const& sourceDir = this->GetState()->GetSourceDirectory();
1963         cm::erase_if(includes, ::NotInProjectDir(sourceDir, binaryDir));
1964       }
1965       for (std::string const& include : includes) {
1966         cmakefileStream << "  \"" << this->MaybeRelativeToTopBinDir(include)
1967                         << "\"\n";
1968       }
1969       cmakefileStream << "  )\n";
1970     }
1971
1972     // Store include transform rule properties.  Write the directory
1973     // rules first because they may be overridden by later target rules.
1974     std::vector<std::string> transformRules;
1975     if (cmValue xform =
1976           this->Makefile->GetProperty("IMPLICIT_DEPENDS_INCLUDE_TRANSFORM")) {
1977       cmExpandList(*xform, transformRules);
1978     }
1979     if (cmValue xform =
1980           target->GetProperty("IMPLICIT_DEPENDS_INCLUDE_TRANSFORM")) {
1981       cmExpandList(*xform, transformRules);
1982     }
1983     if (!transformRules.empty()) {
1984       cmakefileStream << "\nset(CMAKE_INCLUDE_TRANSFORMS\n";
1985       for (std::string const& tr : transformRules) {
1986         cmakefileStream << "  " << cmOutputConverter::EscapeForCMake(tr)
1987                         << "\n";
1988       }
1989       cmakefileStream << "  )\n";
1990     }
1991   }
1992
1993   auto const& compilerLangs =
1994     this->GetImplicitDepends(target, cmDependencyScannerKind::Compiler);
1995
1996   // list the dependency files managed by the compiler
1997   cmakefileStream << "\n# The set of dependency files which are needed:\n";
1998   cmakefileStream << "set(CMAKE_DEPENDS_DEPENDENCY_FILES\n";
1999   for (auto const& compilerLang : compilerLangs) {
2000     auto const& compilerPairs = compilerLang.second;
2001     if (compilerLang.first == "CUSTOM"_s) {
2002       for (auto const& compilerPair : compilerPairs) {
2003         for (auto const& src : compilerPair.second) {
2004           cmakefileStream << R"(  "" ")"
2005                           << this->MaybeRelativeToTopBinDir(compilerPair.first)
2006                           << R"(" "custom" ")"
2007                           << this->MaybeRelativeToTopBinDir(src) << "\"\n";
2008         }
2009       }
2010     } else {
2011       auto depFormat = this->Makefile->GetSafeDefinition(
2012         cmStrCat("CMAKE_", compilerLang.first, "_DEPFILE_FORMAT"));
2013       for (auto const& compilerPair : compilerPairs) {
2014         for (auto const& src : compilerPair.second) {
2015           cmakefileStream << "  \"" << src << "\" \""
2016                           << this->MaybeRelativeToTopBinDir(compilerPair.first)
2017                           << "\" \"" << depFormat << "\" \""
2018                           << this->MaybeRelativeToTopBinDir(compilerPair.first)
2019                           << ".d\"\n";
2020         }
2021       }
2022     }
2023   }
2024   cmakefileStream << "  )\n";
2025 }
2026
2027 void cmLocalUnixMakefileGenerator3::WriteDisclaimer(std::ostream& os)
2028 {
2029   os << "# CMAKE generated file: DO NOT EDIT!\n"
2030      << "# Generated by \"" << this->GlobalGenerator->GetName() << "\""
2031      << " Generator, CMake Version " << cmVersion::GetMajorVersion() << "."
2032      << cmVersion::GetMinorVersion() << "\n\n";
2033 }
2034
2035 std::string cmLocalUnixMakefileGenerator3::GetRecursiveMakeCall(
2036   const std::string& makefile, const std::string& tgt)
2037 {
2038   // Call make on the given file.
2039   std::string cmd = cmStrCat(
2040     "$(MAKE) $(MAKESILENT) -f ",
2041     this->ConvertToOutputFormat(makefile, cmOutputConverter::SHELL), ' ');
2042
2043   cmGlobalUnixMakefileGenerator3* gg =
2044     static_cast<cmGlobalUnixMakefileGenerator3*>(this->GlobalGenerator);
2045   // Pass down verbosity level.
2046   if (!gg->MakeSilentFlag.empty()) {
2047     cmd += gg->MakeSilentFlag;
2048     cmd += " ";
2049   }
2050
2051   // Most unix makes will pass the command line flags to make down to
2052   // sub-invoked makes via an environment variable.  However, some
2053   // makes do not support that, so you have to pass the flags
2054   // explicitly.
2055   if (gg->PassMakeflags) {
2056     cmd += "-$(MAKEFLAGS) ";
2057   }
2058
2059   // Add the target.
2060   if (!tgt.empty()) {
2061     // The make target is always relative to the top of the build tree.
2062     std::string tgt2 = this->MaybeRelativeToTopBinDir(tgt);
2063
2064     // The target may have been written with windows paths.
2065     cmSystemTools::ConvertToOutputSlashes(tgt2);
2066
2067     // Escape one extra time if the make tool requires it.
2068     if (this->MakeCommandEscapeTargetTwice) {
2069       tgt2 = this->EscapeForShell(tgt2, true, false);
2070     }
2071
2072     // The target name is now a string that should be passed verbatim
2073     // on the command line.
2074     cmd += this->EscapeForShell(tgt2, true, false);
2075   }
2076   return cmd;
2077 }
2078
2079 void cmLocalUnixMakefileGenerator3::WriteDivider(std::ostream& os)
2080 {
2081   os << "#======================================"
2082         "=======================================\n";
2083 }
2084
2085 void cmLocalUnixMakefileGenerator3::WriteCMakeArgument(std::ostream& os,
2086                                                        const std::string& s)
2087 {
2088   // Write the given string to the stream with escaping to get it back
2089   // into CMake through the lexical scanner.
2090   os << '"';
2091   for (char c : s) {
2092     if (c == '\\') {
2093       os << "\\\\";
2094     } else if (c == '"') {
2095       os << "\\\"";
2096     } else {
2097       os << c;
2098     }
2099   }
2100   os << '"';
2101 }
2102
2103 std::string cmLocalUnixMakefileGenerator3::ConvertToQuotedOutputPath(
2104   const std::string& p, bool useWatcomQuote)
2105 {
2106   // Split the path into its components.
2107   std::vector<std::string> components;
2108   cmSystemTools::SplitPath(p, components);
2109
2110   // Open the quoted result.
2111   std::string result;
2112   if (useWatcomQuote) {
2113 #if defined(_WIN32) && !defined(__CYGWIN__)
2114     result = "'";
2115 #else
2116     result = "\"'";
2117 #endif
2118   } else {
2119     result = "\"";
2120   }
2121
2122   // Return an empty path if there are no components.
2123   if (!components.empty()) {
2124     // Choose a slash direction and fix root component.
2125     const char* slash = "/";
2126 #if defined(_WIN32) && !defined(__CYGWIN__)
2127     if (!cmSystemTools::GetForceUnixPaths()) {
2128       slash = "\\";
2129       for (char& i : components[0]) {
2130         if (i == '/') {
2131           i = '\\';
2132         }
2133       }
2134     }
2135 #endif
2136
2137     // Begin the quoted result with the root component.
2138     result += components[0];
2139
2140     if (components.size() > 1) {
2141       // Now add the rest of the components separated by the proper slash
2142       // direction for this platform.
2143       auto compEnd = std::remove(components.begin() + 1, components.end() - 1,
2144                                  std::string());
2145       auto compStart = components.begin() + 1;
2146       result += cmJoin(cmMakeRange(compStart, compEnd), slash);
2147       // Only the last component can be empty to avoid double slashes.
2148       result += slash;
2149       result += components.back();
2150     }
2151   }
2152
2153   // Close the quoted result.
2154   if (useWatcomQuote) {
2155 #if defined(_WIN32) && !defined(__CYGWIN__)
2156     result += "'";
2157 #else
2158     result += "'\"";
2159 #endif
2160   } else {
2161     result += "\"";
2162   }
2163
2164   return result;
2165 }
2166
2167 std::string cmLocalUnixMakefileGenerator3::GetTargetDirectory(
2168   cmGeneratorTarget const* target) const
2169 {
2170   std::string dir = cmStrCat("CMakeFiles/", target->GetName());
2171 #if defined(__VMS)
2172   dir += "_dir";
2173 #else
2174   dir += ".dir";
2175 #endif
2176   return dir;
2177 }
2178
2179 cmLocalUnixMakefileGenerator3::ImplicitDependLanguageMap const&
2180 cmLocalUnixMakefileGenerator3::GetImplicitDepends(
2181   const cmGeneratorTarget* tgt, cmDependencyScannerKind scanner)
2182 {
2183   return this->ImplicitDepends[tgt->GetName()][scanner];
2184 }
2185
2186 void cmLocalUnixMakefileGenerator3::AddImplicitDepends(
2187   const cmGeneratorTarget* tgt, const std::string& lang,
2188   const std::string& obj, const std::string& src,
2189   cmDependencyScannerKind scanner)
2190 {
2191   this->ImplicitDepends[tgt->GetName()][scanner][lang][obj].push_back(src);
2192 }
2193
2194 void cmLocalUnixMakefileGenerator3::CreateCDCommand(
2195   std::vector<std::string>& commands, std::string const& tgtDir,
2196   std::string const& relDir)
2197 {
2198   // do we need to cd?
2199   if (tgtDir == relDir) {
2200     return;
2201   }
2202
2203   // In a Windows shell we must change drive letter too.  The shell
2204   // used by NMake and Borland make does not support "cd /d" so this
2205   // feature simply cannot work with them (Borland make does not even
2206   // support changing the drive letter with just "d:").
2207   const char* cd_cmd = this->IsMinGWMake() ? "cd /d " : "cd ";
2208
2209   cmGlobalUnixMakefileGenerator3* gg =
2210     static_cast<cmGlobalUnixMakefileGenerator3*>(this->GlobalGenerator);
2211   if (!gg->UnixCD) {
2212     // On Windows we must perform each step separately and then change
2213     // back because the shell keeps the working directory between
2214     // commands.
2215     std::string cmd =
2216       cmStrCat(cd_cmd, this->ConvertToOutputForExisting(tgtDir));
2217     commands.insert(commands.begin(), cmd);
2218
2219     // Change back to the starting directory.
2220     cmd = cmStrCat(cd_cmd, this->ConvertToOutputForExisting(relDir));
2221     commands.push_back(std::move(cmd));
2222   } else {
2223     // On UNIX we must construct a single shell command to change
2224     // directory and build because make resets the directory between
2225     // each command.
2226     std::string outputForExisting = this->ConvertToOutputForExisting(tgtDir);
2227     std::string prefix = cd_cmd + outputForExisting + " && ";
2228     std::transform(commands.begin(), commands.end(), commands.begin(),
2229                    [&prefix](std::string const& s) { return prefix + s; });
2230   }
2231 }