Coverage Report

Created: 2026-04-29 07:01

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