Coverage Report

Created: 2026-02-09 06:05

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