Coverage Report

Created: 2026-03-12 06:35

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