Coverage Report

Created: 2026-07-30 06:52

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/CMake/Source/cmLocalGenerator.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 "cmLocalGenerator.h"
4
5
#include <algorithm>
6
#include <array>
7
#include <cassert>
8
#include <cstdio>
9
#include <cstdlib>
10
#include <initializer_list>
11
#include <iterator>
12
#include <sstream>
13
#include <unordered_set>
14
#include <utility>
15
#include <vector>
16
17
#include <cm/memory>
18
#include <cm/optional>
19
#include <cm/string_view>
20
#include <cmext/algorithm>
21
#include <cmext/string_view>
22
23
#include "cmsys/RegularExpression.hxx"
24
#include "cmsys/String.h"
25
26
#include "cmAlgorithms.h"
27
#include "cmCMakePath.h"
28
#include "cmComputeLinkInformation.h"
29
#include "cmCryptoHash.h"
30
#include "cmCustomCommand.h"
31
#include "cmCustomCommandGenerator.h"
32
#include "cmCustomCommandLines.h"
33
#include "cmCustomCommandTypes.h"
34
#include "cmFileSetMetadata.h"
35
#include "cmGeneratedFileStream.h"
36
#include "cmGeneratorExpression.h"
37
#include "cmGeneratorExpressionEvaluationFile.h"
38
#include "cmGeneratorFileSet.h"
39
#include "cmGeneratorTarget.h"
40
#include "cmGlobalGenerator.h"
41
#include "cmInstallGenerator.h"
42
#include "cmInstallScriptGenerator.h"
43
#include "cmInstallTargetGenerator.h"
44
#include "cmLinkLineComputer.h"
45
#include "cmLinkLineDeviceComputer.h"
46
#include "cmList.h"
47
#include "cmMakefile.h"
48
#include "cmMessageType.h"
49
#include "cmObjectLocation.h"
50
#include "cmRange.h"
51
#include "cmRulePlaceholderExpander.h"
52
#include "cmScriptGenerator.h"
53
#include "cmSourceFile.h"
54
#include "cmSourceFileLocation.h"
55
#include "cmSourceFileLocationKind.h"
56
#include "cmSourceGroup.h"
57
#include "cmStandardLevelResolver.h"
58
#include "cmState.h"
59
#include "cmStateDirectory.h"
60
#include "cmStateTypes.h"
61
#include "cmStringAlgorithms.h"
62
#include "cmSystemTools.h"
63
#include "cmTarget.h"
64
#include "cmTargetTypes.h"
65
#include "cmTestGenerator.h"
66
#include "cmValue.h"
67
#include "cmake.h"
68
69
#if defined(__HAIKU__)
70
#  include <FindDirectory.h>
71
#  include <StorageDefs.h>
72
#endif
73
74
namespace {
75
// List of variables that are replaced when
76
// rules are expanded.  These variables are
77
// replaced in the form <var> with GetSafeDefinition(var).
78
// ${LANG} is replaced in the variable first with all enabled
79
// languages.
80
auto ruleReplaceVars = {
81
  "CMAKE_${LANG}_COMPILER",
82
  "CMAKE_SHARED_MODULE_${LANG}_FLAGS",
83
  "CMAKE_SHARED_LIBRARY_${LANG}_FLAGS",
84
  "CMAKE_SHARED_LIBRARY_SONAME_${LANG}_FLAG",
85
  "CMAKE_${LANG}_ARCHIVE",
86
  "CMAKE_AR",
87
  "CMAKE_SOURCE_DIR",
88
  "CMAKE_BINARY_DIR",
89
  "CMAKE_CURRENT_SOURCE_DIR",
90
  "CMAKE_CURRENT_BINARY_DIR",
91
  "CMAKE_RANLIB",
92
  "CMAKE_MT",
93
  "CMAKE_TAPI",
94
  "CMAKE_CUDA_HOST_COMPILER",
95
  "CMAKE_CUDA_HOST_LINK_LAUNCHER",
96
  "CMAKE_HIP_HOST_COMPILER",
97
  "CMAKE_HIP_HOST_LINK_LAUNCHER",
98
  "CMAKE_CL_SHOWINCLUDES_PREFIX",
99
};
100
101
// Variables whose placeholders now map to an empty string.
102
// Our platform modules no longer use these, but third-party code might.
103
auto ruleReplaceEmptyVars = {
104
  "CMAKE_SHARED_LIBRARY_CREATE_${LANG}_FLAGS",
105
  "CMAKE_SHARED_MODULE_CREATE_${LANG}_FLAGS",
106
  "CMAKE_${LANG}_LINK_FLAGS",
107
};
108
}
109
110
cmLocalGenerator::cmLocalGenerator(cmGlobalGenerator* gg, cmMakefile* makefile)
111
0
  : cmOutputConverter(makefile->GetStateSnapshot())
112
0
  , DirectoryBacktrace(makefile->GetBacktrace())
113
0
{
114
0
  this->GlobalGenerator = gg;
115
116
0
  this->Makefile = makefile;
117
118
0
  this->AliasTargets = makefile->GetAliasTargets();
119
120
0
  this->EmitUniversalBinaryFlags = true;
121
122
0
  this->ComputeObjectMaxPath();
123
124
  // Canonicalize entries of the CPATH environment variable the same
125
  // way detection of CMAKE_<LANG>_IMPLICIT_INCLUDE_DIRECTORIES does.
126
0
  {
127
0
    std::vector<std::string> cpath;
128
0
    cmSystemTools::GetPath(cpath, "CPATH");
129
0
    for (std::string const& cp : cpath) {
130
0
      if (cmSystemTools::FileIsFullPath(cp)) {
131
0
        this->EnvCPATH.emplace_back(cmSystemTools::CollapseFullPath(cp));
132
0
      }
133
0
    }
134
0
  }
135
136
0
  std::vector<std::string> enabledLanguages =
137
0
    this->GetState()->GetEnabledLanguages();
138
139
0
  if (cmValue sysrootCompile =
140
0
        this->Makefile->GetDefinition("CMAKE_SYSROOT_COMPILE")) {
141
0
    this->CompilerSysroot = *sysrootCompile;
142
0
  } else {
143
0
    this->CompilerSysroot = this->Makefile->GetSafeDefinition("CMAKE_SYSROOT");
144
0
  }
145
146
0
  if (cmValue sysrootLink =
147
0
        this->Makefile->GetDefinition("CMAKE_SYSROOT_LINK")) {
148
0
    this->LinkerSysroot = *sysrootLink;
149
0
  } else {
150
0
    this->LinkerSysroot = this->Makefile->GetSafeDefinition("CMAKE_SYSROOT");
151
0
  }
152
153
  // OSX SYSROOT can be required by some tools, like tapi
154
0
  {
155
0
    cmValue osxSysroot = this->Makefile->GetDefinition("CMAKE_OSX_SYSROOT");
156
0
    this->VariableMappings["CMAKE_OSX_SYSROOT"] =
157
0
      osxSysroot.IsEmpty() ? "/" : this->EscapeForShell(*osxSysroot, true);
158
0
  }
159
160
0
  if (cmValue appleArchSysroots =
161
0
        this->Makefile->GetDefinition("CMAKE_APPLE_ARCH_SYSROOTS")) {
162
0
    std::string const& appleArchs =
163
0
      this->Makefile->GetSafeDefinition("CMAKE_OSX_ARCHITECTURES");
164
0
    cmList archs(appleArchs);
165
0
    cmList sysroots{ appleArchSysroots, cmList::EmptyElements::Yes };
166
0
    if (archs.size() == sysroots.size()) {
167
0
      for (cmList::size_type i = 0; i < archs.size(); ++i) {
168
0
        this->AppleArchSysroots[archs[i]] = sysroots[i];
169
0
      }
170
0
    } else {
171
0
      std::string const e =
172
0
        cmStrCat("CMAKE_APPLE_ARCH_SYSROOTS:\n  ", *appleArchSysroots,
173
0
                 "\n"
174
0
                 "is not the same length as CMAKE_OSX_ARCHITECTURES:\n  ",
175
0
                 appleArchs);
176
0
      this->IssueMessage(MessageType::FATAL_ERROR, e);
177
0
    }
178
0
  }
179
180
0
  for (std::string const& lang : enabledLanguages) {
181
0
    if (lang == "NONE") {
182
0
      continue;
183
0
    }
184
0
    this->Compilers["CMAKE_" + lang + "_COMPILER"] = lang;
185
186
0
    this->VariableMappings["CMAKE_" + lang + "_COMPILER"] =
187
0
      this->Makefile->GetSafeDefinition("CMAKE_" + lang + "_COMPILER");
188
189
0
    std::string const& compilerArg1 = "CMAKE_" + lang + "_COMPILER_ARG1";
190
0
    std::string const& compilerTarget = "CMAKE_" + lang + "_COMPILER_TARGET";
191
0
    std::string const& compilerOptionTarget =
192
0
      "CMAKE_" + lang + "_COMPILE_OPTIONS_TARGET";
193
0
    std::string const& compilerExternalToolchain =
194
0
      "CMAKE_" + lang + "_COMPILER_EXTERNAL_TOOLCHAIN";
195
0
    std::string const& compilerOptionExternalToolchain =
196
0
      "CMAKE_" + lang + "_COMPILE_OPTIONS_EXTERNAL_TOOLCHAIN";
197
0
    std::string const& compilerOptionSysroot =
198
0
      "CMAKE_" + lang + "_COMPILE_OPTIONS_SYSROOT";
199
200
0
    this->VariableMappings[compilerArg1] =
201
0
      this->Makefile->GetSafeDefinition(compilerArg1);
202
0
    this->VariableMappings[compilerTarget] =
203
0
      this->Makefile->GetSafeDefinition(compilerTarget);
204
0
    this->VariableMappings[compilerOptionTarget] =
205
0
      this->Makefile->GetSafeDefinition(compilerOptionTarget);
206
0
    this->VariableMappings[compilerExternalToolchain] =
207
0
      this->Makefile->GetSafeDefinition(compilerExternalToolchain);
208
0
    this->VariableMappings[compilerOptionExternalToolchain] =
209
0
      this->Makefile->GetSafeDefinition(compilerOptionExternalToolchain);
210
0
    this->VariableMappings[compilerOptionSysroot] =
211
0
      this->Makefile->GetSafeDefinition(compilerOptionSysroot);
212
213
0
    for (std::string replaceVar : ruleReplaceVars) {
214
0
      if (replaceVar.find("${LANG}") != std::string::npos) {
215
0
        cmSystemTools::ReplaceString(replaceVar, "${LANG}", lang);
216
0
      }
217
218
0
      this->VariableMappings[replaceVar] =
219
0
        this->Makefile->GetSafeDefinition(replaceVar);
220
0
    }
221
222
0
    for (std::string replaceVar : ruleReplaceEmptyVars) {
223
0
      if (replaceVar.find("${LANG}") != std::string::npos) {
224
0
        cmSystemTools::ReplaceString(replaceVar, "${LANG}", lang);
225
0
      }
226
227
0
      this->VariableMappings[replaceVar] = std::string();
228
0
    }
229
0
  }
230
0
}
231
232
std::unique_ptr<cmRulePlaceholderExpander>
233
cmLocalGenerator::CreateRulePlaceholderExpander(cmBuildStep buildStep) const
234
0
{
235
0
  return cm::make_unique<cmRulePlaceholderExpander>(
236
0
    buildStep, this->Compilers, this->VariableMappings, this->CompilerSysroot,
237
0
    this->LinkerSysroot,
238
0
    this->GetState()->UseWatcomWMake() || this->GetState()->UseBorlandMake()
239
0
      ? cmRulePlaceholderExpander::UseShortPaths::Yes
240
0
      : cmRulePlaceholderExpander::UseShortPaths::No);
241
0
}
242
243
0
cmLocalGenerator::~cmLocalGenerator() = default;
244
245
void cmLocalGenerator::IssueMessage(MessageType type, std::string const& text,
246
                                    cmListFileBacktrace const& bt) const
247
0
{
248
0
  this->GetMakefile()->IssueMessage(type, text, bt);
249
0
}
250
251
void cmLocalGenerator::IssueDiagnostic(
252
  cmDiagnosticCategory category, std::string const& text,
253
  cmDiagnosticContext const& context) const
254
0
{
255
0
  this->GetMakefile()->IssueDiagnostic(category, text, context);
256
0
}
257
258
void cmLocalGenerator::IssuePolicyWarning(cmPolicies::PolicyID policy,
259
                                          cm::string_view preface,
260
                                          cm::string_view postface,
261
                                          cmListFileBacktrace const& bt) const
262
0
{
263
0
  this->GetMakefile()->IssuePolicyWarning(policy, preface, postface, bt);
264
0
}
265
266
void cmLocalGenerator::ComputeObjectMaxPath()
267
0
{
268
// Choose a maximum object file name length.
269
#if defined(_WIN32) || defined(__CYGWIN__)
270
  this->ObjectPathMax = 250;
271
#else
272
0
  this->ObjectPathMax = 1000;
273
0
#endif
274
0
  cmValue plen = this->Makefile->GetDefinition("CMAKE_OBJECT_PATH_MAX");
275
0
  if (cmNonempty(plen)) {
276
0
    unsigned int pmax;
277
0
    if (sscanf(plen->c_str(), "%u", &pmax) == 1) {
278
0
      if (pmax >= 128) {
279
0
        this->ObjectPathMax = pmax;
280
0
      } else {
281
0
        std::ostringstream w;
282
0
        w << "CMAKE_OBJECT_PATH_MAX is set to " << pmax
283
0
          << ", which is less than the minimum of 128.  "
284
0
             "The value will be ignored.";
285
0
        this->IssueDiagnostic(cmDiagnostics::CMD_AUTHOR, w.str());
286
0
      }
287
0
    } else {
288
0
      std::ostringstream w;
289
0
      w << "CMAKE_OBJECT_PATH_MAX is set to \"" << *plen
290
0
        << "\", which fails to parse as a positive integer.  "
291
0
           "The value will be ignored.";
292
0
      this->IssueDiagnostic(cmDiagnostics::CMD_AUTHOR, w.str());
293
0
    }
294
0
  }
295
0
  this->ObjectMaxPathViolations.clear();
296
0
}
297
298
static void MoveSystemIncludesToEnd(std::vector<std::string>& includeDirs,
299
                                    std::string const& config,
300
                                    std::string const& lang,
301
                                    cmGeneratorTarget const* target)
302
0
{
303
0
  if (!target) {
304
0
    return;
305
0
  }
306
307
0
  std::stable_sort(
308
0
    includeDirs.begin(), includeDirs.end(),
309
0
    [&target, &config, &lang](std::string const& a, std::string const& b) {
310
0
      return !target->IsSystemIncludeDirectory(a, config, lang) &&
311
0
        target->IsSystemIncludeDirectory(b, config, lang);
312
0
    });
313
0
}
314
315
static void MoveSystemIncludesToEnd(std::vector<BT<std::string>>& includeDirs,
316
                                    std::string const& config,
317
                                    std::string const& lang,
318
                                    cmGeneratorTarget const* target)
319
0
{
320
0
  if (!target) {
321
0
    return;
322
0
  }
323
324
0
  std::stable_sort(includeDirs.begin(), includeDirs.end(),
325
0
                   [target, &config, &lang](BT<std::string> const& a,
326
0
                                            BT<std::string> const& b) {
327
0
                     return !target->IsSystemIncludeDirectory(a.Value, config,
328
0
                                                              lang) &&
329
0
                       target->IsSystemIncludeDirectory(b.Value, config, lang);
330
0
                   });
331
0
}
332
333
void cmLocalGenerator::TraceDependencies() const
334
0
{
335
  // Generate the rule files for each target.
336
0
  auto const& targets = this->GetGeneratorTargets();
337
0
  for (auto const& target : targets) {
338
0
    if (!target->IsInBuildSystem()) {
339
0
      continue;
340
0
    }
341
0
    target->TraceDependencies();
342
0
  }
343
0
}
344
345
#ifndef CMAKE_BOOTSTRAP
346
void cmLocalGenerator::ResolveSourceGroupGenex()
347
0
{
348
0
  this->Makefile->ResolveSourceGroupGenex(this);
349
0
}
350
#endif
351
352
void cmLocalGenerator::GenerateTestFiles()
353
0
{
354
0
  if (!this->Makefile->IsOn("CMAKE_TESTING_ENABLED")) {
355
0
    return;
356
0
  }
357
358
  // Compute the set of configurations.
359
0
  std::vector<std::string> configurationTypes =
360
0
    this->Makefile->GetGeneratorConfigs(cmMakefile::OnlyMultiConfig);
361
0
  std::string config = this->Makefile->GetDefaultConfiguration();
362
363
0
  std::string file =
364
0
    cmStrCat(this->StateSnapshot.GetDirectory().GetCurrentBinary(),
365
0
             "/CTestTestfile.cmake");
366
0
  this->GlobalGenerator->AddTestFile(file);
367
368
0
  cmGeneratedFileStream fout(file);
369
370
0
  fout << "# CMake generated Testfile for \n"
371
0
          "# Source directory: "
372
0
       << this->StateSnapshot.GetDirectory().GetCurrentSource()
373
0
       << "\n"
374
0
          "# Build directory: "
375
0
       << this->StateSnapshot.GetDirectory().GetCurrentBinary()
376
0
       << "\n"
377
0
          "# \n"
378
0
          "# This file includes the relevant testing commands "
379
0
          "required for \n"
380
0
          "# testing this directory and lists subdirectories to "
381
0
          "be tested as well.\n";
382
383
0
  std::string resourceSpecFile =
384
0
    this->Makefile->GetSafeDefinition("CTEST_RESOURCE_SPEC_FILE");
385
0
  if (!resourceSpecFile.empty()) {
386
0
    fout << "set(CTEST_RESOURCE_SPEC_FILE \"" << resourceSpecFile << "\")\n";
387
0
  }
388
389
0
  auto writeTestIncludeFile = [this, &fout, &configurationTypes,
390
0
                               &config](std::string const& entry) {
391
    // Entries without a generator expression are emitted verbatim,
392
    // preserving CTest-time ${VAR} expansion of the path.
393
0
    if (cmGeneratorExpression::Find(entry) == std::string::npos) {
394
0
      fout << "include(\"" << entry << "\")\n";
395
0
      return;
396
0
    }
397
398
    // Emit one include() per path in an evaluated result.  As for list-valued
399
    // properties, the result is split on ';', and each path is quoted so that
400
    // any '"', '$', or '\' cannot break the include() argument or trigger a
401
    // second-stage CTest ${...} expansion.  An empty result adds no include.
402
0
    auto writeIncludes = [&fout](std::vector<std::string> const& paths,
403
0
                                 char const* indent) {
404
0
      for (std::string const& path : paths) {
405
0
        fout << indent << "include(" << cmScriptGenerator::Quote(path)
406
0
             << ")\n";
407
0
      }
408
0
    };
409
410
0
    if (!this->GlobalGenerator->IsMultiConfig() ||
411
0
        configurationTypes.empty()) {
412
      // Single-config generator, or a multi-config generator with no
413
      // configuration types: evaluate once with the default configuration
414
      // and emit unconditional includes.
415
0
      std::vector<std::string> paths;
416
0
      cmExpandList(cmGeneratorExpression::Evaluate(entry, this, config),
417
0
                   paths);
418
0
      writeIncludes(paths, "");
419
0
      return;
420
0
    }
421
422
    // Multi-config generator: evaluate the entry for every configuration.
423
0
    std::vector<std::string> results;
424
0
    results.reserve(configurationTypes.size());
425
0
    bool allSame = true;
426
0
    for (std::string const& ct : configurationTypes) {
427
0
      results.emplace_back(cmGeneratorExpression::Evaluate(entry, this, ct));
428
0
      if (results.back() != results.front()) {
429
0
        allSame = false;
430
0
      }
431
0
    }
432
433
    // A config-independent result collapses to unconditional includes, so it
434
    // still runs when ctest is invoked without -C.
435
0
    if (allSame) {
436
0
      std::vector<std::string> paths;
437
0
      cmExpandList(results.front(), paths);
438
0
      writeIncludes(paths, "");
439
0
      return;
440
0
    }
441
442
    // Otherwise guard each per-config result to match the config guards used
443
    // for add_test().  A configuration whose result yields no include is
444
    // skipped so no empty guard is emitted.
445
0
    bool first = true;
446
0
    for (size_t i = 0; i < configurationTypes.size(); ++i) {
447
0
      std::vector<std::string> paths;
448
0
      cmExpandList(results[i], paths);
449
0
      if (paths.empty()) {
450
0
        continue;
451
0
      }
452
0
      fout << (first ? "if(" : "elseif(")
453
0
           << cmScriptGenerator::CreateConfigTest("CTEST_CONFIGURATION_TYPE",
454
0
                                                  configurationTypes[i])
455
0
           << ")\n";
456
0
      writeIncludes(paths, "  ");
457
0
      first = false;
458
0
    }
459
0
    if (!first) {
460
0
      fout << "endif()\n";
461
0
    }
462
0
  };
463
464
0
  cmValue testIncludeFile = this->Makefile->GetProperty("TEST_INCLUDE_FILE");
465
0
  if (testIncludeFile) {
466
0
    writeTestIncludeFile(*testIncludeFile);
467
0
  }
468
469
0
  cmValue testIncludeFiles = this->Makefile->GetProperty("TEST_INCLUDE_FILES");
470
0
  if (testIncludeFiles) {
471
0
    cmList includesList{ *testIncludeFiles };
472
0
    for (std::string const& i : includesList) {
473
0
      writeTestIncludeFile(i);
474
0
    }
475
0
  }
476
477
  // Ask each test generator to write its code.
478
0
  for (auto const& tester : this->Makefile->GetTestGenerators()) {
479
0
    tester->Compute(this);
480
0
    tester->Generate(fout, config, configurationTypes);
481
0
  }
482
0
  using vec_t = std::vector<cmStateSnapshot>;
483
0
  vec_t const& children = this->Makefile->GetStateSnapshot().GetChildren();
484
0
  for (cmStateSnapshot const& i : children) {
485
    // TODO: Use add_subdirectory instead?
486
0
    std::string outP = i.GetDirectory().GetCurrentBinary();
487
0
    outP = this->MaybeRelativeToCurBinDir(outP);
488
0
    fout << "subdirs(" << cmScriptGenerator::Quote(outP) << ")\n";
489
0
  }
490
491
  // Add directory labels property
492
0
  cmValue directoryLabels =
493
0
    this->Makefile->GetDefinition("CMAKE_DIRECTORY_LABELS");
494
0
  cmValue labels = this->Makefile->GetProperty("LABELS");
495
496
0
  if (labels || directoryLabels) {
497
0
    fout << "set_directory_properties(PROPERTIES LABELS ";
498
0
    if (labels) {
499
0
      fout << cmScriptGenerator::Quote(*labels);
500
0
    }
501
0
    if (labels && directoryLabels) {
502
0
      fout << ";";
503
0
    }
504
0
    if (directoryLabels) {
505
0
      fout << cmScriptGenerator::Quote(*directoryLabels);
506
0
    }
507
0
    fout << ")\n";
508
0
  }
509
0
}
510
511
void cmLocalGenerator::CreateEvaluationFileOutputs()
512
0
{
513
0
  std::vector<std::string> const& configs =
514
0
    this->Makefile->GetGeneratorConfigs(cmMakefile::IncludeEmptyConfig);
515
0
  for (std::string const& c : configs) {
516
0
    this->CreateEvaluationFileOutputs(c);
517
0
  }
518
0
}
519
520
void cmLocalGenerator::CreateEvaluationFileOutputs(std::string const& config)
521
0
{
522
0
  for (auto const& geef : this->Makefile->GetEvaluationFiles()) {
523
0
    geef->CreateOutputFile(this, config);
524
0
  }
525
0
}
526
527
void cmLocalGenerator::ProcessEvaluationFiles(
528
  std::vector<std::string>& generatedFiles)
529
0
{
530
0
  for (auto const& geef : this->Makefile->GetEvaluationFiles()) {
531
0
    geef->Generate(this);
532
0
    if (cmSystemTools::GetFatalErrorOccurred()) {
533
0
      return;
534
0
    }
535
0
    std::vector<std::string> files = geef->GetFiles();
536
0
    std::sort(files.begin(), files.end());
537
538
0
    std::vector<std::string> intersection;
539
0
    std::set_intersection(files.begin(), files.end(), generatedFiles.begin(),
540
0
                          generatedFiles.end(),
541
0
                          std::back_inserter(intersection));
542
0
    if (!intersection.empty()) {
543
0
      cmSystemTools::Error("Files to be generated by multiple different "
544
0
                           "commands: " +
545
0
                           cmWrap('"', intersection, '"', " "));
546
0
      return;
547
0
    }
548
549
0
    cm::append(generatedFiles, files);
550
0
    std::inplace_merge(generatedFiles.begin(),
551
0
                       generatedFiles.end() - files.size(),
552
0
                       generatedFiles.end());
553
0
  }
554
0
}
555
556
void cmLocalGenerator::GenerateInstallRules()
557
0
{
558
  // Compute the install prefix.
559
0
  cmValue installPrefix =
560
0
    this->Makefile->GetDefinition("CMAKE_INSTALL_PREFIX");
561
0
  std::string prefix = *installPrefix;
562
563
#if defined(_WIN32) && !defined(__CYGWIN__)
564
  if (!installPrefix) {
565
    if (!cmSystemTools::GetEnv("SystemDrive", prefix)) {
566
      prefix = "C:";
567
    }
568
    cmValue project_name = this->Makefile->GetDefinition("PROJECT_NAME");
569
    if (cmNonempty(project_name)) {
570
      prefix += "/Program Files/";
571
      prefix += *project_name;
572
    } else {
573
      prefix += "/InstalledCMakeProject";
574
    }
575
  }
576
#elif defined(__HAIKU__)
577
  char dir[B_PATH_NAME_LENGTH];
578
  if (!installPrefix) {
579
    if (find_directory(B_SYSTEM_DIRECTORY, -1, false, dir, sizeof(dir)) ==
580
        B_OK) {
581
      prefix = dir;
582
    } else {
583
      prefix = "/boot/system";
584
    }
585
  }
586
#else
587
0
  if (!installPrefix) {
588
0
    prefix = "/usr/local";
589
0
  }
590
0
#endif
591
0
  if (cmValue stagingPrefix =
592
0
        this->Makefile->GetDefinition("CMAKE_STAGING_PREFIX")) {
593
0
    prefix = *stagingPrefix;
594
0
  }
595
596
  // Compute the set of configurations.
597
0
  std::vector<std::string> configurationTypes =
598
0
    this->Makefile->GetGeneratorConfigs(cmMakefile::OnlyMultiConfig);
599
0
  std::string config = this->Makefile->GetDefaultConfiguration();
600
601
  // Choose a default install configuration.
602
0
  std::string default_config = config;
603
0
  char const* default_order[] = { "RELEASE", "MINSIZEREL", "RELWITHDEBINFO",
604
0
                                  "DEBUG", nullptr };
605
0
  for (char const** c = default_order; *c && default_config.empty(); ++c) {
606
0
    for (std::string const& configurationType : configurationTypes) {
607
0
      if (cmSystemTools::UpperCase(configurationType) == *c) {
608
0
        default_config = configurationType;
609
0
      }
610
0
    }
611
0
  }
612
0
  if (default_config.empty() && !configurationTypes.empty()) {
613
0
    default_config = configurationTypes[0];
614
0
  }
615
616
  // Create the install script file.
617
0
  std::string file = this->StateSnapshot.GetDirectory().GetCurrentBinary();
618
0
  std::string homedir = this->GetState()->GetBinaryDirectory();
619
0
  int toplevel_install = 0;
620
0
  if (file == homedir) {
621
0
    toplevel_install = 1;
622
0
  }
623
0
  file += "/cmake_install.cmake";
624
0
  this->GetGlobalGenerator()->AddInstallScript(file);
625
0
  cmGeneratedFileStream fout(file);
626
627
  // Write the header.
628
  /* clang-format off */
629
0
  fout << "# Install script for directory: "
630
0
       << this->StateSnapshot.GetDirectory().GetCurrentSource()
631
0
       << "\n\n"
632
0
          "# Set the install prefix\n"
633
0
          "if(NOT DEFINED CMAKE_INSTALL_PREFIX)\n"
634
0
          "  set(CMAKE_INSTALL_PREFIX \"" << prefix << "\")\n"
635
0
          "endif()\n"
636
0
       << R"(string(REGEX REPLACE "/$" "" CMAKE_INSTALL_PREFIX )"
637
0
       << "\"${CMAKE_INSTALL_PREFIX}\")\n\n";
638
  /* clang-format on */
639
640
  // Write support code for generating per-configuration install rules.
641
  /* clang-format off */
642
0
  fout <<
643
0
    "# Set the install configuration name.\n"
644
0
    "if(NOT DEFINED CMAKE_INSTALL_CONFIG_NAME)\n"
645
0
    "  if(BUILD_TYPE)\n"
646
0
    "    string(REGEX REPLACE \"^[^A-Za-z0-9_]+\" \"\"\n"
647
0
    "           CMAKE_INSTALL_CONFIG_NAME \"${BUILD_TYPE}\")\n"
648
0
    "  else()\n"
649
0
    "    set(CMAKE_INSTALL_CONFIG_NAME \"" << default_config << "\")\n"
650
0
    "  endif()\n"
651
0
    "  message(STATUS \"Install configuration: "
652
0
    "\\\"${CMAKE_INSTALL_CONFIG_NAME}\\\"\")\n"
653
0
    "endif()\n"
654
0
    "\n";
655
  /* clang-format on */
656
657
  // Write support code for dealing with component-specific installs.
658
  /* clang-format off */
659
0
  fout <<
660
0
    "# Set the component getting installed.\n"
661
0
    "if(NOT CMAKE_INSTALL_COMPONENT)\n"
662
0
    "  if(COMPONENT)\n"
663
0
    "    message(STATUS \"Install component: \\\"${COMPONENT}\\\"\")\n"
664
0
    "    set(CMAKE_INSTALL_COMPONENT \"${COMPONENT}\")\n"
665
0
    "  else()\n"
666
0
    "    set(CMAKE_INSTALL_COMPONENT)\n"
667
0
    "  endif()\n"
668
0
    "endif()\n"
669
0
    "\n";
670
  /* clang-format on */
671
672
  // Copy user-specified install options to the install code.
673
0
  if (cmValue so_no_exe =
674
0
        this->Makefile->GetDefinition("CMAKE_INSTALL_SO_NO_EXE")) {
675
    /* clang-format off */
676
0
    fout <<
677
0
      "# Install shared libraries without execute permission?\n"
678
0
      "if(NOT DEFINED CMAKE_INSTALL_SO_NO_EXE)\n"
679
0
      "  set(CMAKE_INSTALL_SO_NO_EXE \"" << *so_no_exe << "\")\n"
680
0
      "endif()\n"
681
0
      "\n";
682
    /* clang-format on */
683
0
  }
684
685
  // Copy cmake cross compile state to install code.
686
0
  if (cmValue crosscompiling =
687
0
        this->Makefile->GetDefinition("CMAKE_CROSSCOMPILING")) {
688
    /* clang-format off */
689
0
    fout <<
690
0
      "# Is this installation the result of a crosscompile?\n"
691
0
      "if(NOT DEFINED CMAKE_CROSSCOMPILING)\n"
692
0
      "  set(CMAKE_CROSSCOMPILING \"" << *crosscompiling << "\")\n"
693
0
      "endif()\n"
694
0
      "\n";
695
    /* clang-format on */
696
0
  }
697
698
  // Write default directory permissions.
699
0
  if (cmValue defaultDirPermissions = this->Makefile->GetDefinition(
700
0
        "CMAKE_INSTALL_DEFAULT_DIRECTORY_PERMISSIONS")) {
701
    /* clang-format off */
702
0
    fout <<
703
0
      "# Set default install directory permissions.\n"
704
0
      "if(NOT DEFINED CMAKE_INSTALL_DEFAULT_DIRECTORY_PERMISSIONS)\n"
705
0
      "  set(CMAKE_INSTALL_DEFAULT_DIRECTORY_PERMISSIONS \""
706
0
         << *defaultDirPermissions << "\")\n"
707
0
      "endif()\n"
708
0
      "\n";
709
    /* clang-format on */
710
0
  }
711
712
  // Write out CMAKE_GET_RUNTIME_DEPENDENCIES_PLATFORM so that
713
  // installed code that uses `file(GET_RUNTIME_DEPENDENCIES)`
714
  // has same platform variable as when running cmake
715
0
  if (cmValue platform = this->Makefile->GetDefinition(
716
0
        "CMAKE_GET_RUNTIME_DEPENDENCIES_PLATFORM")) {
717
    /* clang-format off */
718
0
    fout <<
719
0
      "# Set OS and executable format for runtime-dependencies.\n"
720
0
      "if(NOT DEFINED CMAKE_GET_RUNTIME_DEPENDENCIES_PLATFORM)\n"
721
0
      "  set(CMAKE_GET_RUNTIME_DEPENDENCIES_PLATFORM \""
722
0
         << *platform << "\")\n"
723
0
      "endif()\n"
724
0
      "\n";
725
    /* clang-format on */
726
0
  }
727
728
  // Write out CMAKE_GET_RUNTIME_DEPENDENCIES_TOOL so that
729
  // installed code that uses `file(GET_RUNTIME_DEPENDENCIES)`
730
  // has same tool selected as when running cmake
731
0
  if (cmValue command =
732
0
        this->Makefile->GetDefinition("CMAKE_GET_RUNTIME_DEPENDENCIES_TOOL")) {
733
    /* clang-format off */
734
0
    fout <<
735
0
      "# Set tool for dependency-resolution of runtime-dependencies.\n"
736
0
      "if(NOT DEFINED CMAKE_GET_RUNTIME_DEPENDENCIES_TOOL)\n"
737
0
      "  set(CMAKE_GET_RUNTIME_DEPENDENCIES_TOOL \""
738
0
         << *command << "\")\n"
739
0
      "endif()\n"
740
0
      "\n";
741
    /* clang-format on */
742
0
  }
743
744
  // Write out CMAKE_GET_RUNTIME_DEPENDENCIES_COMMAND so that
745
  // installed code that uses `file(GET_RUNTIME_DEPENDENCIES)`
746
  // has same path to the tool as when running cmake
747
0
  if (cmValue command = this->Makefile->GetDefinition(
748
0
        "CMAKE_GET_RUNTIME_DEPENDENCIES_COMMAND")) {
749
    /* clang-format off */
750
0
    fout <<
751
0
      "# Set path to tool for dependency-resolution of runtime-dependencies.\n"
752
0
      "if(NOT DEFINED CMAKE_GET_RUNTIME_DEPENDENCIES_COMMAND)\n"
753
0
      "  set(CMAKE_GET_RUNTIME_DEPENDENCIES_COMMAND \""
754
0
         << *command << "\")\n"
755
0
      "endif()\n"
756
0
      "\n";
757
    /* clang-format on */
758
0
  }
759
760
  // Write out CMAKE_OBJDUMP so that installed code that uses
761
  // `file(GET_RUNTIME_DEPENDENCIES)` and hasn't specified
762
  // CMAKE_GET_RUNTIME_DEPENDENCIES_COMMAND has consistent
763
  // logic to fallback to CMAKE_OBJDUMP when `objdump` is
764
  // not on the path
765
0
  if (cmValue command = this->Makefile->GetDefinition("CMAKE_OBJDUMP")) {
766
    /* clang-format off */
767
0
    fout <<
768
0
      "# Set path to fallback-tool for dependency-resolution.\n"
769
0
      "if(NOT DEFINED CMAKE_OBJDUMP)\n"
770
0
      "  set(CMAKE_OBJDUMP \""
771
0
         << *command << "\")\n"
772
0
      "endif()\n"
773
0
      "\n";
774
    /* clang-format on */
775
0
  }
776
777
0
  this->AddGeneratorSpecificInstallSetup(fout);
778
779
  // Ask each install generator to write its code.
780
0
  cmPolicies::PolicyStatus status = this->GetPolicyStatus(cmPolicies::CMP0082);
781
0
  auto const& installers = this->Makefile->GetInstallGenerators();
782
0
  bool haveSubdirectoryInstall = false;
783
0
  bool haveInstallAfterSubdirectory = false;
784
0
  if (status == cmPolicies::WARN) {
785
0
    for (auto const& installer : installers) {
786
0
      installer->CheckCMP0082(haveSubdirectoryInstall,
787
0
                              haveInstallAfterSubdirectory);
788
0
      installer->Generate(fout, config, configurationTypes);
789
0
    }
790
0
  } else {
791
0
    for (auto const& installer : installers) {
792
0
      installer->Generate(fout, config, configurationTypes);
793
0
    }
794
0
  }
795
796
  // Write rules from old-style specification stored in targets.
797
0
  this->GenerateTargetInstallRules(fout, config, configurationTypes);
798
799
  // Include install scripts from subdirectories.
800
0
  switch (status) {
801
0
    case cmPolicies::WARN:
802
0
      if (haveInstallAfterSubdirectory &&
803
0
          this->Makefile->PolicyOptionalWarningEnabled(
804
0
            "CMAKE_POLICY_WARNING_CMP0082")) {
805
0
        this->IssuePolicyWarning(cmPolicies::CMP0082);
806
0
      }
807
0
      CM_FALLTHROUGH;
808
0
    case cmPolicies::OLD: {
809
0
      std::vector<cmStateSnapshot> children =
810
0
        this->Makefile->GetStateSnapshot().GetChildren();
811
0
      if (!children.empty()) {
812
0
        fout << "if(NOT CMAKE_INSTALL_LOCAL_ONLY)\n";
813
0
        fout << "  # Include the install script for each subdirectory.\n";
814
0
        for (cmStateSnapshot const& c : children) {
815
0
          if (!c.GetDirectory().GetPropertyAsBool("EXCLUDE_FROM_ALL")) {
816
0
            std::string odir = c.GetDirectory().GetCurrentBinary();
817
0
            cmSystemTools::ConvertToUnixSlashes(odir);
818
0
            fout << "  include(\"" << odir << "/cmake_install.cmake\")\n";
819
0
          }
820
0
        }
821
0
        fout << "\n";
822
0
        fout << "endif()\n\n";
823
0
      }
824
0
    } break;
825
826
0
    case cmPolicies::NEW:
827
      // NEW behavior is handled in
828
      // cmInstallSubdirectoryGenerator::GenerateScript()
829
0
      break;
830
0
  }
831
832
  /* clang-format off */
833
834
0
    fout <<
835
0
      "string(REPLACE \";\" \"\\n\" CMAKE_INSTALL_MANIFEST_CONTENT\n"
836
0
      "       \"${CMAKE_INSTALL_MANIFEST_FILES}\")\n"
837
0
      "if(CMAKE_INSTALL_LOCAL_ONLY)\n"
838
0
      "  file(WRITE \"" <<
839
0
      this->StateSnapshot.GetDirectory().GetCurrentBinary() <<
840
0
      "/install_local_manifest.txt\"\n"
841
0
      "     \"${CMAKE_INSTALL_MANIFEST_CONTENT}\")\n"
842
0
      "endif()\n";
843
844
0
    if (toplevel_install) {
845
0
      fout <<
846
0
        "if(CMAKE_INSTALL_COMPONENT)\n"
847
0
        "  if(CMAKE_INSTALL_COMPONENT MATCHES \"^[a-zA-Z0-9_.+-]+$\")\n"
848
0
        "    set(CMAKE_INSTALL_MANIFEST \"install_manifest_"
849
0
        "${CMAKE_INSTALL_COMPONENT}.txt\")\n"
850
0
        "  else()\n"
851
0
        "    string(MD5 CMAKE_INST_COMP_HASH \"${CMAKE_INSTALL_COMPONENT}\")\n"
852
0
        "    set(CMAKE_INSTALL_MANIFEST \"install_manifest_"
853
0
        "${CMAKE_INST_COMP_HASH}.txt\")\n"
854
0
        "    unset(CMAKE_INST_COMP_HASH)\n"
855
0
        "  endif()\n"
856
0
        "else()\n"
857
0
        "  set(CMAKE_INSTALL_MANIFEST \"install_manifest.txt\")\n"
858
0
        "endif()\n"
859
0
        "\n"
860
0
        "if(NOT CMAKE_INSTALL_LOCAL_ONLY)\n"
861
0
        "  file(WRITE \"" << homedir << "/${CMAKE_INSTALL_MANIFEST}\"\n"
862
0
        "     \"${CMAKE_INSTALL_MANIFEST_CONTENT}\")\n"
863
0
        "endif()\n";
864
0
    }
865
  /* clang-format on */
866
0
}
867
868
void cmLocalGenerator::AddGeneratorTarget(
869
  std::unique_ptr<cmGeneratorTarget> gt)
870
0
{
871
0
  cmGeneratorTarget* gt_ptr = gt.get();
872
873
0
  this->GeneratorTargets.push_back(std::move(gt));
874
0
  this->GeneratorTargetSearchIndex.emplace(gt_ptr->GetName(), gt_ptr);
875
0
  this->GlobalGenerator->IndexGeneratorTarget(gt_ptr);
876
0
}
877
878
void cmLocalGenerator::AddImportedGeneratorTarget(cmGeneratorTarget* gt)
879
0
{
880
0
  this->ImportedGeneratorTargets.emplace(gt->GetName(), gt);
881
0
  this->GlobalGenerator->IndexGeneratorTarget(gt);
882
0
}
883
884
void cmLocalGenerator::AddOwnedImportedGeneratorTarget(
885
  std::unique_ptr<cmGeneratorTarget> gt)
886
0
{
887
0
  this->OwnedImportedGeneratorTargets.push_back(std::move(gt));
888
0
}
889
890
cmGeneratorTarget* cmLocalGenerator::FindLocalNonAliasGeneratorTarget(
891
  std::string const& name) const
892
0
{
893
0
  auto ti = this->GeneratorTargetSearchIndex.find(name);
894
0
  if (ti != this->GeneratorTargetSearchIndex.end()) {
895
0
    return ti->second;
896
0
  }
897
0
  return nullptr;
898
0
}
899
900
void cmLocalGenerator::ComputeTargetManifest()
901
0
{
902
  // Collect the set of configuration types.
903
0
  std::vector<std::string> configNames =
904
0
    this->Makefile->GetGeneratorConfigs(cmMakefile::IncludeEmptyConfig);
905
906
  // Add our targets to the manifest for each configuration.
907
0
  auto const& targets = this->GetGeneratorTargets();
908
0
  for (auto const& target : targets) {
909
0
    if (!target->IsInBuildSystem()) {
910
0
      continue;
911
0
    }
912
0
    for (std::string const& c : configNames) {
913
0
      target->ComputeTargetManifest(c);
914
0
    }
915
0
  }
916
0
}
917
918
bool cmLocalGenerator::ComputeTargetCompileFeatures()
919
0
{
920
  // Collect the set of configuration types.
921
0
  std::vector<std::string> configNames =
922
0
    this->Makefile->GetGeneratorConfigs(cmMakefile::IncludeEmptyConfig);
923
924
0
  using LanguagePair = std::pair<std::string, std::string>;
925
0
  std::vector<LanguagePair> pairedLanguages{
926
0
    { "OBJC", "C" }, { "OBJCXX", "CXX" }, { "CUDA", "CXX" }, { "HIP", "CXX" }
927
0
  };
928
0
  std::set<LanguagePair> inferredEnabledLanguages;
929
0
  for (auto const& lang : pairedLanguages) {
930
0
    if (this->Makefile->GetState()->GetLanguageEnabled(lang.first)) {
931
0
      inferredEnabledLanguages.insert(lang);
932
0
    }
933
0
  }
934
935
  // Process compile features of all targets.
936
0
  auto const& targets = this->GetGeneratorTargets();
937
0
  for (auto const& target : targets) {
938
0
    for (std::string const& c : configNames) {
939
0
      if (!target->ComputeCompileFeatures(c)) {
940
0
        return false;
941
0
      }
942
0
    }
943
944
    // Now that C/C++ _STANDARD values have been computed
945
    // set the values to ObjC/ObjCXX _STANDARD variables
946
0
    if (target->CanCompileSources()) {
947
0
      for (std::string const& c : configNames) {
948
0
        target->ComputeCompileFeatures(c, inferredEnabledLanguages);
949
0
      }
950
0
    }
951
0
  }
952
953
0
  return true;
954
0
}
955
956
bool cmLocalGenerator::IsRootMakefile() const
957
0
{
958
0
  return !this->StateSnapshot.GetBuildsystemDirectoryParent().IsValid();
959
0
}
960
961
cmState* cmLocalGenerator::GetState() const
962
0
{
963
0
  return this->GlobalGenerator->GetCMakeInstance()->GetState();
964
0
}
965
966
cmStateSnapshot cmLocalGenerator::GetStateSnapshot() const
967
0
{
968
0
  return this->Makefile->GetStateSnapshot();
969
0
}
970
971
std::string cmLocalGenerator::GetRuleLauncher(cmGeneratorTarget* target,
972
                                              std::string const& prop,
973
                                              std::string const& config)
974
0
{
975
0
  cmValue value = this->Makefile->GetProperty(prop);
976
0
  if (target) {
977
0
    value = target->GetProperty(prop);
978
0
  }
979
0
  if (value) {
980
0
    return cmGeneratorExpression::Evaluate(*value, this, config, target);
981
0
  }
982
0
  return "";
983
0
}
984
985
std::string cmLocalGenerator::ConvertToIncludeReference(
986
  std::string const& path, OutputFormat format)
987
0
{
988
0
  return this->ConvertToOutputForExisting(path, format);
989
0
}
990
991
std::string cmLocalGenerator::GetIncludeFlags(
992
  std::vector<std::string> const& includeDirs, cmGeneratorTarget* target,
993
  std::string const& lang, std::string const& config, bool forResponseFile)
994
0
{
995
0
  if (lang.empty()) {
996
0
    return "";
997
0
  }
998
999
0
  std::vector<std::string> includes = includeDirs;
1000
0
  MoveSystemIncludesToEnd(includes, config, lang, target);
1001
1002
0
  OutputFormat shellFormat = forResponseFile ? RESPONSE : SHELL;
1003
0
  std::ostringstream includeFlags;
1004
1005
0
  std::string const& includeFlag =
1006
0
    this->Makefile->GetSafeDefinition(cmStrCat("CMAKE_INCLUDE_FLAG_", lang));
1007
0
  bool quotePaths = false;
1008
0
  if (this->Makefile->GetDefinition("CMAKE_QUOTE_INCLUDE_PATHS")) {
1009
0
    quotePaths = true;
1010
0
  }
1011
0
  std::string sep = " ";
1012
0
  bool repeatFlag = true;
1013
  // should the include flag be repeated like ie. -IA -IB
1014
0
  if (cmValue incSep = this->Makefile->GetDefinition(
1015
0
        cmStrCat("CMAKE_INCLUDE_FLAG_SEP_", lang))) {
1016
    // if there is a separator then the flag is not repeated but is only
1017
    // given once i.e.  -classpath a:b:c
1018
0
    sep = *incSep;
1019
0
    repeatFlag = false;
1020
0
  }
1021
1022
  // Support special system include flag if it is available and the
1023
  // normal flag is repeated for each directory.
1024
0
  cmValue sysIncludeFlag = nullptr;
1025
0
  cmValue sysIncludeFlagWarning = nullptr;
1026
0
  if (repeatFlag) {
1027
0
    sysIncludeFlag = this->Makefile->GetDefinition(
1028
0
      cmStrCat("CMAKE_INCLUDE_SYSTEM_FLAG_", lang));
1029
0
    sysIncludeFlagWarning = this->Makefile->GetDefinition(
1030
0
      cmStrCat("CMAKE_INCLUDE_SYSTEM_FLAG_", lang, "_WARNING"));
1031
0
  }
1032
1033
0
  cmValue fwSearchFlag = this->Makefile->GetDefinition(
1034
0
    cmStrCat("CMAKE_", lang, "_FRAMEWORK_SEARCH_FLAG"));
1035
0
  cmValue sysFwSearchFlag = this->Makefile->GetDefinition(
1036
0
    cmStrCat("CMAKE_", lang, "_SYSTEM_FRAMEWORK_SEARCH_FLAG"));
1037
1038
0
  bool flagUsed = false;
1039
0
  bool sysIncludeFlagUsed = false;
1040
0
  std::set<std::string> emitted;
1041
#ifdef __APPLE__
1042
  emitted.insert("/System/Library/Frameworks");
1043
#endif
1044
0
  for (std::string const& i : includes) {
1045
0
    if (cmNonempty(fwSearchFlag) && this->Makefile->IsOn("APPLE") &&
1046
0
        cmSystemTools::IsPathToFramework(i)) {
1047
0
      std::string const frameworkDir = cmSystemTools::GetFilenamePath(i);
1048
0
      if (emitted.insert(frameworkDir).second) {
1049
0
        if (sysFwSearchFlag && target &&
1050
0
            target->IsSystemIncludeDirectory(frameworkDir, config, lang)) {
1051
0
          includeFlags << *sysFwSearchFlag;
1052
0
        } else {
1053
0
          includeFlags << *fwSearchFlag;
1054
0
        }
1055
0
        includeFlags << this->ConvertToOutputFormat(frameworkDir, shellFormat)
1056
0
                     << " ";
1057
0
      }
1058
0
      continue;
1059
0
    }
1060
1061
0
    if (!flagUsed || repeatFlag) {
1062
0
      if (sysIncludeFlag && target &&
1063
0
          target->IsSystemIncludeDirectory(i, config, lang)) {
1064
0
        includeFlags << *sysIncludeFlag;
1065
0
        sysIncludeFlagUsed = true;
1066
0
      } else {
1067
0
        includeFlags << includeFlag;
1068
0
      }
1069
0
      flagUsed = true;
1070
0
    }
1071
0
    std::string includePath = this->ConvertToIncludeReference(i, shellFormat);
1072
0
    if (quotePaths && !includePath.empty() && includePath.front() != '\"') {
1073
0
      includeFlags << "\"";
1074
0
    }
1075
0
    includeFlags << includePath;
1076
0
    if (quotePaths && !includePath.empty() && includePath.front() != '\"') {
1077
0
      includeFlags << "\"";
1078
0
    }
1079
0
    includeFlags << sep;
1080
0
  }
1081
0
  if (sysIncludeFlagUsed && sysIncludeFlagWarning) {
1082
0
    includeFlags << *sysIncludeFlagWarning;
1083
0
  }
1084
0
  std::string flags = includeFlags.str();
1085
  // remove trailing separators
1086
0
  if ((sep[0] != ' ') && !flags.empty() && flags.back() == sep[0]) {
1087
0
    flags.back() = ' ';
1088
0
  }
1089
0
  return cmTrimWhitespace(flags);
1090
0
}
1091
1092
void cmLocalGenerator::AddCompileOptions(std::string& flags,
1093
                                         cmGeneratorTarget* target,
1094
                                         std::string const& lang,
1095
                                         std::string const& config)
1096
0
{
1097
0
  std::vector<BT<std::string>> tmpFlags;
1098
0
  this->AddCompileOptions(tmpFlags, target, lang, config);
1099
0
  this->AppendFlags(flags, tmpFlags);
1100
0
}
1101
1102
void cmLocalGenerator::AddCompileOptions(std::vector<BT<std::string>>& flags,
1103
                                         cmGeneratorTarget* target,
1104
                                         std::string const& lang,
1105
                                         std::string const& config)
1106
0
{
1107
0
  std::string langFlagRegexVar = cmStrCat("CMAKE_", lang, "_FLAG_REGEX");
1108
1109
0
  if (cmValue langFlagRegexStr =
1110
0
        this->Makefile->GetDefinition(langFlagRegexVar)) {
1111
    // Filter flags acceptable to this language.
1112
0
    if (cmValue targetFlags = target->GetProperty("COMPILE_FLAGS")) {
1113
0
      std::vector<std::string> opts;
1114
0
      cmSystemTools::ParseWindowsCommandLine(targetFlags->c_str(), opts);
1115
      // Re-escape these flags since COMPILE_FLAGS were already parsed
1116
      // as a command line above.
1117
0
      std::string compileOpts;
1118
0
      this->AppendCompileOptions(compileOpts, opts, langFlagRegexStr->c_str());
1119
0
      if (!compileOpts.empty()) {
1120
0
        flags.emplace_back(std::move(compileOpts));
1121
0
      }
1122
0
    }
1123
0
    std::vector<BT<std::string>> targetCompileOpts =
1124
0
      target->GetCompileOptions(config, lang);
1125
    // COMPILE_OPTIONS are escaped.
1126
0
    this->AppendCompileOptions(flags, targetCompileOpts,
1127
0
                               langFlagRegexStr->c_str());
1128
0
  } else {
1129
    // Use all flags.
1130
0
    if (cmValue targetFlags = target->GetProperty("COMPILE_FLAGS")) {
1131
      // COMPILE_FLAGS are not escaped for historical reasons.
1132
0
      std::string compileFlags;
1133
0
      this->AppendFlags(compileFlags, *targetFlags);
1134
0
      if (!compileFlags.empty()) {
1135
0
        flags.emplace_back(std::move(compileFlags));
1136
0
      }
1137
0
    }
1138
0
    std::vector<BT<std::string>> targetCompileOpts =
1139
0
      target->GetCompileOptions(config, lang);
1140
    // COMPILE_OPTIONS are escaped.
1141
0
    this->AppendCompileOptions(flags, targetCompileOpts);
1142
0
  }
1143
1144
0
  cmStandardLevelResolver standardResolver(this->Makefile);
1145
0
  for (auto const& it : target->GetMaxLanguageStandards()) {
1146
0
    cmValue standard = target->GetLanguageStandard(it.first, config);
1147
0
    if (!standard) {
1148
0
      continue;
1149
0
    }
1150
0
    if (standardResolver.IsLaterStandard(it.first, *standard, it.second)) {
1151
0
      std::ostringstream e;
1152
0
      e << "The COMPILE_FEATURES property of target \"" << target->GetName()
1153
0
        << "\" was evaluated when computing the link "
1154
0
           "implementation, and the \""
1155
0
        << it.first << "_STANDARD\" was \"" << it.second
1156
0
        << "\" for that computation.  Computing the "
1157
0
           "COMPILE_FEATURES based on the link implementation resulted in a "
1158
0
           "higher \""
1159
0
        << it.first << "_STANDARD\" \"" << *standard
1160
0
        << "\".  "
1161
0
           "This is not permitted. The COMPILE_FEATURES may not both depend "
1162
0
           "on "
1163
0
           "and be depended on by the link implementation.\n";
1164
0
      this->IssueMessage(MessageType::FATAL_ERROR, e.str());
1165
0
      return;
1166
0
    }
1167
0
  }
1168
1169
  // Add Warning as errors flags
1170
0
  if (!this->GetCMakeInstance()->GetIgnoreCompileWarningAsError()) {
1171
0
    cmValue const wError = target->GetProperty("COMPILE_WARNING_AS_ERROR");
1172
0
    cmValue const wErrorOpts = this->Makefile->GetDefinition(
1173
0
      cmStrCat("CMAKE_", lang, "_COMPILE_OPTIONS_WARNING_AS_ERROR"));
1174
0
    if (wError.IsOn() && wErrorOpts.IsSet()) {
1175
0
      std::string wErrorFlags;
1176
0
      this->AppendCompileOptions(wErrorFlags, *wErrorOpts);
1177
0
      if (!wErrorFlags.empty()) {
1178
0
        flags.emplace_back(std::move(wErrorFlags));
1179
0
      }
1180
0
    }
1181
0
  }
1182
1183
  // Add compile flag for the MSVC compiler only.
1184
0
  cmMakefile* mf = this->GetMakefile();
1185
0
  if (cmValue jmc =
1186
0
        mf->GetDefinition("CMAKE_" + lang + "_COMPILE_OPTIONS_JMC")) {
1187
1188
    // Handle Just My Code debugging flags, /JMC.
1189
    // If the target is a Managed C++ one, /JMC is not compatible.
1190
0
    if (target->GetManagedType(config) !=
1191
0
        cmGeneratorTarget::ManagedType::Managed) {
1192
      // add /JMC flags if target property VS_JUST_MY_CODE_DEBUGGING is set
1193
      // to ON
1194
0
      if (cmValue jmcExprGen =
1195
0
            target->GetProperty("VS_JUST_MY_CODE_DEBUGGING")) {
1196
0
        std::string isJMCEnabled =
1197
0
          cmGeneratorExpression::Evaluate(*jmcExprGen, this, config);
1198
0
        if (cmIsOn(isJMCEnabled)) {
1199
0
          cmList optList{ *jmc };
1200
0
          std::string jmcFlags;
1201
0
          this->AppendCompileOptions(jmcFlags, optList);
1202
0
          if (!jmcFlags.empty()) {
1203
0
            flags.emplace_back(std::move(jmcFlags));
1204
0
          }
1205
0
        }
1206
0
      }
1207
0
    }
1208
0
  }
1209
0
}
1210
1211
cmTarget* cmLocalGenerator::AddCustomCommandToTarget(
1212
  std::string const& target, cmCustomCommandType type,
1213
  std::unique_ptr<cmCustomCommand> cc, cmObjectLibraryCommands objLibCommands)
1214
0
{
1215
0
  cmTarget* t = this->Makefile->GetCustomCommandTarget(
1216
0
    target, objLibCommands, this->DirectoryBacktrace);
1217
0
  if (!t) {
1218
0
    return nullptr;
1219
0
  }
1220
1221
0
  cc->SetBacktrace(this->DirectoryBacktrace);
1222
1223
0
  detail::AddCustomCommandToTarget(*this, cmCommandOrigin::Generator, t, type,
1224
0
                                   std::move(cc));
1225
1226
0
  return t;
1227
0
}
1228
1229
cmSourceFile* cmLocalGenerator::AddCustomCommandToOutput(
1230
  std::unique_ptr<cmCustomCommand> cc, bool replace)
1231
0
{
1232
  // Make sure there is at least one output.
1233
0
  if (cc->GetOutputs().empty()) {
1234
0
    cmSystemTools::Error("Attempt to add a custom rule with no output!");
1235
0
    return nullptr;
1236
0
  }
1237
1238
0
  cc->SetBacktrace(this->DirectoryBacktrace);
1239
0
  return detail::AddCustomCommandToOutput(*this, cmCommandOrigin::Generator,
1240
0
                                          std::move(cc), replace);
1241
0
}
1242
1243
cmTarget* cmLocalGenerator::AddUtilityCommand(
1244
  std::string const& utilityName, bool excludeFromAll,
1245
  std::unique_ptr<cmCustomCommand> cc)
1246
0
{
1247
0
  cmTarget* target =
1248
0
    this->Makefile->AddNewUtilityTarget(utilityName, excludeFromAll);
1249
0
  target->SetIsGeneratorProvided(true);
1250
1251
0
  if (cc->GetCommandLines().empty() && cc->GetDepends().empty()) {
1252
0
    return target;
1253
0
  }
1254
1255
0
  cc->SetBacktrace(this->DirectoryBacktrace);
1256
0
  detail::AddUtilityCommand(*this, cmCommandOrigin::Generator, target,
1257
0
                            std::move(cc));
1258
1259
0
  return target;
1260
0
}
1261
1262
std::vector<BT<std::string>> cmLocalGenerator::GetIncludeDirectoriesImplicit(
1263
  cmGeneratorTarget const* target, std::string const& lang,
1264
  std::string const& config, bool stripImplicitDirs,
1265
  bool appendAllImplicitDirs) const
1266
0
{
1267
0
  std::vector<BT<std::string>> result;
1268
  // Do not repeat an include path.
1269
0
  std::set<std::string> emitted;
1270
1271
0
  auto emitDir = [&result, &emitted](std::string const& dir) {
1272
0
    if (emitted.insert(dir).second) {
1273
0
      result.emplace_back(dir);
1274
0
    }
1275
0
  };
1276
1277
0
  auto emitBT = [&result, &emitted](BT<std::string> const& dir) {
1278
0
    if (emitted.insert(dir.Value).second) {
1279
0
      result.emplace_back(dir);
1280
0
    }
1281
0
  };
1282
1283
  // When automatic include directories are requested for a build then
1284
  // include the source and binary directories at the beginning of the
1285
  // include path to approximate include file behavior for an
1286
  // in-source build.  This does not account for the case of a source
1287
  // file in a subdirectory of the current source directory but we
1288
  // cannot fix this because not all native build tools support
1289
  // per-source-file include paths.
1290
0
  if (this->Makefile->IsOn("CMAKE_INCLUDE_CURRENT_DIR")) {
1291
    // Current binary directory
1292
0
    emitDir(this->StateSnapshot.GetDirectory().GetCurrentBinary());
1293
    // Current source directory
1294
0
    emitDir(this->StateSnapshot.GetDirectory().GetCurrentSource());
1295
0
  }
1296
1297
0
  if (!target) {
1298
0
    return result;
1299
0
  }
1300
1301
  // Standard include directories to be added unconditionally at the end.
1302
  // These are intended to simulate additional implicit include directories.
1303
0
  cmList userStandardDirs;
1304
0
  {
1305
0
    std::string const value = this->Makefile->GetSafeDefinition(
1306
0
      cmStrCat("CMAKE_", lang, "_STANDARD_INCLUDE_DIRECTORIES"));
1307
0
    userStandardDirs.assign(value);
1308
0
    for (std::string& usd : userStandardDirs) {
1309
0
      cmSystemTools::ConvertToUnixSlashes(usd);
1310
0
    }
1311
0
  }
1312
1313
  // Implicit include directories
1314
0
  std::vector<std::string> implicitDirs;
1315
0
  std::set<std::string> implicitSet;
1316
  // Include directories to be excluded as if they were implicit.
1317
0
  std::set<std::string> implicitExclude;
1318
0
  {
1319
    // Raw list of implicit include directories
1320
    // Start with "standard" directories that we unconditionally add below.
1321
0
    std::vector<std::string> impDirVec = userStandardDirs;
1322
1323
    // Load implicit include directories for this language.
1324
    // We ignore this for Fortran because:
1325
    // * There are no standard library headers to avoid overriding.
1326
    // * Compilers like gfortran do not search their own implicit include
1327
    //   directories for modules ('.mod' files).
1328
0
    if (lang != "Fortran") {
1329
0
      size_t const impDirVecOldSize = impDirVec.size();
1330
0
      cmList::append(impDirVec,
1331
0
                     this->Makefile->GetDefinition(cmStrCat(
1332
0
                       "CMAKE_", lang, "_IMPLICIT_INCLUDE_DIRECTORIES")));
1333
      // FIXME: Use cmRange with 'advance()' when it supports non-const.
1334
0
      for (size_t i = impDirVecOldSize; i < impDirVec.size(); ++i) {
1335
0
        cmSystemTools::ConvertToUnixSlashes(impDirVec[i]);
1336
0
      }
1337
1338
      // The CMAKE_<LANG>_IMPLICIT_INCLUDE_DIRECTORIES are computed using
1339
      // try_compile in CMAKE_DETERMINE_COMPILER_ABI, but the implicit include
1340
      // directories are not known during that try_compile.  This can be a
1341
      // problem when the HIP runtime include path is /usr/include because the
1342
      // runtime include path is always added to the userDirs and the compiler
1343
      // includes standard library headers via "__clang_hip_runtime_wrapper.h".
1344
0
      if (lang == "HIP" && impDirVec.size() == impDirVecOldSize &&
1345
0
          !cm::contains(impDirVec, "/usr/include")) {
1346
0
        implicitExclude.emplace("/usr/include");
1347
0
      }
1348
0
    }
1349
1350
    // The Platform/UnixPaths module used to hard-code /usr/include for C, CXX,
1351
    // and CUDA in CMAKE_<LANG>_IMPLICIT_INCLUDE_DIRECTORIES, but those
1352
    // variables are now computed.  On macOS the /usr/include directory is
1353
    // inside the platform SDK so the computed value does not contain it
1354
    // directly.  In this case adding -I/usr/include can hide SDK headers so we
1355
    // must still exclude it.
1356
0
    if ((lang == "C" || lang == "CXX" || lang == "CUDA") &&
1357
0
        !cm::contains(impDirVec, "/usr/include") &&
1358
0
        std::find_if(impDirVec.begin(), impDirVec.end(),
1359
0
                     [](std::string const& d) {
1360
0
                       return cmHasLiteralSuffix(d, "/usr/include");
1361
0
                     }) != impDirVec.end()) {
1362
      // Only exclude this hard coded path for backwards compatibility.
1363
0
      implicitExclude.emplace("/usr/include");
1364
0
    }
1365
1366
0
    for (std::string const& i : impDirVec) {
1367
0
      if (implicitSet.insert(this->GlobalGenerator->GetRealPath(i)).second) {
1368
0
        implicitDirs.emplace_back(i);
1369
0
      }
1370
0
    }
1371
0
  }
1372
1373
0
  bool const isCorCxx = (lang == "C" || lang == "CXX");
1374
1375
  // Resolve symlinks in CPATH for comparison with resolved include paths.
1376
  // We do this here instead of when EnvCPATH is populated in case symlinks
1377
  // on disk have changed in the meantime.
1378
0
  std::set<std::string> resolvedEnvCPATH;
1379
0
  if (isCorCxx) {
1380
0
    for (std::string const& i : this->EnvCPATH) {
1381
0
      resolvedEnvCPATH.emplace(this->GlobalGenerator->GetRealPath(i));
1382
0
    }
1383
0
  }
1384
1385
  // Checks if this is not an excluded (implicit) include directory.
1386
0
  auto notExcluded = [this, &implicitSet, &implicitExclude, &resolvedEnvCPATH,
1387
0
                      isCorCxx](std::string const& dir) -> bool {
1388
0
    std::string const& real_dir = this->GlobalGenerator->GetRealPath(dir);
1389
0
    return
1390
      // Do not exclude directories that are not in any excluded set.
1391
0
      !(cm::contains(implicitSet, real_dir) ||
1392
0
        cm::contains(implicitExclude, dir))
1393
      // Do not exclude entries of the CPATH environment variable even though
1394
      // they are implicitly searched by the compiler.  They are meant to be
1395
      // user-specified directories that can be re-ordered or converted to
1396
      // -isystem without breaking real compiler builtin headers.
1397
0
      || (isCorCxx && cm::contains(resolvedEnvCPATH, real_dir));
1398
0
  };
1399
1400
  // Get the target-specific include directories.
1401
0
  std::vector<BT<std::string>> userDirs =
1402
0
    target->GetIncludeDirectories(config, lang);
1403
1404
  // Support putting all the in-project include directories first if
1405
  // it is requested by the project.
1406
0
  if (this->Makefile->IsOn("CMAKE_INCLUDE_DIRECTORIES_PROJECT_BEFORE")) {
1407
0
    std::string const& topSourceDir = this->GetState()->GetSourceDirectory();
1408
0
    std::string const& topBinaryDir = this->GetState()->GetBinaryDirectory();
1409
0
    for (BT<std::string> const& udr : userDirs) {
1410
      // Emit this directory only if it is a subdirectory of the
1411
      // top-level source or binary tree.
1412
0
      if (cmSystemTools::ComparePath(udr.Value, topSourceDir) ||
1413
0
          cmSystemTools::ComparePath(udr.Value, topBinaryDir) ||
1414
0
          cmSystemTools::IsSubDirectory(udr.Value, topSourceDir) ||
1415
0
          cmSystemTools::IsSubDirectory(udr.Value, topBinaryDir)) {
1416
0
        if (notExcluded(udr.Value)) {
1417
0
          emitBT(udr);
1418
0
        }
1419
0
      }
1420
0
    }
1421
0
  }
1422
1423
  // Emit remaining non implicit user directories.
1424
0
  for (BT<std::string> const& udr : userDirs) {
1425
0
    if (notExcluded(udr.Value)) {
1426
0
      emitBT(udr);
1427
0
    }
1428
0
  }
1429
1430
  // Sort result
1431
0
  MoveSystemIncludesToEnd(result, config, lang, target);
1432
1433
  // Append standard include directories for this language.
1434
0
  userDirs.reserve(userDirs.size() + userStandardDirs.size());
1435
0
  for (std::string& usd : userStandardDirs) {
1436
0
    emitDir(usd);
1437
0
    userDirs.emplace_back(std::move(usd));
1438
0
  }
1439
1440
  // Append compiler implicit include directories
1441
0
  if (!stripImplicitDirs) {
1442
    // Append implicit directories that were requested by the user only
1443
0
    for (BT<std::string> const& udr : userDirs) {
1444
0
      if (cm::contains(implicitSet, cmSystemTools::GetRealPath(udr.Value))) {
1445
0
        emitBT(udr);
1446
0
      }
1447
0
    }
1448
    // Append remaining implicit directories (on demand)
1449
0
    if (appendAllImplicitDirs) {
1450
0
      for (std::string& imd : implicitDirs) {
1451
0
        emitDir(imd);
1452
0
      }
1453
0
    }
1454
0
  }
1455
1456
0
  return result;
1457
0
}
1458
1459
void cmLocalGenerator::GetIncludeDirectoriesImplicit(
1460
  std::vector<std::string>& dirs, cmGeneratorTarget const* target,
1461
  std::string const& lang, std::string const& config, bool stripImplicitDirs,
1462
  bool appendAllImplicitDirs) const
1463
0
{
1464
0
  std::vector<BT<std::string>> tmp = this->GetIncludeDirectoriesImplicit(
1465
0
    target, lang, config, stripImplicitDirs, appendAllImplicitDirs);
1466
0
  dirs.reserve(dirs.size() + tmp.size());
1467
0
  for (BT<std::string>& v : tmp) {
1468
0
    dirs.emplace_back(std::move(v.Value));
1469
0
  }
1470
0
}
1471
1472
std::vector<BT<std::string>> cmLocalGenerator::GetIncludeDirectories(
1473
  cmGeneratorTarget const* target, std::string const& lang,
1474
  std::string const& config) const
1475
0
{
1476
0
  return this->GetIncludeDirectoriesImplicit(target, lang, config);
1477
0
}
1478
1479
void cmLocalGenerator::GetIncludeDirectories(std::vector<std::string>& dirs,
1480
                                             cmGeneratorTarget const* target,
1481
                                             std::string const& lang,
1482
                                             std::string const& config) const
1483
0
{
1484
0
  this->GetIncludeDirectoriesImplicit(dirs, target, lang, config);
1485
0
}
1486
1487
void cmLocalGenerator::GetStaticLibraryFlags(std::string& flags,
1488
                                             std::string const& config,
1489
                                             std::string const& linkLanguage,
1490
                                             cmGeneratorTarget* target)
1491
0
{
1492
0
  std::vector<BT<std::string>> tmpFlags =
1493
0
    this->GetStaticLibraryFlags(config, linkLanguage, target);
1494
0
  this->AppendFlags(flags, tmpFlags);
1495
0
}
1496
1497
std::vector<BT<std::string>> cmLocalGenerator::GetStaticLibraryFlags(
1498
  std::string const& config, std::string const& linkLanguage,
1499
  cmGeneratorTarget* target)
1500
0
{
1501
0
  std::vector<BT<std::string>> flags;
1502
0
  if (linkLanguage != "Swift" && !this->IsSplitSwiftBuild()) {
1503
0
    std::string staticLibFlags;
1504
0
    this->AddConfigVariableFlags(staticLibFlags, "CMAKE_STATIC_LINKER_FLAGS",
1505
0
                                 config);
1506
0
    if (!staticLibFlags.empty()) {
1507
0
      flags.emplace_back(std::move(staticLibFlags));
1508
0
    }
1509
0
  }
1510
1511
0
  std::string staticLibFlags;
1512
0
  std::string const configUpper = cmSystemTools::UpperCase(config);
1513
0
  this->AppendFlags(staticLibFlags,
1514
0
                    target->GetSafeProperty("STATIC_LIBRARY_FLAGS"));
1515
0
  if (!configUpper.empty()) {
1516
0
    std::string name = "STATIC_LIBRARY_FLAGS_" + configUpper;
1517
0
    this->AppendFlags(staticLibFlags, target->GetSafeProperty(name));
1518
0
  }
1519
1520
0
  if (!staticLibFlags.empty()) {
1521
0
    flags.emplace_back(std::move(staticLibFlags));
1522
0
  }
1523
1524
0
  std::vector<BT<std::string>> staticLibOpts =
1525
0
    target->GetStaticLibraryLinkOptions(config, linkLanguage);
1526
  // STATIC_LIBRARY_OPTIONS are escaped.
1527
0
  this->AppendCompileOptions(flags, staticLibOpts);
1528
1529
0
  return flags;
1530
0
}
1531
1532
void cmLocalGenerator::GetDeviceLinkFlags(
1533
  cmLinkLineDeviceComputer& linkLineComputer, std::string const& config,
1534
  std::string& linkLibs, std::string& linkFlags, std::string& frameworkPath,
1535
  std::string& linkPath, cmGeneratorTarget* target)
1536
0
{
1537
0
  cmGeneratorTarget::DeviceLinkSetter setter(*target);
1538
1539
0
  cmComputeLinkInformation* pcli = target->GetLinkInformation(config);
1540
1541
0
  auto linklang = linkLineComputer.GetLinkerLanguage(target, config);
1542
0
  auto ipoEnabled = target->IsIPOEnabled(linklang, config);
1543
0
  if (!ipoEnabled && pcli) {
1544
0
    ipoEnabled = linkLineComputer.ComputeRequiresDeviceLinkingIPOFlag(*pcli);
1545
0
  }
1546
0
  if (ipoEnabled) {
1547
0
    if (cmValue cudaIPOFlags = this->Makefile->GetDefinition(
1548
0
          "CMAKE_CUDA_DEVICE_LINK_OPTIONS_IPO")) {
1549
0
      linkFlags += *cudaIPOFlags;
1550
0
    }
1551
0
  }
1552
1553
0
  if (pcli) {
1554
    // Compute the required device link libraries when
1555
    // resolving gpu lang device symbols
1556
0
    this->OutputLinkLibraries(pcli, &linkLineComputer, linkLibs, frameworkPath,
1557
0
                              linkPath);
1558
0
  }
1559
1560
0
  this->AddVisibilityPresetFlags(linkFlags, target, "CUDA");
1561
0
  this->GetGlobalGenerator()->EncodeLiteral(linkFlags);
1562
1563
0
  std::vector<std::string> linkOpts;
1564
0
  target->GetLinkOptions(linkOpts, config, "CUDA");
1565
0
  this->SetLinkScriptShell(this->GetGlobalGenerator()->GetUseLinkScript());
1566
  // LINK_OPTIONS are escaped.
1567
0
  this->AppendCompileOptions(linkFlags, linkOpts);
1568
0
  this->SetLinkScriptShell(false);
1569
0
}
1570
1571
void cmLocalGenerator::GetTargetFlags(
1572
  cmLinkLineComputer* linkLineComputer, std::string const& config,
1573
  std::string& linkLibs, std::string& flags, std::string& linkFlags,
1574
  std::string& frameworkPath, std::string& linkPath, cmGeneratorTarget* target)
1575
0
{
1576
0
  std::vector<BT<std::string>> linkFlagsList;
1577
0
  std::vector<BT<std::string>> linkPathList;
1578
0
  std::vector<BT<std::string>> linkLibsList;
1579
0
  this->GetTargetFlags(linkLineComputer, config, linkLibsList, flags,
1580
0
                       linkFlagsList, frameworkPath, linkPathList, target);
1581
0
  this->AppendFlags(linkFlags, linkFlagsList);
1582
0
  this->AppendFlags(linkPath, linkPathList);
1583
0
  this->AppendFlags(linkLibs, linkLibsList);
1584
0
}
1585
1586
void cmLocalGenerator::GetTargetFlags(
1587
  cmLinkLineComputer* linkLineComputer, std::string const& config,
1588
  std::vector<BT<std::string>>& linkLibs, std::string& flags,
1589
  std::vector<BT<std::string>>& linkFlags, std::string& frameworkPath,
1590
  std::vector<BT<std::string>>& linkPath, cmGeneratorTarget* target)
1591
0
{
1592
0
  std::string const configUpper = cmSystemTools::UpperCase(config);
1593
0
  cmComputeLinkInformation* pcli = target->GetLinkInformation(config);
1594
1595
0
  std::string const linkLanguage =
1596
0
    linkLineComputer->GetLinkerLanguage(target, config);
1597
1598
0
  {
1599
0
    std::string createFlags;
1600
0
    this->AppendTargetCreationLinkFlags(createFlags, target, linkLanguage);
1601
0
    if (!createFlags.empty()) {
1602
0
      linkFlags.emplace_back(std::move(createFlags));
1603
0
    }
1604
0
  }
1605
1606
0
  switch (target->GetType()) {
1607
0
    case cm::TargetType::STATIC_LIBRARY:
1608
0
      linkFlags = this->GetStaticLibraryFlags(config, linkLanguage, target);
1609
0
      break;
1610
0
    case cm::TargetType::MODULE_LIBRARY:
1611
0
      CM_FALLTHROUGH;
1612
0
    case cm::TargetType::SHARED_LIBRARY: {
1613
0
      if (this->IsSplitSwiftBuild() || linkLanguage != "Swift") {
1614
0
        std::string libFlags;
1615
0
        this->AddTargetTypeLinkerFlags(libFlags, target, linkLanguage, config);
1616
0
        if (!libFlags.empty()) {
1617
0
          linkFlags.emplace_back(std::move(libFlags));
1618
0
        }
1619
0
      }
1620
1621
0
      std::string langLinkFlags;
1622
0
      this->AddPerLanguageLinkFlags(langLinkFlags, target, linkLanguage,
1623
0
                                    config);
1624
0
      if (!langLinkFlags.empty()) {
1625
0
        linkFlags.emplace_back(std::move(langLinkFlags));
1626
0
      }
1627
1628
0
      std::string sharedLibFlags;
1629
0
      this->AddTargetPropertyLinkFlags(sharedLibFlags, target, config);
1630
0
      if (!sharedLibFlags.empty()) {
1631
0
        this->GetGlobalGenerator()->EncodeLiteral(sharedLibFlags);
1632
0
        linkFlags.emplace_back(std::move(sharedLibFlags));
1633
0
      }
1634
1635
0
      std::vector<BT<std::string>> linkOpts =
1636
0
        target->GetLinkOptions(config, linkLanguage);
1637
0
      this->SetLinkScriptShell(this->GetGlobalGenerator()->GetUseLinkScript());
1638
      // LINK_OPTIONS are escaped.
1639
0
      this->AppendCompileOptions(linkFlags, linkOpts);
1640
0
      this->SetLinkScriptShell(false);
1641
1642
0
      if (pcli) {
1643
0
        this->OutputLinkLibraries(pcli, linkLineComputer, linkLibs,
1644
0
                                  frameworkPath, linkPath);
1645
0
      }
1646
0
    } break;
1647
0
    case cm::TargetType::EXECUTABLE: {
1648
0
      if (linkLanguage != "Swift" ||
1649
0
          (this->IsSplitSwiftBuild() &&
1650
0
           target->GetPolicyStatusCMP0214() == cmPolicies::NEW)) {
1651
0
        std::string exeFlags;
1652
0
        this->AddTargetTypeLinkerFlags(exeFlags, target, linkLanguage, config);
1653
0
        if (!exeFlags.empty()) {
1654
0
          linkFlags.emplace_back(std::move(exeFlags));
1655
0
        }
1656
0
      }
1657
1658
0
      std::string langLinkFlags;
1659
0
      this->AddPerLanguageLinkFlags(langLinkFlags, target, linkLanguage,
1660
0
                                    config);
1661
0
      if (!langLinkFlags.empty()) {
1662
0
        linkFlags.emplace_back(std::move(langLinkFlags));
1663
0
      }
1664
1665
0
      {
1666
0
        auto exeType = cmStrCat(
1667
0
          "CMAKE_", linkLanguage, "_CREATE_",
1668
0
          (target->IsWin32Executable(config) ? "WIN32" : "CONSOLE"), "_EXE");
1669
0
        std::string exeFlags;
1670
0
        this->AppendFlags(exeFlags, this->Makefile->GetDefinition(exeType),
1671
0
                          exeType, target, cmBuildStep::Link, linkLanguage);
1672
0
        if (!exeFlags.empty()) {
1673
0
          linkFlags.emplace_back(std::move(exeFlags));
1674
0
        }
1675
0
      }
1676
1677
0
      std::string exeFlags;
1678
0
      if (target->IsExecutableWithExports()) {
1679
0
        exeFlags += this->Makefile->GetSafeDefinition(
1680
0
          cmStrCat("CMAKE_EXE_EXPORTS_", linkLanguage, "_FLAG"));
1681
0
        exeFlags += " ";
1682
0
      }
1683
1684
0
      this->AddLanguageFlagsForLinking(flags, target, linkLanguage, config);
1685
0
      if (pcli) {
1686
0
        this->OutputLinkLibraries(pcli, linkLineComputer, linkLibs,
1687
0
                                  frameworkPath, linkPath);
1688
0
      }
1689
1690
0
      if (this->Makefile->IsOn("BUILD_SHARED_LIBS")) {
1691
0
        std::string sFlagVar = "CMAKE_SHARED_BUILD_" + linkLanguage + "_FLAGS";
1692
0
        exeFlags += this->Makefile->GetSafeDefinition(sFlagVar);
1693
0
        exeFlags += " ";
1694
0
      }
1695
1696
0
      std::string exeExportFlags =
1697
0
        this->GetExeExportFlags(linkLanguage, *target);
1698
0
      if (!exeExportFlags.empty()) {
1699
0
        exeFlags += exeExportFlags;
1700
0
        exeFlags += " ";
1701
0
      }
1702
1703
0
      this->AddTargetPropertyLinkFlags(exeFlags, target, config);
1704
1705
0
      if (!exeFlags.empty()) {
1706
0
        this->GetGlobalGenerator()->EncodeLiteral(exeFlags);
1707
0
        linkFlags.emplace_back(std::move(exeFlags));
1708
0
      }
1709
1710
0
      std::vector<BT<std::string>> linkOpts =
1711
0
        target->GetLinkOptions(config, linkLanguage);
1712
0
      this->SetLinkScriptShell(this->GetGlobalGenerator()->GetUseLinkScript());
1713
      // LINK_OPTIONS are escaped.
1714
0
      this->AppendCompileOptions(linkFlags, linkOpts);
1715
0
      this->SetLinkScriptShell(false);
1716
0
    } break;
1717
0
    default:
1718
0
      break;
1719
0
  }
1720
1721
0
  std::string extraLinkFlags;
1722
0
  this->AppendLinkerTypeFlags(extraLinkFlags, target, config, linkLanguage);
1723
0
  this->AppendPositionIndependentLinkerFlags(extraLinkFlags, target, config,
1724
0
                                             linkLanguage);
1725
0
  this->AppendWarningAsErrorLinkerFlags(extraLinkFlags, target, linkLanguage);
1726
0
  this->AppendIPOLinkerFlags(extraLinkFlags, target, config, linkLanguage);
1727
0
  this->AppendModuleDefinitionFlag(extraLinkFlags, target, linkLineComputer,
1728
0
                                   config, linkLanguage);
1729
1730
0
  if (!extraLinkFlags.empty()) {
1731
0
    this->GetGlobalGenerator()->EncodeLiteral(extraLinkFlags);
1732
0
    linkFlags.emplace_back(std::move(extraLinkFlags));
1733
0
  }
1734
0
}
1735
1736
void cmLocalGenerator::GetTargetCompileFlags(cmGeneratorTarget* target,
1737
                                             std::string const& config,
1738
                                             std::string const& lang,
1739
                                             std::string& flags,
1740
                                             std::string const& arch)
1741
0
{
1742
0
  std::vector<BT<std::string>> tmpFlags =
1743
0
    this->GetTargetCompileFlags(target, config, lang, arch);
1744
0
  this->AppendFlags(flags, tmpFlags);
1745
0
}
1746
1747
std::vector<BT<std::string>> cmLocalGenerator::GetTargetCompileFlags(
1748
  cmGeneratorTarget* target, std::string const& config,
1749
  std::string const& lang, std::string const& arch)
1750
0
{
1751
0
  std::vector<BT<std::string>> flags;
1752
0
  std::string compileFlags;
1753
1754
0
  cmMakefile* mf = this->GetMakefile();
1755
1756
  // Add language-specific flags.
1757
0
  this->AddLanguageFlags(compileFlags, target, cmBuildStep::Compile, lang,
1758
0
                         config);
1759
1760
0
  if (target->IsIPOEnabled(lang, config)) {
1761
0
    this->AppendFeatureOptions(compileFlags, lang, "IPO");
1762
0
  }
1763
1764
0
  this->AddArchitectureFlags(compileFlags, target, lang, config, arch);
1765
1766
0
  if (lang == "Fortran") {
1767
0
    this->AppendFlags(compileFlags,
1768
0
                      this->GetTargetFortranFlags(target, config));
1769
0
  } else if (lang == "Swift") {
1770
    // Only set the compile mode if CMP0157 is set
1771
0
    if (cm::optional<cmSwiftCompileMode> swiftCompileMode =
1772
0
          this->GetSwiftCompileMode(target, config)) {
1773
0
      std::string swiftCompileModeFlag;
1774
0
      switch (*swiftCompileMode) {
1775
0
        case cmSwiftCompileMode::Incremental: {
1776
0
          swiftCompileModeFlag = "-incremental";
1777
0
          if (cmValue flag =
1778
0
                mf->GetDefinition("CMAKE_Swift_COMPILE_OPTIONS_INCREMENTAL")) {
1779
0
            swiftCompileModeFlag = *flag;
1780
0
          }
1781
0
          break;
1782
0
        }
1783
0
        case cmSwiftCompileMode::Wholemodule: {
1784
0
          swiftCompileModeFlag = "-wmo";
1785
0
          if (cmValue flag =
1786
0
                mf->GetDefinition("CMAKE_Swift_COMPILE_OPTIONS_WMO")) {
1787
0
            swiftCompileModeFlag = *flag;
1788
0
          }
1789
0
          break;
1790
0
        }
1791
0
        case cmSwiftCompileMode::Singlefile:
1792
0
          break;
1793
0
        case cmSwiftCompileMode::Unknown: {
1794
0
          this->IssueDiagnostic(
1795
0
            cmDiagnostics::CMD_AUTHOR,
1796
0
            cmStrCat("Unknown Swift_COMPILATION_MODE on target '",
1797
0
                     target->GetName(), '\''));
1798
0
        }
1799
0
      }
1800
0
      this->AppendFlags(compileFlags, swiftCompileModeFlag);
1801
0
    }
1802
0
  }
1803
1804
0
  this->AddFeatureFlags(compileFlags, target, lang, config);
1805
0
  this->AddVisibilityPresetFlags(compileFlags, target, lang);
1806
0
  this->AddColorDiagnosticsFlags(compileFlags, lang);
1807
0
  this->AppendFlags(compileFlags, mf->GetDefineFlags());
1808
0
  this->AppendFlags(compileFlags,
1809
0
                    this->GetFrameworkFlags(lang, config, target));
1810
0
  this->AppendFlags(compileFlags,
1811
0
                    this->GetXcFrameworkFlags(lang, config, target));
1812
1813
0
  if (!compileFlags.empty()) {
1814
0
    flags.emplace_back(std::move(compileFlags));
1815
0
  }
1816
0
  this->AddCompileOptions(flags, target, lang, config);
1817
0
  return flags;
1818
0
}
1819
1820
std::string cmLocalGenerator::GetFrameworkFlags(std::string const& lang,
1821
                                                std::string const& config,
1822
                                                cmGeneratorTarget* target)
1823
0
{
1824
0
  cmLocalGenerator* lg = target->GetLocalGenerator();
1825
0
  cmMakefile* mf = lg->GetMakefile();
1826
1827
0
  if (!target->IsApple()) {
1828
0
    return std::string();
1829
0
  }
1830
1831
0
  cmValue fwSearchFlag =
1832
0
    mf->GetDefinition(cmStrCat("CMAKE_", lang, "_FRAMEWORK_SEARCH_FLAG"));
1833
0
  cmValue sysFwSearchFlag = mf->GetDefinition(
1834
0
    cmStrCat("CMAKE_", lang, "_SYSTEM_FRAMEWORK_SEARCH_FLAG"));
1835
1836
0
  if (!fwSearchFlag && !sysFwSearchFlag) {
1837
0
    return std::string{};
1838
0
  }
1839
1840
0
  std::set<std::string> emitted;
1841
#ifdef __APPLE__ /* don't insert this when crosscompiling e.g. to iphone */
1842
  emitted.insert("/System/Library/Frameworks");
1843
#endif
1844
0
  std::vector<std::string> includes;
1845
1846
0
  lg->GetIncludeDirectories(includes, target, "C", config);
1847
  // check all include directories for frameworks as this
1848
  // will already have added a -F for the framework
1849
0
  for (std::string const& include : includes) {
1850
0
    if (lg->GetGlobalGenerator()->NameResolvesToFramework(include)) {
1851
0
      std::string frameworkDir = cmStrCat(include, "/../");
1852
0
      frameworkDir = cmSystemTools::CollapseFullPath(frameworkDir);
1853
0
      emitted.insert(frameworkDir);
1854
0
    }
1855
0
  }
1856
1857
0
  std::string flags;
1858
0
  if (cmComputeLinkInformation* cli = target->GetLinkInformation(config)) {
1859
0
    std::vector<std::string> const& frameworks = cli->GetFrameworkPaths();
1860
0
    for (std::string const& framework : frameworks) {
1861
0
      if (emitted.insert(framework).second) {
1862
0
        if (sysFwSearchFlag &&
1863
0
            target->IsSystemIncludeDirectory(framework, config, lang)) {
1864
0
          flags += *sysFwSearchFlag;
1865
0
        } else {
1866
0
          flags += *fwSearchFlag;
1867
0
        }
1868
0
        flags +=
1869
0
          lg->ConvertToOutputFormat(framework, cmOutputConverter::SHELL);
1870
0
        flags += " ";
1871
0
      }
1872
0
    }
1873
0
  }
1874
0
  return flags;
1875
0
}
1876
1877
std::string cmLocalGenerator::GetXcFrameworkFlags(std::string const& lang,
1878
                                                  std::string const& config,
1879
                                                  cmGeneratorTarget* target)
1880
0
{
1881
0
  cmLocalGenerator* lg = target->GetLocalGenerator();
1882
0
  cmMakefile* mf = lg->GetMakefile();
1883
1884
0
  if (!target->IsApple()) {
1885
0
    return std::string();
1886
0
  }
1887
1888
0
  cmValue includeSearchFlag =
1889
0
    mf->GetDefinition(cmStrCat("CMAKE_INCLUDE_FLAG_", lang));
1890
0
  cmValue sysIncludeSearchFlag =
1891
0
    mf->GetDefinition(cmStrCat("CMAKE_INCLUDE_SYSTEM_FLAG_", lang));
1892
1893
0
  if (!includeSearchFlag && !sysIncludeSearchFlag) {
1894
0
    return std::string{};
1895
0
  }
1896
1897
0
  std::string flags;
1898
0
  if (cmComputeLinkInformation* cli = target->GetLinkInformation(config)) {
1899
0
    std::vector<std::string> const& paths = cli->GetXcFrameworkHeaderPaths();
1900
0
    for (std::string const& path : paths) {
1901
0
      if (sysIncludeSearchFlag &&
1902
0
          target->IsSystemIncludeDirectory(path, config, lang)) {
1903
0
        flags += *sysIncludeSearchFlag;
1904
0
      } else {
1905
0
        flags += *includeSearchFlag;
1906
0
      }
1907
0
      flags += lg->ConvertToOutputFormat(path, cmOutputConverter::SHELL);
1908
0
      flags += " ";
1909
0
    }
1910
0
  }
1911
0
  return flags;
1912
0
}
1913
1914
void cmLocalGenerator::GetTargetDefines(cmGeneratorTarget const* target,
1915
                                        std::string const& config,
1916
                                        std::string const& lang,
1917
                                        std::set<std::string>& defines) const
1918
0
{
1919
0
  std::set<BT<std::string>> tmp = this->GetTargetDefines(target, config, lang);
1920
0
  for (BT<std::string> const& v : tmp) {
1921
0
    defines.emplace(v.Value);
1922
0
  }
1923
0
}
1924
1925
std::set<BT<std::string>> cmLocalGenerator::GetTargetDefines(
1926
  cmGeneratorTarget const* target, std::string const& config,
1927
  std::string const& lang) const
1928
0
{
1929
0
  std::set<BT<std::string>> defines;
1930
1931
  // Add the export symbol definition for shared library objects.
1932
0
  if (std::string const* exportMacro = target->GetExportMacro()) {
1933
0
    this->AppendDefines(defines, *exportMacro);
1934
0
  }
1935
0
  for (auto const& sharedLibCompileDef :
1936
0
       target->GetSharedLibraryCompileDefs(config)) {
1937
0
    this->AppendDefines(defines, sharedLibCompileDef);
1938
0
  }
1939
1940
  // Add preprocessor definitions for this target and configuration.
1941
0
  std::vector<BT<std::string>> targetDefines =
1942
0
    target->GetCompileDefinitions(config, lang);
1943
0
  this->AppendDefines(defines, targetDefines);
1944
1945
0
  return defines;
1946
0
}
1947
1948
std::string cmLocalGenerator::GetTargetFortranFlags(
1949
  cmGeneratorTarget const* /*unused*/, std::string const& /*unused*/)
1950
0
{
1951
  // Implemented by specific generators that override this.
1952
0
  return std::string();
1953
0
}
1954
1955
/**
1956
 * Output the linking rules on a command line.  For executables,
1957
 * targetLibrary should be a NULL pointer.  For libraries, it should point
1958
 * to the name of the library.  This will not link a library against itself.
1959
 */
1960
void cmLocalGenerator::OutputLinkLibraries(
1961
  cmComputeLinkInformation* pcli, cmLinkLineComputer* linkLineComputer,
1962
  std::string& linkLibraries, std::string& frameworkPath,
1963
  std::string& linkPath)
1964
0
{
1965
0
  std::vector<BT<std::string>> linkLibrariesList;
1966
0
  std::vector<BT<std::string>> linkPathList;
1967
0
  this->OutputLinkLibraries(pcli, linkLineComputer, linkLibrariesList,
1968
0
                            frameworkPath, linkPathList);
1969
0
  pcli->AppendValues(linkLibraries, linkLibrariesList);
1970
0
  pcli->AppendValues(linkPath, linkPathList);
1971
0
}
1972
1973
void cmLocalGenerator::OutputLinkLibraries(
1974
  cmComputeLinkInformation* pcli, cmLinkLineComputer* linkLineComputer,
1975
  std::vector<BT<std::string>>& linkLibraries, std::string& frameworkPath,
1976
  std::vector<BT<std::string>>& linkPath)
1977
0
{
1978
0
  cmComputeLinkInformation& cli = *pcli;
1979
1980
0
  std::string linkLanguage = cli.GetLinkLanguage();
1981
1982
0
  std::string libPathFlag;
1983
0
  if (cmValue value = this->Makefile->GetDefinition(
1984
0
        "CMAKE_" + cli.GetLinkLanguage() + "_LIBRARY_PATH_FLAG")) {
1985
0
    libPathFlag = *value;
1986
0
  } else {
1987
0
    libPathFlag =
1988
0
      this->Makefile->GetRequiredDefinition("CMAKE_LIBRARY_PATH_FLAG");
1989
0
  }
1990
1991
0
  std::string libPathTerminator;
1992
0
  if (cmValue value = this->Makefile->GetDefinition(
1993
0
        "CMAKE_" + cli.GetLinkLanguage() + "_LIBRARY_PATH_TERMINATOR")) {
1994
0
    libPathTerminator = *value;
1995
0
  } else {
1996
0
    libPathTerminator =
1997
0
      this->Makefile->GetRequiredDefinition("CMAKE_LIBRARY_PATH_TERMINATOR");
1998
0
  }
1999
2000
  // Add standard link directories for this language
2001
0
  std::string stdLinkDirString = this->Makefile->GetSafeDefinition(
2002
0
    cmStrCat("CMAKE_", cli.GetLinkLanguage(), "_STANDARD_LINK_DIRECTORIES"));
2003
2004
  // Add standard libraries for this language.
2005
0
  std::string stdLibString = this->Makefile->GetSafeDefinition(
2006
0
    cmStrCat("CMAKE_", cli.GetLinkLanguage(), "_STANDARD_LIBRARIES"));
2007
2008
  // Append the framework search path flags.
2009
0
  cmValue fwSearchFlag = this->Makefile->GetDefinition(
2010
0
    cmStrCat("CMAKE_", linkLanguage, "_FRAMEWORK_SEARCH_FLAG"));
2011
2012
0
  frameworkPath = linkLineComputer->ComputeFrameworkPath(cli, fwSearchFlag);
2013
0
  linkLineComputer->ComputeLinkPath(cli, libPathFlag, libPathTerminator,
2014
0
                                    stdLinkDirString, linkPath);
2015
0
  linkLineComputer->ComputeLinkLibraries(cli, stdLibString, linkLibraries);
2016
0
}
2017
2018
std::string cmLocalGenerator::GetExeExportFlags(
2019
  std::string const& linkLanguage, cmGeneratorTarget& tgt) const
2020
0
{
2021
0
  std::string linkFlags;
2022
2023
  // Flags to export symbols from an executable.
2024
0
  if (tgt.GetType() == cm::TargetType::EXECUTABLE &&
2025
0
      this->StateSnapshot.GetState()->GetGlobalPropertyAsBool(
2026
0
        "TARGET_SUPPORTS_SHARED_LIBS")) {
2027
    // Only add the flags if ENABLE_EXPORTS is on,
2028
    // except on AIX where we compute symbol exports.
2029
0
    if (!tgt.IsAIX() && tgt.GetPropertyAsBool("ENABLE_EXPORTS")) {
2030
0
      linkFlags = this->Makefile->GetSafeDefinition(
2031
0
        cmStrCat("CMAKE_SHARED_LIBRARY_LINK_", linkLanguage, "_FLAGS"));
2032
0
    }
2033
0
  }
2034
0
  return linkFlags;
2035
0
}
2036
2037
bool cmLocalGenerator::AllAppleArchSysrootsAreTheSame(
2038
  std::vector<std::string> const& archs, cmValue sysroot)
2039
0
{
2040
0
  if (!sysroot) {
2041
0
    return false;
2042
0
  }
2043
2044
0
  return std::all_of(archs.begin(), archs.end(),
2045
0
                     [this, sysroot](std::string const& arch) -> bool {
2046
0
                       std::string const& archSysroot =
2047
0
                         this->AppleArchSysroots[arch];
2048
0
                       return cmIsOff(archSysroot) || *sysroot == archSysroot;
2049
0
                     });
2050
0
}
2051
2052
void cmLocalGenerator::AddArchitectureFlags(std::string& flags,
2053
                                            cmGeneratorTarget const* target,
2054
                                            std::string const& lang,
2055
                                            std::string const& config,
2056
                                            std::string const& filterArch)
2057
0
{
2058
  // Only add Apple specific flags on Apple platforms
2059
0
  if (target->IsApple() && this->EmitUniversalBinaryFlags) {
2060
0
    std::vector<std::string> archs = target->GetAppleArchs(config, lang);
2061
0
    if (!archs.empty() &&
2062
0
        (lang == "C" || lang == "CXX" || lang == "OBJC" || lang == "OBJCXX" ||
2063
0
         lang == "ASM")) {
2064
0
      for (std::string const& arch : archs) {
2065
0
        if (filterArch.empty() || filterArch == arch) {
2066
0
          flags += " -arch ";
2067
0
          flags += arch;
2068
0
        }
2069
0
      }
2070
0
    }
2071
2072
0
    cmValue sysroot = this->Makefile->GetDefinition("CMAKE_OSX_SYSROOT");
2073
0
    if (sysroot.IsEmpty() &&
2074
0
        this->Makefile->IsOn(
2075
0
          cmStrCat("CMAKE_", lang, "_COMPILER_APPLE_SYSROOT_REQUIRED"))) {
2076
0
      sysroot = this->Makefile->GetDefinition("_CMAKE_OSX_SYSROOT_PATH");
2077
0
    }
2078
0
    if (sysroot && *sysroot == "/") {
2079
0
      sysroot = nullptr;
2080
0
    }
2081
0
    std::string sysrootFlagVar = "CMAKE_" + lang + "_SYSROOT_FLAG";
2082
0
    cmValue sysrootFlag = this->Makefile->GetDefinition(sysrootFlagVar);
2083
0
    if (cmNonempty(sysrootFlag)) {
2084
0
      if (!this->AppleArchSysroots.empty() &&
2085
0
          !this->AllAppleArchSysrootsAreTheSame(archs, sysroot)) {
2086
0
        for (std::string const& arch : archs) {
2087
0
          std::string const& archSysroot = this->AppleArchSysroots[arch];
2088
0
          if (cmIsOff(archSysroot)) {
2089
0
            continue;
2090
0
          }
2091
0
          if (filterArch.empty() || filterArch == arch) {
2092
0
            flags += " -Xarch_" + arch + " ";
2093
            // Combine sysroot flag and path to work with -Xarch
2094
0
            std::string arch_sysroot = *sysrootFlag + archSysroot;
2095
0
            flags += this->ConvertToOutputFormat(arch_sysroot, SHELL);
2096
0
          }
2097
0
        }
2098
0
      } else if (cmNonempty(sysroot)) {
2099
0
        flags += " ";
2100
0
        flags += *sysrootFlag;
2101
0
        flags += " ";
2102
0
        flags += this->ConvertToOutputFormat(*sysroot, SHELL);
2103
0
      }
2104
0
    }
2105
2106
0
    cmValue deploymentTarget =
2107
0
      this->Makefile->GetDefinition("CMAKE_OSX_DEPLOYMENT_TARGET");
2108
0
    if (cmNonempty(deploymentTarget)) {
2109
0
      std::string deploymentTargetFlagVar =
2110
0
        "CMAKE_" + lang + "_OSX_DEPLOYMENT_TARGET_FLAG";
2111
0
      cmValue deploymentTargetFlag =
2112
0
        this->Makefile->GetDefinition(deploymentTargetFlagVar);
2113
0
      if (cmNonempty(deploymentTargetFlag) &&
2114
          // CMAKE_<LANG>_COMPILER_TARGET overrides a --target= for
2115
          // CMAKE_OSX_DEPLOYMENT_TARGET, e.g., for visionOS.
2116
0
          (!cmHasLiteralPrefix(*deploymentTarget, "--target=") ||
2117
0
           this->Makefile
2118
0
             ->GetDefinition(cmStrCat("CMAKE_", lang, "_COMPILER_TARGET"))
2119
0
             .IsEmpty())) {
2120
0
        std::string flag = *deploymentTargetFlag;
2121
2122
        // Add the deployment target architecture to the flag, if needed.
2123
0
        static std::string const kARCH = "<ARCH>";
2124
0
        std::string::size_type archPos = flag.find(kARCH);
2125
0
        if (archPos != std::string::npos) {
2126
          // This placeholder is meant for visionOS, so default to arm64
2127
          // unless only non-arm64 archs are given.
2128
0
          std::string const arch =
2129
0
            (archs.empty() || cm::contains(archs, "arm64")) ? "arm64"
2130
0
                                                            : archs[0];
2131
          // Replace the placeholder with its value.
2132
0
          flag = cmStrCat(flag.substr(0, archPos), arch,
2133
0
                          flag.substr(archPos + kARCH.size()));
2134
0
        }
2135
2136
        // Add the deployment target version to the flag.
2137
0
        static std::string const kVERSION_MIN = "<VERSION_MIN>";
2138
0
        std::string::size_type verPos = flag.find(kVERSION_MIN);
2139
0
        if (verPos != std::string::npos) {
2140
          // Replace the placeholder with its value.
2141
0
          flag = cmStrCat(flag.substr(0, verPos), *deploymentTarget,
2142
0
                          flag.substr(verPos + kVERSION_MIN.size()));
2143
0
        } else {
2144
          // There is no placeholder, so append the value.
2145
0
          flag = cmStrCat(flag, *deploymentTarget);
2146
0
        }
2147
2148
0
        flags += " ";
2149
0
        flags += flag;
2150
0
      }
2151
0
    }
2152
0
  }
2153
0
}
2154
2155
void cmLocalGenerator::AddLanguageFlags(std::string& flags,
2156
                                        cmGeneratorTarget const* target,
2157
                                        cmBuildStep compileOrLink,
2158
                                        std::string const& lang,
2159
                                        std::string const& config)
2160
0
{
2161
  // Add language-specific flags.
2162
0
  this->AddConfigVariableFlags(flags, cmStrCat("CMAKE_", lang, "_FLAGS"),
2163
0
                               config);
2164
2165
  // Add the language standard flag for compiling, and sometimes linking.
2166
0
  if (compileOrLink == cmBuildStep::Compile ||
2167
0
      (compileOrLink == cmBuildStep::Link &&
2168
       // Some toolchains require use of the language standard flag
2169
       // when linking in order to use the matching standard library.
2170
       // FIXME: If CMake gains an abstraction for standard library
2171
       // selection, this will have to be reconciled with it.
2172
0
       this->Makefile->IsOn(
2173
0
         cmStrCat("CMAKE_", lang, "_LINK_WITH_STANDARD_COMPILE_OPTION")))) {
2174
0
    cmStandardLevelResolver standardResolver(this->Makefile);
2175
0
    std::string const& optionFlagDef =
2176
0
      standardResolver.GetCompileOptionDef(target, lang, config);
2177
0
    if (!optionFlagDef.empty()) {
2178
0
      cmValue opt =
2179
0
        target->Target->GetMakefile()->GetDefinition(optionFlagDef);
2180
0
      if (opt) {
2181
0
        cmList optList{ *opt };
2182
0
        for (std::string const& i : optList) {
2183
0
          this->AppendFlagEscape(flags, i);
2184
0
        }
2185
0
      }
2186
0
    }
2187
0
  }
2188
2189
0
  std::string compilerId = this->Makefile->GetSafeDefinition(
2190
0
    cmStrCat("CMAKE_", lang, "_COMPILER_ID"));
2191
2192
0
  std::string compilerSimulateId = this->Makefile->GetSafeDefinition(
2193
0
    cmStrCat("CMAKE_", lang, "_SIMULATE_ID"));
2194
2195
0
  bool const compilerTargetsMsvcABI =
2196
0
    (compilerId == "MSVC" || compilerSimulateId == "MSVC");
2197
0
  bool const compilerTargetsWatcomABI =
2198
0
    (compilerId == "OpenWatcom" || compilerSimulateId == "OpenWatcom");
2199
2200
0
  if (lang == "Swift") {
2201
0
    target->AddSwiftTargetFlags(flags);
2202
0
  } else if (lang == "CUDA") {
2203
0
    target->AddCUDAArchitectureFlags(compileOrLink, config, flags);
2204
0
    target->AddCUDAToolkitFlags(flags);
2205
0
  } else if (lang == "ISPC") {
2206
0
    target->AddISPCTargetFlags(flags);
2207
0
  } else if (lang == "RC" &&
2208
0
             this->Makefile->GetSafeDefinition("CMAKE_RC_COMPILER")
2209
0
                 .find("llvm-rc") != std::string::npos) {
2210
0
    compilerId = this->Makefile->GetSafeDefinition("CMAKE_C_COMPILER_ID");
2211
0
    if (!compilerId.empty()) {
2212
0
      compilerSimulateId =
2213
0
        this->Makefile->GetSafeDefinition("CMAKE_C_SIMULATE_ID");
2214
0
    } else {
2215
0
      compilerId = this->Makefile->GetSafeDefinition("CMAKE_CXX_COMPILER_ID");
2216
0
      compilerSimulateId =
2217
0
        this->Makefile->GetSafeDefinition("CMAKE_CXX_SIMULATE_ID");
2218
0
    }
2219
0
  } else if (lang == "HIP") {
2220
0
    target->AddHIPArchitectureFlags(compileOrLink, config, flags);
2221
0
  } else if (lang == "Rust") {
2222
0
    target->AddRustTargetFlags(flags);
2223
0
  }
2224
2225
  // Add VFS Overlay for Clang compilers
2226
0
  if (compilerId == "Clang") {
2227
0
    if (cmValue vfsOverlay =
2228
0
          this->Makefile->GetDefinition("CMAKE_CLANG_VFS_OVERLAY")) {
2229
0
      if (compilerSimulateId == "MSVC") {
2230
0
        this->AppendCompileOptions(
2231
0
          flags,
2232
0
          std::vector<std::string>{ "-Xclang", "-ivfsoverlay", "-Xclang",
2233
0
                                    *vfsOverlay });
2234
0
      } else {
2235
0
        this->AppendCompileOptions(
2236
0
          flags, std::vector<std::string>{ "-ivfsoverlay", *vfsOverlay });
2237
0
      }
2238
0
    }
2239
0
  }
2240
  // Add MSVC runtime library flags.  This is activated by the presence
2241
  // of a default selection whether or not it is overridden by a property.
2242
0
  cmValue msvcRuntimeLibraryDefault =
2243
0
    this->Makefile->GetDefinition("CMAKE_MSVC_RUNTIME_LIBRARY_DEFAULT");
2244
0
  if (cmNonempty(msvcRuntimeLibraryDefault)) {
2245
0
    cmValue msvcRuntimeLibraryValue =
2246
0
      target->GetProperty("MSVC_RUNTIME_LIBRARY");
2247
0
    if (!msvcRuntimeLibraryValue) {
2248
0
      msvcRuntimeLibraryValue = msvcRuntimeLibraryDefault;
2249
0
    }
2250
0
    std::string const msvcRuntimeLibrary = cmGeneratorExpression::Evaluate(
2251
0
      *msvcRuntimeLibraryValue, this, config, target);
2252
0
    if (!msvcRuntimeLibrary.empty()) {
2253
0
      if (cmValue msvcRuntimeLibraryOptions = this->Makefile->GetDefinition(
2254
0
            "CMAKE_" + lang + "_COMPILE_OPTIONS_MSVC_RUNTIME_LIBRARY_" +
2255
0
            msvcRuntimeLibrary)) {
2256
0
        this->AppendCompileOptions(flags, *msvcRuntimeLibraryOptions);
2257
0
      } else if (compilerTargetsMsvcABI &&
2258
0
                 !cmSystemTools::GetErrorOccurredFlag()) {
2259
        // The compiler uses the MSVC ABI so it needs a known runtime library.
2260
0
        this->IssueMessage(MessageType::FATAL_ERROR,
2261
0
                           "MSVC_RUNTIME_LIBRARY value '" +
2262
0
                             msvcRuntimeLibrary + "' not known for this " +
2263
0
                             lang + " compiler.");
2264
0
      }
2265
0
    }
2266
0
  }
2267
2268
  // Add Watcom runtime library flags.  This is activated by the presence
2269
  // of a default selection whether or not it is overridden by a property.
2270
0
  cmValue watcomRuntimeLibraryDefault =
2271
0
    this->Makefile->GetDefinition("CMAKE_WATCOM_RUNTIME_LIBRARY_DEFAULT");
2272
0
  if (cmNonempty(watcomRuntimeLibraryDefault)) {
2273
0
    cmValue watcomRuntimeLibraryValue =
2274
0
      target->GetProperty("WATCOM_RUNTIME_LIBRARY");
2275
0
    if (!watcomRuntimeLibraryValue) {
2276
0
      watcomRuntimeLibraryValue = watcomRuntimeLibraryDefault;
2277
0
    }
2278
0
    std::string const watcomRuntimeLibrary = cmGeneratorExpression::Evaluate(
2279
0
      *watcomRuntimeLibraryValue, this, config, target);
2280
0
    if (!watcomRuntimeLibrary.empty()) {
2281
0
      if (cmValue watcomRuntimeLibraryOptions = this->Makefile->GetDefinition(
2282
0
            "CMAKE_" + lang + "_COMPILE_OPTIONS_WATCOM_RUNTIME_LIBRARY_" +
2283
0
            watcomRuntimeLibrary)) {
2284
0
        this->AppendCompileOptions(flags, *watcomRuntimeLibraryOptions);
2285
0
      } else if (compilerTargetsWatcomABI &&
2286
0
                 !cmSystemTools::GetErrorOccurredFlag()) {
2287
        // The compiler uses the Watcom ABI so it needs a known runtime
2288
        // library.
2289
0
        this->IssueMessage(MessageType::FATAL_ERROR,
2290
0
                           "WATCOM_RUNTIME_LIBRARY value '" +
2291
0
                             watcomRuntimeLibrary + "' not known for this " +
2292
0
                             lang + " compiler.");
2293
0
      }
2294
0
    }
2295
0
  }
2296
2297
  // Add MSVC runtime checks flags. This is activated by the presence
2298
  // of a default selection whether or not it is overridden by a property.
2299
0
  cmValue msvcRuntimeChecksDefault =
2300
0
    this->Makefile->GetDefinition("CMAKE_MSVC_RUNTIME_CHECKS_DEFAULT");
2301
0
  if (cmNonempty(msvcRuntimeChecksDefault)) {
2302
0
    cmValue msvcRuntimeChecksValue =
2303
0
      target->GetProperty("MSVC_RUNTIME_CHECKS");
2304
0
    if (!msvcRuntimeChecksValue) {
2305
0
      msvcRuntimeChecksValue = msvcRuntimeChecksDefault;
2306
0
    }
2307
0
    cmList msvcRuntimeChecksList = cmGeneratorExpression::Evaluate(
2308
0
      *msvcRuntimeChecksValue, this, config, target);
2309
0
    msvcRuntimeChecksList.remove_duplicates();
2310
2311
    // RTC1/RTCsu VS GUI workaround
2312
0
    std::string const stackFrameErrorCheck = "StackFrameErrorCheck";
2313
0
    std::string const unitinitializedVariable = "UninitializedVariable";
2314
0
    std::string const rtcSU = "RTCsu";
2315
0
    if ((cm::contains(msvcRuntimeChecksList, stackFrameErrorCheck) &&
2316
0
         cm::contains(msvcRuntimeChecksList, unitinitializedVariable)) ||
2317
0
        cm::contains(msvcRuntimeChecksList, rtcSU)) {
2318
0
      msvcRuntimeChecksList.remove_items(
2319
0
        { stackFrameErrorCheck, unitinitializedVariable, rtcSU });
2320
0
      msvcRuntimeChecksList.append(rtcSU);
2321
0
    }
2322
2323
0
    for (std::string const& msvcRuntimeChecks : msvcRuntimeChecksList) {
2324
0
      if (cmValue msvcRuntimeChecksOptions =
2325
0
            this->Makefile->GetDefinition(cmStrCat(
2326
0
              "CMAKE_", lang,
2327
0
              "_COMPILE_OPTIONS_MSVC_RUNTIME_CHECKS_" + msvcRuntimeChecks))) {
2328
0
        this->AppendCompileOptions(flags, *msvcRuntimeChecksOptions);
2329
0
      } else if (compilerTargetsMsvcABI &&
2330
0
                 !cmSystemTools::GetErrorOccurredFlag()) {
2331
        // The compiler uses the MSVC ABI so it needs a known runtime checks.
2332
0
        this->IssueMessage(MessageType::FATAL_ERROR,
2333
0
                           cmStrCat("MSVC_RUNTIME_CHECKS value '",
2334
0
                                    msvcRuntimeChecks, "' not known for this ",
2335
0
                                    lang, " compiler."));
2336
0
      }
2337
0
    }
2338
0
  }
2339
2340
  // Add MSVC debug information format flags if CMP0141 is NEW.
2341
0
  if (cm::optional<std::string> msvcDebugInformationFormat =
2342
0
        this->GetMSVCDebugFormatName(config, target)) {
2343
0
    if (!msvcDebugInformationFormat->empty()) {
2344
0
      if (cmValue msvcDebugInformationFormatOptions =
2345
0
            this->Makefile->GetDefinition(
2346
0
              cmStrCat("CMAKE_", lang,
2347
0
                       "_COMPILE_OPTIONS_MSVC_DEBUG_INFORMATION_FORMAT_",
2348
0
                       *msvcDebugInformationFormat))) {
2349
0
        this->AppendCompileOptions(flags, *msvcDebugInformationFormatOptions);
2350
0
      } else if (compilerTargetsMsvcABI &&
2351
0
                 !cmSystemTools::GetErrorOccurredFlag()) {
2352
        // The compiler uses the MSVC ABI so it needs a known runtime library.
2353
0
        this->IssueMessage(MessageType::FATAL_ERROR,
2354
0
                           cmStrCat("MSVC_DEBUG_INFORMATION_FORMAT value '",
2355
0
                                    *msvcDebugInformationFormat,
2356
0
                                    "' not known for this ", lang,
2357
0
                                    " compiler."));
2358
0
      }
2359
0
    }
2360
0
  }
2361
0
}
2362
2363
void cmLocalGenerator::AddLanguageFlagsForLinking(
2364
  std::string& flags, cmGeneratorTarget const* target, std::string const& lang,
2365
  std::string const& config)
2366
0
{
2367
0
  this->AddLanguageFlags(flags, target, cmBuildStep::Link, lang, config);
2368
2369
0
  if (target->IsIPOEnabled(lang, config)) {
2370
0
    this->AppendFeatureOptions(flags, lang, "IPO");
2371
0
  }
2372
0
}
2373
2374
cmGeneratorTarget* cmLocalGenerator::FindGeneratorTargetToUse(
2375
  std::string const& name) const
2376
0
{
2377
0
  auto imported = this->ImportedGeneratorTargets.find(name);
2378
0
  if (imported != this->ImportedGeneratorTargets.end()) {
2379
0
    return imported->second;
2380
0
  }
2381
2382
  // find local alias to imported target
2383
0
  auto aliased = this->AliasTargets.find(name);
2384
0
  if (aliased != this->AliasTargets.end()) {
2385
0
    imported = this->ImportedGeneratorTargets.find(aliased->second);
2386
0
    if (imported != this->ImportedGeneratorTargets.end()) {
2387
0
      return imported->second;
2388
0
    }
2389
0
  }
2390
2391
0
  if (cmGeneratorTarget* t = this->FindLocalNonAliasGeneratorTarget(name)) {
2392
0
    return t;
2393
0
  }
2394
2395
0
  return this->GetGlobalGenerator()->FindGeneratorTarget(name);
2396
0
}
2397
2398
bool cmLocalGenerator::GetRealDependency(std::string const& inName,
2399
                                         std::string const& config,
2400
                                         std::string& dep,
2401
                                         cmPolicies::PolicyStatus cmp0212)
2402
0
{
2403
  // Older CMake code may specify the dependency using the target
2404
  // output file rather than the target name.  Such code would have
2405
  // been written before there was support for target properties that
2406
  // modify the name so stripping down to just the file name should
2407
  // produce the target name in this case.
2408
0
  std::string name = cmSystemTools::GetFilenameName(inName);
2409
2410
  // If the input name is the empty string, there is no real
2411
  // dependency. Short-circuit the other checks:
2412
0
  if (name.empty()) {
2413
0
    return false;
2414
0
  }
2415
2416
  // Look for a CMake target with the given name.
2417
0
  cmGeneratorTarget* target = this->FindGeneratorTargetToUse(name);
2418
0
  if (!target && cmHasSuffix(name, ".exe"_s) && cmp0212 != cmPolicies::NEW) {
2419
    // If it doesn't exist, try to strip the `.exe` suffix per CMP0212.
2420
0
    std::string strippedName =
2421
0
      cmSystemTools::GetFilenameWithoutLastExtension(name);
2422
0
    if (cmGeneratorTarget* strippedTarget =
2423
0
          this->FindGeneratorTargetToUse(strippedName)) {
2424
0
      name = strippedName;
2425
0
      target = strippedTarget;
2426
0
    }
2427
0
  }
2428
2429
0
  if (target) {
2430
    // make sure it is not just a coincidence that the target name
2431
    // found is part of the inName
2432
0
    if (cmSystemTools::FileIsFullPath(inName)) {
2433
0
      std::string tLocation;
2434
0
      if (target->GetType() >= cm::TargetType::EXECUTABLE &&
2435
0
          target->GetType() <= cm::TargetType::MODULE_LIBRARY) {
2436
0
        tLocation = target->GetLocation(config);
2437
0
        tLocation = cmSystemTools::GetFilenamePath(tLocation);
2438
0
        tLocation = cmSystemTools::CollapseFullPath(tLocation);
2439
0
      }
2440
0
      std::string depLocation =
2441
0
        cmSystemTools::GetFilenamePath(std::string(inName));
2442
0
      depLocation = cmSystemTools::CollapseFullPath(depLocation);
2443
0
      if (depLocation != tLocation) {
2444
        // it is a full path to a depend that has the same name
2445
        // as a target but is in a different location so do not use
2446
        // the target as the depend
2447
0
        dep = inName;
2448
0
        return true;
2449
0
      }
2450
0
    }
2451
0
    switch (target->GetType()) {
2452
0
      case cm::TargetType::EXECUTABLE:
2453
0
      case cm::TargetType::STATIC_LIBRARY:
2454
0
      case cm::TargetType::SHARED_LIBRARY:
2455
0
      case cm::TargetType::MODULE_LIBRARY:
2456
0
      case cm::TargetType::UNKNOWN_LIBRARY:
2457
0
        dep = target->GetFullPath(config, cmStateEnums::RuntimeBinaryArtifact,
2458
0
                                  /*realname=*/true);
2459
0
        return true;
2460
0
      case cm::TargetType::OBJECT_LIBRARY:
2461
        // An object library has no single file on which to depend.
2462
        // This was listed to get the target-level dependency.
2463
0
      case cm::TargetType::INTERFACE_LIBRARY:
2464
        // An interface library has no file on which to depend.
2465
        // This was listed to get the target-level dependency.
2466
0
      case cm::TargetType::UTILITY:
2467
0
      case cm::TargetType::GLOBAL_TARGET:
2468
        // A utility target has no file on which to depend.  This was listed
2469
        // only to get the target-level dependency.
2470
0
        return false;
2471
0
    }
2472
0
  }
2473
2474
  // The name was not that of a CMake target.  It must name a file.
2475
0
  if (cmSystemTools::FileIsFullPath(inName)) {
2476
    // This is a full path.  Return it as given.
2477
0
    dep = inName;
2478
0
    return true;
2479
0
  }
2480
2481
  // Check for a source file in this directory that matches the
2482
  // dependency.
2483
0
  if (cmSourceFile* sf = this->Makefile->GetSource(inName)) {
2484
0
    dep = sf->ResolveFullPath();
2485
0
    return true;
2486
0
  }
2487
2488
  // Treat the name as relative to the source directory in which it
2489
  // was given.
2490
0
  dep = cmStrCat(this->GetCurrentSourceDirectory(), '/', inName);
2491
2492
  // If the in-source path does not exist, assume it instead lives in the
2493
  // binary directory.
2494
0
  if (!cmSystemTools::FileExists(dep)) {
2495
0
    dep = cmStrCat(this->GetCurrentBinaryDirectory(), '/', inName);
2496
0
  }
2497
2498
0
  dep = cmSystemTools::CollapseFullPath(dep);
2499
2500
0
  return true;
2501
0
}
2502
2503
static void AddVisibilityCompileOption(std::string& flags,
2504
                                       cmGeneratorTarget const* target,
2505
                                       cmLocalGenerator* lg,
2506
                                       std::string const& lang)
2507
0
{
2508
0
  std::string compileOption = "CMAKE_" + lang + "_COMPILE_OPTIONS_VISIBILITY";
2509
0
  cmValue opt = lg->GetMakefile()->GetDefinition(compileOption);
2510
0
  if (!opt) {
2511
0
    return;
2512
0
  }
2513
0
  std::string flagDefine = lang + "_VISIBILITY_PRESET";
2514
2515
0
  cmValue prop = target->GetProperty(flagDefine);
2516
0
  if (!prop) {
2517
0
    return;
2518
0
  }
2519
0
  if ((*prop != "hidden") && (*prop != "default") && (*prop != "protected") &&
2520
0
      (*prop != "internal")) {
2521
0
    std::ostringstream e;
2522
0
    e << "Target " << target->GetName() << " uses unsupported value \""
2523
0
      << *prop << "\" for " << flagDefine << "."
2524
0
      << " The supported values are: default, hidden, protected, and "
2525
0
         "internal.";
2526
0
    cmSystemTools::Error(e.str());
2527
0
    return;
2528
0
  }
2529
0
  std::string option = *opt + *prop;
2530
0
  lg->AppendFlags(flags, option);
2531
0
}
2532
2533
static void AddInlineVisibilityCompileOption(std::string& flags,
2534
                                             cmGeneratorTarget const* target,
2535
                                             cmLocalGenerator* lg,
2536
                                             std::string const& lang)
2537
0
{
2538
0
  std::string compileOption =
2539
0
    cmStrCat("CMAKE_", lang, "_COMPILE_OPTIONS_VISIBILITY_INLINES_HIDDEN");
2540
0
  cmValue opt = lg->GetMakefile()->GetDefinition(compileOption);
2541
0
  if (!opt) {
2542
0
    return;
2543
0
  }
2544
2545
0
  bool prop = target->GetPropertyAsBool("VISIBILITY_INLINES_HIDDEN");
2546
0
  if (!prop) {
2547
0
    return;
2548
0
  }
2549
0
  lg->AppendFlags(flags, *opt);
2550
0
}
2551
2552
void cmLocalGenerator::AddVisibilityPresetFlags(
2553
  std::string& flags, cmGeneratorTarget const* target, std::string const& lang)
2554
0
{
2555
0
  if (lang.empty()) {
2556
0
    return;
2557
0
  }
2558
2559
0
  AddVisibilityCompileOption(flags, target, this, lang);
2560
2561
0
  if (lang == "CXX" || lang == "OBJCXX") {
2562
0
    AddInlineVisibilityCompileOption(flags, target, this, lang);
2563
0
  }
2564
0
}
2565
2566
void cmLocalGenerator::AddFeatureFlags(std::string& flags,
2567
                                       cmGeneratorTarget const* target,
2568
                                       std::string const& lang,
2569
                                       std::string const& config)
2570
0
{
2571
0
  cm::TargetType const targetType = target->GetType();
2572
2573
0
  bool shared = ((targetType == cm::TargetType::SHARED_LIBRARY) ||
2574
0
                 (targetType == cm::TargetType::MODULE_LIBRARY));
2575
2576
0
  if (target->GetLinkInterfaceDependentBoolProperty(
2577
0
        "POSITION_INDEPENDENT_CODE", config)) {
2578
0
    this->AddPositionIndependentFlags(flags, lang, targetType);
2579
0
  }
2580
0
  if (shared) {
2581
0
    this->AppendFeatureOptions(flags, lang, "DLL");
2582
0
  }
2583
0
}
2584
2585
void cmLocalGenerator::AddPositionIndependentFlags(std::string& flags,
2586
                                                   std::string const& lang,
2587
                                                   cm::TargetType targetType)
2588
0
{
2589
0
  std::string picFlags;
2590
2591
0
  if (targetType == cm::TargetType::EXECUTABLE) {
2592
0
    picFlags = this->Makefile->GetSafeDefinition(
2593
0
      cmStrCat("CMAKE_", lang, "_COMPILE_OPTIONS_PIE"));
2594
0
  }
2595
0
  if (picFlags.empty()) {
2596
0
    picFlags = this->Makefile->GetSafeDefinition(
2597
0
      cmStrCat("CMAKE_", lang, "_COMPILE_OPTIONS_PIC"));
2598
0
  }
2599
0
  if (!picFlags.empty()) {
2600
0
    cmList options{ picFlags };
2601
0
    for (std::string const& o : options) {
2602
0
      this->AppendFlagEscape(flags, o);
2603
0
    }
2604
0
  }
2605
0
}
2606
2607
void cmLocalGenerator::AddColorDiagnosticsFlags(std::string& flags,
2608
                                                std::string const& lang)
2609
0
{
2610
0
  cmValue diag = this->Makefile->GetDefinition("CMAKE_COLOR_DIAGNOSTICS");
2611
0
  if (diag.IsSet()) {
2612
0
    std::string colorFlagName;
2613
0
    if (diag.IsOn()) {
2614
0
      colorFlagName =
2615
0
        cmStrCat("CMAKE_", lang, "_COMPILE_OPTIONS_COLOR_DIAGNOSTICS");
2616
0
    } else {
2617
0
      colorFlagName =
2618
0
        cmStrCat("CMAKE_", lang, "_COMPILE_OPTIONS_COLOR_DIAGNOSTICS_OFF");
2619
0
    }
2620
2621
0
    cmList options{ this->Makefile->GetDefinition(colorFlagName) };
2622
2623
0
    for (auto const& option : options) {
2624
0
      this->AppendFlagEscape(flags, option);
2625
0
    }
2626
0
  }
2627
0
}
2628
2629
void cmLocalGenerator::AddConfigVariableFlags(std::string& flags,
2630
                                              std::string const& var,
2631
                                              std::string const& config)
2632
0
{
2633
  // Add the flags from the variable itself.
2634
0
  this->AppendFlags(flags, this->Makefile->GetSafeDefinition(var));
2635
  // Add the flags from the build-type specific variable.
2636
0
  if (!config.empty()) {
2637
0
    std::string const flagsVar =
2638
0
      cmStrCat(var, '_', cmSystemTools::UpperCase(config));
2639
0
    this->AppendFlags(flags, this->Makefile->GetSafeDefinition(flagsVar));
2640
0
  }
2641
0
}
2642
void cmLocalGenerator::AddConfigVariableFlags(std::string& flags,
2643
                                              std::string const& var,
2644
                                              cmGeneratorTarget const* target,
2645
                                              cmBuildStep compileOrLink,
2646
                                              std::string const& lang,
2647
                                              std::string const& config)
2648
0
{
2649
0
  std::string newFlags;
2650
0
  this->AddConfigVariableFlags(newFlags, var, config);
2651
0
  if (!newFlags.empty()) {
2652
0
    this->AppendFlags(flags, newFlags, var, target, compileOrLink, lang);
2653
0
  }
2654
0
}
2655
2656
void cmLocalGenerator::AppendFlags(std::string& flags,
2657
                                   std::string const& newFlags) const
2658
0
{
2659
0
  bool allSpaces =
2660
0
    std::all_of(newFlags.begin(), newFlags.end(), cmsysString_isspace);
2661
2662
0
  if (!newFlags.empty() && !allSpaces) {
2663
0
    if (!flags.empty()) {
2664
0
      flags += " ";
2665
0
    }
2666
0
    flags += newFlags;
2667
0
  }
2668
0
}
2669
2670
void cmLocalGenerator::AppendFlags(
2671
  std::string& flags, std::vector<BT<std::string>> const& newFlags) const
2672
0
{
2673
0
  for (BT<std::string> const& flag : newFlags) {
2674
0
    this->AppendFlags(flags, flag.Value);
2675
0
  }
2676
0
}
2677
2678
void cmLocalGenerator::AppendFlagEscape(std::string& flags,
2679
                                        std::string const& rawFlag) const
2680
0
{
2681
0
  this->AppendFlags(
2682
0
    flags,
2683
0
    this->EscapeForShell(rawFlag, false, false, false, this->IsNinjaMulti()));
2684
0
}
2685
2686
void cmLocalGenerator::AppendLinkFlagsWithParsing(
2687
  std::string& flags, std::string const& newFlags,
2688
  cmGeneratorTarget const* target, std::string const& language)
2689
0
{
2690
0
  std::vector<std::string> options;
2691
0
  cmSystemTools::ParseUnixCommandLine(newFlags.c_str(), options);
2692
0
  this->SetLinkScriptShell(this->GlobalGenerator->GetUseLinkScript());
2693
0
  std::vector<BT<std::string>> optionsWithBT{ options.size() };
2694
0
  std::transform(options.cbegin(), options.cend(), optionsWithBT.begin(),
2695
0
                 [](std::string const& item) -> BT<std::string> {
2696
0
                   return BT<std::string>{ item };
2697
0
                 });
2698
0
  target->ResolveLinkerWrapper(optionsWithBT, language);
2699
0
  for (auto const& item : optionsWithBT) {
2700
0
    this->AppendFlagEscape(flags, item.Value);
2701
0
  }
2702
0
  this->SetLinkScriptShell(false);
2703
0
}
2704
2705
void cmLocalGenerator::AppendFlags(std::string& flags,
2706
                                   std::string const& newFlags,
2707
                                   std::string const& name,
2708
                                   cmGeneratorTarget const* target,
2709
                                   cmBuildStep compileOrLink,
2710
                                   std::string const& language)
2711
0
{
2712
0
  switch (target->GetPolicyStatusCMP0181()) {
2713
0
    case cmPolicies::WARN:
2714
0
      if (!this->Makefile->GetCMakeInstance()->GetIsInTryCompile() &&
2715
0
          this->Makefile->PolicyOptionalWarningEnabled(
2716
0
            "CMAKE_POLICY_WARNING_CMP0181")) {
2717
0
        this->Makefile->IssuePolicyWarning(
2718
0
          cmPolicies::CMP0181, {},
2719
0
          cmStrCat("Since the policy is not set, the contents of variable '"_s,
2720
0
                   name, "' will be used as is."_s),
2721
0
          target->GetBacktrace());
2722
0
      }
2723
0
      CM_FALLTHROUGH;
2724
0
    case cmPolicies::OLD:
2725
0
      this->AppendFlags(
2726
0
        flags, this->GetGlobalGenerator()->GetEncodedLiteral(newFlags));
2727
0
      break;
2728
0
    case cmPolicies::NEW:
2729
0
      if (compileOrLink == cmBuildStep::Link) {
2730
0
        this->AppendLinkFlagsWithParsing(flags, newFlags, target, language);
2731
0
      } else {
2732
0
        this->AppendFlags(flags, newFlags);
2733
0
      }
2734
0
  }
2735
0
}
2736
2737
void cmLocalGenerator::AddISPCDependencies(cmGeneratorTarget* target)
2738
0
{
2739
0
  std::vector<std::string> enabledLanguages =
2740
0
    this->GetState()->GetEnabledLanguages();
2741
0
  if (std::find(enabledLanguages.begin(), enabledLanguages.end(), "ISPC") ==
2742
0
      enabledLanguages.end()) {
2743
0
    return;
2744
0
  }
2745
2746
0
  cmValue ispcHeaderSuffixProp = target->GetProperty("ISPC_HEADER_SUFFIX");
2747
0
  assert(ispcHeaderSuffixProp);
2748
2749
0
  std::vector<std::string> ispcArchSuffixes =
2750
0
    detail::ComputeISPCObjectSuffixes(target);
2751
0
  bool const extra_objects = (ispcArchSuffixes.size() > 1);
2752
2753
0
  std::vector<std::string> configsList =
2754
0
    this->Makefile->GetGeneratorConfigs(cmMakefile::IncludeEmptyConfig);
2755
0
  for (std::string const& config : configsList) {
2756
2757
0
    std::string rootObjectDir = target->GetObjectDirectory(config);
2758
0
    std::string headerDir = rootObjectDir;
2759
0
    if (cmValue prop = target->GetProperty("ISPC_HEADER_DIRECTORY")) {
2760
0
      headerDir = cmSystemTools::CollapseFullPath(
2761
0
        cmStrCat(this->GetBinaryDirectory(), '/', *prop));
2762
0
    }
2763
2764
0
    std::vector<cmSourceFile*> sources;
2765
0
    target->GetSourceFiles(sources, config);
2766
2767
    // build up the list of ispc headers and extra objects that this target is
2768
    // generating
2769
0
    for (cmSourceFile const* sf : sources) {
2770
      // Generate this object file's rule file.
2771
0
      std::string const& lang = sf->GetLanguage();
2772
0
      if (lang == "ISPC") {
2773
0
        std::string const& objectName = target->GetObjectName(sf);
2774
2775
        // Drop both ".obj" and the source file extension
2776
0
        std::string ispcSource =
2777
0
          cmSystemTools::GetFilenameWithoutLastExtension(objectName);
2778
0
        ispcSource =
2779
0
          cmSystemTools::GetFilenameWithoutLastExtension(ispcSource);
2780
2781
0
        auto headerPath =
2782
0
          cmStrCat(headerDir, '/', ispcSource, *ispcHeaderSuffixProp);
2783
0
        target->AddISPCGeneratedHeader(headerPath, config);
2784
0
        if (extra_objects) {
2785
0
          std::vector<std::pair<cmSourceFile const*, std::string>> objs;
2786
0
          for (auto& obj : detail::ComputeISPCExtraObjects(
2787
0
                 objectName, rootObjectDir, ispcArchSuffixes)) {
2788
0
            objs.push_back({ sf, std::move(obj) });
2789
0
          }
2790
0
          target->AddISPCGeneratedObject(std::move(objs), config);
2791
0
        }
2792
0
      }
2793
0
    }
2794
0
  }
2795
0
}
2796
2797
void cmLocalGenerator::AddPchDependencies(cmGeneratorTarget* target)
2798
0
{
2799
0
  std::vector<std::string> configsList =
2800
0
    this->Makefile->GetGeneratorConfigs(cmMakefile::IncludeEmptyConfig);
2801
2802
0
  for (std::string const& config : configsList) {
2803
    // FIXME: Refactor collection of sources to not evaluate object
2804
    // libraries.
2805
0
    std::vector<cmSourceFile*> sources;
2806
0
    target->GetSourceFiles(sources, config);
2807
2808
0
    std::string const configUpper = cmSystemTools::UpperCase(config);
2809
0
    static std::array<std::string, 4> const langs = { { "C", "CXX", "OBJC",
2810
0
                                                        "OBJCXX" } };
2811
2812
0
    std::set<std::string> pchLangSet;
2813
0
    if (this->GetGlobalGenerator()->IsXcode()) {
2814
0
      for (std::string const& lang : langs) {
2815
0
        std::string const pchHeader = target->GetPchHeader(config, lang, "");
2816
0
        if (!pchHeader.empty()) {
2817
0
          pchLangSet.emplace(lang);
2818
0
        }
2819
0
      }
2820
0
    }
2821
2822
0
    for (std::string const& lang : langs) {
2823
0
      auto langSources = std::count_if(
2824
0
        sources.begin(), sources.end(),
2825
0
        [&target, &config, &lang](cmSourceFile* sf) {
2826
0
          auto const* const fileSet = target->GetFileSetForSource(config, sf);
2827
0
          return lang == sf->GetLanguage() &&
2828
0
            !((fileSet && fileSet->GetProperty("SKIP_PRECOMPILE_HEADERS")) ||
2829
0
              sf->GetProperty("SKIP_PRECOMPILE_HEADERS"));
2830
0
        });
2831
0
      if (langSources == 0) {
2832
0
        continue;
2833
0
      }
2834
2835
0
      std::vector<std::string> pchArchs = target->GetPchArchs(config, lang);
2836
0
      if (pchArchs.size() > 1) {
2837
0
        std::string useMultiArchPch;
2838
0
        for (std::string const& arch : pchArchs) {
2839
0
          std::string const pchHeader =
2840
0
            target->GetPchHeader(config, lang, arch);
2841
0
          if (!pchHeader.empty()) {
2842
0
            useMultiArchPch = cmStrCat(useMultiArchPch, ";-Xarch_", arch,
2843
0
                                       ";-include", pchHeader);
2844
0
          }
2845
0
        }
2846
2847
0
        if (!useMultiArchPch.empty()) {
2848
2849
0
          target->Target->AppendProperty(
2850
0
            cmStrCat(lang, "_COMPILE_OPTIONS_USE_PCH"),
2851
0
            cmStrCat("$<$<CONFIG:", config, ">:", useMultiArchPch, '>'));
2852
0
        }
2853
0
      }
2854
2855
0
      for (std::string const& arch : pchArchs) {
2856
0
        std::string const pchSource = target->GetPchSource(config, lang, arch);
2857
0
        std::string const pchHeader = target->GetPchHeader(config, lang, arch);
2858
2859
0
        if (pchSource.empty() || pchHeader.empty()) {
2860
0
          if (this->GetGlobalGenerator()->IsXcode() && !pchLangSet.empty()) {
2861
0
            for (auto* sf : sources) {
2862
0
              auto const sourceLanguage = sf->GetLanguage();
2863
0
              if (!sourceLanguage.empty() &&
2864
0
                  pchLangSet.find(sourceLanguage) == pchLangSet.end()) {
2865
0
                sf->SetProperty("SKIP_PRECOMPILE_HEADERS", "ON");
2866
0
              }
2867
0
            }
2868
0
          }
2869
0
          continue;
2870
0
        }
2871
2872
0
        cmValue pchExtension =
2873
0
          this->Makefile->GetDefinition("CMAKE_PCH_EXTENSION");
2874
2875
0
        if (pchExtension.IsEmpty()) {
2876
0
          continue;
2877
0
        }
2878
2879
0
        auto* reuseTarget = target->GetPchReuseTarget();
2880
0
        bool const haveReuseTarget = reuseTarget && reuseTarget != target;
2881
2882
0
        auto* pch_sf = this->Makefile->GetOrCreateSource(
2883
0
          pchSource, false, cmSourceFileLocationKind::Known);
2884
0
        pch_sf->SetSpecialSourceType(
2885
0
          cmSourceFile::SpecialSourceType::PchSource);
2886
        // PCH sources should never be scanned as they cannot contain C++
2887
        // module references.
2888
0
        pch_sf->SetProperty("CXX_SCAN_FOR_MODULES", "0");
2889
2890
0
        if (!this->GetGlobalGenerator()->IsXcode()) {
2891
0
          if (!haveReuseTarget) {
2892
0
            target->AddSource(pchSource, true);
2893
0
          }
2894
2895
0
          std::string const pchFile = target->GetPchFile(config, lang, arch);
2896
2897
          // Exclude the pch files from linking
2898
0
          if (this->Makefile->IsOn("CMAKE_LINK_PCH")) {
2899
0
            if (!haveReuseTarget) {
2900
0
              pch_sf->AppendProperty(
2901
0
                "OBJECT_OUTPUTS",
2902
0
                cmStrCat("$<$<CONFIG:", config, ">:", pchFile, '>'));
2903
0
            } else {
2904
0
              if (this->Makefile->IsOn("CMAKE_PCH_COPY_COMPILE_PDB")) {
2905
2906
0
                std::string const compilerId =
2907
0
                  this->Makefile->GetSafeDefinition(
2908
0
                    cmStrCat("CMAKE_", lang, "_COMPILER_ID"));
2909
2910
0
                std::string const compilerVersion =
2911
0
                  this->Makefile->GetSafeDefinition(
2912
0
                    cmStrCat("CMAKE_", lang, "_COMPILER_VERSION"));
2913
2914
0
                std::string const langFlags =
2915
0
                  this->Makefile->GetSafeDefinition(
2916
0
                    cmStrCat("CMAKE_", lang, "_FLAGS_", configUpper));
2917
2918
0
                bool editAndContinueDebugInfo = false;
2919
0
                bool programDatabaseDebugInfo = false;
2920
0
                cm::optional<std::string> msvcDebugInformationFormat =
2921
0
                  this->GetMSVCDebugFormatName(config, target);
2922
0
                if (msvcDebugInformationFormat &&
2923
0
                    !msvcDebugInformationFormat->empty()) {
2924
0
                  editAndContinueDebugInfo =
2925
0
                    *msvcDebugInformationFormat == "EditAndContinue";
2926
0
                  programDatabaseDebugInfo =
2927
0
                    *msvcDebugInformationFormat == "ProgramDatabase";
2928
0
                } else {
2929
0
                  editAndContinueDebugInfo =
2930
0
                    langFlags.find("/ZI") != std::string::npos ||
2931
0
                    langFlags.find("-ZI") != std::string::npos;
2932
0
                  programDatabaseDebugInfo =
2933
0
                    langFlags.find("/Zi") != std::string::npos ||
2934
0
                    langFlags.find("-Zi") != std::string::npos;
2935
0
                }
2936
2937
0
                if (editAndContinueDebugInfo) {
2938
0
                  this->CopyPchCompilePdb(config, lang, target, reuseTarget,
2939
0
                                          { ".pdb", ".idb" });
2940
0
                } else if (programDatabaseDebugInfo) {
2941
0
                  this->CopyPchCompilePdb(config, lang, target, reuseTarget,
2942
0
                                          { ".pdb" });
2943
0
                }
2944
0
              }
2945
2946
              // Link to the pch object file
2947
0
              std::string pchSourceObj;
2948
              // Fastbuild will propagate pch.obj for us, no need to link to it
2949
              // explicitly.
2950
0
              if (!this->GetGlobalGenerator()->IsFastbuild()) {
2951
0
                pchSourceObj =
2952
0
                  reuseTarget->GetPchFileObject(config, lang, arch);
2953
0
              }
2954
2955
0
              if (target->GetType() != cm::TargetType::OBJECT_LIBRARY) {
2956
0
                std::string linkerProperty = "LINK_FLAGS_";
2957
0
                if (target->GetType() == cm::TargetType::STATIC_LIBRARY) {
2958
0
                  linkerProperty = "STATIC_LIBRARY_FLAGS_";
2959
0
                }
2960
0
                target->Target->AppendProperty(
2961
0
                  cmStrCat(linkerProperty, configUpper),
2962
0
                  cmStrCat(' ',
2963
0
                           this->ConvertToOutputFormat(pchSourceObj, SHELL)),
2964
0
                  cm::nullopt, true);
2965
0
              } else if (reuseTarget->GetType() ==
2966
0
                         cm::TargetType::OBJECT_LIBRARY) {
2967
0
                target->Target->AppendProperty(
2968
0
                  "INTERFACE_LINK_LIBRARIES",
2969
0
                  cmStrCat("$<$<CONFIG:", config,
2970
0
                           ">:$<LINK_ONLY:", pchSourceObj, ">>"));
2971
0
              }
2972
0
            }
2973
0
          } else {
2974
0
            pch_sf->SetProperty("PCH_EXTENSION", pchExtension);
2975
0
          }
2976
2977
          // Add pchHeader to source files, which will
2978
          // be grouped as "Precompile Header File"
2979
0
          auto* pchHeader_sf = this->Makefile->GetOrCreateSource(
2980
0
            pchHeader, false, cmSourceFileLocationKind::Known);
2981
0
          pchHeader_sf->SetSpecialSourceType(
2982
0
            cmSourceFile::SpecialSourceType::PchHeader);
2983
0
          std::string err;
2984
0
          pchHeader_sf->ResolveFullPath(&err);
2985
0
          if (!err.empty()) {
2986
0
            std::ostringstream msg;
2987
0
            msg << "Unable to resolve full path of PCH-header '" << pchHeader
2988
0
                << "' assigned to target " << target->GetName()
2989
0
                << ", although its path is supposed to be known!";
2990
0
            this->IssueMessage(MessageType::FATAL_ERROR, msg.str());
2991
0
          }
2992
0
          target->AddSource(pchHeader);
2993
0
        }
2994
0
      }
2995
0
    }
2996
0
  }
2997
0
}
2998
2999
void cmLocalGenerator::CopyPchCompilePdb(
3000
  std::string const& config, std::string const& language,
3001
  cmGeneratorTarget* target, cmGeneratorTarget* reuseTarget,
3002
  std::vector<std::string> const& extensions)
3003
0
{
3004
0
  std::string const copy_script = cmStrCat(target->GetSupportDirectory(),
3005
0
                                           "/copy_idb_pdb_", config, ".cmake");
3006
0
  cmGeneratedFileStream file(copy_script);
3007
0
  file.SetCopyIfDifferent(true);
3008
3009
0
  file << "# CMake generated file\n";
3010
3011
0
  file << "# The compiler generated pdb file needs to be written to disk\n"
3012
0
       << "# by mspdbsrv. The foreach retry loop is needed to make sure\n"
3013
0
       << "# the pdb file is ready to be copied.\n\n";
3014
3015
0
  auto configGenex = [&](cm::string_view expr) -> std::string {
3016
0
    if (this->GetGlobalGenerator()->IsMultiConfig()) {
3017
0
      return cmStrCat("$<$<CONFIG:", config, ">:", expr, '>');
3018
0
    }
3019
0
    return std::string(expr);
3020
0
  };
3021
3022
0
  std::vector<std::string> outputs;
3023
0
  auto replaceExtension = [](std::string const& path,
3024
0
                             std::string const& ext) -> std::string {
3025
0
    auto const dir = cmSystemTools::GetFilenamePath(path);
3026
0
    auto const base = cmSystemTools::GetFilenameWithoutLastExtension(path);
3027
0
    if (dir.empty()) {
3028
0
      return cmStrCat(base, ext);
3029
0
    }
3030
0
    return cmStrCat(dir, '/', base, ext);
3031
0
  };
3032
0
  for (auto const& extension : extensions) {
3033
0
    std::string const from_file =
3034
0
      replaceExtension(reuseTarget->GetCompilePDBPath(config), extension);
3035
0
    std::string const to_dir = target->GetCompilePDBDirectory(config);
3036
0
    std::string const to_file =
3037
0
      replaceExtension(reuseTarget->GetCompilePDBName(config), extension);
3038
0
    std::string const dest_file = cmStrCat(to_dir, '/', to_file);
3039
3040
0
    file << "foreach(retry RANGE 1 30)\n";
3041
0
    file << "  if (EXISTS \"" << from_file << "\" AND (NOT EXISTS \""
3042
0
         << dest_file << "\" OR NOT \"" << dest_file << "\" IS_NEWER_THAN \""
3043
0
         << from_file << "\"))\n";
3044
0
    file << "    file(MAKE_DIRECTORY \"" << to_dir << "\")\n";
3045
0
    file << "    execute_process(COMMAND ${CMAKE_COMMAND} -E copy";
3046
0
    file << " \"" << from_file << "\"" << " \"" << to_dir
3047
0
         << "\" RESULT_VARIABLE result " << " ERROR_QUIET)\n";
3048
0
    file << "    if (NOT result EQUAL 0)\n"
3049
0
         << "      execute_process(COMMAND ${CMAKE_COMMAND}"
3050
0
         << " -E sleep 1)\n"
3051
0
         << "    else()\n";
3052
0
    file << "      break()\n"
3053
0
         << "    endif()\n";
3054
0
    file << "  elseif(NOT EXISTS \"" << from_file << "\")\n"
3055
0
         << "    execute_process(COMMAND ${CMAKE_COMMAND}" << " -E sleep 1)\n"
3056
0
         << "  endif()\n";
3057
0
    file << "endforeach()\n";
3058
0
    outputs.push_back(configGenex(dest_file));
3059
0
  }
3060
3061
0
  cmCustomCommandLines commandLines =
3062
0
    cmMakeSingleCommandLine({ configGenex(cmSystemTools::GetCMakeCommand()),
3063
0
                              configGenex("-P"), configGenex(copy_script) });
3064
3065
0
  auto const comment =
3066
0
    cmStrCat("Copying PDB for PCH reuse from ", reuseTarget->GetName(),
3067
0
             " for ", target->GetName());
3068
0
  ;
3069
3070
0
  auto cc = cm::make_unique<cmCustomCommand>();
3071
0
  cc->SetCommandLines(commandLines);
3072
0
  cc->SetComment(comment.c_str());
3073
0
  cc->SetStdPipesUTF8(true);
3074
0
  cc->AppendDepends(
3075
0
    { reuseTarget->GetPchFile(config, language), copy_script });
3076
  // Fastbuild needs to know that this custom command actually depends on a
3077
  // target that produces PCH, so it can sort by dependencies correctly.
3078
0
  if (this->GetGlobalGenerator()->IsFastbuild()) {
3079
0
    cc->AppendDepends({ reuseTarget->GetName() });
3080
0
  }
3081
3082
0
  if (this->GetGlobalGenerator()->IsVisualStudio()) {
3083
0
    cc->SetByproducts(outputs);
3084
0
    this->AddCustomCommandToTarget(
3085
0
      target->GetName(), cmCustomCommandType::PRE_BUILD, std::move(cc),
3086
0
      cmObjectLibraryCommands::Accept);
3087
0
  } else {
3088
0
    cc->SetOutputs(outputs);
3089
0
    cmSourceFile* copy_rule = this->AddCustomCommandToOutput(std::move(cc));
3090
0
    if (copy_rule) {
3091
0
      copy_rule->SetProperty("CXX_SCAN_FOR_MODULES", "0");
3092
0
      auto* pch_pdb_sf = target->AddSource(copy_rule->ResolveFullPath());
3093
0
      pch_pdb_sf->SetSpecialSourceType(
3094
0
        cmSourceFile::SpecialSourceType::PchPdbReuseSource);
3095
0
    }
3096
0
  }
3097
0
}
3098
3099
cm::optional<std::string> cmLocalGenerator::GetMSVCDebugFormatName(
3100
  std::string const& config, cmGeneratorTarget const* target)
3101
0
{
3102
  // MSVC debug information format selection is activated by the presence
3103
  // of a default whether or not it is overridden by a property.
3104
0
  cm::optional<std::string> msvcDebugInformationFormat;
3105
0
  cmValue msvcDebugInformationFormatDefault = this->Makefile->GetDefinition(
3106
0
    "CMAKE_MSVC_DEBUG_INFORMATION_FORMAT_DEFAULT");
3107
0
  if (cmNonempty(msvcDebugInformationFormatDefault)) {
3108
0
    cmValue msvcDebugInformationFormatValue =
3109
0
      target->GetProperty("MSVC_DEBUG_INFORMATION_FORMAT");
3110
0
    if (!msvcDebugInformationFormatValue) {
3111
0
      msvcDebugInformationFormatValue = msvcDebugInformationFormatDefault;
3112
0
    }
3113
0
    msvcDebugInformationFormat = cmGeneratorExpression::Evaluate(
3114
0
      *msvcDebugInformationFormatValue, this, config, target);
3115
0
  }
3116
0
  return msvcDebugInformationFormat;
3117
0
}
3118
3119
cm::optional<cmSwiftCompileMode> cmLocalGenerator::GetSwiftCompileMode(
3120
  cmGeneratorTarget const* target, std::string const& config)
3121
0
{
3122
0
  cmMakefile const* mf = this->GetMakefile();
3123
0
  cmValue const swiftCompileModeDefault =
3124
0
    mf->GetDefinition("CMAKE_Swift_COMPILATION_MODE_DEFAULT");
3125
0
  if (!cmNonempty(swiftCompileModeDefault)) {
3126
0
    return {};
3127
0
  }
3128
0
  cmValue swiftCompileMode = target->GetProperty("Swift_COMPILATION_MODE");
3129
0
  if (!swiftCompileMode) {
3130
0
    swiftCompileMode = swiftCompileModeDefault;
3131
0
  }
3132
3133
0
  std::string const expandedCompileMode =
3134
0
    cmGeneratorExpression::Evaluate(*swiftCompileMode, this, config, target);
3135
0
  if (expandedCompileMode == "wholemodule") {
3136
0
    return cmSwiftCompileMode::Wholemodule;
3137
0
  }
3138
0
  if (expandedCompileMode == "singlefile") {
3139
0
    return cmSwiftCompileMode::Singlefile;
3140
0
  }
3141
0
  if (expandedCompileMode == "incremental") {
3142
0
    return cmSwiftCompileMode::Incremental;
3143
0
  }
3144
0
  return cmSwiftCompileMode::Unknown;
3145
0
}
3146
3147
bool cmLocalGenerator::IsSplitSwiftBuild() const
3148
0
{
3149
0
  return cmNonempty(this->GetMakefile()->GetDefinition(
3150
0
    "CMAKE_Swift_COMPILATION_MODE_DEFAULT"));
3151
0
}
3152
3153
namespace {
3154
3155
inline void RegisterUnitySources(cmGeneratorTarget* target, cmSourceFile* sf,
3156
                                 std::string const& filename)
3157
0
{
3158
0
  target->AddSourceFileToUnityBatch(sf->ResolveFullPath());
3159
0
  sf->SetProperty("UNITY_SOURCE_FILE", filename);
3160
0
}
3161
}
3162
3163
cmLocalGenerator::UnitySource cmLocalGenerator::WriteUnitySource(
3164
  cmGeneratorTarget* target, std::vector<std::string> const& configs,
3165
  cmRange<std::vector<UnityBatchedSource>::const_iterator> sources,
3166
  cmValue beforeInclude, cmValue afterInclude, std::string filename,
3167
  std::string const& unityFileDirectory, UnityPathMode pathMode) const
3168
0
{
3169
0
  cmValue uniqueIdName = target->GetProperty("UNITY_BUILD_UNIQUE_ID");
3170
0
  cmGeneratedFileStream file(
3171
0
    filename, false, target->GetGlobalGenerator()->GetMakefileEncoding());
3172
0
  file.SetCopyIfDifferent(true);
3173
0
  file << "/* generated by CMake */\n\n";
3174
3175
0
  bool perConfig = false;
3176
0
  for (UnityBatchedSource const& ubs : sources) {
3177
0
    cm::optional<std::string> cond;
3178
0
    if (ubs.Configs.size() != configs.size()) {
3179
0
      perConfig = true;
3180
0
      cond = std::string();
3181
0
      cm::string_view sep;
3182
0
      for (size_t ci : ubs.Configs) {
3183
0
        cond = cmStrCat(*cond, sep, "defined(CMAKE_UNITY_CONFIG_",
3184
0
                        cmSystemTools::UpperCase(configs[ci]), ')');
3185
0
        sep = " || "_s;
3186
0
      }
3187
0
    }
3188
0
    RegisterUnitySources(target, ubs.Source, filename);
3189
0
    WriteUnitySourceInclude(file, cond, ubs.Source->ResolveFullPath(),
3190
0
                            beforeInclude, afterInclude, uniqueIdName,
3191
0
                            pathMode, unityFileDirectory);
3192
0
  }
3193
3194
0
  return UnitySource(std::move(filename), perConfig);
3195
0
}
3196
3197
void cmLocalGenerator::WriteUnitySourceInclude(
3198
  std::ostream& unity_file, cm::optional<std::string> const& cond,
3199
  std::string const& sf_full_path, cmValue beforeInclude, cmValue afterInclude,
3200
  cmValue uniqueIdName, UnityPathMode pathMode,
3201
  std::string const& unityFileDirectory) const
3202
0
{
3203
0
  if (cond) {
3204
0
    unity_file << "#if " << *cond << "\n";
3205
0
  }
3206
3207
0
  std::string pathToHash;
3208
0
  std::string relocatableIncludePath;
3209
0
  auto PathEqOrSubDir = [](std::string const& a, std::string const& b) {
3210
0
    return (cmSystemTools::ComparePath(a, b) ||
3211
0
            cmSystemTools::IsSubDirectory(a, b));
3212
0
  };
3213
0
  auto const path = cmSystemTools::GetFilenamePath(sf_full_path);
3214
0
  if (PathEqOrSubDir(path, this->GetBinaryDirectory())) {
3215
0
    relocatableIncludePath =
3216
0
      cmSystemTools::RelativePath(unityFileDirectory, sf_full_path);
3217
0
    pathToHash = "BLD_" +
3218
0
      cmSystemTools::RelativePath(this->GetBinaryDirectory(), sf_full_path);
3219
0
  } else if (PathEqOrSubDir(path, this->GetSourceDirectory())) {
3220
0
    relocatableIncludePath =
3221
0
      cmSystemTools::RelativePath(this->GetSourceDirectory(), sf_full_path);
3222
0
    pathToHash = "SRC_" + relocatableIncludePath;
3223
0
  } else {
3224
0
    relocatableIncludePath = sf_full_path;
3225
0
    pathToHash = "ABS_" + sf_full_path;
3226
0
  }
3227
3228
0
  if (cmNonempty(uniqueIdName)) {
3229
0
    cmCryptoHash hasher(cmCryptoHash::AlgoMD5);
3230
0
    unity_file << "/* " << pathToHash << " */\n"
3231
0
               << "#undef " << *uniqueIdName << "\n"
3232
0
               << "#define " << *uniqueIdName << " unity_"
3233
0
               << hasher.HashString(pathToHash) << "\n";
3234
0
  }
3235
3236
0
  if (beforeInclude) {
3237
0
    unity_file << *beforeInclude << "\n";
3238
0
  }
3239
3240
  // clang-tidy-17 has new include checks that needs NOLINT too.
3241
0
  unity_file
3242
0
    << "/* NOLINTNEXTLINE(bugprone-suspicious-include,misc-include-cleaner) "
3243
0
       "*/\n";
3244
0
  if (pathMode == UnityPathMode::Relative) {
3245
0
    unity_file << "#include \"" << relocatableIncludePath << "\"\n";
3246
0
  } else {
3247
0
    unity_file << "#include \"" << sf_full_path << "\"\n";
3248
0
  }
3249
3250
0
  if (afterInclude) {
3251
0
    unity_file << *afterInclude << "\n";
3252
0
  }
3253
0
  if (cond) {
3254
0
    unity_file << "#endif\n";
3255
0
  }
3256
0
  unity_file << "\n";
3257
0
}
3258
3259
namespace {
3260
std::string unity_file_extension(std::string const& lang)
3261
0
{
3262
0
  std::string extension;
3263
0
  if (lang == "C") {
3264
0
    extension = "_c.c";
3265
0
  } else if (lang == "CXX") {
3266
0
    extension = "_cxx.cxx";
3267
0
  } else if (lang == "CUDA") {
3268
0
    extension = "_cu.cu";
3269
0
  } else if (lang == "OBJC") {
3270
0
    extension = "_m.m";
3271
0
  } else if (lang == "OBJCXX") {
3272
0
    extension = "_mm.mm";
3273
0
  }
3274
0
  return extension;
3275
0
}
3276
3277
char const* unity_file_prefix(cmGeneratorTarget* target)
3278
0
{
3279
0
  if (cmValue val = target->GetProperty("UNITY_BUILD_FILENAME_PREFIX")) {
3280
0
    return val->c_str();
3281
0
  }
3282
0
  return "unity_";
3283
0
}
3284
}
3285
3286
std::vector<cmLocalGenerator::UnitySource>
3287
cmLocalGenerator::AddUnityFilesModeAuto(
3288
  cmGeneratorTarget* target, std::string const& lang,
3289
  std::vector<std::string> const& configs,
3290
  std::vector<UnityBatchedSource> const& filtered_sources,
3291
  cmValue beforeInclude, cmValue afterInclude,
3292
  std::string const& filename_base, UnityPathMode pathMode, size_t batchSize)
3293
0
{
3294
0
  if (batchSize == 0) {
3295
0
    batchSize = filtered_sources.size();
3296
0
  }
3297
0
  char const* filename_prefix = unity_file_prefix(target);
3298
0
  std::vector<UnitySource> unity_files;
3299
0
  for (size_t itemsLeft = filtered_sources.size(), chunk, batch = 0;
3300
0
       itemsLeft > 0; itemsLeft -= chunk, ++batch) {
3301
3302
0
    chunk = std::min(itemsLeft, batchSize);
3303
3304
0
    std::string filename = cmStrCat(filename_base, filename_prefix, batch,
3305
0
                                    unity_file_extension(lang));
3306
0
    auto const begin = filtered_sources.begin() + batch * batchSize;
3307
0
    auto const end = begin + chunk;
3308
0
    unity_files.emplace_back(this->WriteUnitySource(
3309
0
      target, configs, cmMakeRange(begin, end), beforeInclude, afterInclude,
3310
0
      std::move(filename), filename_base, pathMode));
3311
0
  }
3312
0
  return unity_files;
3313
0
}
3314
3315
std::vector<cmLocalGenerator::UnitySource>
3316
cmLocalGenerator::AddUnityFilesModeGroup(
3317
  cmGeneratorTarget* target, std::string const& lang,
3318
  std::vector<std::string> const& configs,
3319
  std::vector<UnityBatchedSource> const& filtered_sources,
3320
  cmValue beforeInclude, cmValue afterInclude,
3321
  std::string const& filename_base, UnityPathMode pathMode)
3322
0
{
3323
0
  std::vector<UnitySource> unity_files;
3324
3325
  // sources organized by group name. Drop any source
3326
  // without a group
3327
0
  std::unordered_map<std::string, std::vector<UnityBatchedSource>>
3328
0
    explicit_mapping;
3329
0
  for (UnityBatchedSource const& ubs : filtered_sources) {
3330
0
    if (cmValue value = ubs.Source->GetProperty("UNITY_GROUP")) {
3331
0
      auto i = explicit_mapping.find(*value);
3332
0
      if (i == explicit_mapping.end()) {
3333
0
        std::vector<UnityBatchedSource> sources{ ubs };
3334
0
        explicit_mapping.emplace(*value, std::move(sources));
3335
0
      } else {
3336
0
        i->second.emplace_back(ubs);
3337
0
      }
3338
0
    }
3339
0
  }
3340
3341
0
  char const* filename_prefix = unity_file_prefix(target);
3342
0
  for (auto const& item : explicit_mapping) {
3343
0
    auto const& name = item.first;
3344
0
    std::string filename = cmStrCat(filename_base, filename_prefix, name,
3345
0
                                    unity_file_extension(lang));
3346
0
    unity_files.emplace_back(this->WriteUnitySource(
3347
0
      target, configs, cmMakeRange(item.second), beforeInclude, afterInclude,
3348
0
      std::move(filename), filename_base, pathMode));
3349
0
  }
3350
3351
0
  return unity_files;
3352
0
}
3353
3354
void cmLocalGenerator::AddUnityBuild(cmGeneratorTarget* target)
3355
0
{
3356
  // cmFastbuildNormalTargetGenerator handles unity build.
3357
0
  if (this->GetGlobalGenerator()->IsFastbuild() ||
3358
0
      !target->GetPropertyAsBool("UNITY_BUILD")) {
3359
0
    return;
3360
0
  }
3361
3362
0
  std::vector<UnityBatchedSource> unitySources;
3363
3364
0
  std::vector<std::string> configs =
3365
0
    this->Makefile->GetGeneratorConfigs(cmMakefile::IncludeEmptyConfig);
3366
3367
0
  std::map<cmSourceFile const*, size_t> index;
3368
3369
0
  for (size_t ci = 0; ci < configs.size(); ++ci) {
3370
    // FIXME: Refactor collection of sources to not evaluate object libraries.
3371
    // Their final set of object files might be transformed by unity builds.
3372
0
    std::vector<cmSourceFile*> sources;
3373
0
    target->GetSourceFiles(sources, configs[ci]);
3374
0
    for (cmSourceFile* sf : sources) {
3375
0
      cmGeneratorFileSet const* fileSet =
3376
0
        target->GetFileSetForSource(configs[ci], sf);
3377
0
      if (fileSet &&
3378
0
          !cm::FileSetMetadata::GetAttributes(fileSet->GetType())
3379
0
             .contains(cm::FileSetMetadata::FileSetAttributes::UnityBuild)) {
3380
0
        continue;
3381
0
      }
3382
      // Files which need C++ scanning cannot participate in unity builds as
3383
      // there is a single place in TUs that may perform module-dependency bits
3384
      // and a unity source cannot `#include` them in-order and represent a
3385
      // valid TU.
3386
0
      if (sf->GetLanguage() == "CXX"_s &&
3387
0
          target->NeedDyndepForSource("CXX", configs[ci], sf)) {
3388
0
        continue;
3389
0
      }
3390
3391
0
      auto mi = index.find(sf);
3392
0
      if (mi == index.end()) {
3393
0
        unitySources.emplace_back(sf);
3394
0
        std::map<cmSourceFile const*, size_t>::value_type entry(
3395
0
          sf, unitySources.size() - 1);
3396
0
        mi = index.insert(entry).first;
3397
0
      }
3398
0
      unitySources[mi->second].Configs.emplace_back(ci);
3399
0
    }
3400
0
  }
3401
3402
0
  std::string filename_base =
3403
0
    cmStrCat(target->GetCMFSupportDirectory(), "/Unity/");
3404
3405
0
  cmValue batchSizeString = target->GetProperty("UNITY_BUILD_BATCH_SIZE");
3406
0
  size_t const unityBatchSize = batchSizeString
3407
0
    ? static_cast<size_t>(std::atoi(batchSizeString->c_str()))
3408
0
    : 0;
3409
3410
0
  cmValue beforeInclude =
3411
0
    target->GetProperty("UNITY_BUILD_CODE_BEFORE_INCLUDE");
3412
0
  cmValue afterInclude = target->GetProperty("UNITY_BUILD_CODE_AFTER_INCLUDE");
3413
0
  cmValue unityMode = target->GetProperty("UNITY_BUILD_MODE");
3414
0
  UnityPathMode pathMode = target->GetPropertyAsBool("UNITY_BUILD_RELOCATABLE")
3415
0
    ? UnityPathMode::Relative
3416
0
    : UnityPathMode::Absolute;
3417
3418
0
  for (std::string lang : { "C", "CXX", "OBJC", "OBJCXX", "CUDA" }) {
3419
0
    std::vector<UnityBatchedSource> filtered_sources;
3420
0
    std::copy_if(
3421
0
      unitySources.begin(), unitySources.end(),
3422
0
      std::back_inserter(filtered_sources),
3423
0
      [&](UnityBatchedSource const& ubs) -> bool {
3424
0
        cmSourceFile* sf = ubs.Source;
3425
0
        if (sf->GetLanguage() != lang) {
3426
0
          return false;
3427
0
        }
3428
0
        for (auto idx : ubs.Configs) {
3429
0
          cmGeneratorFileSet const* fileSet =
3430
0
            target->GetFileSetForSource(configs[idx], sf);
3431
0
          if (fileSet &&
3432
0
              (fileSet->GetProperty("SKIP_UNITY_BUILD_INCLUSION").IsOn() ||
3433
0
               fileSet->GetProperty(fileSet->BelongsTo(target)
3434
0
                                      ? "COMPILE_OPTIONS"
3435
0
                                      : "INTERFACE_COMPILE_OPTIONS") ||
3436
0
               fileSet->GetProperty(fileSet->BelongsTo(target)
3437
0
                                      ? "COMPILE_DEFINITIONS"
3438
0
                                      : "INTERFACE_COMPILE_DEFINITIONS") ||
3439
0
               fileSet->GetProperty(fileSet->BelongsTo(target)
3440
0
                                      ? "INCLUDE_DIRECTORIES"
3441
0
                                      : "INTERFACE_INCLUDE_DIRECTORIES"))) {
3442
0
            return false;
3443
0
          }
3444
0
        }
3445
0
        return !sf->GetPropertyAsBool("SKIP_UNITY_BUILD_INCLUSION") &&
3446
0
          !sf->GetPropertyAsBool("HEADER_FILE_ONLY") &&
3447
0
          !sf->GetProperty("COMPILE_OPTIONS") &&
3448
0
          !sf->GetProperty("COMPILE_DEFINITIONS") &&
3449
0
          !sf->GetProperty("COMPILE_FLAGS") &&
3450
0
          !sf->GetProperty("INCLUDE_DIRECTORIES");
3451
0
      });
3452
3453
0
    std::vector<UnitySource> unity_files;
3454
0
    if (!unityMode || *unityMode == "BATCH") {
3455
0
      unity_files = AddUnityFilesModeAuto(
3456
0
        target, lang, configs, filtered_sources, beforeInclude, afterInclude,
3457
0
        filename_base, pathMode, unityBatchSize);
3458
0
    } else if (unityMode && *unityMode == "GROUP") {
3459
0
      unity_files = AddUnityFilesModeGroup(
3460
0
        target, lang, configs, filtered_sources, beforeInclude, afterInclude,
3461
0
        filename_base, pathMode);
3462
0
    } else {
3463
      // unity mode is set to an unsupported value
3464
0
      std::string e("Invalid UNITY_BUILD_MODE value of " + *unityMode +
3465
0
                    " assigned to target " + target->GetName() +
3466
0
                    ". Acceptable values are BATCH and GROUP.");
3467
0
      this->IssueMessage(MessageType::FATAL_ERROR, e);
3468
0
    }
3469
3470
0
    for (UnitySource const& file : unity_files) {
3471
0
      auto* unity = this->GetMakefile()->GetOrCreateSource(file.Path);
3472
0
      unity->SetSpecialSourceType(
3473
0
        cmSourceFile::SpecialSourceType::UnitySource);
3474
0
      target->AddSource(file.Path, true);
3475
0
      unity->SetProperty("SKIP_UNITY_BUILD_INCLUSION", "ON");
3476
0
      unity->SetProperty("UNITY_SOURCE_FILE", file.Path);
3477
0
      unity->SetProperty("CXX_SCAN_FOR_MODULES", "0");
3478
0
      if (file.PerConfig) {
3479
0
        unity->SetProperty("COMPILE_DEFINITIONS",
3480
0
                           "CMAKE_UNITY_CONFIG_$<UPPER_CASE:$<CONFIG>>");
3481
0
      }
3482
3483
0
      if (pathMode == UnityPathMode::Relative) {
3484
0
        unity->AppendProperty("INCLUDE_DIRECTORIES",
3485
0
                              this->GetSourceDirectory(), false);
3486
0
      }
3487
0
    }
3488
0
  }
3489
0
}
3490
3491
void cmLocalGenerator::AddPerLanguageLinkFlags(std::string& flags,
3492
                                               cmGeneratorTarget const* target,
3493
                                               std::string const& lang,
3494
                                               std::string const& config)
3495
0
{
3496
0
  switch (target->GetType()) {
3497
0
    case cm::TargetType::MODULE_LIBRARY:
3498
0
    case cm::TargetType::SHARED_LIBRARY:
3499
0
    case cm::TargetType::EXECUTABLE:
3500
0
      break;
3501
0
    default:
3502
0
      return;
3503
0
  }
3504
3505
0
  std::string langLinkFlags =
3506
0
    this->Makefile->GetSafeDefinition(cmStrCat("CMAKE_", lang, "_LINK_FLAGS"));
3507
3508
0
  switch (target->GetPolicyStatusCMP0210()) {
3509
0
    case cmPolicies::WARN:
3510
      // WARN only when CMAKE_<LANG>_LINK_FLAGS is set, and when the current
3511
      // target is not an executable, and CMAKE_<LANG>_LINK_FLAGS is not equal
3512
      // to CMAKE_EXECUTABLE_CREATE_<LANG>_FLAGS. This warns users trying to
3513
      // use the NEW behavior on old projects (since CMake will be ignoring
3514
      // their wishes), while also exempting cases when the latter variable
3515
      // (substituted for the former spelling under the NEW behavior) is being
3516
      // used legitimately by CMake.
3517
      // Additionally, WARN at most once per language, instead of on every
3518
      // target.
3519
0
      if (!langLinkFlags.empty() &&
3520
0
          target->GetType() != cm::TargetType::EXECUTABLE &&
3521
0
          langLinkFlags !=
3522
0
            this->Makefile->GetSafeDefinition(
3523
0
              cmStrCat("CMAKE_EXECUTABLE_CREATE_", lang, "_FLAGS")) &&
3524
0
          this->GlobalGenerator->ShouldWarnCMP0210(lang)) {
3525
0
        this->IssuePolicyWarning(
3526
0
          cmPolicies::CMP0210, {},
3527
0
          cmStrCat("For compatibility with older versions of CMake, CMAKE_"_s,
3528
0
                   lang,
3529
0
                   "_LINK_FLAGS will be ignored for all non-EXECUTABLE "
3530
0
                   "targets which use these flags."_s));
3531
0
      }
3532
0
      CM_FALLTHROUGH;
3533
0
    case cmPolicies::OLD:
3534
      // OLD behavior is to do nothing here, since the use of
3535
      // CMAKE_<LANG>_LINK_FLAGS for EXECUTABLEs is handled elsewhere.
3536
0
      break;
3537
0
    case cmPolicies::NEW:
3538
      // NEW behavior is to support per-language link flags for all target
3539
      // types.
3540
0
      this->AppendLinkFlagsWithParsing(flags, langLinkFlags, target, lang);
3541
0
      if (!config.empty()) {
3542
0
        std::string lankLinkFlagsConfig =
3543
0
          this->Makefile->GetSafeDefinition(cmStrCat(
3544
0
            "CMAKE_", lang, "_LINK_FLAGS_", cmSystemTools::UpperCase(config)));
3545
0
        this->AppendLinkFlagsWithParsing(flags, lankLinkFlagsConfig, target,
3546
0
                                         lang);
3547
0
      }
3548
0
      break;
3549
0
  }
3550
0
}
3551
3552
void cmLocalGenerator::AppendTargetCreationLinkFlags(
3553
  std::string& flags, cmGeneratorTarget const* target,
3554
  std::string const& linkLanguage)
3555
0
{
3556
0
  std::string createFlagsVar;
3557
0
  cmValue createFlagsVal;
3558
0
  switch (target->GetType()) {
3559
0
    case cm::TargetType::STATIC_LIBRARY:
3560
0
      break;
3561
0
    case cm::TargetType::MODULE_LIBRARY:
3562
0
      createFlagsVar =
3563
0
        cmStrCat("CMAKE_SHARED_MODULE_CREATE_", linkLanguage, "_FLAGS");
3564
0
      createFlagsVal = this->Makefile->GetDefinition(createFlagsVar);
3565
      // On some platforms we use shared library creation flags for modules.
3566
0
      CM_FALLTHROUGH;
3567
0
    case cm::TargetType::SHARED_LIBRARY:
3568
0
      if (!createFlagsVal) {
3569
0
        createFlagsVar =
3570
0
          cmStrCat("CMAKE_SHARED_LIBRARY_CREATE_", linkLanguage, "_FLAGS");
3571
0
        createFlagsVal = this->Makefile->GetDefinition(createFlagsVar);
3572
0
      }
3573
0
      break;
3574
0
    case cm::TargetType::EXECUTABLE:
3575
0
      createFlagsVar = target->GetPolicyStatusCMP0210() == cmPolicies::NEW
3576
0
        ? cmStrCat("CMAKE_EXECUTABLE_CREATE_", linkLanguage, "_FLAGS")
3577
0
        : cmStrCat("CMAKE_", linkLanguage, "_LINK_FLAGS");
3578
0
      createFlagsVal = this->Makefile->GetDefinition(createFlagsVar);
3579
0
      break;
3580
0
    default:
3581
0
      break;
3582
0
  }
3583
0
  if (createFlagsVal) {
3584
0
    this->AppendFlags(flags, *createFlagsVal, createFlagsVar, target,
3585
0
                      cmBuildStep::Link, linkLanguage);
3586
0
  }
3587
0
}
3588
3589
void cmLocalGenerator::AppendLinkerTypeFlags(std::string& flags,
3590
                                             cmGeneratorTarget* target,
3591
                                             std::string const& config,
3592
                                             std::string const& linkLanguage)
3593
0
{
3594
0
  switch (target->GetType()) {
3595
0
    case cm::TargetType::EXECUTABLE:
3596
0
    case cm::TargetType::SHARED_LIBRARY:
3597
0
    case cm::TargetType::MODULE_LIBRARY:
3598
0
      break;
3599
0
    default:
3600
0
      return;
3601
0
  }
3602
3603
0
  auto linkMode =
3604
0
    cmStrCat("CMAKE_", linkLanguage, target->IsDeviceLink() ? "_DEVICE_" : "_",
3605
0
             "LINK_MODE");
3606
0
  auto mode = this->Makefile->GetDefinition(linkMode);
3607
0
  if (mode && mode != "DRIVER"_s) {
3608
0
    return;
3609
0
  }
3610
3611
0
  auto linkerType = target->GetLinkerTypeProperty(linkLanguage, config);
3612
0
  if (linkerType.empty()) {
3613
0
    linkerType = "DEFAULT";
3614
0
  }
3615
0
  auto usingLinker =
3616
0
    cmStrCat("CMAKE_", linkLanguage, "_USING_",
3617
0
             target->IsDeviceLink() ? "DEVICE_" : "", "LINKER_", linkerType);
3618
0
  auto linkerTypeFlags = this->Makefile->GetDefinition(usingLinker);
3619
0
  if (linkerTypeFlags) {
3620
0
    if (!linkerTypeFlags.IsEmpty()) {
3621
0
      auto linkerFlags = cmExpandListWithBacktrace(linkerTypeFlags);
3622
0
      target->ResolveLinkerWrapper(linkerFlags, linkLanguage);
3623
0
      this->AppendFlags(flags, linkerFlags);
3624
0
    }
3625
0
  } else if (linkerType != "DEFAULT"_s) {
3626
0
    auto isCMakeLinkerType = [](std::string const& type) -> bool {
3627
0
      return std::all_of(type.cbegin(), type.cend(), cmsysString_isupper);
3628
0
    };
3629
0
    if (isCMakeLinkerType(linkerType)) {
3630
0
      this->IssueMessage(
3631
0
        MessageType::FATAL_ERROR,
3632
0
        cmStrCat("LINKER_TYPE '", linkerType,
3633
0
                 "' is unknown or not supported by this toolchain."));
3634
0
    } else {
3635
0
      this->IssueMessage(
3636
0
        MessageType::FATAL_ERROR,
3637
0
        cmStrCat("LINKER_TYPE '", linkerType,
3638
0
                 "' is unknown. Did you forget to define the '", usingLinker,
3639
0
                 "' variable?"));
3640
0
    }
3641
0
  }
3642
0
}
3643
3644
void cmLocalGenerator::AddTargetTypeLinkerFlags(
3645
  std::string& flags, cmGeneratorTarget const* target, std::string const& lang,
3646
  std::string const& config)
3647
0
{
3648
0
  std::string linkerFlagsVar;
3649
0
  switch (target->GetType()) {
3650
0
    case cm::TargetType::EXECUTABLE:
3651
0
      linkerFlagsVar = "CMAKE_EXE_LINKER_FLAGS";
3652
0
      break;
3653
0
    case cm::TargetType::SHARED_LIBRARY:
3654
0
      linkerFlagsVar = "CMAKE_SHARED_LINKER_FLAGS";
3655
0
      break;
3656
0
    case cm::TargetType::MODULE_LIBRARY:
3657
0
      linkerFlagsVar = "CMAKE_MODULE_LINKER_FLAGS";
3658
0
      break;
3659
0
    default:
3660
0
      return;
3661
0
  }
3662
0
  this->AddConfigVariableFlags(flags, linkerFlagsVar, target,
3663
0
                               cmBuildStep::Link, lang, config);
3664
0
}
3665
3666
void cmLocalGenerator::AddTargetPropertyLinkFlags(
3667
  std::string& flags, cmGeneratorTarget const* target,
3668
  std::string const& config)
3669
0
{
3670
0
  cmValue targetLinkFlags = target->GetProperty("LINK_FLAGS");
3671
0
  if (targetLinkFlags) {
3672
0
    this->AppendFlags(flags, *targetLinkFlags);
3673
0
  }
3674
0
  if (!config.empty()) {
3675
0
    cmValue targetLinkFlagsConfig = target->GetProperty(
3676
0
      cmStrCat("LINK_FLAGS_", cmSystemTools::UpperCase(config)));
3677
0
    if (targetLinkFlagsConfig) {
3678
0
      this->AppendFlags(flags, *targetLinkFlagsConfig);
3679
0
    }
3680
0
  }
3681
0
}
3682
3683
void cmLocalGenerator::AppendIPOLinkerFlags(std::string& flags,
3684
                                            cmGeneratorTarget* target,
3685
                                            std::string const& config,
3686
                                            std::string const& lang)
3687
0
{
3688
0
  if (!target->IsIPOEnabled(lang, config)) {
3689
0
    return;
3690
0
  }
3691
3692
0
  switch (target->GetType()) {
3693
0
    case cm::TargetType::EXECUTABLE:
3694
0
    case cm::TargetType::SHARED_LIBRARY:
3695
0
    case cm::TargetType::MODULE_LIBRARY:
3696
0
      break;
3697
0
    default:
3698
0
      return;
3699
0
  }
3700
3701
0
  std::string const name = "CMAKE_" + lang + "_LINK_OPTIONS_IPO";
3702
0
  cmValue rawFlagsList = this->Makefile->GetDefinition(name);
3703
0
  if (!rawFlagsList) {
3704
0
    return;
3705
0
  }
3706
3707
0
  cmList flagsList{ *rawFlagsList };
3708
0
  for (std::string const& o : flagsList) {
3709
0
    this->AppendFlagEscape(flags, o);
3710
0
  }
3711
0
}
3712
3713
void cmLocalGenerator::AppendPositionIndependentLinkerFlags(
3714
  std::string& flags, cmGeneratorTarget* target, std::string const& config,
3715
  std::string const& lang)
3716
0
{
3717
  // For now, only EXECUTABLE is concerned
3718
0
  if (target->GetType() != cm::TargetType::EXECUTABLE) {
3719
0
    return;
3720
0
  }
3721
3722
0
  char const* PICValue = target->GetLinkPIEProperty(config);
3723
0
  if (!PICValue && lang != "Rust") {
3724
    // POSITION_INDEPENDENT_CODE is not set, note that for Rust we do not
3725
    // return as the compiler tends to enable PIE all the time, which is the
3726
    // opposite of what C & C++ compilers do. So instead of letting the rust
3727
    // compiler decide on its own whether PIE should be enabled, we explicit
3728
    // set it.
3729
0
    return;
3730
0
  }
3731
3732
0
  std::string const mode = cmIsOn(PICValue) ? "PIE" : "NO_PIE";
3733
3734
0
  std::string supported = "CMAKE_" + lang + "_LINK_" + mode + "_SUPPORTED";
3735
0
  if (this->Makefile->GetDefinition(supported).IsOff()) {
3736
0
    return;
3737
0
  }
3738
3739
0
  std::string name = "CMAKE_" + lang + "_LINK_OPTIONS_" + mode;
3740
3741
0
  auto pieFlags = this->Makefile->GetSafeDefinition(name);
3742
0
  if (pieFlags.empty()) {
3743
0
    return;
3744
0
  }
3745
3746
0
  cmList flagsList{ pieFlags };
3747
0
  for (auto const& flag : flagsList) {
3748
0
    this->AppendFlagEscape(flags, flag);
3749
0
  }
3750
0
}
3751
3752
void cmLocalGenerator::AppendWarningAsErrorLinkerFlags(
3753
  std::string& flags, cmGeneratorTarget* target, std::string const& lang)
3754
0
{
3755
0
  if (this->GetCMakeInstance()->GetIgnoreLinkWarningAsError()) {
3756
0
    return;
3757
0
  }
3758
3759
0
  switch (target->GetType()) {
3760
0
    case cm::TargetType::EXECUTABLE:
3761
0
    case cm::TargetType::SHARED_LIBRARY:
3762
0
    case cm::TargetType::MODULE_LIBRARY:
3763
0
      break;
3764
0
    default:
3765
0
      return;
3766
0
  }
3767
3768
0
  auto const wError = target->GetProperty("LINK_WARNING_AS_ERROR");
3769
0
  if (wError.IsOff()) {
3770
0
    return;
3771
0
  }
3772
0
  cmList wErrorOptions;
3773
0
  if (wError.IsOn()) {
3774
0
    wErrorOptions = { "DRIVER", "LINKER" };
3775
0
  } else {
3776
0
    wErrorOptions = wError;
3777
0
    std::sort(wErrorOptions.begin(), wErrorOptions.end());
3778
0
    wErrorOptions.erase(
3779
0
      std::unique(wErrorOptions.begin(), wErrorOptions.end()),
3780
0
      wErrorOptions.end());
3781
0
  }
3782
3783
0
  auto linkModeIsDriver =
3784
0
    this->Makefile->GetDefinition(cmStrCat("CMAKE_", lang, "_LINK_MODE")) ==
3785
0
    "DRIVER"_s;
3786
0
  std::string errorMessage;
3787
0
  for (auto const& option : wErrorOptions) {
3788
0
    if (option != "DRIVER"_s && option != "LINKER"_s) {
3789
0
      errorMessage += cmStrCat("  ", option, '\n');
3790
0
      continue;
3791
0
    }
3792
3793
0
    if (option == "DRIVER"_s && !linkModeIsDriver) {
3794
0
      continue;
3795
0
    }
3796
3797
0
    auto const wErrorOpts = this->Makefile->GetDefinition(cmStrCat(
3798
0
      "CMAKE_", lang, '_', (option == "DRIVER"_s ? "COMPILE" : "LINK"),
3799
0
      "_OPTIONS_WARNING_AS_ERROR"));
3800
0
    if (wErrorOpts.IsSet()) {
3801
0
      auto items =
3802
0
        cmExpandListWithBacktrace(wErrorOpts, target->GetBacktrace());
3803
0
      if (option == "LINKER"_s) {
3804
0
        target->ResolveLinkerWrapper(items, lang);
3805
0
      }
3806
0
      for (auto const& item : items) {
3807
0
        this->AppendFlagEscape(flags, item.Value);
3808
0
      }
3809
0
    }
3810
0
  }
3811
0
  if (!errorMessage.empty()) {
3812
0
    this->Makefile->GetCMakeInstance()->IssueMessage(
3813
0
      MessageType::FATAL_ERROR,
3814
0
      cmStrCat(
3815
0
        "Erroneous value(s) for 'LINK_WARNING_AS_ERROR' property of target '",
3816
0
        target->GetName(), "':\n", errorMessage));
3817
0
  }
3818
0
}
3819
3820
void cmLocalGenerator::AppendDependencyInfoLinkerFlags(
3821
  std::string& flags, cmGeneratorTarget* target, std::string const& config,
3822
  std::string const& linkLanguage)
3823
0
{
3824
0
  if (!this->GetGlobalGenerator()->SupportsLinkerDependencyFile() ||
3825
0
      !target->HasLinkDependencyFile(config)) {
3826
0
    return;
3827
0
  }
3828
3829
0
  auto depFlag = *this->Makefile->GetDefinition(
3830
0
    cmStrCat("CMAKE_", linkLanguage, "_LINKER_DEPFILE_FLAGS"));
3831
0
  if (depFlag.empty()) {
3832
0
    return;
3833
0
  }
3834
3835
0
  auto depFile = this->ConvertToOutputFormat(
3836
0
    this->MaybeRelativeToWorkDir(this->GetLinkDependencyFile(target, config)),
3837
0
    cmOutputConverter::SHELL);
3838
0
  auto rulePlaceholderExpander = this->CreateRulePlaceholderExpander();
3839
0
  cmRulePlaceholderExpander::RuleVariables linkDepsVariables;
3840
0
  linkDepsVariables.DependencyFile = depFile.c_str();
3841
0
  rulePlaceholderExpander->ExpandRuleVariables(this, depFlag,
3842
0
                                               linkDepsVariables);
3843
0
  auto depFlags = cmExpandListWithBacktrace(depFlag);
3844
0
  target->ResolveLinkerWrapper(depFlags, linkLanguage);
3845
3846
0
  this->AppendFlags(flags, depFlags);
3847
0
}
3848
3849
std::string cmLocalGenerator::GetLinkDependencyFile(
3850
  cmGeneratorTarget* /*target*/, std::string const& /*config*/) const
3851
0
{
3852
0
  return "link.d";
3853
0
}
3854
3855
void cmLocalGenerator::AppendModuleDefinitionFlag(
3856
  std::string& flags, cmGeneratorTarget const* target,
3857
  cmLinkLineComputer* linkLineComputer, std::string const& config,
3858
  std::string const& lang)
3859
0
{
3860
0
  cmGeneratorTarget::ModuleDefinitionInfo const* mdi =
3861
0
    target->GetModuleDefinitionInfo(config);
3862
0
  if (!mdi || mdi->DefFile.empty()) {
3863
0
    return;
3864
0
  }
3865
3866
0
  cmValue defFileFlag = this->Makefile->GetDefinition(
3867
0
    cmStrCat("CMAKE_", lang, "_LINK_DEF_FILE_FLAG"));
3868
0
  if (!defFileFlag) {
3869
0
    defFileFlag = this->Makefile->GetDefinition("CMAKE_LINK_DEF_FILE_FLAG");
3870
0
  }
3871
0
  if (!defFileFlag) {
3872
0
    return;
3873
0
  }
3874
3875
  // Append the flag and value.  Use ConvertToLinkReference to help
3876
  // vs6's "cl -link" pass it to the linker.
3877
0
  std::string flag =
3878
0
    cmStrCat(*defFileFlag,
3879
0
             this->ConvertToOutputFormat(
3880
0
               linkLineComputer->ConvertToLinkReference(mdi->DefFile),
3881
0
               cmOutputConverter::SHELL));
3882
0
  this->AppendFlags(flags, flag);
3883
0
}
3884
3885
bool cmLocalGenerator::AppendLWYUFlags(std::string& flags,
3886
                                       cmGeneratorTarget const* target,
3887
                                       std::string const& lang)
3888
0
{
3889
0
  auto useLWYU = target->GetPropertyAsBool("LINK_WHAT_YOU_USE") &&
3890
0
    (target->GetType() == cm::TargetType::EXECUTABLE ||
3891
0
     target->GetType() == cm::TargetType::SHARED_LIBRARY ||
3892
0
     target->GetType() == cm::TargetType::MODULE_LIBRARY);
3893
3894
0
  if (useLWYU) {
3895
0
    auto const& lwyuFlag = this->GetMakefile()->GetSafeDefinition(
3896
0
      cmStrCat("CMAKE_", lang, "_LINK_WHAT_YOU_USE_FLAG"));
3897
0
    useLWYU = !lwyuFlag.empty();
3898
3899
0
    if (useLWYU) {
3900
0
      std::vector<BT<std::string>> lwyuOpts;
3901
0
      lwyuOpts.emplace_back(lwyuFlag);
3902
0
      this->AppendFlags(flags, target->ResolveLinkerWrapper(lwyuOpts, lang));
3903
0
    }
3904
0
  }
3905
3906
0
  return useLWYU;
3907
0
}
3908
3909
void cmLocalGenerator::AppendCompileOptions(std::string& options,
3910
                                            std::string const& options_list,
3911
                                            char const* regex) const
3912
0
{
3913
  // Short-circuit if there are no options.
3914
0
  if (options_list.empty()) {
3915
0
    return;
3916
0
  }
3917
3918
  // Expand the list of options.
3919
0
  cmList options_vec{ options_list };
3920
0
  this->AppendCompileOptions(options, options_vec, regex);
3921
0
}
3922
3923
void cmLocalGenerator::AppendCompileOptions(
3924
  std::string& options, std::vector<std::string> const& options_vec,
3925
  char const* regex) const
3926
0
{
3927
0
  if (regex) {
3928
    // Filter flags upon specified reges.
3929
0
    cmsys::RegularExpression r(regex);
3930
3931
0
    for (std::string const& opt : options_vec) {
3932
0
      if (r.find(opt)) {
3933
0
        this->AppendFlagEscape(options, opt);
3934
0
      }
3935
0
    }
3936
0
  } else {
3937
0
    for (std::string const& opt : options_vec) {
3938
0
      this->AppendFlagEscape(options, opt);
3939
0
    }
3940
0
  }
3941
0
}
3942
3943
void cmLocalGenerator::AppendCompileOptions(
3944
  std::vector<BT<std::string>>& options,
3945
  std::vector<BT<std::string>> const& options_vec, char const* regex) const
3946
0
{
3947
0
  if (regex) {
3948
    // Filter flags upon specified regular expressions.
3949
0
    cmsys::RegularExpression r(regex);
3950
3951
0
    for (BT<std::string> const& opt : options_vec) {
3952
0
      if (r.find(opt.Value)) {
3953
0
        std::string flag;
3954
0
        this->AppendFlagEscape(flag, opt.Value);
3955
0
        options.emplace_back(std::move(flag), opt.Backtrace);
3956
0
      }
3957
0
    }
3958
0
  } else {
3959
0
    for (BT<std::string> const& opt : options_vec) {
3960
0
      std::string flag;
3961
0
      this->AppendFlagEscape(flag, opt.Value);
3962
0
      options.emplace_back(std::move(flag), opt.Backtrace);
3963
0
    }
3964
0
  }
3965
0
}
3966
3967
void cmLocalGenerator::AppendIncludeDirectories(
3968
  std::vector<std::string>& includes, std::string const& includes_list,
3969
  cmSourceFile const& sourceFile) const
3970
0
{
3971
  // Short-circuit if there are no includes.
3972
0
  if (includes_list.empty()) {
3973
0
    return;
3974
0
  }
3975
3976
  // Expand the list of includes.
3977
0
  cmList includes_vec{ includes_list };
3978
0
  this->AppendIncludeDirectories(includes, includes_vec, sourceFile);
3979
0
}
3980
3981
void cmLocalGenerator::AppendIncludeDirectories(
3982
  std::vector<std::string>& includes,
3983
  std::vector<std::string> const& includes_vec,
3984
  cmSourceFile const& sourceFile) const
3985
0
{
3986
0
  std::unordered_set<std::string> uniqueIncludes;
3987
3988
0
  for (std::string const& include : includes_vec) {
3989
0
    if (!cmSystemTools::FileIsFullPath(include)) {
3990
0
      std::ostringstream e;
3991
0
      e << "Found relative path while evaluating include directories of "
3992
0
           "\""
3993
0
        << sourceFile.GetLocation().GetName() << "\":\n  \"" << include
3994
0
        << "\"\n";
3995
3996
0
      this->IssueMessage(MessageType::FATAL_ERROR, e.str());
3997
0
      return;
3998
0
    }
3999
4000
0
    std::string inc = include;
4001
4002
0
    if (!cmIsOff(inc)) {
4003
0
      cmSystemTools::ConvertToUnixSlashes(inc);
4004
0
    }
4005
4006
0
    if (uniqueIncludes.insert(inc).second) {
4007
0
      includes.push_back(std::move(inc));
4008
0
    }
4009
0
  }
4010
0
}
4011
4012
void cmLocalGenerator::AppendDefines(std::set<std::string>& defines,
4013
                                     std::string const& defines_list) const
4014
0
{
4015
0
  std::set<BT<std::string>> tmp;
4016
0
  this->AppendDefines(tmp, cmExpandListWithBacktrace(defines_list));
4017
0
  for (BT<std::string> const& i : tmp) {
4018
0
    defines.emplace(i.Value);
4019
0
  }
4020
0
}
4021
4022
void cmLocalGenerator::AppendDefines(
4023
  std::set<std::string>& defines,
4024
  std::vector<BT<std::string>> const& defines_vec) const
4025
0
{
4026
0
  std::set<BT<std::string>> tmp;
4027
0
  this->AppendDefines(tmp, defines_vec);
4028
0
  for (BT<std::string> const& i : tmp) {
4029
0
    defines.emplace(i.Value);
4030
0
  }
4031
0
}
4032
4033
void cmLocalGenerator::AppendDefines(std::set<BT<std::string>>& defines,
4034
                                     std::string const& defines_list) const
4035
0
{
4036
  // Short-circuit if there are no definitions.
4037
0
  if (defines_list.empty()) {
4038
0
    return;
4039
0
  }
4040
4041
  // Expand the list of definitions.
4042
0
  this->AppendDefines(defines, cmExpandListWithBacktrace(defines_list));
4043
0
}
4044
4045
void cmLocalGenerator::AppendDefines(
4046
  std::set<BT<std::string>>& defines,
4047
  std::vector<BT<std::string>> const& defines_vec) const
4048
0
{
4049
0
  for (BT<std::string> const& d : defines_vec) {
4050
    // Skip unsupported definitions.
4051
0
    if (!this->CheckDefinition(d.Value)) {
4052
0
      continue;
4053
0
    }
4054
    // remove any leading -D
4055
0
    if (cmHasLiteralPrefix(d.Value, "-D")) {
4056
0
      defines.emplace(d.Value.substr(2), d.Backtrace);
4057
0
    } else {
4058
0
      defines.insert(d);
4059
0
    }
4060
0
  }
4061
0
}
4062
4063
void cmLocalGenerator::JoinDefines(std::set<std::string> const& defines,
4064
                                   std::string& definesString,
4065
                                   std::string const& lang)
4066
0
{
4067
  // Lookup the define flag for the current language.
4068
0
  std::string dflag = "-D";
4069
0
  if (!lang.empty()) {
4070
0
    cmValue df =
4071
0
      this->Makefile->GetDefinition(cmStrCat("CMAKE_", lang, "_DEFINE_FLAG"));
4072
0
    if (cmNonempty(df)) {
4073
0
      dflag = *df;
4074
0
    }
4075
0
  }
4076
0
  char const* itemSeparator = definesString.empty() ? "" : " ";
4077
0
  for (std::string const& define : defines) {
4078
    // Append the definition with proper escaping.
4079
0
    std::string def = dflag;
4080
0
    if (this->GetState()->UseWatcomWMake()) {
4081
      // The Watcom compiler does its own command line parsing instead
4082
      // of using the windows shell rules.  Definitions are one of
4083
      //   -DNAME
4084
      //   -DNAME=<cpp-token>
4085
      //   -DNAME="c-string with spaces and other characters(?@#$)"
4086
      //
4087
      // Watcom will properly parse each of these cases from the
4088
      // command line without any escapes.  However we still have to
4089
      // get the '$' and '#' characters through WMake as '$$' and
4090
      // '$#'.
4091
0
      for (char c : define) {
4092
0
        if (c == '$' || c == '#') {
4093
0
          def += '$';
4094
0
        }
4095
0
        def += c;
4096
0
      }
4097
0
    } else {
4098
      // Make the definition appear properly on the command line.  Use
4099
      // -DNAME="value" instead of -D"NAME=value" for historical reasons.
4100
0
      std::string::size_type eq = define.find('=');
4101
0
      def += define.substr(0, eq);
4102
0
      if (eq != std::string::npos) {
4103
0
        def += "=";
4104
0
        def += this->EscapeForShell(define.substr(eq + 1), true);
4105
0
      }
4106
0
    }
4107
0
    definesString += itemSeparator;
4108
0
    itemSeparator = " ";
4109
0
    definesString += def;
4110
0
  }
4111
0
}
4112
4113
void cmLocalGenerator::AppendFeatureOptions(std::string& flags,
4114
                                            std::string const& lang,
4115
                                            char const* feature)
4116
0
{
4117
0
  cmValue optionList = this->Makefile->GetDefinition(
4118
0
    cmStrCat("CMAKE_", lang, "_COMPILE_OPTIONS_", feature));
4119
0
  if (optionList) {
4120
0
    cmList options{ *optionList };
4121
0
    for (std::string const& o : options) {
4122
0
      this->AppendFlagEscape(flags, o);
4123
0
    }
4124
0
  }
4125
0
}
4126
4127
cmValue cmLocalGenerator::GetFeature(std::string const& feature,
4128
                                     std::string const& config)
4129
0
{
4130
0
  std::string featureName = feature;
4131
  // TODO: Define accumulation policy for features (prepend, append,
4132
  // replace). Currently we always replace.
4133
0
  if (!config.empty()) {
4134
0
    featureName += "_";
4135
0
    featureName += cmSystemTools::UpperCase(config);
4136
0
  }
4137
0
  cmStateSnapshot snp = this->StateSnapshot;
4138
0
  while (snp.IsValid()) {
4139
0
    if (cmValue value = snp.GetDirectory().GetProperty(featureName)) {
4140
0
      return value;
4141
0
    }
4142
0
    snp = snp.GetBuildsystemDirectoryParent();
4143
0
  }
4144
0
  return nullptr;
4145
0
}
4146
4147
std::string cmLocalGenerator::GetProjectName() const
4148
0
{
4149
0
  return this->StateSnapshot.GetProjectName();
4150
0
}
4151
4152
std::string cmLocalGenerator::ConstructComment(
4153
  cmCustomCommandGenerator const& ccg, char const* default_comment) const
4154
0
{
4155
  // Check for a comment provided with the command.
4156
0
  if (cm::optional<std::string> comment = ccg.GetComment()) {
4157
0
    return *comment;
4158
0
  }
4159
4160
  // Construct a reasonable default comment if possible.
4161
0
  if (!ccg.GetOutputs().empty()) {
4162
0
    std::string comment;
4163
0
    comment = "Generating ";
4164
0
    char const* sep = "";
4165
0
    for (std::string const& o : ccg.GetOutputs()) {
4166
0
      comment += sep;
4167
0
      comment += this->MaybeRelativeToCurBinDir(o);
4168
0
      sep = ", ";
4169
0
    }
4170
0
    return comment;
4171
0
  }
4172
4173
  // Otherwise use the provided default.
4174
0
  return default_comment;
4175
0
}
4176
4177
class cmInstallTargetGeneratorLocal : public cmInstallTargetGenerator
4178
{
4179
public:
4180
  cmInstallTargetGeneratorLocal(cmLocalGenerator* lg, std::string const& t,
4181
                                std::string const& dest, bool implib)
4182
0
    : cmInstallTargetGenerator(
4183
0
        t, dest, implib, "", std::vector<std::string>(), "Unspecified",
4184
0
        cmInstallGenerator::SelectMessageLevel(lg->GetMakefile()), false,
4185
0
        false)
4186
0
  {
4187
0
    this->Compute(lg);
4188
0
  }
4189
};
4190
4191
void cmLocalGenerator::GenerateTargetInstallRules(
4192
  std::ostream& os, std::string const& config,
4193
  std::vector<std::string> const& configurationTypes)
4194
0
{
4195
  // Convert the old-style install specification from each target to
4196
  // an install generator and run it.
4197
0
  auto const& tgts = this->GetGeneratorTargets();
4198
0
  for (auto const& l : tgts) {
4199
0
    if (l->GetType() == cm::TargetType::INTERFACE_LIBRARY) {
4200
0
      continue;
4201
0
    }
4202
4203
    // Include the user-specified pre-install script for this target.
4204
0
    if (cmValue preinstall = l->GetProperty("PRE_INSTALL_SCRIPT")) {
4205
0
      cmInstallScriptGenerator g(*preinstall, false, "", false, false);
4206
0
      g.Generate(os, config, configurationTypes);
4207
0
    }
4208
4209
    // Install this target if a destination is given.
4210
0
    if (!l->Target->GetInstallPath().empty()) {
4211
      // Compute the full install destination.  Note that converting
4212
      // to unix slashes also removes any trailing slash.
4213
      // We also skip over the leading slash given by the user.
4214
0
      std::string destination = l->Target->GetInstallPath().substr(1);
4215
0
      cmSystemTools::ConvertToUnixSlashes(destination);
4216
0
      if (destination.empty()) {
4217
0
        destination = ".";
4218
0
      }
4219
4220
      // Generate the proper install generator for this target type.
4221
0
      switch (l->GetType()) {
4222
0
        case cm::TargetType::EXECUTABLE:
4223
0
        case cm::TargetType::STATIC_LIBRARY:
4224
0
        case cm::TargetType::MODULE_LIBRARY: {
4225
          // Use a target install generator.
4226
0
          cmInstallTargetGeneratorLocal g(this, l->GetName(), destination,
4227
0
                                          false);
4228
0
          g.Generate(os, config, configurationTypes);
4229
0
        } break;
4230
0
        case cm::TargetType::SHARED_LIBRARY: {
4231
#if defined(_WIN32) || defined(__CYGWIN__)
4232
          // Special code to handle DLL.  Install the import library
4233
          // to the normal destination and the DLL to the runtime
4234
          // destination.
4235
          cmInstallTargetGeneratorLocal g1(this, l->GetName(), destination,
4236
                                           true);
4237
          g1.Generate(os, config, configurationTypes);
4238
          // We also skip over the leading slash given by the user.
4239
          destination = l->Target->GetRuntimeInstallPath().substr(1);
4240
          cmSystemTools::ConvertToUnixSlashes(destination);
4241
          cmInstallTargetGeneratorLocal g2(this, l->GetName(), destination,
4242
                                           false);
4243
          g2.Generate(os, config, configurationTypes);
4244
#else
4245
          // Use a target install generator.
4246
0
          cmInstallTargetGeneratorLocal g(this, l->GetName(), destination,
4247
0
                                          false);
4248
0
          g.Generate(os, config, configurationTypes);
4249
0
#endif
4250
0
        } break;
4251
0
        default:
4252
0
          break;
4253
0
      }
4254
0
    }
4255
4256
    // Include the user-specified post-install script for this target.
4257
0
    if (cmValue postinstall = l->GetProperty("POST_INSTALL_SCRIPT")) {
4258
0
      cmInstallScriptGenerator g(*postinstall, false, "", false, false);
4259
0
      g.Generate(os, config, configurationTypes);
4260
0
    }
4261
0
  }
4262
0
}
4263
4264
namespace {
4265
bool cmLocalGeneratorShortenObjectName(std::string& objName,
4266
                                       std::string::size_type max_len)
4267
0
{
4268
  // Check if the path can be shortened using an md5 sum replacement for
4269
  // a portion of the path.
4270
0
  std::string::size_type md5Len = 32;
4271
0
  std::string::size_type numExtraChars = objName.size() - max_len + md5Len;
4272
0
  std::string::size_type pos = objName.find('/', numExtraChars);
4273
0
  if (pos == std::string::npos) {
4274
0
    pos = objName.rfind('/', numExtraChars);
4275
0
    if (pos == std::string::npos || pos <= md5Len) {
4276
0
      return false;
4277
0
    }
4278
0
  }
4279
4280
  // Replace the beginning of the path portion of the object name with
4281
  // its own md5 sum.
4282
0
  cmCryptoHash md5(cmCryptoHash::AlgoMD5);
4283
0
  std::string md5name = cmStrCat(md5.HashString(objName.substr(0, pos)),
4284
0
                                 cm::string_view(objName).substr(pos));
4285
0
  objName = md5name;
4286
4287
  // The object name is now shorter, check if it is short enough.
4288
0
  return pos >= numExtraChars;
4289
0
}
4290
4291
bool cmLocalGeneratorCheckObjectName(std::string& objName,
4292
                                     std::string::size_type dir_len,
4293
                                     std::string::size_type max_total_len)
4294
0
{
4295
  // Enforce the maximum file name length if possible.
4296
0
  std::string::size_type max_obj_len = max_total_len;
4297
0
  if (dir_len < max_total_len) {
4298
0
    max_obj_len = max_total_len - dir_len;
4299
0
    if (objName.size() > max_obj_len) {
4300
      // The current object file name is too long.  Try to shorten it.
4301
0
      return cmLocalGeneratorShortenObjectName(objName, max_obj_len);
4302
0
    }
4303
    // The object file name is short enough.
4304
0
    return true;
4305
0
  }
4306
  // The build directory in which the object will be stored is
4307
  // already too deep.
4308
0
  return false;
4309
0
}
4310
}
4311
4312
std::string cmLocalGenerator::CreateSafeObjectFileName(
4313
  std::string const& sin) const
4314
0
{
4315
  // Start with the original name.
4316
0
  std::string ssin = sin;
4317
4318
  // Avoid full paths by removing leading slashes.
4319
0
  ssin.erase(0, ssin.find_first_not_of('/'));
4320
4321
  // Avoid full paths by removing colons.
4322
0
  std::replace(ssin.begin(), ssin.end(), ':', '_');
4323
4324
  // Avoid relative paths that go up the tree.
4325
0
  cmSystemTools::ReplaceString(ssin, "../", "__/");
4326
4327
  // Avoid spaces.
4328
0
  std::replace(ssin.begin(), ssin.end(), ' ', '_');
4329
4330
0
  return ssin;
4331
0
}
4332
4333
// search a the source group defined for the file set or the source itself
4334
// in case of match, result is stored in a cache to speed-up future searches
4335
cmSourceGroup* cmLocalGenerator::FindSourceGroup(
4336
  cmGeneratorTarget const* target, cmSourceFile const* source,
4337
  std::string const& config)
4338
0
{
4339
0
#if !defined(CMAKE_BOOTSTRAP)
4340
0
  std::string const SOURCE_GROUP{ "SOURCE_GROUP" };
4341
0
  std::string const& targetName = target->GetName();
4342
0
  cmGeneratorFileSet const* fileSet =
4343
0
    target->GetFileSetForSource(config, source);
4344
4345
0
  if (fileSet) {
4346
0
    std::string fsName = fileSet->GetName();
4347
0
    std::string const fsKey = cmStrCat(targetName, "::", fsName);
4348
0
    auto const indexIt = this->SourceGroupSearchIndex.find(fsKey);
4349
0
    if (indexIt != this->SourceGroupSearchIndex.cend()) {
4350
0
      return indexIt->second;
4351
0
    }
4352
4353
0
    cmValue fsSG = fileSet->GetProperty(SOURCE_GROUP);
4354
0
    if (!fsSG.IsEmpty()) {
4355
0
      cmSourceGroup* sg = this->GetMakefile()->GetOrCreateSourceGroup(*fsSG);
4356
0
      this->SourceGroupSearchIndex.emplace(fsKey, sg);
4357
0
      return sg;
4358
0
    }
4359
4360
0
    cmSourceGroup* sourceGroup = cmSourceGroup::FindSourceGroup(
4361
0
      targetName, fsName, this->Makefile->GetSourceGroups());
4362
0
    if (sourceGroup) {
4363
0
      this->SourceGroupSearchIndex.emplace(fsKey, sourceGroup);
4364
0
      return sourceGroup;
4365
0
    }
4366
0
  }
4367
4368
  // no source group defined for the file set or the source is not part of a
4369
  // file set.
4370
  // search for source group defined at source level
4371
0
  auto const indexIt =
4372
0
    this->SourceGroupSearchIndex.find(source->GetFullPath());
4373
0
  if (indexIt != this->SourceGroupSearchIndex.cend()) {
4374
0
    return indexIt->second;
4375
0
  }
4376
4377
0
  cmValue srcSG = source->GetProperty(SOURCE_GROUP);
4378
0
  if (!srcSG.IsEmpty()) {
4379
0
    cmSourceGroup* sg = this->GetMakefile()->GetOrCreateSourceGroup(*srcSG);
4380
0
    this->SourceGroupSearchIndex.emplace(source->GetFullPath(), sg);
4381
0
    return sg;
4382
0
  }
4383
4384
  // look-up in source groups definitions
4385
0
  return this->FindSourceGroup(source->GetFullPath());
4386
#else
4387
  static_cast<void>(target);
4388
  static_cast<void>(source);
4389
  static_cast<void>(config);
4390
  return nullptr;
4391
#endif
4392
0
}
4393
4394
cmSourceGroup* cmLocalGenerator::FindSourceGroup(std::string const& source)
4395
0
{
4396
0
#if !defined(CMAKE_BOOTSTRAP)
4397
0
  auto const indexIt = SourceGroupSearchIndex.find(source);
4398
0
  if (indexIt != SourceGroupSearchIndex.cend()) {
4399
0
    if (cmSourceGroup* result = indexIt->second) {
4400
0
      return result;
4401
0
    }
4402
0
  }
4403
4404
0
  cmSourceGroup* sourceGroup =
4405
0
    cmSourceGroup::FindSourceGroup(source, this->Makefile->GetSourceGroups());
4406
0
  if (sourceGroup) {
4407
    // Update index if we have a miss
4408
0
    SourceGroupSearchIndex.emplace(source, sourceGroup);
4409
0
  }
4410
0
  return sourceGroup;
4411
#else
4412
  static_cast<void>(source);
4413
  return nullptr;
4414
#endif
4415
0
}
4416
4417
std::string& cmLocalGenerator::CreateSafeUniqueObjectFileName(
4418
  std::string const& sin, std::string const& dir_max)
4419
0
{
4420
  // Look for an existing mapped name for this object file.
4421
0
  auto it = this->UniqueObjectNamesMap.find(sin);
4422
4423
  // If no entry exists create one.
4424
0
  if (it == this->UniqueObjectNamesMap.end()) {
4425
0
    auto ssin = this->CreateSafeObjectFileName(sin);
4426
4427
    // Mangle the name if necessary.
4428
0
    if (this->Makefile->IsOn("CMAKE_MANGLE_OBJECT_FILE_NAMES")) {
4429
0
      bool done;
4430
0
      int cc = 0;
4431
0
      char rpstr[100];
4432
0
      snprintf(rpstr, sizeof(rpstr), "_p_");
4433
0
      cmSystemTools::ReplaceString(ssin, "+", rpstr);
4434
0
      std::string sssin = sin;
4435
0
      do {
4436
0
        done = true;
4437
0
        for (it = this->UniqueObjectNamesMap.begin();
4438
0
             it != this->UniqueObjectNamesMap.end(); ++it) {
4439
0
          if (it->second == ssin) {
4440
0
            done = false;
4441
0
          }
4442
0
        }
4443
0
        if (done) {
4444
0
          break;
4445
0
        }
4446
0
        sssin = ssin;
4447
0
        cmSystemTools::ReplaceString(ssin, "_p_", rpstr);
4448
0
        snprintf(rpstr, sizeof(rpstr), "_p%d_", cc++);
4449
0
      } while (!done);
4450
0
    }
4451
4452
0
    if (!cmLocalGeneratorCheckObjectName(ssin, dir_max.size(),
4453
0
                                         this->ObjectPathMax)) {
4454
      // Warn if this is the first time the path has been seen.
4455
0
      if (this->ObjectMaxPathViolations.insert(dir_max).second) {
4456
0
        std::ostringstream m;
4457
        /* clang-format off */
4458
0
        m << "The object file directory\n"
4459
0
          << "  " << dir_max << "\n"
4460
0
          << "has " << dir_max.size() << " characters.  "
4461
0
          << "The maximum full path to an object file is "
4462
0
          << this->ObjectPathMax << " characters "
4463
0
          << "(see CMAKE_OBJECT_PATH_MAX).  "
4464
0
          << "Object file\n"
4465
0
          << "  " << ssin << "\n"
4466
0
          << "cannot be safely placed under this directory.  "
4467
0
          << "The build may not work correctly.";
4468
        /* clang-format on */
4469
0
        this->IssueMessage(MessageType::WARNING, m.str());
4470
0
      }
4471
0
    }
4472
4473
    // Insert the newly mapped object file name.
4474
0
    std::map<std::string, std::string>::value_type e(sin, ssin);
4475
0
    it = this->UniqueObjectNamesMap.insert(e).first;
4476
0
  }
4477
4478
  // Return the map entry.
4479
0
  return it->second;
4480
0
}
4481
4482
void cmLocalGenerator::ComputeObjectFilenames(
4483
  std::map<cmSourceFile const*, cmObjectLocations>& /*unused*/,
4484
  std::string const& /*unused*/, cmGeneratorTarget const* /*unused*/)
4485
0
{
4486
0
}
4487
4488
bool cmLocalGenerator::IsWindowsShell() const
4489
0
{
4490
0
  return this->GetState()->UseWindowsShell();
4491
0
}
4492
4493
bool cmLocalGenerator::IsWatcomWMake() const
4494
0
{
4495
0
  return this->GetState()->UseWatcomWMake();
4496
0
}
4497
4498
bool cmLocalGenerator::IsMinGWMake() const
4499
0
{
4500
0
  return this->GetState()->UseMinGWMake();
4501
0
}
4502
4503
bool cmLocalGenerator::IsNMake() const
4504
0
{
4505
0
  return this->GetState()->UseNMake();
4506
0
}
4507
4508
bool cmLocalGenerator::IsNinjaMulti() const
4509
0
{
4510
0
  return this->GetState()->UseNinjaMulti();
4511
0
}
4512
4513
bool cmLocalGenerator::IsWindowsVSIDE() const
4514
0
{
4515
0
  return this->GetState()->UseWindowsVSIDE();
4516
0
}
4517
4518
namespace {
4519
std::string relativeIfUnder(std::string const& top, std::string const& cur,
4520
                            std::string const& path)
4521
0
{
4522
  // Use a path relative to 'cur' if it can be expressed without
4523
  // a `../` sequence that leaves 'top'.
4524
0
  if (cmSystemTools::IsSubDirectory(path, cur) ||
4525
0
      (cmSystemTools::IsSubDirectory(cur, top) &&
4526
0
       cmSystemTools::IsSubDirectory(path, top))) {
4527
0
    return cmSystemTools::ForceToRelativePath(cur, path);
4528
0
  }
4529
0
  return path;
4530
0
}
4531
}
4532
4533
std::string cmLocalGenerator::GetRelativeSourceFileName(
4534
  cmSourceFile const& source) const
4535
0
{
4536
  // Construct the object file name using the full path to the source
4537
  // file which is its only unique identification.
4538
0
  std::string const& fullPath = source.GetFullPath();
4539
4540
  // Try referencing the source relative to the source tree.
4541
0
  std::string relFromSource = relativeIfUnder(
4542
0
    this->GetSourceDirectory(), this->GetCurrentSourceDirectory(), fullPath);
4543
0
  assert(!relFromSource.empty());
4544
0
  bool relSource = !cmSystemTools::FileIsFullPath(relFromSource);
4545
0
  bool subSource = relSource && relFromSource[0] != '.';
4546
4547
  // Try referencing the source relative to the binary tree.
4548
0
  std::string relFromBinary = relativeIfUnder(
4549
0
    this->GetBinaryDirectory(), this->GetCurrentBinaryDirectory(), fullPath);
4550
0
  assert(!relFromBinary.empty());
4551
0
  bool relBinary = !cmSystemTools::FileIsFullPath(relFromBinary);
4552
0
  bool subBinary = relBinary && relFromBinary[0] != '.';
4553
4554
  // Select a nice-looking reference to the source file to construct
4555
  // the object file name.
4556
0
  std::string objectName;
4557
  // XXX(clang-tidy): https://bugs.llvm.org/show_bug.cgi?id=44165
4558
  // NOLINTNEXTLINE(bugprone-branch-clone)
4559
0
  if ((relSource && !relBinary) || (subSource && !subBinary)) {
4560
0
    objectName = relFromSource;
4561
0
  } else if ((relBinary && !relSource) || (subBinary && !subSource) ||
4562
0
             relFromBinary.length() < relFromSource.length()) {
4563
0
    objectName = relFromBinary;
4564
0
  } else {
4565
0
    objectName = relFromSource;
4566
0
  }
4567
0
  return objectName;
4568
0
}
4569
4570
std::string cmLocalGenerator::GetCustomObjectFileName(
4571
  cmSourceFile const& source) const
4572
0
{
4573
0
  if (!this->GetGlobalGenerator()->SupportsCustomObjectNames()) {
4574
0
    return std::string{};
4575
0
  }
4576
4577
0
  if (auto objName = source.GetProperty("OBJECT_NAME")) {
4578
0
    cmGeneratorExpression ge(*this->GetCMakeInstance());
4579
0
    auto cge = ge.Parse(objName);
4580
0
    static std::string const INVALID_GENEX =
4581
0
      "_cmake_invalid_object_name_genex";
4582
0
    static std::string const INVALID_VALUE =
4583
0
      "_cmake_invalid_object_name_value";
4584
4585
0
    if (!cge) {
4586
0
      this->Makefile->IssueMessage(
4587
0
        MessageType::FATAL_ERROR,
4588
0
        cmStrCat("The  \"OBJECT_NAME\" property for\n  ", source.GetFullPath(),
4589
0
                 "\nis not a valid generator expression (", objName, ")."));
4590
0
      return INVALID_GENEX;
4591
0
    }
4592
0
    if (cge->GetHadHeadSensitiveCondition()) {
4593
      // Not reachable; all target-sensitive  genexes actually fail to parse.
4594
0
      this->Makefile->IssueMessage(
4595
0
        MessageType::FATAL_ERROR,
4596
0
        cmStrCat("The  \"OBJECT_NAME\" property for\n  ", source.GetFullPath(),
4597
0
                 "\ncontains a condition that queries the consuming target "
4598
0
                 "which is not supported (",
4599
0
                 objName, ")."));
4600
0
      return INVALID_GENEX;
4601
0
    }
4602
0
    if (cge->GetHadLinkLanguageSensitiveCondition()) {
4603
      // Not reachable; all target-sensitive  genexes actually fail to parse.
4604
0
      this->Makefile->IssueMessage(
4605
0
        MessageType::FATAL_ERROR,
4606
0
        cmStrCat("The  \"OBJECT_NAME\" property for\n  ", source.GetFullPath(),
4607
0
                 "\ncontains a condition that queries the link language "
4608
0
                 "which is not supported (",
4609
0
                 objName, ")."));
4610
0
      return INVALID_GENEX;
4611
0
    }
4612
4613
0
    auto objNameValue = cge->Evaluate(this, "");
4614
0
    if (cge->GetHadContextSensitiveCondition()) {
4615
0
      this->Makefile->IssueMessage(
4616
0
        MessageType::FATAL_ERROR,
4617
0
        cmStrCat("The  \"OBJECT_NAME\" property for\n  ", source.GetFullPath(),
4618
0
                 "\ncontains a context-sensitive condition which is not "
4619
0
                 "supported (",
4620
0
                 objName, ")."));
4621
0
      return INVALID_GENEX;
4622
0
    }
4623
4624
    // Skip if it evaluates to empty.
4625
0
    if (!objNameValue.empty()) {
4626
0
      cmCMakePath objNamePath = objNameValue;
4627
      // Verify that it is a relative path.
4628
0
      if (objNamePath.IsAbsolute()) {
4629
0
        this->Makefile->IssueMessage(
4630
0
          MessageType::FATAL_ERROR,
4631
0
          cmStrCat(
4632
0
            "The  \"OBJECT_NAME\" property for\n  ", source.GetFullPath(),
4633
0
            "\nresolves to an absolute path which is not supported:\n  ",
4634
0
            objNameValue));
4635
0
        return INVALID_VALUE;
4636
0
      }
4637
0
      auto isInvalidComponent = [](cmCMakePath const& component) -> bool {
4638
0
        return component == ".."_s;
4639
0
      };
4640
      // Verify that it contains no `..` components.
4641
0
      if (std::any_of(objNamePath.begin(), objNamePath.end(),
4642
0
                      isInvalidComponent)) {
4643
0
        this->Makefile->IssueMessage(
4644
0
          MessageType::FATAL_ERROR,
4645
0
          cmStrCat("The  \"OBJECT_NAME\" property for\n  ",
4646
0
                   source.GetFullPath(), "\ncontains an invalid component (",
4647
0
                   objNameValue, ")."));
4648
0
        return INVALID_VALUE;
4649
0
      }
4650
4651
0
      return objNameValue;
4652
0
    }
4653
0
  }
4654
4655
0
  return std::string{};
4656
0
}
4657
4658
std::string cmLocalGenerator::GetCustomInstallObjectFileName(
4659
  cmSourceFile const& source, std::string const& config,
4660
  char const* custom_ext) const
4661
0
{
4662
0
  if (auto objName = source.GetProperty("INSTALL_OBJECT_NAME")) {
4663
0
    cmGeneratorExpression ge(*this->GetCMakeInstance());
4664
0
    auto cge = ge.Parse(objName);
4665
0
    static std::string const INVALID_GENEX =
4666
0
      "_cmake_invalid_object_name_genex";
4667
0
    static std::string const INVALID_VALUE =
4668
0
      "_cmake_invalid_object_name_value";
4669
4670
0
    if (!cge) {
4671
0
      this->Makefile->IssueMessage(
4672
0
        MessageType::FATAL_ERROR,
4673
0
        cmStrCat("The  \"INSTALL_OBJECT_NAME\" property for\n  ",
4674
0
                 source.GetFullPath(),
4675
0
                 "\nis not a valid generator expression (", objName, ")."));
4676
0
      return INVALID_GENEX;
4677
0
    }
4678
0
    if (cge->GetHadHeadSensitiveCondition()) {
4679
      // Not reachable; all target-sensitive  genexes actually fail to parse.
4680
0
      this->Makefile->IssueMessage(
4681
0
        MessageType::FATAL_ERROR,
4682
0
        cmStrCat("The  \"INSTALL_OBJECT_NAME\" property for\n  ",
4683
0
                 source.GetFullPath(),
4684
0
                 "\ncontains a condition that queries the consuming target "
4685
0
                 "which is not supported (",
4686
0
                 objName, ")."));
4687
0
      return INVALID_GENEX;
4688
0
    }
4689
0
    if (cge->GetHadLinkLanguageSensitiveCondition()) {
4690
      // Not reachable; all target-sensitive  genexes actually fail to parse.
4691
0
      this->Makefile->IssueMessage(
4692
0
        MessageType::FATAL_ERROR,
4693
0
        cmStrCat("The  \"INSTALL_OBJECT_NAME\" property for\n  ",
4694
0
                 source.GetFullPath(),
4695
0
                 "\ncontains a condition that queries the link language "
4696
0
                 "which is not supported (",
4697
0
                 objName, ")."));
4698
0
      return INVALID_GENEX;
4699
0
    }
4700
4701
0
    auto objNameValue = cge->Evaluate(this, config);
4702
4703
    // Skip if it evaluates to empty.
4704
0
    if (!objNameValue.empty()) {
4705
0
      cmCMakePath objNamePath = objNameValue;
4706
      // Verify that it is a relative path.
4707
0
      if (objNamePath.IsAbsolute()) {
4708
0
        this->Makefile->IssueMessage(
4709
0
          MessageType::FATAL_ERROR,
4710
0
          cmStrCat(
4711
0
            "The  \"INSTALL_OBJECT_NAME\" property for\n  ",
4712
0
            source.GetFullPath(),
4713
0
            "\nresolves to an absolute path which is not supported:\n  ",
4714
0
            objNameValue));
4715
0
        return INVALID_VALUE;
4716
0
      }
4717
0
      auto isInvalidComponent = [](cmCMakePath const& component) -> bool {
4718
0
        return component == ".."_s;
4719
0
      };
4720
      // Verify that it contains no `..` components.
4721
0
      if (std::any_of(objNamePath.begin(), objNamePath.end(),
4722
0
                      isInvalidComponent)) {
4723
0
        this->Makefile->IssueMessage(
4724
0
          MessageType::FATAL_ERROR,
4725
0
          cmStrCat("The  \"INSTALL_OBJECT_NAME\" property for\n  ",
4726
0
                   source.GetFullPath(), "\ncontains an invalid component (",
4727
0
                   objNameValue, ")."));
4728
0
        return INVALID_VALUE;
4729
0
      }
4730
4731
0
      if (custom_ext) {
4732
0
        objNameValue += custom_ext;
4733
0
      } else {
4734
0
        objNameValue +=
4735
0
          this->GetGlobalGenerator()->GetLanguageOutputExtension(source);
4736
0
      }
4737
4738
0
      return objNameValue;
4739
0
    }
4740
0
  }
4741
4742
0
  return std::string{};
4743
0
}
4744
4745
void cmLocalGenerator::FillCustomInstallObjectLocations(
4746
  cmSourceFile const& source, std::string const& config,
4747
  char const* custom_ext,
4748
  std::map<std::string, cmObjectLocation>& mapping) const
4749
0
{
4750
0
  auto installLoc =
4751
0
    this->GetCustomInstallObjectFileName(source, config, custom_ext);
4752
0
  if (!installLoc.empty()) {
4753
0
    mapping[config] = installLoc;
4754
0
  }
4755
0
}
4756
4757
std::string cmLocalGenerator::GetObjectFileNameWithoutTarget(
4758
  cmSourceFile const& source, std::string const& dir_max,
4759
  bool* hasSourceExtension, char const* customOutputExtension,
4760
  bool const* forceShortObjectName)
4761
0
{
4762
0
  bool useShortObjectNames = this->UseShortObjectNames();
4763
0
  if (forceShortObjectName) {
4764
0
    useShortObjectNames = *forceShortObjectName;
4765
0
  }
4766
4767
0
  if (!useShortObjectNames &&
4768
0
      this->GetGlobalGenerator()->SupportsCustomObjectNames()) {
4769
0
    auto customName = this->GetCustomObjectFileName(source);
4770
0
    if (!customName.empty()) {
4771
0
      auto ext = this->GlobalGenerator->GetLanguageOutputExtension(source);
4772
0
      if (customOutputExtension) {
4773
0
        ext = *customOutputExtension;
4774
0
      }
4775
0
      return cmStrCat(customName, ext);
4776
0
    }
4777
0
  }
4778
4779
  // This can return an absolute path in the case where source is
4780
  // not relative to the current source or binary directories
4781
0
  std::string objectName = this->GetRelativeSourceFileName(source);
4782
  // if it is still a full path check for the try compile case
4783
  // try compile never have in source sources, and should not
4784
  // have conflicting source file names in the same target
4785
0
  if (cmSystemTools::FileIsFullPath(objectName)) {
4786
0
    if (this->GetGlobalGenerator()->GetCMakeInstance()->GetIsInTryCompile()) {
4787
0
      objectName = cmSystemTools::GetFilenameName(source.GetFullPath());
4788
0
    }
4789
0
  }
4790
0
  bool const isPchObject = source.IsPchHeader() || source.IsPchSource();
4791
4792
  // Short object path policy selected, use as little info as necessary to
4793
  // select an object name
4794
0
  bool keptSourceExtension = true;
4795
0
  if (useShortObjectNames) {
4796
0
    objectName = this->GetShortObjectFileName(source);
4797
0
    keptSourceExtension = false;
4798
0
  }
4799
4800
  // Ensure that for the CMakeFiles/<target>.dir/generated_source_file
4801
  // we don't end up having:
4802
  // CMakeFiles/<target>.dir/CMakeFiles/<target>.dir/generated_source_file.obj
4803
0
  cmValue unitySourceFile = source.GetProperty("UNITY_SOURCE_FILE");
4804
0
  cmValue pchExtension = source.GetProperty("PCH_EXTENSION");
4805
0
  if (unitySourceFile || pchExtension || isPchObject) {
4806
0
    if (pchExtension) {
4807
0
      customOutputExtension = pchExtension->c_str();
4808
0
    }
4809
4810
0
    cmsys::RegularExpression var("(CMakeFiles/[^/]+.dir/)");
4811
0
    if (var.find(objectName)) {
4812
0
      objectName.erase(var.start(), var.end() - var.start());
4813
0
    }
4814
0
  }
4815
4816
  // Replace the original source file extension with the object file
4817
  // extension.
4818
0
  if (!source.GetPropertyAsBool("KEEP_EXTENSION")) {
4819
    // Decide whether this language wants to replace the source
4820
    // extension with the object extension.
4821
0
    bool replaceExt = false;
4822
0
    std::string lang = source.GetLanguage();
4823
0
    if (!lang.empty()) {
4824
0
      replaceExt = this->Makefile->IsOn(
4825
0
        cmStrCat("CMAKE_", lang, "_OUTPUT_EXTENSION_REPLACE"));
4826
0
    }
4827
4828
    // Remove the source extension if it is to be replaced.
4829
0
    if (replaceExt || customOutputExtension) {
4830
0
      keptSourceExtension = false;
4831
0
      std::string::size_type dot_pos = objectName.rfind('.');
4832
0
      if (dot_pos != std::string::npos) {
4833
0
        objectName = objectName.substr(0, dot_pos);
4834
0
      }
4835
0
    }
4836
4837
    // Strip source file extension when shortening object file paths
4838
0
    if (useShortObjectNames) {
4839
0
      objectName = cmSystemTools::GetFilenameWithoutExtension(objectName);
4840
0
    }
4841
    // Store the new extension.
4842
0
    if (customOutputExtension) {
4843
0
      objectName += customOutputExtension;
4844
0
    } else {
4845
0
      objectName += this->GlobalGenerator->GetLanguageOutputExtension(source);
4846
0
    }
4847
0
  }
4848
0
  if (hasSourceExtension) {
4849
0
    *hasSourceExtension = keptSourceExtension;
4850
0
  }
4851
4852
0
  if (source.GetLanguage() == "Rust") {
4853
0
    cmValue const rustEmit = source.GetRustEmitProperty();
4854
    // Rust requires any rlib to start with lib prefix on all platforms to
4855
    // allow linking to them as crate. So we enforce having lib prefix for rust
4856
    // "object" files.
4857
0
    if (rustEmit == "link") {
4858
0
      cmCMakePath objectPath(objectName);
4859
0
      std::string const objectFileName =
4860
0
        "lib" + objectPath.GetFileName().String();
4861
0
      objectPath.ReplaceFileName(objectFileName);
4862
0
      objectName = objectPath.String();
4863
0
    }
4864
0
  }
4865
4866
  // Convert to a safe name.
4867
0
  return this->CreateSafeUniqueObjectFileName(objectName, dir_max);
4868
0
}
4869
4870
bool cmLocalGenerator::UseShortObjectNames(
4871
  cmStateEnums::IntermediateDirKind kind) const
4872
0
{
4873
0
  return this->GlobalGenerator->UseShortObjectNames(kind);
4874
0
}
4875
4876
std::string cmLocalGenerator::GetObjectOutputRoot(
4877
  cmStateEnums::IntermediateDirKind kind) const
4878
0
{
4879
0
  if (this->UseShortObjectNames(kind)) {
4880
0
    return cmStrCat(this->GetCurrentBinaryDirectory(), '/',
4881
0
                    this->GlobalGenerator->GetShortBinaryOutputDir());
4882
0
  }
4883
0
  return cmStrCat(this->GetCurrentBinaryDirectory(), "/CMakeFiles");
4884
0
}
4885
4886
bool cmLocalGenerator::AlwaysUsesCMFPaths() const
4887
0
{
4888
0
  return true;
4889
0
}
4890
4891
std::string cmLocalGenerator::GetShortObjectFileName(
4892
  cmSourceFile const& source) const
4893
0
{
4894
0
  std::string objectName = this->GetRelativeSourceFileName(source);
4895
0
  cmCryptoHash objNameHasher(cmCryptoHash::AlgoSHA3_512);
4896
0
  std::string terseObjectName =
4897
0
    objNameHasher.HashString(objectName).substr(0, 8);
4898
0
  return terseObjectName;
4899
0
}
4900
4901
std::string cmLocalGenerator::ComputeShortTargetDirectory(
4902
  cmGeneratorTarget const* target) const
4903
0
{
4904
0
  auto const& tgtName = target->GetName();
4905
0
  return this->GetGlobalGenerator()->ComputeTargetShortName(
4906
0
    this->GetCurrentBinaryDirectory(), tgtName);
4907
0
}
4908
4909
std::string cmLocalGenerator::GetSourceFileLanguage(cmSourceFile const& source)
4910
0
{
4911
0
  return source.GetLanguage();
4912
0
}
4913
4914
cmake* cmLocalGenerator::GetCMakeInstance() const
4915
0
{
4916
0
  return this->GlobalGenerator->GetCMakeInstance();
4917
0
}
4918
4919
std::string const& cmLocalGenerator::GetSourceDirectory() const
4920
0
{
4921
0
  return this->GetCMakeInstance()->GetHomeDirectory();
4922
0
}
4923
4924
std::string const& cmLocalGenerator::GetBinaryDirectory() const
4925
0
{
4926
0
  return this->GetCMakeInstance()->GetHomeOutputDirectory();
4927
0
}
4928
4929
std::string const& cmLocalGenerator::GetCurrentBinaryDirectory() const
4930
0
{
4931
0
  return this->StateSnapshot.GetDirectory().GetCurrentBinary();
4932
0
}
4933
4934
std::string const& cmLocalGenerator::GetCurrentSourceDirectory() const
4935
0
{
4936
0
  return this->StateSnapshot.GetDirectory().GetCurrentSource();
4937
0
}
4938
4939
std::string cmLocalGenerator::GetTargetDirectory(
4940
  cmGeneratorTarget const* /*unused*/,
4941
  cmStateEnums::IntermediateDirKind /*kind*/) const
4942
0
{
4943
0
  cmSystemTools::Error("GetTargetDirectory"
4944
0
                       " called on cmLocalGenerator");
4945
0
  return "";
4946
0
}
4947
4948
cmPolicies::PolicyStatus cmLocalGenerator::GetPolicyStatus(
4949
  cmPolicies::PolicyID id) const
4950
0
{
4951
0
  return this->Makefile->GetPolicyStatus(id);
4952
0
}
4953
4954
bool cmLocalGenerator::CheckDefinition(std::string const& define) const
4955
0
{
4956
  // Many compilers do not support -DNAME(arg)=sdf so we disable it.
4957
0
  std::string::size_type pos = define.find_first_of("(=");
4958
0
  if (pos != std::string::npos) {
4959
0
    if (define[pos] == '(') {
4960
0
      std::ostringstream e;
4961
      /* clang-format off */
4962
0
      e << "WARNING: Function-style preprocessor definitions may not be "
4963
0
           "passed on the compiler command line because many compilers "
4964
0
           "do not support it.\n"
4965
0
           "CMake is dropping a preprocessor definition: " << define << "\n"
4966
0
           "Consider defining the macro in a (configured) header file.\n";
4967
      /* clang-format on */
4968
0
      cmSystemTools::Message(e.str());
4969
0
      return false;
4970
0
    }
4971
0
  }
4972
4973
  // Many compilers do not support # in the value so we disable it.
4974
0
  if (define.find_first_of('#') != std::string::npos) {
4975
0
    std::ostringstream e;
4976
    /* clang-format off */
4977
0
    e << "WARNING: Preprocessor definitions containing '#' may not be "
4978
0
         "passed on the compiler command line because many compilers "
4979
0
         "do not support it.\n"
4980
0
         "CMake is dropping a preprocessor definition: " << define << "\n"
4981
0
         "Consider defining the macro in a (configured) header file.\n";
4982
    /* clang-format on */
4983
0
    cmSystemTools::Message(e.str());
4984
0
    return false;
4985
0
  }
4986
4987
  // Assume it is supported.
4988
0
  return true;
4989
0
}
4990
4991
static void cmLGInfoProp(cmMakefile* mf, cmGeneratorTarget* target,
4992
                         std::string const& prop)
4993
0
{
4994
0
  if (cmValue val = target->GetProperty(prop)) {
4995
0
    mf->AddDefinition(prop, *val);
4996
0
  }
4997
0
}
4998
4999
void cmLocalGenerator::GenerateAppleInfoPList(cmGeneratorTarget* target,
5000
                                              std::string const& targetName,
5001
                                              std::string const& fname)
5002
0
{
5003
  // Find the Info.plist template.
5004
0
  cmValue in = target->GetProperty("MACOSX_BUNDLE_INFO_PLIST");
5005
0
  std::string inFile = cmNonempty(in) ? *in : "MacOSXBundleInfo.plist.in";
5006
0
  if (!cmSystemTools::FileIsFullPath(inFile)) {
5007
0
    std::string inMod = this->Makefile->GetModulesFile(inFile);
5008
0
    if (!inMod.empty()) {
5009
0
      inFile = inMod;
5010
0
    }
5011
0
  }
5012
0
  if (!cmSystemTools::FileExists(inFile, true)) {
5013
0
    std::ostringstream e;
5014
0
    e << "Target " << target->GetName() << " Info.plist template \"" << inFile
5015
0
      << "\" could not be found.";
5016
0
    cmSystemTools::Error(e.str());
5017
0
    return;
5018
0
  }
5019
5020
  // Convert target properties to variables in an isolated makefile
5021
  // scope to configure the file.  If properties are set they will
5022
  // override user make variables.  If not the configuration will fall
5023
  // back to the directory-level values set by the user.
5024
0
  cmMakefile* mf = this->Makefile;
5025
0
  cmMakefile::ScopePushPop varScope(mf);
5026
0
  mf->AddDefinition("MACOSX_BUNDLE_EXECUTABLE_NAME", targetName);
5027
0
  cmLGInfoProp(mf, target, "MACOSX_BUNDLE_INFO_STRING");
5028
0
  cmLGInfoProp(mf, target, "MACOSX_BUNDLE_ICON_FILE");
5029
0
  cmLGInfoProp(mf, target, "MACOSX_BUNDLE_GUI_IDENTIFIER");
5030
0
  cmLGInfoProp(mf, target, "MACOSX_BUNDLE_LONG_VERSION_STRING");
5031
0
  cmLGInfoProp(mf, target, "MACOSX_BUNDLE_BUNDLE_NAME");
5032
0
  cmLGInfoProp(mf, target, "MACOSX_BUNDLE_SHORT_VERSION_STRING");
5033
0
  cmLGInfoProp(mf, target, "MACOSX_BUNDLE_BUNDLE_VERSION");
5034
0
  cmLGInfoProp(mf, target, "MACOSX_BUNDLE_COPYRIGHT");
5035
0
  mf->ConfigureFile(inFile, fname, false, false, false);
5036
0
}
5037
5038
void cmLocalGenerator::GenerateFrameworkInfoPList(
5039
  cmGeneratorTarget* target, std::string const& targetName,
5040
  std::string const& fname)
5041
0
{
5042
  // Find the Info.plist template.
5043
0
  cmValue in = target->GetProperty("MACOSX_FRAMEWORK_INFO_PLIST");
5044
0
  std::string inFile = cmNonempty(in) ? *in : "MacOSXFrameworkInfo.plist.in";
5045
0
  if (!cmSystemTools::FileIsFullPath(inFile)) {
5046
0
    std::string inMod = this->Makefile->GetModulesFile(inFile);
5047
0
    if (!inMod.empty()) {
5048
0
      inFile = inMod;
5049
0
    }
5050
0
  }
5051
0
  if (!cmSystemTools::FileExists(inFile, true)) {
5052
0
    std::ostringstream e;
5053
0
    e << "Target " << target->GetName() << " Info.plist template \"" << inFile
5054
0
      << "\" could not be found.";
5055
0
    cmSystemTools::Error(e.str());
5056
0
    return;
5057
0
  }
5058
5059
  // Convert target properties to variables in an isolated makefile
5060
  // scope to configure the file.  If properties are set they will
5061
  // override user make variables.  If not the configuration will fall
5062
  // back to the directory-level values set by the user.
5063
0
  cmMakefile* mf = this->Makefile;
5064
0
  cmMakefile::ScopePushPop varScope(mf);
5065
0
  mf->AddDefinition("MACOSX_FRAMEWORK_NAME", targetName);
5066
0
  cmLGInfoProp(mf, target, "MACOSX_FRAMEWORK_ICON_FILE");
5067
0
  cmLGInfoProp(mf, target, "MACOSX_FRAMEWORK_IDENTIFIER");
5068
0
  cmLGInfoProp(mf, target, "MACOSX_FRAMEWORK_SHORT_VERSION_STRING");
5069
0
  cmLGInfoProp(mf, target, "MACOSX_FRAMEWORK_BUNDLE_NAME");
5070
0
  cmLGInfoProp(mf, target, "MACOSX_FRAMEWORK_BUNDLE_VERSION");
5071
0
  mf->ConfigureFile(inFile, fname, false, false, false);
5072
0
}
5073
5074
namespace {
5075
cm::string_view CustomOutputRoleKeyword(cmLocalGenerator::OutputRole role)
5076
0
{
5077
0
  return (role == cmLocalGenerator::OutputRole::Primary ? "OUTPUT"_s
5078
0
                                                        : "BYPRODUCTS"_s);
5079
0
}
5080
5081
void CreateGeneratedSource(cmLocalGenerator& lg, std::string const& output,
5082
                           cmLocalGenerator::OutputRole role,
5083
                           cmCommandOrigin origin,
5084
                           cmListFileBacktrace const& lfbt)
5085
0
{
5086
0
  if (cmGeneratorExpression::Find(output) != std::string::npos) {
5087
0
    lg.GetCMakeInstance()->IssueMessage(
5088
0
      MessageType::FATAL_ERROR,
5089
0
      "Generator expressions in custom command outputs are not implemented!",
5090
0
      lfbt);
5091
0
    return;
5092
0
  }
5093
5094
  // Make sure the file will not be generated into the source
5095
  // directory during an out of source build.
5096
0
  if (!lg.GetMakefile()->CanIWriteThisFile(output)) {
5097
0
    lg.GetCMakeInstance()->IssueMessage(
5098
0
      MessageType::FATAL_ERROR,
5099
0
      cmStrCat(CustomOutputRoleKeyword(role), " path\n  ", output,
5100
0
               "\nin a source directory as an output of custom command."),
5101
0
      lfbt);
5102
0
    return;
5103
0
  }
5104
5105
  // Make sure the output file name has no invalid characters.
5106
0
  bool const hashNotAllowed = lg.GetState()->UseBorlandMake();
5107
0
  std::string::size_type pos = output.find_first_of("<>");
5108
0
  if (pos == std::string::npos && hashNotAllowed) {
5109
0
    pos = output.find_first_of('#');
5110
0
  }
5111
5112
0
  if (pos != std::string::npos) {
5113
0
    lg.GetCMakeInstance()->IssueMessage(
5114
0
      MessageType::FATAL_ERROR,
5115
0
      cmStrCat(CustomOutputRoleKeyword(role), " containing a \"", output[pos],
5116
0
               "\" is not allowed."),
5117
0
      lfbt);
5118
0
    return;
5119
0
  }
5120
5121
  // Outputs without generator expressions from the project are already
5122
  // created and marked as generated.  Do not mark them again, because
5123
  // other commands might have overwritten the property.
5124
0
  if (origin == cmCommandOrigin::Generator) {
5125
0
    lg.GetMakefile()->GetOrCreateGeneratedSource(output);
5126
0
  }
5127
0
}
5128
5129
std::string ComputeCustomCommandRuleFileName(cmLocalGenerator& lg,
5130
                                             cmListFileBacktrace const& bt,
5131
                                             std::string const& output)
5132
0
{
5133
  // If the output path has no generator expressions, use it directly.
5134
0
  if (cmGeneratorExpression::Find(output) == std::string::npos) {
5135
0
    return output;
5136
0
  }
5137
5138
  // The output path contains a generator expression, but we must choose
5139
  // a single source file path to which to attach the custom command.
5140
  // Use some heuristics to provide a nice-looking name when possible.
5141
5142
  // If the only genex is $<CONFIG>, replace that gracefully.
5143
0
  {
5144
0
    std::string simple = output;
5145
0
    cmSystemTools::ReplaceString(simple, "$<CONFIG>", "(CONFIG)");
5146
0
    if (cmGeneratorExpression::Find(simple) == std::string::npos) {
5147
0
      return simple;
5148
0
    }
5149
0
  }
5150
5151
  // If the genex evaluates to the same value in all configurations, use that.
5152
0
  {
5153
0
    std::vector<std::string> allConfigOutputs =
5154
0
      lg.ExpandCustomCommandOutputGenex(output, bt);
5155
0
    if (allConfigOutputs.size() == 1) {
5156
0
      return allConfigOutputs.front();
5157
0
    }
5158
0
  }
5159
5160
  // Fall back to a deterministic unique name.
5161
0
  cmCryptoHash h(cmCryptoHash::AlgoSHA256);
5162
0
  return cmStrCat(lg.GetCurrentBinaryDirectory(), "/CMakeFiles/",
5163
0
                  h.HashString(output).substr(0, 16));
5164
0
}
5165
5166
cmSourceFile* AddCustomCommand(cmLocalGenerator& lg, cmCommandOrigin origin,
5167
                               std::unique_ptr<cmCustomCommand> cc,
5168
                               bool replace)
5169
0
{
5170
0
  cmMakefile* mf = lg.GetMakefile();
5171
0
  auto const& lfbt = cc->GetBacktrace();
5172
0
  auto const& outputs = cc->GetOutputs();
5173
0
  auto const& byproducts = cc->GetByproducts();
5174
0
  auto const& commandLines = cc->GetCommandLines();
5175
5176
  // Choose a source file on which to store the custom command.
5177
0
  cmSourceFile* file = nullptr;
5178
0
  if (!commandLines.empty() && cc->HasMainDependency()) {
5179
0
    auto const& main_dependency = cc->GetMainDependency();
5180
    // The main dependency was specified.  Use it unless a different
5181
    // custom command already used it.
5182
0
    file = mf->GetSource(main_dependency);
5183
0
    if (file && file->GetCustomCommand() && !replace) {
5184
      // The main dependency already has a custom command.
5185
0
      if (commandLines == file->GetCustomCommand()->GetCommandLines()) {
5186
        // The existing custom command is identical.  Silently ignore
5187
        // the duplicate.
5188
0
        return file;
5189
0
      }
5190
      // The existing custom command is different.  We need to
5191
      // generate a rule file for this new command.
5192
0
      file = nullptr;
5193
0
    } else if (!file) {
5194
0
      file = mf->CreateSource(main_dependency);
5195
0
    }
5196
0
  }
5197
5198
  // Generate a rule file if the main dependency is not available.
5199
0
  if (!file) {
5200
0
    cmGlobalGenerator* gg = lg.GetGlobalGenerator();
5201
5202
    // Construct a rule file associated with the first output produced.
5203
0
    std::string outName = gg->GenerateRuleFile(
5204
0
      ComputeCustomCommandRuleFileName(lg, lfbt, outputs[0]));
5205
5206
    // Check if the rule file already exists.
5207
0
    file = mf->GetSource(outName, cmSourceFileLocationKind::Known);
5208
0
    if (file && file->GetCustomCommand() && !replace) {
5209
      // The rule file already exists.
5210
0
      if (commandLines != file->GetCustomCommand()->GetCommandLines()) {
5211
0
        lg.GetCMakeInstance()->IssueMessage(
5212
0
          MessageType::FATAL_ERROR,
5213
0
          cmStrCat("Attempt to add a custom rule to output\n  ", outName,
5214
0
                   "\nwhich already has a custom rule."),
5215
0
          lfbt);
5216
0
      }
5217
0
      return file;
5218
0
    }
5219
5220
    // Create a cmSourceFile for the rule file.
5221
0
    if (!file) {
5222
0
      file = mf->CreateSource(outName, true, cmSourceFileLocationKind::Known);
5223
0
    }
5224
0
    file->SetProperty("__CMAKE_RULE", "1");
5225
0
  }
5226
5227
  // Attach the custom command to the file.
5228
0
  if (file) {
5229
0
    cc->SetEscapeAllowMakeVars(true);
5230
5231
0
    lg.AddSourceOutputs(file, outputs, cmLocalGenerator::OutputRole::Primary,
5232
0
                        lfbt, origin);
5233
0
    lg.AddSourceOutputs(file, byproducts,
5234
0
                        cmLocalGenerator::OutputRole::Byproduct, lfbt, origin);
5235
5236
0
    file->SetCustomCommand(std::move(cc));
5237
0
  }
5238
0
  return file;
5239
0
}
5240
5241
bool AnyOutputMatches(std::string const& name,
5242
                      std::vector<std::string> const& outputs)
5243
0
{
5244
0
  return std::any_of(outputs.begin(), outputs.end(),
5245
0
                     [&name](std::string const& output) -> bool {
5246
0
                       std::string::size_type pos = output.rfind(name);
5247
                       // If the output matches exactly
5248
0
                       return (pos != std::string::npos &&
5249
0
                               pos == output.size() - name.size() &&
5250
0
                               (pos == 0 || output[pos - 1] == '/'));
5251
0
                     });
5252
0
}
5253
5254
bool AnyTargetCommandOutputMatches(
5255
  std::string const& name, std::vector<cmCustomCommand> const& commands)
5256
0
{
5257
0
  return std::any_of(commands.begin(), commands.end(),
5258
0
                     [&name](cmCustomCommand const& command) -> bool {
5259
0
                       return AnyOutputMatches(name, command.GetByproducts());
5260
0
                     });
5261
0
}
5262
}
5263
5264
namespace detail {
5265
void AddCustomCommandToTarget(cmLocalGenerator& lg, cmCommandOrigin origin,
5266
                              cmTarget* target, cmCustomCommandType type,
5267
                              std::unique_ptr<cmCustomCommand> cc)
5268
0
{
5269
  // Add the command to the appropriate build step for the target.
5270
0
  cc->SetEscapeAllowMakeVars(true);
5271
0
  cc->SetTarget(target->GetName());
5272
5273
0
  lg.AddTargetByproducts(target, cc->GetByproducts(), cc->GetBacktrace(),
5274
0
                         origin);
5275
5276
0
  switch (type) {
5277
0
    case cmCustomCommandType::PRE_BUILD:
5278
0
      target->AddPreBuildCommand(std::move(*cc));
5279
0
      break;
5280
0
    case cmCustomCommandType::PRE_LINK:
5281
0
      target->AddPreLinkCommand(std::move(*cc));
5282
0
      break;
5283
0
    case cmCustomCommandType::POST_BUILD:
5284
0
      target->AddPostBuildCommand(std::move(*cc));
5285
0
      break;
5286
0
  }
5287
5288
0
  cc.reset();
5289
0
}
5290
5291
cmSourceFile* AddCustomCommandToOutput(cmLocalGenerator& lg,
5292
                                       cmCommandOrigin origin,
5293
                                       std::unique_ptr<cmCustomCommand> cc,
5294
                                       bool replace)
5295
0
{
5296
0
  return AddCustomCommand(lg, origin, std::move(cc), replace);
5297
0
}
5298
5299
void AppendCustomCommandToOutput(cmLocalGenerator& lg,
5300
                                 cmListFileBacktrace const& lfbt,
5301
                                 std::string const& output,
5302
                                 std::vector<std::string> const& depends,
5303
                                 cmImplicitDependsList const& implicit_depends,
5304
                                 cmCustomCommandLines const& commandLines)
5305
0
{
5306
  // Lookup an existing command.
5307
0
  cmSourceFile* sf = nullptr;
5308
0
  if (cmGeneratorExpression::Find(output) == std::string::npos) {
5309
0
    sf = lg.GetSourceFileWithOutput(output);
5310
0
  } else {
5311
    // This output path has a generator expression.  Evaluate it to
5312
    // find the output for any configurations.
5313
0
    for (std::string const& out :
5314
0
         lg.ExpandCustomCommandOutputGenex(output, lfbt)) {
5315
0
      sf = lg.GetSourceFileWithOutput(out);
5316
0
      if (sf) {
5317
0
        break;
5318
0
      }
5319
0
    }
5320
0
  }
5321
5322
0
  if (sf) {
5323
0
    if (cmCustomCommand* cc = sf->GetCustomCommand()) {
5324
0
      cc->AppendCommands(commandLines);
5325
0
      cc->AppendDepends(depends);
5326
0
      if (cc->GetCodegen() && !implicit_depends.empty()) {
5327
0
        lg.GetCMakeInstance()->IssueMessage(
5328
0
          MessageType::FATAL_ERROR,
5329
0
          "Cannot append IMPLICIT_DEPENDS to existing CODEGEN custom "
5330
0
          "command.");
5331
0
      }
5332
0
      cc->AppendImplicitDepends(implicit_depends);
5333
0
      return;
5334
0
    }
5335
0
  }
5336
5337
  // No existing command found.
5338
0
  lg.GetCMakeInstance()->IssueMessage(
5339
0
    MessageType::FATAL_ERROR,
5340
0
    cmStrCat("Attempt to APPEND to custom command with output\n  ", output,
5341
0
             "\nwhich is not already a custom command output."),
5342
0
    lfbt);
5343
0
}
5344
5345
void AddUtilityCommand(cmLocalGenerator& lg, cmCommandOrigin origin,
5346
                       cmTarget* target, std::unique_ptr<cmCustomCommand> cc)
5347
0
{
5348
  // They might be moved away
5349
0
  auto byproducts = cc->GetByproducts();
5350
0
  auto lfbt = cc->GetBacktrace();
5351
5352
  // Use an empty comment to avoid generation of default comment.
5353
0
  if (!cc->GetComment()) {
5354
0
    cc->SetComment("");
5355
0
  }
5356
5357
  // Create the generated symbolic output name of the utility target.
5358
0
  std::string output =
5359
0
    lg.CreateUtilityOutput(target->GetName(), byproducts, lfbt);
5360
0
  cc->SetOutputs(output);
5361
5362
0
  cmSourceFile* rule = AddCustomCommand(lg, origin, std::move(cc),
5363
0
                                        /*replace=*/false);
5364
0
  if (rule) {
5365
0
    lg.AddTargetByproducts(target, byproducts, lfbt, origin);
5366
0
  }
5367
5368
0
  target->AddSource(output);
5369
0
}
5370
5371
std::vector<std::string> ComputeISPCObjectSuffixes(cmGeneratorTarget* target)
5372
0
{
5373
0
  cmValue const targetProperty = target->GetProperty("ISPC_INSTRUCTION_SETS");
5374
0
  cmList ispcTargets;
5375
5376
0
  if (!targetProperty.IsOff()) {
5377
0
    ispcTargets.assign(targetProperty);
5378
0
    for (auto& ispcTarget : ispcTargets) {
5379
      // transform targets into the suffixes
5380
0
      auto pos = ispcTarget.find('-');
5381
0
      auto target_suffix = ispcTarget.substr(0, pos);
5382
      // ISPC uses underscores in output file suffixes where the target name
5383
      // has dots (e.g. "avx10.2dmr" produces files with "_avx10_2dmr" suffix)
5384
0
      std::replace(target_suffix.begin(), target_suffix.end(), '.', '_');
5385
0
      if (target_suffix ==
5386
0
          "avx1") { // when targeting avx1 ISPC uses the 'avx' output string
5387
0
        target_suffix = "avx";
5388
0
      } else if (target_suffix == "sse4_1" || target_suffix == "sse4_2") {
5389
        // when targeting sse4.1 or sse4.2 ISPC uses the 'sse4' output string
5390
0
        target_suffix = "sse4";
5391
0
      }
5392
0
      ispcTarget = target_suffix;
5393
0
    }
5394
0
  }
5395
0
  return std::move(ispcTargets.data());
5396
0
}
5397
5398
std::vector<std::string> ComputeISPCExtraObjects(
5399
  std::string const& objectName, std::string const& buildDirectory,
5400
  std::vector<std::string> const& ispcSuffixes)
5401
0
{
5402
0
  auto normalizedDir = cmSystemTools::CollapseFullPath(buildDirectory);
5403
0
  std::vector<std::string> computedObjects;
5404
0
  computedObjects.reserve(ispcSuffixes.size());
5405
5406
0
  auto extension = cmSystemTools::GetFilenameLastExtensionView(objectName);
5407
5408
  // We can't use cmSystemTools::GetFilenameWithoutLastExtension as it
5409
  // drops any directories in objectName
5410
0
  auto objNameNoExt = objectName;
5411
0
  std::string::size_type dot_pos = objectName.rfind('.');
5412
0
  if (dot_pos != std::string::npos) {
5413
0
    objNameNoExt.resize(dot_pos);
5414
0
  }
5415
5416
0
  for (auto const& ispcTarget : ispcSuffixes) {
5417
0
    computedObjects.emplace_back(
5418
0
      cmStrCat(normalizedDir, '/', objNameNoExt, '_', ispcTarget, extension));
5419
0
  }
5420
5421
0
  return computedObjects;
5422
0
}
5423
}
5424
5425
cmSourcesWithOutput cmLocalGenerator::GetSourcesWithOutput(
5426
  std::string const& name) const
5427
0
{
5428
  // Linear search?  Also see GetSourceFileWithOutput for detail.
5429
0
  if (!cmSystemTools::FileIsFullPath(name)) {
5430
0
    cmSourcesWithOutput sources;
5431
0
    sources.Target = this->LinearGetTargetWithOutput(name);
5432
0
    sources.Source = this->LinearGetSourceFileWithOutput(
5433
0
      name, cmSourceOutputKind::OutputOrByproduct, sources.SourceIsByproduct);
5434
0
    return sources;
5435
0
  }
5436
  // Otherwise we use an efficient lookup map.
5437
0
  auto o = this->OutputToSource.find(name);
5438
0
  if (o != this->OutputToSource.end()) {
5439
0
    return o->second.Sources;
5440
0
  }
5441
0
  return {};
5442
0
}
5443
5444
cmSourceFile* cmLocalGenerator::GetSourceFileWithOutput(
5445
  std::string const& name, cmSourceOutputKind kind) const
5446
0
{
5447
  // If the queried path is not absolute we use the backward compatible
5448
  // linear-time search for an output with a matching suffix.
5449
0
  if (!cmSystemTools::FileIsFullPath(name)) {
5450
0
    bool byproduct = false;
5451
0
    return this->LinearGetSourceFileWithOutput(name, kind, byproduct);
5452
0
  }
5453
  // Otherwise we use an efficient lookup map.
5454
0
  auto o = this->OutputToSource.find(name);
5455
0
  if (o != this->OutputToSource.end() &&
5456
0
      (!o->second.Sources.SourceIsByproduct ||
5457
0
       kind == cmSourceOutputKind::OutputOrByproduct)) {
5458
    // Source file could also be null pointer for example if we found the
5459
    // byproduct of a utility target, a PRE_BUILD, PRE_LINK, or POST_BUILD
5460
    // command of a target, or a not yet created custom command.
5461
0
    return o->second.Sources.Source;
5462
0
  }
5463
0
  return nullptr;
5464
0
}
5465
5466
std::string cmLocalGenerator::CreateUtilityOutput(
5467
  std::string const& targetName, std::vector<std::string> const&,
5468
  cmListFileBacktrace const&)
5469
0
{
5470
0
  std::string force =
5471
0
    cmStrCat(this->GetCurrentBinaryDirectory(), "/CMakeFiles/", targetName);
5472
  // The output is not actually created so mark it symbolic.
5473
0
  if (cmSourceFile* sf = this->Makefile->GetOrCreateGeneratedSource(force)) {
5474
0
    sf->SetProperty("SYMBOLIC", "1");
5475
0
  } else {
5476
0
    cmSystemTools::Error("Could not get source file entry for " + force);
5477
0
  }
5478
0
  return force;
5479
0
}
5480
5481
std::vector<cmCustomCommandGenerator>
5482
cmLocalGenerator::MakeCustomCommandGenerators(cmCustomCommand const& cc,
5483
                                              std::string const& config)
5484
0
{
5485
0
  std::vector<cmCustomCommandGenerator> ccgs;
5486
0
  ccgs.emplace_back(cc, config, this);
5487
0
  return ccgs;
5488
0
}
5489
5490
std::vector<std::string> cmLocalGenerator::ExpandCustomCommandOutputPaths(
5491
  cmCompiledGeneratorExpression const& cge, std::string const& config)
5492
0
{
5493
0
  cmList paths{ cge.Evaluate(this, config) };
5494
0
  for (std::string& p : paths) {
5495
0
    p = cmSystemTools::CollapseFullPath(p, this->GetCurrentBinaryDirectory());
5496
0
  }
5497
0
  return std::move(paths.data());
5498
0
}
5499
5500
std::vector<std::string> cmLocalGenerator::ExpandCustomCommandOutputGenex(
5501
  std::string const& o, cmListFileBacktrace const& bt)
5502
0
{
5503
0
  std::vector<std::string> allConfigOutputs;
5504
0
  cmGeneratorExpression ge(*this->GetCMakeInstance(), bt);
5505
0
  std::unique_ptr<cmCompiledGeneratorExpression> cge = ge.Parse(o);
5506
0
  std::vector<std::string> configs =
5507
0
    this->Makefile->GetGeneratorConfigs(cmMakefile::IncludeEmptyConfig);
5508
0
  for (std::string const& config : configs) {
5509
0
    std::vector<std::string> configOutputs =
5510
0
      this->ExpandCustomCommandOutputPaths(*cge, config);
5511
0
    allConfigOutputs.reserve(allConfigOutputs.size() + configOutputs.size());
5512
0
    std::move(configOutputs.begin(), configOutputs.end(),
5513
0
              std::back_inserter(allConfigOutputs));
5514
0
  }
5515
0
  auto endUnique =
5516
0
    cmRemoveDuplicates(allConfigOutputs.begin(), allConfigOutputs.end());
5517
0
  allConfigOutputs.erase(endUnique, allConfigOutputs.end());
5518
0
  return allConfigOutputs;
5519
0
}
5520
5521
void cmLocalGenerator::AddTargetByproducts(
5522
  cmTarget* target, std::vector<std::string> const& byproducts,
5523
  cmListFileBacktrace const& bt, cmCommandOrigin origin)
5524
0
{
5525
0
  for (std::string const& o : byproducts) {
5526
0
    if (cmGeneratorExpression::Find(o) == std::string::npos) {
5527
0
      this->UpdateOutputToSourceMap(o, target, bt, origin);
5528
0
      continue;
5529
0
    }
5530
5531
    // This byproduct path has a generator expression.  Evaluate it to
5532
    // register the byproducts for all configurations.
5533
0
    for (std::string const& b : this->ExpandCustomCommandOutputGenex(o, bt)) {
5534
0
      this->UpdateOutputToSourceMap(b, target, bt, cmCommandOrigin::Generator);
5535
0
    }
5536
0
  }
5537
0
}
5538
5539
void cmLocalGenerator::AddSourceOutputs(
5540
  cmSourceFile* source, std::vector<std::string> const& outputs,
5541
  OutputRole role, cmListFileBacktrace const& bt, cmCommandOrigin origin)
5542
0
{
5543
0
  for (std::string const& o : outputs) {
5544
0
    if (cmGeneratorExpression::Find(o) == std::string::npos) {
5545
0
      this->UpdateOutputToSourceMap(o, source, role, bt, origin);
5546
0
      continue;
5547
0
    }
5548
5549
    // This output path has a generator expression.  Evaluate it to
5550
    // register the outputs for all configurations.
5551
0
    for (std::string const& out :
5552
0
         this->ExpandCustomCommandOutputGenex(o, bt)) {
5553
0
      this->UpdateOutputToSourceMap(out, source, role, bt,
5554
0
                                    cmCommandOrigin::Generator);
5555
0
    }
5556
0
  }
5557
0
}
5558
5559
void cmLocalGenerator::UpdateOutputToSourceMap(std::string const& byproduct,
5560
                                               cmTarget* target,
5561
                                               cmListFileBacktrace const& bt,
5562
                                               cmCommandOrigin origin)
5563
0
{
5564
0
  SourceEntry entry;
5565
0
  entry.Sources.Target = target;
5566
5567
0
  auto pr = this->OutputToSource.emplace(byproduct, entry);
5568
0
  if (pr.second) {
5569
0
    CreateGeneratedSource(*this, byproduct, OutputRole::Byproduct, origin, bt);
5570
0
  } else {
5571
0
    SourceEntry& current = pr.first->second;
5572
    // Has the target already been set?
5573
0
    if (!current.Sources.Target) {
5574
0
      current.Sources.Target = target;
5575
0
    } else {
5576
      // Multiple custom commands/targets produce the same output (source file
5577
      // or target).  See also comment in other UpdateOutputToSourceMap
5578
      // overload.
5579
      //
5580
      // TODO: Warn the user about this case.
5581
0
    }
5582
0
  }
5583
0
}
5584
5585
void cmLocalGenerator::UpdateOutputToSourceMap(std::string const& output,
5586
                                               cmSourceFile* source,
5587
                                               OutputRole role,
5588
                                               cmListFileBacktrace const& bt,
5589
                                               cmCommandOrigin origin)
5590
0
{
5591
0
  SourceEntry entry;
5592
0
  entry.Sources.Source = source;
5593
0
  entry.Sources.SourceIsByproduct = role == OutputRole::Byproduct;
5594
5595
0
  auto pr = this->OutputToSource.emplace(output, entry);
5596
0
  if (pr.second) {
5597
0
    CreateGeneratedSource(*this, output, role, origin, bt);
5598
0
  } else {
5599
0
    SourceEntry& current = pr.first->second;
5600
    // Outputs take precedence over byproducts
5601
0
    if (!current.Sources.Source ||
5602
0
        (current.Sources.SourceIsByproduct && role == OutputRole::Primary)) {
5603
0
      current.Sources.Source = source;
5604
0
      current.Sources.SourceIsByproduct = false;
5605
0
    } else {
5606
      // Multiple custom commands produce the same output but may
5607
      // be attached to a different source file (MAIN_DEPENDENCY).
5608
      // LinearGetSourceFileWithOutput would return the first one,
5609
      // so keep the mapping for the first one.
5610
      //
5611
      // TODO: Warn the user about this case.  However, the VS 8 generator
5612
      // triggers it for separate generate.stamp rules in ZERO_CHECK and
5613
      // individual targets.
5614
0
    }
5615
0
  }
5616
0
}
5617
5618
cmTarget* cmLocalGenerator::LinearGetTargetWithOutput(
5619
  std::string const& name) const
5620
0
{
5621
  // We go through the ordered vector of targets to get reproducible results
5622
  // should multiple names match.
5623
0
  for (cmTarget* t : this->Makefile->GetOrderedTargets()) {
5624
    // Does the output of any command match the source file name?
5625
0
    if (AnyTargetCommandOutputMatches(name, t->GetPreBuildCommands())) {
5626
0
      return t;
5627
0
    }
5628
0
    if (AnyTargetCommandOutputMatches(name, t->GetPreLinkCommands())) {
5629
0
      return t;
5630
0
    }
5631
0
    if (AnyTargetCommandOutputMatches(name, t->GetPostBuildCommands())) {
5632
0
      return t;
5633
0
    }
5634
0
  }
5635
0
  return nullptr;
5636
0
}
5637
5638
cmSourceFile* cmLocalGenerator::LinearGetSourceFileWithOutput(
5639
  std::string const& name, cmSourceOutputKind kind, bool& byproduct) const
5640
0
{
5641
  // Outputs take precedence over byproducts.
5642
0
  byproduct = false;
5643
0
  cmSourceFile* fallback = nullptr;
5644
5645
  // Look through all the source files that have custom commands and see if the
5646
  // custom command has the passed source file as an output.
5647
0
  for (auto const& src : this->Makefile->GetSourceFiles()) {
5648
    // Does this source file have a custom command?
5649
0
    if (src->GetCustomCommand()) {
5650
      // Does the output of the custom command match the source file name?
5651
0
      if (AnyOutputMatches(name, src->GetCustomCommand()->GetOutputs())) {
5652
        // Return the first matching output.
5653
0
        return src.get();
5654
0
      }
5655
0
      if (kind == cmSourceOutputKind::OutputOrByproduct) {
5656
0
        if (AnyOutputMatches(name, src->GetCustomCommand()->GetByproducts())) {
5657
          // Do not return the source yet as there might be a matching output.
5658
0
          fallback = src.get();
5659
0
        }
5660
0
      }
5661
0
    }
5662
0
  }
5663
5664
  // Did we find a byproduct?
5665
0
  byproduct = fallback != nullptr;
5666
0
  return fallback;
5667
0
}