e125470bd2e016754e8b668dbb715513fa4790ff
[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       std::string targetName = cmSystemTools::GetFilenameName(targetDir);
1416       targetName = targetName.substr(0, targetName.length() - 4);
1417       std::string message =
1418         cmStrCat("Scanning dependencies of target ", targetName);
1419       cmSystemTools::MakefileColorEcho(cmsysTerminal_Color_ForegroundMagenta |
1420                                          cmsysTerminal_Color_ForegroundBold,
1421                                        message.c_str(), true, color);
1422
1423       status = this->ScanDependencies(targetDir, dependFile,
1424                                       internalDependFile, validDependencies);
1425     }
1426   }
1427
1428   auto depends =
1429     this->Makefile->GetSafeDefinition("CMAKE_DEPENDS_DEPENDENCY_FILES");
1430   if (!depends.empty()) {
1431     // dependencies are managed by compiler
1432     auto depFiles = cmExpandedList(depends, true);
1433     std::string const internalDepFile =
1434       targetDir + "/compiler_depend.internal";
1435     std::string const depFile = targetDir + "/compiler_depend.make";
1436     cmDepends::DependencyMap dependencies;
1437     cmDependsCompiler depsManager;
1438     bool projectOnly = cmIsOn(
1439       this->Makefile->GetSafeDefinition("CMAKE_DEPENDS_IN_PROJECT_ONLY"));
1440
1441     depsManager.SetVerbose(verbose);
1442     depsManager.SetLocalGenerator(this);
1443
1444     if (!depsManager.CheckDependencies(
1445           internalDepFile, depFiles, dependencies,
1446           projectOnly ? NotInProjectDir(this->GetSourceDirectory(),
1447                                         this->GetBinaryDirectory())
1448                       : std::function<bool(const std::string&)>())) {
1449       // regenerate dependencies files
1450       std::string targetName =
1451         cmCMakePath(targetDir).GetFileName().RemoveExtension().GenericString();
1452       auto message = cmStrCat(
1453         "Consolidate compiler generated dependencies of target ", targetName);
1454       cmSystemTools::MakefileColorEcho(cmsysTerminal_Color_ForegroundMagenta |
1455                                          cmsysTerminal_Color_ForegroundBold,
1456                                        message.c_str(), true, color);
1457
1458       // Open the make depends file.  This should be copy-if-different
1459       // because the make tool may try to reload it needlessly otherwise.
1460       cmGeneratedFileStream ruleFileStream(
1461         depFile, false, this->GlobalGenerator->GetMakefileEncoding());
1462       ruleFileStream.SetCopyIfDifferent(true);
1463       if (!ruleFileStream) {
1464         return false;
1465       }
1466
1467       // Open the cmake dependency tracking file.  This should not be
1468       // copy-if-different because dependencies are re-scanned when it is
1469       // older than the DependInfo.cmake.
1470       cmGeneratedFileStream internalRuleFileStream(
1471         internalDepFile, false, this->GlobalGenerator->GetMakefileEncoding());
1472       if (!internalRuleFileStream) {
1473         return false;
1474       }
1475
1476       this->WriteDisclaimer(ruleFileStream);
1477       this->WriteDisclaimer(internalRuleFileStream);
1478
1479       depsManager.WriteDependencies(dependencies, ruleFileStream,
1480                                     internalRuleFileStream);
1481     }
1482   }
1483
1484   // The dependencies are already up-to-date.
1485   return status;
1486 }
1487
1488 bool cmLocalUnixMakefileGenerator3::ScanDependencies(
1489   std::string const& targetDir, std::string const& dependFile,
1490   std::string const& internalDependFile, cmDepends::DependencyMap& validDeps)
1491 {
1492   // Read the directory information file.
1493   cmMakefile* mf = this->Makefile;
1494   bool haveDirectoryInfo = false;
1495   {
1496     std::string dirInfoFile =
1497       cmStrCat(this->GetCurrentBinaryDirectory(),
1498                "/CMakeFiles/CMakeDirectoryInformation.cmake");
1499     if (mf->ReadListFile(dirInfoFile) &&
1500         !cmSystemTools::GetErrorOccurredFlag()) {
1501       haveDirectoryInfo = true;
1502     }
1503   }
1504
1505   // Lookup useful directory information.
1506   if (haveDirectoryInfo) {
1507     // Test whether we need to force Unix paths.
1508     if (cmValue force = mf->GetDefinition("CMAKE_FORCE_UNIX_PATHS")) {
1509       if (!cmIsOff(force)) {
1510         cmSystemTools::SetForceUnixPaths(true);
1511       }
1512     }
1513
1514     // Setup relative path top directories.
1515     cmValue relativePathTopSource =
1516       mf->GetDefinition("CMAKE_RELATIVE_PATH_TOP_SOURCE");
1517     cmValue relativePathTopBinary =
1518       mf->GetDefinition("CMAKE_RELATIVE_PATH_TOP_BINARY");
1519     if (relativePathTopSource && relativePathTopBinary) {
1520       this->SetRelativePathTop(*relativePathTopSource, *relativePathTopBinary);
1521     }
1522   } else {
1523     cmSystemTools::Error("Directory Information file not found");
1524   }
1525
1526   // Open the make depends file.  This should be copy-if-different
1527   // because the make tool may try to reload it needlessly otherwise.
1528   cmGeneratedFileStream ruleFileStream(
1529     dependFile, false, this->GlobalGenerator->GetMakefileEncoding());
1530   ruleFileStream.SetCopyIfDifferent(true);
1531   if (!ruleFileStream) {
1532     return false;
1533   }
1534
1535   // Open the cmake dependency tracking file.  This should not be
1536   // copy-if-different because dependencies are re-scanned when it is
1537   // older than the DependInfo.cmake.
1538   cmGeneratedFileStream internalRuleFileStream(
1539     internalDependFile, false, this->GlobalGenerator->GetMakefileEncoding());
1540   if (!internalRuleFileStream) {
1541     return false;
1542   }
1543
1544   this->WriteDisclaimer(ruleFileStream);
1545   this->WriteDisclaimer(internalRuleFileStream);
1546
1547   // for each language we need to scan, scan it
1548   std::vector<std::string> langs =
1549     cmExpandedList(mf->GetSafeDefinition("CMAKE_DEPENDS_LANGUAGES"));
1550   for (std::string const& lang : langs) {
1551     // construct the checker
1552     // Create the scanner for this language
1553     std::unique_ptr<cmDepends> scanner;
1554     if (lang == "C" || lang == "CXX" || lang == "RC" || lang == "ASM" ||
1555         lang == "OBJC" || lang == "OBJCXX" || lang == "CUDA" ||
1556         lang == "HIP" || lang == "ISPC") {
1557       // TODO: Handle RC (resource files) dependencies correctly.
1558       scanner = cm::make_unique<cmDependsC>(this, targetDir, lang, &validDeps);
1559     }
1560 #ifndef CMAKE_BOOTSTRAP
1561     else if (lang == "Fortran") {
1562       ruleFileStream << "# Note that incremental build could trigger "
1563                      << "a call to cmake_copy_f90_mod on each re-build\n";
1564       scanner = cm::make_unique<cmDependsFortran>(this);
1565     } else if (lang == "Java") {
1566       scanner = cm::make_unique<cmDependsJava>();
1567     }
1568 #endif
1569
1570     if (scanner) {
1571       scanner->SetLocalGenerator(this);
1572       scanner->SetFileTimeCache(
1573         this->GlobalGenerator->GetCMakeInstance()->GetFileTimeCache());
1574       scanner->SetLanguage(lang);
1575       scanner->SetTargetDirectory(targetDir);
1576       scanner->Write(ruleFileStream, internalRuleFileStream);
1577     }
1578   }
1579
1580   return true;
1581 }
1582
1583 void cmLocalUnixMakefileGenerator3::CheckMultipleOutputs(bool verbose)
1584 {
1585   cmMakefile* mf = this->Makefile;
1586
1587   // Get the string listing the multiple output pairs.
1588   cmValue pairs_string = mf->GetDefinition("CMAKE_MULTIPLE_OUTPUT_PAIRS");
1589   if (!pairs_string) {
1590     return;
1591   }
1592
1593   // Convert the string to a list and preserve empty entries.
1594   std::vector<std::string> pairs = cmExpandedList(*pairs_string, true);
1595   for (auto i = pairs.begin(); i != pairs.end() && (i + 1) != pairs.end();) {
1596     const std::string& depender = *i++;
1597     const std::string& dependee = *i++;
1598
1599     // If the depender is missing then delete the dependee to make
1600     // sure both will be regenerated.
1601     if (cmSystemTools::FileExists(dependee) &&
1602         !cmSystemTools::FileExists(depender)) {
1603       if (verbose) {
1604         cmSystemTools::Stdout(cmStrCat(
1605           "Deleting primary custom command output \"", dependee,
1606           "\" because another output \"", depender, "\" does not exist.\n"));
1607       }
1608       cmSystemTools::RemoveFile(dependee);
1609     }
1610   }
1611 }
1612
1613 void cmLocalUnixMakefileGenerator3::WriteLocalAllRules(
1614   std::ostream& ruleFileStream)
1615 {
1616   this->WriteDisclaimer(ruleFileStream);
1617
1618   // Write the main entry point target.  This must be the VERY first
1619   // target so that make with no arguments will run it.
1620   {
1621     // Just depend on the all target to drive the build.
1622     std::vector<std::string> depends;
1623     std::vector<std::string> no_commands;
1624     depends.emplace_back("all");
1625
1626     // Write the rule.
1627     this->WriteMakeRule(ruleFileStream,
1628                         "Default target executed when no arguments are "
1629                         "given to make.",
1630                         "default_target", depends, no_commands, true);
1631
1632     // Help out users that try "gmake target1 target2 -j".
1633     cmGlobalUnixMakefileGenerator3* gg =
1634       static_cast<cmGlobalUnixMakefileGenerator3*>(this->GlobalGenerator);
1635     if (gg->AllowNotParallel()) {
1636       std::vector<std::string> no_depends;
1637       this->WriteMakeRule(ruleFileStream,
1638                           "Allow only one \"make -f "
1639                           "Makefile2\" at a time, but pass "
1640                           "parallelism.",
1641                           ".NOTPARALLEL", no_depends, no_commands, false);
1642     }
1643   }
1644
1645   this->WriteSpecialTargetsTop(ruleFileStream);
1646
1647   // Include the progress variables for the target.
1648   // Write all global targets
1649   this->WriteDivider(ruleFileStream);
1650   ruleFileStream << "# Targets provided globally by CMake.\n"
1651                  << "\n";
1652   const auto& targets = this->GetGeneratorTargets();
1653   for (const auto& gt : targets) {
1654     if (gt->GetType() == cmStateEnums::GLOBAL_TARGET) {
1655       std::string targetString =
1656         "Special rule for the target " + gt->GetName();
1657       std::vector<std::string> commands;
1658       std::vector<std::string> depends;
1659
1660       cmValue p = gt->GetProperty("EchoString");
1661       const char* text = p ? p->c_str() : "Running external command ...";
1662       depends.reserve(gt->GetUtilities().size());
1663       for (BT<std::pair<std::string, bool>> const& u : gt->GetUtilities()) {
1664         depends.push_back(u.Value.first);
1665       }
1666       this->AppendEcho(commands, text,
1667                        cmLocalUnixMakefileGenerator3::EchoGlobal);
1668
1669       // Global targets store their rules in pre- and post-build commands.
1670       this->AppendCustomDepends(depends, gt->GetPreBuildCommands());
1671       this->AppendCustomDepends(depends, gt->GetPostBuildCommands());
1672       this->AppendCustomCommands(commands, gt->GetPreBuildCommands(), gt.get(),
1673                                  this->GetCurrentBinaryDirectory());
1674       this->AppendCustomCommands(commands, gt->GetPostBuildCommands(),
1675                                  gt.get(), this->GetCurrentBinaryDirectory());
1676       std::string targetName = gt->GetName();
1677       this->WriteMakeRule(ruleFileStream, targetString.c_str(), targetName,
1678                           depends, commands, true);
1679
1680       // Provide a "/fast" version of the target.
1681       depends.clear();
1682       if ((targetName == "install") || (targetName == "install/local") ||
1683           (targetName == "install/strip")) {
1684         // Provide a fast install target that does not depend on all
1685         // but has the same command.
1686         depends.emplace_back("preinstall/fast");
1687       } else {
1688         // Just forward to the real target so at least it will work.
1689         depends.push_back(targetName);
1690         commands.clear();
1691       }
1692       targetName += "/fast";
1693       this->WriteMakeRule(ruleFileStream, targetString.c_str(), targetName,
1694                           depends, commands, true);
1695     }
1696   }
1697
1698   std::vector<std::string> depends;
1699   std::vector<std::string> commands;
1700
1701   // Write the all rule.
1702   std::string recursiveTarget =
1703     cmStrCat(this->GetCurrentBinaryDirectory(), "/all");
1704
1705   bool regenerate =
1706     !this->GlobalGenerator->GlobalSettingIsOn("CMAKE_SUPPRESS_REGENERATION");
1707   if (regenerate) {
1708     depends.emplace_back("cmake_check_build_system");
1709   }
1710
1711   std::string progressDir =
1712     cmStrCat(this->GetBinaryDirectory(), "/CMakeFiles");
1713   {
1714     std::ostringstream progCmd;
1715     progCmd << "$(CMAKE_COMMAND) -E cmake_progress_start ";
1716     progCmd << this->ConvertToOutputFormat(progressDir,
1717                                            cmOutputConverter::SHELL);
1718
1719     std::string progressFile = "/CMakeFiles/progress.marks";
1720     std::string progressFileNameFull = this->ConvertToFullPath(progressFile);
1721     progCmd << " "
1722             << this->ConvertToOutputFormat(progressFileNameFull,
1723                                            cmOutputConverter::SHELL);
1724     commands.push_back(progCmd.str());
1725   }
1726   std::string mf2Dir = "CMakeFiles/Makefile2";
1727   commands.push_back(this->GetRecursiveMakeCall(mf2Dir, recursiveTarget));
1728   this->CreateCDCommand(commands, this->GetBinaryDirectory(),
1729                         this->GetCurrentBinaryDirectory());
1730   {
1731     std::ostringstream progCmd;
1732     progCmd << "$(CMAKE_COMMAND) -E cmake_progress_start "; // # 0
1733     progCmd << this->ConvertToOutputFormat(progressDir,
1734                                            cmOutputConverter::SHELL);
1735     progCmd << " 0";
1736     commands.push_back(progCmd.str());
1737   }
1738   this->WriteMakeRule(ruleFileStream, "The main all target", "all", depends,
1739                       commands, true);
1740
1741   // Write the clean rule.
1742   recursiveTarget = cmStrCat(this->GetCurrentBinaryDirectory(), "/clean");
1743   commands.clear();
1744   depends.clear();
1745   commands.push_back(this->GetRecursiveMakeCall(mf2Dir, recursiveTarget));
1746   this->CreateCDCommand(commands, this->GetBinaryDirectory(),
1747                         this->GetCurrentBinaryDirectory());
1748   this->WriteMakeRule(ruleFileStream, "The main clean target", "clean",
1749                       depends, commands, true);
1750   commands.clear();
1751   depends.clear();
1752   depends.emplace_back("clean");
1753   this->WriteMakeRule(ruleFileStream, "The main clean target", "clean/fast",
1754                       depends, commands, true);
1755
1756   // Write the preinstall rule.
1757   recursiveTarget = cmStrCat(this->GetCurrentBinaryDirectory(), "/preinstall");
1758   commands.clear();
1759   depends.clear();
1760   cmValue noall =
1761     this->Makefile->GetDefinition("CMAKE_SKIP_INSTALL_ALL_DEPENDENCY");
1762   if (cmIsOff(noall)) {
1763     // Drive the build before installing.
1764     depends.emplace_back("all");
1765   } else if (regenerate) {
1766     // At least make sure the build system is up to date.
1767     depends.emplace_back("cmake_check_build_system");
1768   }
1769   commands.push_back(this->GetRecursiveMakeCall(mf2Dir, recursiveTarget));
1770   this->CreateCDCommand(commands, this->GetBinaryDirectory(),
1771                         this->GetCurrentBinaryDirectory());
1772   this->WriteMakeRule(ruleFileStream, "Prepare targets for installation.",
1773                       "preinstall", depends, commands, true);
1774   depends.clear();
1775   this->WriteMakeRule(ruleFileStream, "Prepare targets for installation.",
1776                       "preinstall/fast", depends, commands, true);
1777
1778   if (regenerate) {
1779     // write the depend rule, really a recompute depends rule
1780     depends.clear();
1781     commands.clear();
1782     cmake* cm = this->GlobalGenerator->GetCMakeInstance();
1783     if (cm->DoWriteGlobVerifyTarget()) {
1784       std::string rescanRule =
1785         cmStrCat("$(CMAKE_COMMAND) -P ",
1786                  this->ConvertToOutputFormat(cm->GetGlobVerifyScript(),
1787                                              cmOutputConverter::SHELL));
1788       commands.push_back(rescanRule);
1789     }
1790     std::string cmakefileName = "CMakeFiles/Makefile.cmake";
1791     {
1792       std::string runRule = cmStrCat(
1793         "$(CMAKE_COMMAND) -S$(CMAKE_SOURCE_DIR) -B$(CMAKE_BINARY_DIR) "
1794         "--check-build-system ",
1795         this->ConvertToOutputFormat(cmakefileName, cmOutputConverter::SHELL),
1796         " 1");
1797       commands.push_back(std::move(runRule));
1798     }
1799     this->CreateCDCommand(commands, this->GetBinaryDirectory(),
1800                           this->GetCurrentBinaryDirectory());
1801     this->WriteMakeRule(ruleFileStream, "clear depends", "depend", depends,
1802                         commands, true);
1803   }
1804 }
1805
1806 void cmLocalUnixMakefileGenerator3::ClearDependencies(cmMakefile* mf,
1807                                                       bool verbose)
1808 {
1809   // Get the list of target files to check
1810   cmValue infoDef = mf->GetDefinition("CMAKE_DEPEND_INFO_FILES");
1811   if (!infoDef) {
1812     return;
1813   }
1814   std::vector<std::string> files = cmExpandedList(*infoDef);
1815
1816   // Each depend information file corresponds to a target.  Clear the
1817   // dependencies for that target.
1818   cmDepends clearer;
1819   clearer.SetVerbose(verbose);
1820   for (std::string const& file : files) {
1821     auto snapshot = mf->GetState()->CreateBaseSnapshot();
1822     cmMakefile lmf(mf->GetGlobalGenerator(), snapshot);
1823     lmf.ReadListFile(file);
1824
1825     if (!lmf.GetSafeDefinition("CMAKE_DEPENDS_LANGUAGES").empty()) {
1826       std::string dir = cmSystemTools::GetFilenamePath(file);
1827
1828       // Clear the implicit dependency makefile.
1829       std::string dependFile = dir + "/depend.make";
1830       clearer.Clear(dependFile);
1831
1832       // Remove the internal dependency check file to force
1833       // regeneration.
1834       std::string internalDependFile = dir + "/depend.internal";
1835       cmSystemTools::RemoveFile(internalDependFile);
1836     }
1837
1838     auto depsFiles = lmf.GetSafeDefinition("CMAKE_DEPENDS_DEPENDENCY_FILES");
1839     if (!depsFiles.empty()) {
1840       auto dir = cmCMakePath(file).GetParentPath();
1841       // Clear the implicit dependency makefile.
1842       auto depFile = cmCMakePath(dir).Append("compiler_depend.make");
1843       clearer.Clear(depFile.GenericString());
1844
1845       // Remove the internal dependency check file
1846       auto internalDepFile =
1847         cmCMakePath(dir).Append("compiler_depend.internal");
1848       cmSystemTools::RemoveFile(internalDepFile.GenericString());
1849
1850       // Touch timestamp file to force dependencies regeneration
1851       auto DepTimestamp = cmCMakePath(dir).Append("compiler_depend.ts");
1852       cmSystemTools::Touch(DepTimestamp.GenericString(), true);
1853
1854       // clear the dependencies files generated by the compiler
1855       std::vector<std::string> dependencies = cmExpandedList(depsFiles, true);
1856       cmDependsCompiler depsManager;
1857       depsManager.SetVerbose(verbose);
1858       depsManager.ClearDependencies(dependencies);
1859     }
1860   }
1861 }
1862
1863 void cmLocalUnixMakefileGenerator3::WriteDependLanguageInfo(
1864   std::ostream& cmakefileStream, cmGeneratorTarget* target)
1865 {
1866   // To enable dependencies filtering
1867   cmakefileStream << "\n"
1868                   << "# Consider dependencies only in project.\n"
1869                   << "set(CMAKE_DEPENDS_IN_PROJECT_ONLY "
1870                   << (cmIsOn(this->Makefile->GetSafeDefinition(
1871                         "CMAKE_DEPENDS_IN_PROJECT_ONLY"))
1872                         ? "ON"
1873                         : "OFF")
1874                   << ")\n\n";
1875
1876   auto const& implicitLangs =
1877     this->GetImplicitDepends(target, cmDependencyScannerKind::CMake);
1878
1879   // list the languages
1880   cmakefileStream << "# The set of languages for which implicit "
1881                      "dependencies are needed:\n";
1882   cmakefileStream << "set(CMAKE_DEPENDS_LANGUAGES\n";
1883   for (auto const& implicitLang : implicitLangs) {
1884     cmakefileStream << "  \"" << implicitLang.first << "\"\n";
1885   }
1886   cmakefileStream << "  )\n";
1887
1888   if (!implicitLangs.empty()) {
1889     // now list the files for each language
1890     cmakefileStream
1891       << "# The set of files for implicit dependencies of each language:\n";
1892     for (auto const& implicitLang : implicitLangs) {
1893       const auto& lang = implicitLang.first;
1894
1895       cmakefileStream << "set(CMAKE_DEPENDS_CHECK_" << lang << "\n";
1896       auto const& implicitPairs = implicitLang.second;
1897
1898       // for each file pair
1899       for (auto const& implicitPair : implicitPairs) {
1900         for (auto const& di : implicitPair.second) {
1901           cmakefileStream << "  \"" << di << "\" ";
1902           cmakefileStream << "\"" << implicitPair.first << "\"\n";
1903         }
1904       }
1905       cmakefileStream << "  )\n";
1906
1907       // Tell the dependency scanner what compiler is used.
1908       std::string cidVar = cmStrCat("CMAKE_", lang, "_COMPILER_ID");
1909       cmValue cid = this->Makefile->GetDefinition(cidVar);
1910       if (cmNonempty(cid)) {
1911         cmakefileStream << "set(CMAKE_" << lang << "_COMPILER_ID \"" << *cid
1912                         << "\")\n";
1913       }
1914
1915       if (lang == "Fortran") {
1916         std::string smodSep =
1917           this->Makefile->GetSafeDefinition("CMAKE_Fortran_SUBMODULE_SEP");
1918         std::string smodExt =
1919           this->Makefile->GetSafeDefinition("CMAKE_Fortran_SUBMODULE_EXT");
1920         cmakefileStream << "set(CMAKE_Fortran_SUBMODULE_SEP \"" << smodSep
1921                         << "\")\n";
1922         cmakefileStream << "set(CMAKE_Fortran_SUBMODULE_EXT \"" << smodExt
1923                         << "\")\n";
1924       }
1925
1926       // Build a list of preprocessor definitions for the target.
1927       std::set<std::string> defines;
1928       this->GetTargetDefines(target, this->GetConfigName(), lang, defines);
1929       if (!defines.empty()) {
1930         /* clang-format off */
1931       cmakefileStream
1932         << "\n"
1933         << "# Preprocessor definitions for this target.\n"
1934         << "set(CMAKE_TARGET_DEFINITIONS_" << lang << "\n";
1935         /* clang-format on */
1936         for (std::string const& define : defines) {
1937           cmakefileStream << "  " << cmOutputConverter::EscapeForCMake(define)
1938                           << "\n";
1939         }
1940         cmakefileStream << "  )\n";
1941       }
1942
1943       // Target-specific include directories:
1944       cmakefileStream << "\n"
1945                       << "# The include file search paths:\n";
1946       cmakefileStream << "set(CMAKE_" << lang << "_TARGET_INCLUDE_PATH\n";
1947       std::vector<std::string> includes;
1948
1949       this->GetIncludeDirectories(includes, target, lang,
1950                                   this->GetConfigName());
1951       std::string const& binaryDir = this->GetState()->GetBinaryDirectory();
1952       if (this->Makefile->IsOn("CMAKE_DEPENDS_IN_PROJECT_ONLY")) {
1953         std::string const& sourceDir = this->GetState()->GetSourceDirectory();
1954         cm::erase_if(includes, ::NotInProjectDir(sourceDir, binaryDir));
1955       }
1956       for (std::string const& include : includes) {
1957         cmakefileStream << "  \"" << this->MaybeRelativeToTopBinDir(include)
1958                         << "\"\n";
1959       }
1960       cmakefileStream << "  )\n";
1961     }
1962
1963     // Store include transform rule properties.  Write the directory
1964     // rules first because they may be overridden by later target rules.
1965     std::vector<std::string> transformRules;
1966     if (cmValue xform =
1967           this->Makefile->GetProperty("IMPLICIT_DEPENDS_INCLUDE_TRANSFORM")) {
1968       cmExpandList(*xform, transformRules);
1969     }
1970     if (cmValue xform =
1971           target->GetProperty("IMPLICIT_DEPENDS_INCLUDE_TRANSFORM")) {
1972       cmExpandList(*xform, transformRules);
1973     }
1974     if (!transformRules.empty()) {
1975       cmakefileStream << "\nset(CMAKE_INCLUDE_TRANSFORMS\n";
1976       for (std::string const& tr : transformRules) {
1977         cmakefileStream << "  " << cmOutputConverter::EscapeForCMake(tr)
1978                         << "\n";
1979       }
1980       cmakefileStream << "  )\n";
1981     }
1982   }
1983
1984   auto const& compilerLangs =
1985     this->GetImplicitDepends(target, cmDependencyScannerKind::Compiler);
1986
1987   // list the dependency files managed by the compiler
1988   cmakefileStream << "\n# The set of dependency files which are needed:\n";
1989   cmakefileStream << "set(CMAKE_DEPENDS_DEPENDENCY_FILES\n";
1990   for (auto const& compilerLang : compilerLangs) {
1991     auto const& compilerPairs = compilerLang.second;
1992     if (compilerLang.first == "CUSTOM"_s) {
1993       for (auto const& compilerPair : compilerPairs) {
1994         for (auto const& src : compilerPair.second) {
1995           cmakefileStream << R"(  "" ")"
1996                           << this->MaybeRelativeToTopBinDir(compilerPair.first)
1997                           << R"(" "custom" ")"
1998                           << this->MaybeRelativeToTopBinDir(src) << "\"\n";
1999         }
2000       }
2001     } else {
2002       auto depFormat = this->Makefile->GetSafeDefinition(
2003         cmStrCat("CMAKE_", compilerLang.first, "_DEPFILE_FORMAT"));
2004       for (auto const& compilerPair : compilerPairs) {
2005         for (auto const& src : compilerPair.second) {
2006           cmakefileStream << "  \"" << src << "\" \""
2007                           << this->MaybeRelativeToTopBinDir(compilerPair.first)
2008                           << "\" \"" << depFormat << "\" \""
2009                           << this->MaybeRelativeToTopBinDir(compilerPair.first)
2010                           << ".d\"\n";
2011         }
2012       }
2013     }
2014   }
2015   cmakefileStream << "  )\n";
2016 }
2017
2018 void cmLocalUnixMakefileGenerator3::WriteDisclaimer(std::ostream& os)
2019 {
2020   os << "# CMAKE generated file: DO NOT EDIT!\n"
2021      << "# Generated by \"" << this->GlobalGenerator->GetName() << "\""
2022      << " Generator, CMake Version " << cmVersion::GetMajorVersion() << "."
2023      << cmVersion::GetMinorVersion() << "\n\n";
2024 }
2025
2026 std::string cmLocalUnixMakefileGenerator3::GetRecursiveMakeCall(
2027   const std::string& makefile, const std::string& tgt)
2028 {
2029   // Call make on the given file.
2030   std::string cmd = cmStrCat(
2031     "$(MAKE) $(MAKESILENT) -f ",
2032     this->ConvertToOutputFormat(makefile, cmOutputConverter::SHELL), ' ');
2033
2034   cmGlobalUnixMakefileGenerator3* gg =
2035     static_cast<cmGlobalUnixMakefileGenerator3*>(this->GlobalGenerator);
2036   // Pass down verbosity level.
2037   if (!gg->MakeSilentFlag.empty()) {
2038     cmd += gg->MakeSilentFlag;
2039     cmd += " ";
2040   }
2041
2042   // Most unix makes will pass the command line flags to make down to
2043   // sub-invoked makes via an environment variable.  However, some
2044   // makes do not support that, so you have to pass the flags
2045   // explicitly.
2046   if (gg->PassMakeflags) {
2047     cmd += "-$(MAKEFLAGS) ";
2048   }
2049
2050   // Add the target.
2051   if (!tgt.empty()) {
2052     // The make target is always relative to the top of the build tree.
2053     std::string tgt2 = this->MaybeRelativeToTopBinDir(tgt);
2054
2055     // The target may have been written with windows paths.
2056     cmSystemTools::ConvertToOutputSlashes(tgt2);
2057
2058     // Escape one extra time if the make tool requires it.
2059     if (this->MakeCommandEscapeTargetTwice) {
2060       tgt2 = this->EscapeForShell(tgt2, true, false);
2061     }
2062
2063     // The target name is now a string that should be passed verbatim
2064     // on the command line.
2065     cmd += this->EscapeForShell(tgt2, true, false);
2066   }
2067   return cmd;
2068 }
2069
2070 void cmLocalUnixMakefileGenerator3::WriteDivider(std::ostream& os)
2071 {
2072   os << "#======================================"
2073         "=======================================\n";
2074 }
2075
2076 void cmLocalUnixMakefileGenerator3::WriteCMakeArgument(std::ostream& os,
2077                                                        const std::string& s)
2078 {
2079   // Write the given string to the stream with escaping to get it back
2080   // into CMake through the lexical scanner.
2081   os << '"';
2082   for (char c : s) {
2083     if (c == '\\') {
2084       os << "\\\\";
2085     } else if (c == '"') {
2086       os << "\\\"";
2087     } else {
2088       os << c;
2089     }
2090   }
2091   os << '"';
2092 }
2093
2094 std::string cmLocalUnixMakefileGenerator3::ConvertToQuotedOutputPath(
2095   const std::string& p, bool useWatcomQuote)
2096 {
2097   // Split the path into its components.
2098   std::vector<std::string> components;
2099   cmSystemTools::SplitPath(p, components);
2100
2101   // Open the quoted result.
2102   std::string result;
2103   if (useWatcomQuote) {
2104 #if defined(_WIN32) && !defined(__CYGWIN__)
2105     result = "'";
2106 #else
2107     result = "\"'";
2108 #endif
2109   } else {
2110     result = "\"";
2111   }
2112
2113   // Return an empty path if there are no components.
2114   if (!components.empty()) {
2115     // Choose a slash direction and fix root component.
2116     const char* slash = "/";
2117 #if defined(_WIN32) && !defined(__CYGWIN__)
2118     if (!cmSystemTools::GetForceUnixPaths()) {
2119       slash = "\\";
2120       for (char& i : components[0]) {
2121         if (i == '/') {
2122           i = '\\';
2123         }
2124       }
2125     }
2126 #endif
2127
2128     // Begin the quoted result with the root component.
2129     result += components[0];
2130
2131     if (components.size() > 1) {
2132       // Now add the rest of the components separated by the proper slash
2133       // direction for this platform.
2134       auto compEnd = std::remove(components.begin() + 1, components.end() - 1,
2135                                  std::string());
2136       auto compStart = components.begin() + 1;
2137       result += cmJoin(cmMakeRange(compStart, compEnd), slash);
2138       // Only the last component can be empty to avoid double slashes.
2139       result += slash;
2140       result += components.back();
2141     }
2142   }
2143
2144   // Close the quoted result.
2145   if (useWatcomQuote) {
2146 #if defined(_WIN32) && !defined(__CYGWIN__)
2147     result += "'";
2148 #else
2149     result += "'\"";
2150 #endif
2151   } else {
2152     result += "\"";
2153   }
2154
2155   return result;
2156 }
2157
2158 std::string cmLocalUnixMakefileGenerator3::GetTargetDirectory(
2159   cmGeneratorTarget const* target) const
2160 {
2161   std::string dir = cmStrCat("CMakeFiles/", target->GetName());
2162 #if defined(__VMS)
2163   dir += "_dir";
2164 #else
2165   dir += ".dir";
2166 #endif
2167   return dir;
2168 }
2169
2170 cmLocalUnixMakefileGenerator3::ImplicitDependLanguageMap const&
2171 cmLocalUnixMakefileGenerator3::GetImplicitDepends(
2172   const cmGeneratorTarget* tgt, cmDependencyScannerKind scanner)
2173 {
2174   return this->ImplicitDepends[tgt->GetName()][scanner];
2175 }
2176
2177 void cmLocalUnixMakefileGenerator3::AddImplicitDepends(
2178   const cmGeneratorTarget* tgt, const std::string& lang,
2179   const std::string& obj, const std::string& src,
2180   cmDependencyScannerKind scanner)
2181 {
2182   this->ImplicitDepends[tgt->GetName()][scanner][lang][obj].push_back(src);
2183 }
2184
2185 void cmLocalUnixMakefileGenerator3::CreateCDCommand(
2186   std::vector<std::string>& commands, std::string const& tgtDir,
2187   std::string const& relDir)
2188 {
2189   // do we need to cd?
2190   if (tgtDir == relDir) {
2191     return;
2192   }
2193
2194   // In a Windows shell we must change drive letter too.  The shell
2195   // used by NMake and Borland make does not support "cd /d" so this
2196   // feature simply cannot work with them (Borland make does not even
2197   // support changing the drive letter with just "d:").
2198   const char* cd_cmd = this->IsMinGWMake() ? "cd /d " : "cd ";
2199
2200   cmGlobalUnixMakefileGenerator3* gg =
2201     static_cast<cmGlobalUnixMakefileGenerator3*>(this->GlobalGenerator);
2202   if (!gg->UnixCD) {
2203     // On Windows we must perform each step separately and then change
2204     // back because the shell keeps the working directory between
2205     // commands.
2206     std::string cmd =
2207       cmStrCat(cd_cmd, this->ConvertToOutputForExisting(tgtDir));
2208     commands.insert(commands.begin(), cmd);
2209
2210     // Change back to the starting directory.
2211     cmd = cmStrCat(cd_cmd, this->ConvertToOutputForExisting(relDir));
2212     commands.push_back(std::move(cmd));
2213   } else {
2214     // On UNIX we must construct a single shell command to change
2215     // directory and build because make resets the directory between
2216     // each command.
2217     std::string outputForExisting = this->ConvertToOutputForExisting(tgtDir);
2218     std::string prefix = cd_cmd + outputForExisting + " && ";
2219     std::transform(commands.begin(), commands.end(), commands.begin(),
2220                    [&prefix](std::string const& s) { return prefix + s; });
2221   }
2222 }