Coverage Report

Created: 2026-06-15 07:03

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/CMake/Source/cmMakefile.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 "cmConfigure.h" // IWYU pragma: keep
4
5
#include "cmMakefile.h"
6
7
#include <algorithm>
8
#include <array>
9
#include <cassert>
10
#include <cstdio>
11
#include <cstdlib>
12
#include <cstring>
13
#include <sstream>
14
#include <utility>
15
16
#include <cm/iterator>
17
#include <cm/memory>
18
#include <cm/optional>
19
#include <cm/type_traits> // IWYU pragma: keep
20
#include <cm/vector>
21
#include <cmext/algorithm>
22
#include <cmext/string_view>
23
24
#ifndef CMAKE_BOOTSTRAP
25
#  include <cm3p/json/value.h>
26
#  include <cm3p/json/writer.h>
27
#endif
28
29
#include "cmsys/FStream.hxx"
30
#include "cmsys/RegularExpression.hxx"
31
#include "cmsys/String.h"
32
33
#ifndef CMAKE_BOOTSTRAP
34
#  include "cmBuildSbomGenerator.h"
35
#endif
36
#include "cmCustomCommand.h"
37
#include "cmCustomCommandLines.h"
38
#include "cmCustomCommandTypes.h"
39
#include "cmExecutionStatus.h"
40
#include "cmExpandedCommandArgument.h" // IWYU pragma: keep
41
#include "cmExportBuildFileGenerator.h"
42
#include "cmFileLockPool.h"
43
#include "cmFunctionBlocker.h"
44
#include "cmGeneratedFileStream.h"
45
#include "cmGeneratorExpression.h"
46
#include "cmGeneratorExpressionEvaluationFile.h"
47
#include "cmGlobalGenerator.h"
48
#include "cmInstallGenerator.h" // IWYU pragma: keep
49
#include "cmInstallSubdirectoryGenerator.h"
50
#include "cmList.h"
51
#include "cmListFileCache.h"
52
#include "cmLocalGenerator.h"
53
#include "cmMessageType.h"
54
#include "cmRange.h"
55
#include "cmSourceFile.h"
56
#include "cmSourceFileLocation.h"
57
#include "cmSourceGroup.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 "cmTargetLinkLibraryType.h"
65
#include "cmTest.h"
66
#include "cmTestGenerator.h" // IWYU pragma: keep
67
#include "cmVersion.h"
68
#include "cmWorkingDirectory.h"
69
#include "cmake.h"
70
71
#ifndef CMAKE_BOOTSTRAP
72
#  include "cmMakefileProfilingData.h"
73
#  include "cmVariableWatch.h"
74
#endif
75
76
#ifdef CMake_ENABLE_DEBUGGER
77
#  include "cmDebuggerAdapter.h"
78
#endif
79
80
#ifndef __has_feature
81
#  define __has_feature(x) 0
82
#endif
83
84
// Select a recursion limit that fits within the stack size.
85
// See stack size flags in '../CompileFlags.cmake'.
86
#ifndef CMake_DEFAULT_RECURSION_LIMIT
87
#  if __has_feature(address_sanitizer)
88
#    define CMake_DEFAULT_RECURSION_LIMIT 400
89
#  elif defined(_MSC_VER) && defined(_DEBUG)
90
#    define CMake_DEFAULT_RECURSION_LIMIT 600
91
#  elif defined(__ibmxl__) && defined(__linux)
92
#    define CMake_DEFAULT_RECURSION_LIMIT 600
93
#  else
94
0
#    define CMake_DEFAULT_RECURSION_LIMIT 1000
95
#  endif
96
#endif
97
98
namespace {
99
std::string const kCMAKE_CURRENT_LIST_DIR = "CMAKE_CURRENT_LIST_DIR";
100
std::string const kCMAKE_CURRENT_LIST_FILE = "CMAKE_CURRENT_LIST_FILE";
101
std::string const kCMAKE_PARENT_LIST_FILE = "CMAKE_PARENT_LIST_FILE";
102
103
class FileScopeBase
104
{
105
protected:
106
  cmMakefile* Makefile;
107
108
private:
109
  std::string OldCurrent;
110
  cm::optional<std::string> OldParent;
111
112
public:
113
  FileScopeBase(cmMakefile* mf)
114
1
    : Makefile(mf)
115
1
  {
116
1
#if !defined(CMAKE_BOOTSTRAP)
117
1
    this->Makefile->GetGlobalGenerator()->GetFileLockPool().PushFileScope();
118
1
#endif
119
1
  }
120
  ~FileScopeBase()
121
1
  {
122
1
#if !defined(CMAKE_BOOTSTRAP)
123
1
    this->Makefile->GetGlobalGenerator()->GetFileLockPool().PopFileScope();
124
1
#endif
125
1
  }
126
  void PushListFileVars(std::string const& newCurrent)
127
1
  {
128
1
    if (cmValue p = this->Makefile->GetDefinition(kCMAKE_PARENT_LIST_FILE)) {
129
0
      this->OldParent = *p;
130
0
    }
131
1
    if (cmValue c = this->Makefile->GetDefinition(kCMAKE_CURRENT_LIST_FILE)) {
132
0
      this->OldCurrent = *c;
133
0
      this->Makefile->AddDefinition(kCMAKE_PARENT_LIST_FILE, this->OldCurrent);
134
0
      this->Makefile->MarkVariableAsUsed(kCMAKE_PARENT_LIST_FILE);
135
0
    }
136
1
    this->Makefile->AddDefinition(kCMAKE_CURRENT_LIST_FILE, newCurrent);
137
1
    this->Makefile->AddDefinition(kCMAKE_CURRENT_LIST_DIR,
138
1
                                  cmSystemTools::GetFilenamePath(newCurrent));
139
1
    this->Makefile->MarkVariableAsUsed(kCMAKE_CURRENT_LIST_FILE);
140
1
    this->Makefile->MarkVariableAsUsed(kCMAKE_CURRENT_LIST_DIR);
141
1
  }
142
  void PopListFileVars()
143
1
  {
144
1
    if (this->OldParent) {
145
0
      this->Makefile->AddDefinition(kCMAKE_PARENT_LIST_FILE, *this->OldParent);
146
0
      this->Makefile->MarkVariableAsUsed(kCMAKE_PARENT_LIST_FILE);
147
1
    } else {
148
1
      this->Makefile->RemoveDefinition(kCMAKE_PARENT_LIST_FILE);
149
1
    }
150
1
    this->Makefile->AddDefinition(kCMAKE_CURRENT_LIST_FILE, this->OldCurrent);
151
1
    this->Makefile->AddDefinition(
152
1
      kCMAKE_CURRENT_LIST_DIR,
153
1
      cmSystemTools::GetFilenamePath(this->OldCurrent));
154
1
    this->Makefile->MarkVariableAsUsed(kCMAKE_CURRENT_LIST_FILE);
155
1
    this->Makefile->MarkVariableAsUsed(kCMAKE_CURRENT_LIST_DIR);
156
1
  }
157
};
158
}
159
160
class cmMessenger;
161
162
cmDirectoryId::cmDirectoryId(std::string s)
163
0
  : String(std::move(s))
164
0
{
165
0
}
166
167
// default is not to be building executables
168
cmMakefile::cmMakefile(cmGlobalGenerator* globalGenerator,
169
                       cmStateSnapshot const& snapshot)
170
1
  : GlobalGenerator(globalGenerator)
171
1
  , StateSnapshot(snapshot)
172
1
{
173
1
  this->IsSourceFileTryCompile = false;
174
175
1
  this->CheckSystemVars = this->GetCMakeInstance()->GetCheckSystemVars();
176
177
  // Setup the default include complaint regular expression (match nothing).
178
1
  this->ComplainFileRegularExpression = "^$";
179
180
1
  this->DefineFlags = " ";
181
182
1
  this->cmDefineRegex.compile("#([ \t]*)cmakedefine[ \t]+([A-Za-z_0-9]*)");
183
1
  this->cmDefine01Regex.compile("#([ \t]*)cmakedefine01[ \t]+([A-Za-z_0-9]*)");
184
1
  this->cmNamedCurly.compile("^[A-Za-z0-9/_.+-]+{");
185
186
1
  this->StateSnapshot =
187
1
    this->StateSnapshot.GetState()->CreatePolicyScopeSnapshot(
188
1
      this->StateSnapshot);
189
190
  // Enter a policy and diagnostic level for this directory.
191
1
  this->PushPolicy();
192
1
  this->PushDiagnostic();
193
194
  // push empty loop block
195
1
  this->PushLoopBlockBarrier();
196
197
  // By default the check is not done.  It is enabled by
198
  // cmMakefile::Configure in the top level if necessary.
199
1
  this->CheckCMP0000 = false;
200
201
1
#if !defined(CMAKE_BOOTSTRAP)
202
1
  this->AddSourceGroup("", "^.*$");
203
1
  this->AddSourceGroup("Source Files", CM_SOURCE_REGEX);
204
1
  this->AddSourceGroup("Header Files", CM_HEADER_REGEX);
205
1
  this->AddSourceGroup("Precompile Header File", CM_PCH_REGEX);
206
1
  this->AddSourceGroup("CMake Rules", "\\.rule$");
207
1
  this->AddSourceGroup("Resources", CM_RESOURCE_REGEX);
208
1
  this->AddSourceGroup("Object Files", "\\.(lo|o|obj)$");
209
210
1
  this->ObjectLibrariesSourceGroupIndex = this->SourceGroups.size();
211
1
  this->SourceGroups.emplace_back(
212
1
    cm::make_unique<cmSourceGroup>("Object Libraries", "^MATCH_NO_SOURCES$"));
213
1
#endif
214
1
}
215
216
1
cmMakefile::~cmMakefile() = default;
217
218
cmDirectoryId cmMakefile::GetDirectoryId() const
219
0
{
220
  // Use the instance pointer value to uniquely identify this directory.
221
  // If we ever need to expose this to CMake language code we should
222
  // add a read-only property in cmMakefile::GetProperty.
223
0
  char buf[32];
224
0
  snprintf(buf, sizeof(buf), "(%p)",
225
0
           static_cast<void const*>(this)); // cast avoids format warning
226
0
  return std::string(buf);
227
0
}
228
229
void cmMakefile::IssueMessage(MessageType t, std::string const& text,
230
                              cmListFileBacktrace const& bt) const
231
0
{
232
0
  if (!this->ExecutionStatusStack.empty()) {
233
0
    if ((t == MessageType::FATAL_ERROR) ||
234
0
        (t == MessageType::INTERNAL_ERROR)) {
235
0
      this->ExecutionStatusStack.back()->SetNestedError();
236
0
    }
237
0
  }
238
0
  this->GetCMakeInstance()->IssueMessage(t, text, bt);
239
0
}
240
241
void cmMakefile::IssueDiagnostic(cmDiagnosticCategory category,
242
                                 std::string const& text,
243
                                 cmDiagnosticContext const& context) const
244
0
{
245
0
  if (!this->ExecutionStatusStack.empty()) {
246
0
    cmDiagnosticAction const action = this->GetDiagnosticAction(category);
247
0
    if (action >= cmDiagnosticAction::SendError) {
248
0
      this->ExecutionStatusStack.back()->SetNestedError();
249
0
    }
250
0
  }
251
0
  this->GetCMakeInstance()->IssueDiagnostic(category, text,
252
0
                                            this->GetStateSnapshot(), context);
253
0
}
254
255
void cmMakefile::IssuePolicyWarning(cmPolicies::PolicyID policy,
256
                                    cm::string_view preface,
257
                                    cm::string_view postface,
258
                                    cmListFileBacktrace const& bt) const
259
0
{
260
0
  std::string msg = cmPolicies::GetPolicyWarning(policy);
261
0
  if (!preface.empty() && !postface.empty()) {
262
0
    msg = cmStrCat(preface, '\n', msg, '\n', postface);
263
0
  } else if (!preface.empty()) {
264
0
    msg = cmStrCat(preface, '\n', msg);
265
0
  } else if (!postface.empty()) {
266
0
    msg = cmStrCat(msg, '\n', postface);
267
0
  }
268
0
  this->IssueDiagnostic(cmDiagnostics::CMD_POLICY, msg,
269
0
                        cmDiagnosticContext{ bt });
270
0
}
271
272
Message::LogLevel cmMakefile::GetCurrentLogLevel() const
273
0
{
274
0
  cmake const* cmakeInstance = this->GetCMakeInstance();
275
276
0
  Message::LogLevel const logLevelCliOrDefault = cmakeInstance->GetLogLevel();
277
0
  assert("Expected a valid log level here" &&
278
0
         logLevelCliOrDefault != Message::LogLevel::LOG_UNDEFINED);
279
280
0
  Message::LogLevel result = logLevelCliOrDefault;
281
282
  // If the log-level was set via the command line option, it takes precedence
283
  // over the CMAKE_MESSAGE_LOG_LEVEL variable.
284
0
  if (!cmakeInstance->WasLogLevelSetViaCLI()) {
285
0
    Message::LogLevel const logLevelFromVar = cmake::StringToLogLevel(
286
0
      this->GetSafeDefinition("CMAKE_MESSAGE_LOG_LEVEL"));
287
0
    if (logLevelFromVar != Message::LogLevel::LOG_UNDEFINED) {
288
0
      result = logLevelFromVar;
289
0
    }
290
0
  }
291
292
0
  return result;
293
0
}
294
295
void cmMakefile::IssueInvalidTargetNameError(
296
  std::string const& targetName) const
297
0
{
298
0
  this->IssueMessage(
299
0
    MessageType::FATAL_ERROR,
300
0
    cmStrCat("The target name \"", targetName,
301
0
             "\" is reserved or not valid for certain "
302
0
             "CMake features, such as generator expressions, and may result "
303
0
             "in undefined behavior."));
304
0
}
305
306
void cmMakefile::MaybeWarnCMP0074(std::string const& rootVar, cmValue rootDef,
307
                                  cm::optional<std::string> const& rootEnv)
308
0
{
309
  // Warn if a <PackageName>_ROOT variable we may use is set.
310
0
  if ((rootDef || rootEnv) && this->WarnedCMP0074.insert(rootVar).second) {
311
0
    std::string e;
312
0
    if (rootDef) {
313
0
      e += cmStrCat("CMake variable ", rootVar, " is set to:\n  ", *rootDef,
314
0
                    '\n');
315
0
    }
316
0
    if (rootEnv) {
317
0
      e += cmStrCat("Environment variable ", rootVar, " is set to:\n  ",
318
0
                    *rootEnv, '\n');
319
0
    }
320
0
    e += "For compatibility, CMake is ignoring the variable.";
321
0
    this->IssuePolicyWarning(cmPolicies::CMP0074, {}, e);
322
0
  }
323
0
}
324
325
void cmMakefile::MaybeWarnCMP0144(std::string const& rootVar, cmValue rootDef,
326
                                  cm::optional<std::string> const& rootEnv)
327
0
{
328
  // Warn if a <PACKAGENAME>_ROOT variable we may use is set.
329
0
  if ((rootDef || rootEnv) && this->WarnedCMP0144.insert(rootVar).second) {
330
0
    std::string e;
331
0
    if (rootDef) {
332
0
      e += cmStrCat("CMake variable ", rootVar, " is set to:\n  ", *rootDef,
333
0
                    '\n');
334
0
    }
335
0
    if (rootEnv) {
336
0
      e += cmStrCat("Environment variable ", rootVar, " is set to:\n  ",
337
0
                    *rootEnv, '\n');
338
0
    }
339
0
    e += "For compatibility, find_package is ignoring the variable, but "
340
0
         "code in a .cmake module might still use it.";
341
0
    this->IssuePolicyWarning(cmPolicies::CMP0144, {}, e);
342
0
  }
343
0
}
344
345
cmBTStringRange cmMakefile::GetIncludeDirectoriesEntries() const
346
0
{
347
0
  return this->StateSnapshot.GetDirectory().GetIncludeDirectoriesEntries();
348
0
}
349
350
cmBTStringRange cmMakefile::GetCompileOptionsEntries() const
351
0
{
352
0
  return this->StateSnapshot.GetDirectory().GetCompileOptionsEntries();
353
0
}
354
355
cmBTStringRange cmMakefile::GetCompileDefinitionsEntries() const
356
0
{
357
0
  return this->StateSnapshot.GetDirectory().GetCompileDefinitionsEntries();
358
0
}
359
360
cmBTStringRange cmMakefile::GetLinkOptionsEntries() const
361
0
{
362
0
  return this->StateSnapshot.GetDirectory().GetLinkOptionsEntries();
363
0
}
364
365
cmBTStringRange cmMakefile::GetLinkDirectoriesEntries() const
366
0
{
367
0
  return this->StateSnapshot.GetDirectory().GetLinkDirectoriesEntries();
368
0
}
369
370
cmListFileBacktrace cmMakefile::GetBacktrace() const
371
0
{
372
0
  return this->Backtrace;
373
0
}
374
375
cmFindPackageStack cmMakefile::GetFindPackageStack() const
376
0
{
377
0
  return this->FindPackageStack;
378
0
}
379
380
void cmMakefile::PrintCommandTrace(cmListFileFunction const& lff,
381
                                   cmListFileBacktrace const& bt,
382
                                   CommandMissingFromStack missing) const
383
0
{
384
  // Check if current file in the list of requested to trace...
385
0
  std::vector<std::string> const& trace_only_this_files =
386
0
    this->GetCMakeInstance()->GetTraceSources();
387
0
  std::string const& full_path = bt.Top().FilePath;
388
0
  cm::string_view only_filename =
389
0
    cmSystemTools::GetFilenameNameView(full_path);
390
0
  bool trace = trace_only_this_files.empty();
391
0
  if (!trace) {
392
0
    for (std::string const& file : trace_only_this_files) {
393
0
      std::string::size_type const pos = full_path.rfind(file);
394
0
      trace = (pos != std::string::npos) &&
395
0
        ((pos + file.size()) == full_path.size()) &&
396
0
        (only_filename == cmSystemTools::GetFilenameNameView(file));
397
0
      if (trace) {
398
0
        break;
399
0
      }
400
0
    }
401
    // Do nothing if current file wasn't requested for trace...
402
0
    if (!trace) {
403
0
      return;
404
0
    }
405
0
  }
406
407
0
  std::vector<std::string> args;
408
0
  std::string temp;
409
0
  bool expand = this->GetCMakeInstance()->GetTraceExpand();
410
411
0
  args.reserve(lff.Arguments().size());
412
0
  for (cmListFileArgument const& arg : lff.Arguments()) {
413
0
    if (expand && arg.Delim != cmListFileArgument::Bracket) {
414
0
      temp = arg.Value;
415
0
      this->ExpandVariablesInString(temp);
416
0
      args.push_back(temp);
417
0
    } else {
418
0
      args.push_back(arg.Value);
419
0
    }
420
0
  }
421
0
  cm::optional<std::string> const& deferId = bt.Top().DeferId;
422
423
0
  std::ostringstream msg;
424
0
  switch (this->GetCMakeInstance()->GetTraceFormat()) {
425
0
    case cmake::TraceFormat::JSONv1: {
426
0
#ifndef CMAKE_BOOTSTRAP
427
0
      Json::Value val;
428
0
      Json::StreamWriterBuilder builder;
429
0
      builder["indentation"] = "";
430
0
      val["file"] = full_path;
431
0
      val["line"] = static_cast<Json::Value::Int64>(lff.Line());
432
0
      if (lff.Line() != lff.LineEnd()) {
433
0
        val["line_end"] = static_cast<Json::Value::Int64>(lff.LineEnd());
434
0
      }
435
0
      if (deferId) {
436
0
        val["defer"] = *deferId;
437
0
      }
438
0
      val["cmd"] = lff.OriginalName();
439
0
      val["args"] = Json::Value(Json::arrayValue);
440
0
      for (std::string const& arg : args) {
441
0
        val["args"].append(arg);
442
0
      }
443
0
      val["time"] = cmSystemTools::GetTime();
444
0
      val["frame"] = int(missing == CommandMissingFromStack::Yes) +
445
0
        static_cast<Json::Value::UInt64>(this->ExecutionStatusStack.size());
446
0
      val["global_frame"] = int(missing == CommandMissingFromStack::Yes) +
447
0
        static_cast<Json::Value::UInt64>(this->RecursionDepth);
448
0
      msg << Json::writeString(builder, val);
449
0
#endif
450
0
      break;
451
0
    }
452
0
    case cmake::TraceFormat::Human:
453
0
      msg << full_path << '(' << lff.Line() << "):";
454
0
      if (deferId) {
455
0
        msg << "DEFERRED:" << *deferId << ':';
456
0
      }
457
0
      msg << "  " << lff.OriginalName() << '(';
458
459
0
      for (std::string const& arg : args) {
460
0
        msg << arg << ' ';
461
0
      }
462
0
      msg << ')';
463
0
      break;
464
0
    case cmake::TraceFormat::Undefined:
465
0
      msg << "INTERNAL ERROR: Trace format is Undefined";
466
0
      break;
467
0
  }
468
469
0
  auto& f = this->GetCMakeInstance()->GetTraceFile();
470
0
  if (f) {
471
0
    f << msg.str() << '\n';
472
0
  } else {
473
0
    cmSystemTools::Message(msg.str());
474
0
  }
475
0
}
476
477
cmMakefile::CallRAII::CallRAII(cmMakefile* mf, std::string const& file,
478
                               cmExecutionStatus& status)
479
0
  : CallRAII(mf, cmListFileContext::FromListFilePath(file), status)
480
0
{
481
0
}
482
483
cmMakefile::CallRAII::CallRAII(cmMakefile* mf, cmListFileContext const& lfc,
484
                               cmExecutionStatus& status)
485
0
  : Makefile{ mf }
486
0
{
487
0
  this->Makefile->Backtrace = this->Makefile->Backtrace.Push(lfc);
488
0
  ++this->Makefile->RecursionDepth;
489
0
  this->Makefile->ExecutionStatusStack.push_back(&status);
490
0
}
491
492
cmMakefile::CallRAII::~CallRAII()
493
0
{
494
0
  if (this->Makefile) {
495
0
    this->Detach();
496
0
  }
497
0
}
498
499
cmMakefile* cmMakefile::CallRAII::Detach()
500
0
{
501
0
  assert(this->Makefile);
502
503
0
  this->Makefile->ExecutionStatusStack.pop_back();
504
0
  --this->Makefile->RecursionDepth;
505
0
  this->Makefile->Backtrace = this->Makefile->Backtrace.Pop();
506
507
0
  auto* const mf = this->Makefile;
508
0
  this->Makefile = nullptr;
509
0
  return mf;
510
0
}
511
512
// Helper class to make sure the call stack is valid.
513
class cmMakefile::CallScope : public CallRAII
514
{
515
public:
516
  CallScope(cmMakefile* mf, cmListFileFunction const& lff,
517
            cm::optional<std::string> deferId, cmExecutionStatus& status)
518
0
    : CallScope{ mf, lff,
519
0
                 cmListFileContext::FromListFileFunction(
520
0
                   lff, mf->StateSnapshot.GetExecutionListFile(),
521
0
                   std::move(deferId)),
522
0
                 status }
523
0
  {
524
0
  }
525
526
  CallScope(cmMakefile* mf, cmListFileFunction const& lff,
527
            cmListFileContext const& lfc, cmExecutionStatus& status)
528
0
    : CallRAII{ mf, lfc, status }
529
0
  {
530
0
#if !defined(CMAKE_BOOTSTRAP)
531
0
    this->ProfilingDataRAII =
532
0
      this->Makefile->GetCMakeInstance()->CreateProfilingEntry(
533
0
        "script", lff.LowerCaseName(), [&lff, &lfc]() -> Json::Value {
534
0
          Json::Value argsValue = Json::objectValue;
535
0
          if (!lff.Arguments().empty()) {
536
0
            std::string args;
537
0
            for (auto const& a : lff.Arguments()) {
538
0
              args = cmStrCat(args, args.empty() ? "" : " ", a.Value);
539
0
            }
540
0
            argsValue["functionArgs"] = args;
541
0
          }
542
0
          argsValue["location"] = cmStrCat(lfc.FilePath, ':', lfc.Line);
543
0
          return argsValue;
544
0
        });
545
0
#endif
546
0
#ifdef CMake_ENABLE_DEBUGGER
547
0
    if (this->Makefile->GetCMakeInstance()->GetDebugAdapter()) {
548
0
      this->Makefile->GetCMakeInstance()
549
0
        ->GetDebugAdapter()
550
0
        ->OnBeginFunctionCall(mf, lfc.FilePath, lff);
551
0
    }
552
0
#endif
553
0
  }
554
555
  ~CallScope()
556
0
  {
557
0
#if !defined(CMAKE_BOOTSTRAP)
558
0
    this->ProfilingDataRAII.reset();
559
0
#endif
560
0
    auto* const mf = this->Detach();
561
0
#ifdef CMake_ENABLE_DEBUGGER
562
0
    if (mf->GetCMakeInstance()->GetDebugAdapter()) {
563
0
      mf->GetCMakeInstance()->GetDebugAdapter()->OnEndFunctionCall();
564
0
    }
565
#else
566
    static_cast<void>(mf);
567
#endif
568
0
  }
569
570
  CallScope(CallScope const&) = delete;
571
  CallScope& operator=(CallScope const&) = delete;
572
573
private:
574
#if !defined(CMAKE_BOOTSTRAP)
575
  cm::optional<cmMakefileProfilingData::RAII> ProfilingDataRAII;
576
#endif
577
};
578
579
void cmMakefile::OnExecuteCommand(std::function<void()> callback)
580
0
{
581
0
  this->ExecuteCommandCallback = std::move(callback);
582
0
}
583
584
bool cmMakefile::ExecuteCommand(cmListFileFunction const& lff,
585
                                cmExecutionStatus& status,
586
                                cm::optional<std::string> deferId)
587
0
{
588
0
  bool result = true;
589
590
  // quick return if blocked
591
0
  if (this->IsFunctionBlocked(lff, status)) {
592
    // No error.
593
0
    return result;
594
0
  }
595
596
  // Place this call on the call stack.
597
0
  CallScope stack_manager(this, lff, std::move(deferId), status);
598
0
  static_cast<void>(stack_manager);
599
600
  // Check for maximum recursion depth.
601
0
  size_t depthLimit = this->GetRecursionDepthLimit();
602
0
  if (this->RecursionDepth > depthLimit) {
603
0
    this->IssueMessage(
604
0
      MessageType::FATAL_ERROR,
605
0
      cmStrCat("Maximum recursion depth of ", depthLimit, " exceeded"));
606
0
    cmSystemTools::SetFatalErrorOccurred();
607
0
    return false;
608
0
  }
609
610
  // Lookup the command prototype.
611
0
  if (cmState::Command command =
612
0
        this->GetState()->GetCommandByExactName(lff.LowerCaseName())) {
613
    // Decide whether to invoke the command.
614
0
    if (!cmSystemTools::GetFatalErrorOccurred()) {
615
      // if trace is enabled, print out invoke information
616
0
      if (this->GetCMakeInstance()->GetTrace()) {
617
0
        this->PrintCommandTrace(lff, this->Backtrace);
618
0
      }
619
      // Try invoking the command.
620
0
      bool invokeSucceeded = command(lff.Arguments(), status);
621
0
      bool hadNestedError = status.GetNestedError();
622
0
      if (!invokeSucceeded || hadNestedError) {
623
0
        if (!hadNestedError) {
624
          // The command invocation requested that we report an error.
625
0
          std::string const error =
626
0
            cmStrCat(lff.OriginalName(), ' ', status.GetError());
627
0
          this->IssueMessage(MessageType::FATAL_ERROR, error);
628
0
        }
629
0
        result = false;
630
0
        if (this->GetCMakeInstance()->GetCommandFailureAction() ==
631
0
            cmake::CommandFailureAction::FATAL_ERROR) {
632
0
          cmSystemTools::SetFatalErrorOccurred();
633
0
        }
634
0
      }
635
0
      if (this->GetCMakeInstance()->HasScriptModeExitCode() &&
636
0
          this->GetCMakeInstance()->RoleSupportsExitCode()) {
637
        // pass-through the exit code from inner cmake_language(EXIT) ,
638
        // possibly from include() or similar command...
639
0
        status.SetExitCode(this->GetCMakeInstance()->GetScriptModeExitCode());
640
0
      }
641
0
    }
642
0
  } else {
643
0
    if (!cmSystemTools::GetFatalErrorOccurred()) {
644
0
      std::string error =
645
0
        cmStrCat("Unknown CMake command \"", lff.OriginalName(), "\".");
646
0
      this->IssueMessage(MessageType::FATAL_ERROR, error);
647
0
      result = false;
648
0
      cmSystemTools::SetFatalErrorOccurred();
649
0
    }
650
0
  }
651
652
0
  if (this->ExecuteCommandCallback) {
653
0
    this->ExecuteCommandCallback();
654
0
  }
655
656
0
  return result;
657
0
}
658
659
bool cmMakefile::IsImportedTargetGlobalScope() const
660
0
{
661
0
  return this->CurrentImportedTargetScope == ImportedTargetScope::Global;
662
0
}
663
664
class cmMakefile::IncludeScope : public FileScopeBase
665
{
666
public:
667
  IncludeScope(cmMakefile* mf, std::string const& filenametoread,
668
               cm::PolicyScope policyScope,
669
               cm::DiagnosticScope diagnosticScope);
670
  ~IncludeScope();
671
0
  void Quiet() { this->ReportError = false; }
672
673
  IncludeScope(IncludeScope const&) = delete;
674
  IncludeScope& operator=(IncludeScope const&) = delete;
675
676
private:
677
  cm::PolicyScope PolicyScope;
678
  cm::DiagnosticScope DiagnosticScope;
679
  bool ReportError = true;
680
};
681
682
cmMakefile::IncludeScope::IncludeScope(cmMakefile* mf,
683
                                       std::string const& filenametoread,
684
                                       cm::PolicyScope policyScope,
685
                                       cm::DiagnosticScope diagnosticScope)
686
0
  : FileScopeBase(mf)
687
0
  , PolicyScope(policyScope)
688
0
  , DiagnosticScope(diagnosticScope)
689
0
{
690
0
  this->Makefile->Backtrace = this->Makefile->Backtrace.Push(
691
0
    cmListFileContext::FromListFilePath(filenametoread));
692
693
0
  this->Makefile->PushFunctionBlockerBarrier();
694
695
0
  this->Makefile->StateSnapshot =
696
0
    this->Makefile->GetState()->CreateIncludeFileSnapshot(
697
0
      this->Makefile->StateSnapshot, filenametoread);
698
0
  if (this->PolicyScope == cm::PolicyScope::Local) {
699
0
    this->Makefile->PushPolicy();
700
0
  }
701
0
  if (this->DiagnosticScope == cm::DiagnosticScope::Local) {
702
0
    this->Makefile->PushDiagnostic();
703
0
  }
704
0
  this->PushListFileVars(filenametoread);
705
0
}
706
707
cmMakefile::IncludeScope::~IncludeScope()
708
0
{
709
0
  this->PopListFileVars();
710
0
  if (this->DiagnosticScope == cm::DiagnosticScope::Local) {
711
    // Pop the scope we pushed for the script.
712
0
    this->Makefile->PopDiagnostic();
713
0
  }
714
0
  if (this->PolicyScope == cm::PolicyScope::Local) {
715
    // Pop the scope we pushed for the script.
716
0
    this->Makefile->PopPolicy();
717
0
  }
718
0
  this->Makefile->PopSnapshot(this->ReportError);
719
720
0
  this->Makefile->PopFunctionBlockerBarrier(this->ReportError);
721
722
0
  this->Makefile->Backtrace = this->Makefile->Backtrace.Pop();
723
0
}
724
725
bool cmMakefile::ReadDependentFile(std::string const& filename,
726
                                   cm::PolicyScope policyScope,
727
                                   cm::DiagnosticScope diagnosticScope)
728
0
{
729
0
  std::string filenametoread = cmSystemTools::CollapseFullPath(
730
0
    filename, this->GetCurrentSourceDirectory());
731
732
0
  IncludeScope incScope(this, filenametoread, policyScope, diagnosticScope);
733
734
0
#ifdef CMake_ENABLE_DEBUGGER
735
0
  if (this->GetCMakeInstance()->GetDebugAdapter()) {
736
0
    this->GetCMakeInstance()->GetDebugAdapter()->OnBeginFileParse(
737
0
      this, filenametoread);
738
0
  }
739
0
#endif
740
741
0
  cmListFile listFile;
742
0
  if (!listFile.ParseFile(filenametoread, this, this->Backtrace)) {
743
0
#ifdef CMake_ENABLE_DEBUGGER
744
0
    if (this->GetCMakeInstance()->GetDebugAdapter()) {
745
0
      this->GetCMakeInstance()->GetDebugAdapter()->OnEndFileParse();
746
0
    }
747
0
#endif
748
749
0
    return false;
750
0
  }
751
752
0
#ifdef CMake_ENABLE_DEBUGGER
753
0
  if (this->GetCMakeInstance()->GetDebugAdapter()) {
754
0
    this->GetCMakeInstance()->GetDebugAdapter()->OnEndFileParse();
755
0
    this->GetCMakeInstance()->GetDebugAdapter()->OnFileParsedSuccessfully(
756
0
      filenametoread, listFile.Functions);
757
0
  }
758
0
#endif
759
760
0
  this->RunListFile(listFile, filenametoread);
761
0
  if (cmSystemTools::GetFatalErrorOccurred()) {
762
0
    incScope.Quiet();
763
0
  }
764
0
  return true;
765
0
}
766
767
class cmMakefile::ListFileScope : public FileScopeBase
768
{
769
public:
770
  ListFileScope(cmMakefile* mf, std::string const& filenametoread)
771
1
    : FileScopeBase(mf)
772
1
  {
773
1
    this->Makefile->Backtrace = this->Makefile->Backtrace.Push(
774
1
      cmListFileContext::FromListFilePath(filenametoread));
775
776
1
    this->Makefile->StateSnapshot =
777
1
      this->Makefile->GetState()->CreateInlineListFileSnapshot(
778
1
        this->Makefile->StateSnapshot, filenametoread);
779
1
    assert(this->Makefile->StateSnapshot.IsValid());
780
781
1
    this->Makefile->PushFunctionBlockerBarrier();
782
1
    this->PushListFileVars(filenametoread);
783
1
  }
784
785
  ~ListFileScope()
786
1
  {
787
1
    this->PopListFileVars();
788
1
    this->Makefile->PopSnapshot(this->ReportError);
789
1
    this->Makefile->PopFunctionBlockerBarrier(this->ReportError);
790
1
    this->Makefile->Backtrace = this->Makefile->Backtrace.Pop();
791
1
  }
792
793
0
  void Quiet() { this->ReportError = false; }
794
795
  ListFileScope(ListFileScope const&) = delete;
796
  ListFileScope& operator=(ListFileScope const&) = delete;
797
798
private:
799
  bool ReportError = true;
800
};
801
802
class cmMakefile::DeferScope
803
{
804
public:
805
  DeferScope(cmMakefile* mf, std::string const& deferredInFile)
806
0
    : Makefile(mf)
807
0
  {
808
0
    cmListFileContext lfc;
809
0
    lfc.Line = cmListFileContext::DeferPlaceholderLine;
810
0
    lfc.FilePath = deferredInFile;
811
0
    this->Makefile->Backtrace = this->Makefile->Backtrace.Push(lfc);
812
0
    this->Makefile->DeferRunning = true;
813
0
  }
814
815
  ~DeferScope()
816
0
  {
817
0
    this->Makefile->DeferRunning = false;
818
0
    this->Makefile->Backtrace = this->Makefile->Backtrace.Pop();
819
0
  }
820
821
  DeferScope(DeferScope const&) = delete;
822
  DeferScope& operator=(DeferScope const&) = delete;
823
824
private:
825
  cmMakefile* Makefile;
826
};
827
828
class cmMakefile::DeferCallScope
829
{
830
public:
831
  DeferCallScope(cmMakefile* mf, std::string const& deferredFromFile)
832
0
    : Makefile(mf)
833
0
  {
834
0
    this->Makefile->StateSnapshot =
835
0
      this->Makefile->GetState()->CreateDeferCallSnapshot(
836
0
        this->Makefile->StateSnapshot, deferredFromFile);
837
0
    assert(this->Makefile->StateSnapshot.IsValid());
838
0
  }
839
840
0
  ~DeferCallScope() { this->Makefile->PopSnapshot(); }
841
842
  DeferCallScope(DeferCallScope const&) = delete;
843
  DeferCallScope& operator=(DeferCallScope const&) = delete;
844
845
private:
846
  cmMakefile* Makefile;
847
};
848
849
bool cmMakefile::ReadListFile(std::string const& filename)
850
1
{
851
1
  std::string filenametoread = cmSystemTools::CollapseFullPath(
852
1
    filename, this->GetCurrentSourceDirectory());
853
854
1
  ListFileScope scope(this, filenametoread);
855
856
1
#ifdef CMake_ENABLE_DEBUGGER
857
1
  if (this->GetCMakeInstance()->GetDebugAdapter()) {
858
0
    this->GetCMakeInstance()->GetDebugAdapter()->OnBeginFileParse(
859
0
      this, filenametoread);
860
0
  }
861
1
#endif
862
863
1
  cmListFile listFile;
864
1
  if (!listFile.ParseFile(filenametoread, this, this->Backtrace)) {
865
1
#ifdef CMake_ENABLE_DEBUGGER
866
1
    if (this->GetCMakeInstance()->GetDebugAdapter()) {
867
0
      this->GetCMakeInstance()->GetDebugAdapter()->OnEndFileParse();
868
0
    }
869
1
#endif
870
871
1
    return false;
872
1
  }
873
874
0
#ifdef CMake_ENABLE_DEBUGGER
875
0
  if (this->GetCMakeInstance()->GetDebugAdapter()) {
876
0
    this->GetCMakeInstance()->GetDebugAdapter()->OnEndFileParse();
877
0
    this->GetCMakeInstance()->GetDebugAdapter()->OnFileParsedSuccessfully(
878
0
      filenametoread, listFile.Functions);
879
0
  }
880
0
#endif
881
882
0
  this->RunListFile(listFile, filenametoread);
883
0
  if (cmSystemTools::GetFatalErrorOccurred()) {
884
0
    scope.Quiet();
885
0
  }
886
0
  return true;
887
1
}
888
889
bool cmMakefile::ReadListFileAsString(std::string const& content,
890
                                      std::string const& virtualFileName)
891
0
{
892
0
  std::string filenametoread = cmSystemTools::CollapseFullPath(
893
0
    virtualFileName, this->GetCurrentSourceDirectory());
894
895
0
  ListFileScope scope(this, filenametoread);
896
897
0
  cmListFile listFile;
898
0
  if (!listFile.ParseString(content, virtualFileName, this, this->Backtrace)) {
899
0
    return false;
900
0
  }
901
902
0
#ifdef CMake_ENABLE_DEBUGGER
903
0
  if (this->GetCMakeInstance()->GetDebugAdapter()) {
904
0
    this->GetCMakeInstance()->GetDebugAdapter()->OnFileParsedSuccessfully(
905
0
      filenametoread, listFile.Functions);
906
0
  }
907
0
#endif
908
909
0
  this->RunListFile(listFile, filenametoread);
910
0
  if (cmSystemTools::GetFatalErrorOccurred()) {
911
0
    scope.Quiet();
912
0
  }
913
0
  return true;
914
0
}
915
916
void cmMakefile::RunListFile(cmListFile const& listFile,
917
                             std::string const& filenametoread,
918
                             DeferCommands* defer)
919
0
{
920
  // add this list file to the list of dependencies
921
0
  this->ListFiles.push_back(filenametoread);
922
923
  // Run the parsed commands.
924
0
  size_t const numberFunctions = listFile.Functions.size();
925
0
  for (size_t i = 0; i < numberFunctions; ++i) {
926
0
    cmExecutionStatus status(*this);
927
0
    this->ExecuteCommand(listFile.Functions[i], status);
928
0
    if (cmSystemTools::GetFatalErrorOccurred()) {
929
0
      break;
930
0
    }
931
0
    if (status.HasExitCode()) {
932
      // cmake_language EXIT was requested, early break.
933
0
      this->GetCMakeInstance()->SetScriptModeExitCode(status.GetExitCode());
934
0
      break;
935
0
    }
936
0
    if (status.GetReturnInvoked()) {
937
0
      this->RaiseScope(status.GetReturnVariables());
938
      // Exit early due to return command.
939
0
      break;
940
0
    }
941
0
  }
942
943
  // Run any deferred commands.
944
0
  if (defer) {
945
    // Add a backtrace level indicating calls are deferred.
946
0
    DeferScope scope(this, filenametoread);
947
948
    // Iterate by index in case one deferred call schedules another.
949
    // NOLINTNEXTLINE(modernize-loop-convert)
950
0
    for (size_t i = 0; i < defer->Commands.size(); ++i) {
951
0
      DeferCommand& d = defer->Commands[i];
952
0
      if (d.Id.empty()) {
953
        // Canceled.
954
0
        continue;
955
0
      }
956
      // Mark as executed.
957
0
      std::string id = std::move(d.Id);
958
959
      // The deferred call may have come from another file.
960
0
      DeferCallScope callScope(this, d.FilePath);
961
962
0
      cmExecutionStatus status(*this);
963
0
      this->ExecuteCommand(d.Command, status, std::move(id));
964
0
      if (cmSystemTools::GetFatalErrorOccurred()) {
965
0
        break;
966
0
      }
967
0
    }
968
0
  }
969
0
}
970
971
void cmMakefile::EnforceDirectoryLevelRules() const
972
0
{
973
  // Diagnose a violation of CMP0000 if necessary.
974
0
  if (this->CheckCMP0000) {
975
0
    std::string e =
976
0
      cmStrCat("No cmake_minimum_required command is present.  "
977
0
               "A line of code such as\n"
978
0
               "  cmake_minimum_required(VERSION ",
979
0
               cmVersion::GetMajorVersion(), '.', cmVersion::GetMinorVersion(),
980
0
               ")\n"
981
0
               "should be added at the top of the file.  "
982
0
               "The version specified may be lower if you wish to "
983
0
               "support older CMake versions for this project.  "
984
0
               "For more information run "
985
0
               "\"cmake --help-policy CMP0000\".");
986
0
    this->GetCMakeInstance()->IssueMessage(MessageType::FATAL_ERROR, e,
987
0
                                           this->Backtrace);
988
0
    cmSystemTools::SetFatalErrorOccurred();
989
0
  }
990
0
}
991
992
void cmMakefile::AddEvaluationFile(
993
  std::string const& inputFile, std::string const& targetName,
994
  std::unique_ptr<cmCompiledGeneratorExpression> outputName,
995
  std::unique_ptr<cmCompiledGeneratorExpression> condition,
996
  std::string const& newLineCharacter, mode_t permissions, bool inputIsContent)
997
0
{
998
0
  this->EvaluationFiles.push_back(
999
0
    cm::make_unique<cmGeneratorExpressionEvaluationFile>(
1000
0
      inputFile, targetName, std::move(outputName), std::move(condition),
1001
0
      inputIsContent, newLineCharacter, permissions,
1002
0
      this->GetPolicyStatus(cmPolicies::CMP0070),
1003
0
      this->GetPolicyStatus(cmPolicies::CMP0189)));
1004
0
}
1005
1006
std::vector<std::unique_ptr<cmGeneratorExpressionEvaluationFile>> const&
1007
cmMakefile::GetEvaluationFiles() const
1008
0
{
1009
0
  return this->EvaluationFiles;
1010
0
}
1011
1012
std::vector<std::unique_ptr<cmExportBuildFileGenerator>> const&
1013
cmMakefile::GetExportBuildFileGenerators() const
1014
0
{
1015
0
  return this->ExportBuildFileGenerators;
1016
0
}
1017
1018
void cmMakefile::AddExportBuildFileGenerator(
1019
  std::unique_ptr<cmExportBuildFileGenerator> gen)
1020
0
{
1021
0
  this->ExportBuildFileGenerators.emplace_back(std::move(gen));
1022
0
}
1023
1024
#ifndef CMAKE_BOOTSTRAP
1025
std::vector<std::unique_ptr<cmBuildSbomGenerator>> const&
1026
cmMakefile::GetBuildSbomGenerators() const
1027
0
{
1028
0
  return this->BuildSbomGenerators;
1029
0
}
1030
1031
void cmMakefile::AddBuildSbomGenerator(
1032
  std::unique_ptr<cmBuildSbomGenerator> gen)
1033
0
{
1034
0
  this->BuildSbomGenerators.emplace_back(std::move(gen));
1035
0
}
1036
#endif
1037
1038
namespace {
1039
struct file_not_persistent
1040
{
1041
  bool operator()(std::string const& path) const
1042
0
  {
1043
0
    return !(path.find("CMakeTmp") == std::string::npos &&
1044
0
             cmSystemTools::FileExists(path));
1045
0
  }
1046
};
1047
}
1048
1049
void cmMakefile::AddGeneratorAction(GeneratorAction&& action)
1050
0
{
1051
0
  assert(!this->GeneratorActionsInvoked);
1052
0
  this->GeneratorActions.emplace_back(std::move(action), this->Backtrace);
1053
0
}
1054
1055
void cmMakefile::GeneratorAction::operator()(cmLocalGenerator& lg,
1056
                                             cmListFileBacktrace const& lfbt,
1057
                                             GeneratorActionWhen when)
1058
0
{
1059
0
  if (this->When != when) {
1060
0
    return;
1061
0
  }
1062
1063
0
  if (cc) {
1064
0
    CCAction(lg, lfbt, std::move(cc));
1065
0
  } else {
1066
0
    assert(Action);
1067
0
    Action(lg, lfbt);
1068
0
  }
1069
0
}
1070
1071
void cmMakefile::DoGenerate(cmLocalGenerator& lg)
1072
0
{
1073
  // give all the commands a chance to do something
1074
  // after the file has been parsed before generation
1075
0
  for (auto& action : this->GeneratorActions) {
1076
0
    action.Value(lg, action.Backtrace, GeneratorActionWhen::AfterConfigure);
1077
0
  }
1078
0
  this->GeneratorActionsInvoked = true;
1079
1080
  // go through all configured files and see which ones still exist.
1081
  // we don't want cmake to re-run if a configured file is created and deleted
1082
  // during processing as that would make it a transient file that can't
1083
  // influence the build process
1084
0
  cm::erase_if(this->OutputFiles, file_not_persistent());
1085
1086
  // if a configured file is used as input for another configured file,
1087
  // and then deleted it will show up in the input list files so we
1088
  // need to scan those too
1089
0
  cm::erase_if(this->ListFiles, file_not_persistent());
1090
0
}
1091
1092
// Generate the output file
1093
void cmMakefile::Generate(cmLocalGenerator& lg)
1094
0
{
1095
0
  this->DoGenerate(lg);
1096
0
  cmValue oldValue = this->GetDefinition("CMAKE_BACKWARDS_COMPATIBILITY");
1097
0
  if (oldValue &&
1098
0
      cmSystemTools::VersionCompare(cmSystemTools::OP_LESS, *oldValue,
1099
0
                                    "2.4")) {
1100
0
    this->GetCMakeInstance()->IssueMessage(
1101
0
      MessageType::FATAL_ERROR,
1102
0
      "You have set CMAKE_BACKWARDS_COMPATIBILITY to a CMake version less "
1103
0
      "than 2.4. This version of CMake only supports backwards compatibility "
1104
0
      "with CMake 2.4 or later. For compatibility with older versions please "
1105
0
      "use any CMake 2.8.x release or lower.",
1106
0
      this->Backtrace);
1107
0
  }
1108
0
}
1109
1110
void cmMakefile::GenerateAfterGeneratorTargets(cmLocalGenerator& lg)
1111
0
{
1112
0
  for (auto& action : this->GeneratorActions) {
1113
0
    action.Value(lg, action.Backtrace,
1114
0
                 GeneratorActionWhen::AfterGeneratorTargets);
1115
0
  }
1116
0
}
1117
1118
namespace {
1119
// There are still too many implicit backtraces through cmMakefile.  As a
1120
// workaround we reset the backtrace temporarily.
1121
struct BacktraceGuard
1122
{
1123
  BacktraceGuard(cmListFileBacktrace& lfbt, cmListFileBacktrace current)
1124
0
    : Backtrace(lfbt)
1125
0
    , Previous(lfbt)
1126
0
  {
1127
0
    this->Backtrace = std::move(current);
1128
0
  }
1129
1130
0
  ~BacktraceGuard() { this->Backtrace = std::move(this->Previous); }
1131
1132
private:
1133
  cmListFileBacktrace& Backtrace;
1134
  cmListFileBacktrace Previous;
1135
};
1136
}
1137
1138
bool cmMakefile::ValidateCustomCommand(
1139
  cmCustomCommandLines const& commandLines) const
1140
0
{
1141
  // TODO: More strict?
1142
0
  auto const it =
1143
0
    std::find_if(commandLines.begin(), commandLines.end(),
1144
0
                 [](cmCustomCommandLine const& cl) {
1145
0
                   return !cl.empty() && !cl[0].empty() && cl[0][0] == '"';
1146
0
                 });
1147
0
  if (it != commandLines.end()) {
1148
0
    this->IssueMessage(
1149
0
      MessageType::FATAL_ERROR,
1150
0
      cmStrCat("COMMAND may not contain literal quotes:\n  ", (*it)[0], '\n'));
1151
0
    return false;
1152
0
  }
1153
0
  return true;
1154
0
}
1155
1156
cmTarget* cmMakefile::GetCustomCommandTarget(
1157
  std::string const& target, cmObjectLibraryCommands objLibCommands,
1158
  cmListFileBacktrace const& lfbt) const
1159
0
{
1160
0
  auto realTarget = target;
1161
1162
0
  auto ai = this->AliasTargets.find(target);
1163
0
  if (ai != this->AliasTargets.end()) {
1164
0
    realTarget = ai->second;
1165
0
  }
1166
1167
  // Find the target to which to add the custom command.
1168
0
  auto ti = this->Targets.find(realTarget);
1169
0
  if (ti == this->Targets.end()) {
1170
0
    std::string e;
1171
0
    if (cmTarget const* t = this->FindTargetToUse(target)) {
1172
0
      if (t->IsImported()) {
1173
0
        e += cmStrCat("TARGET '", target,
1174
0
                      "' is IMPORTED and does not build here.");
1175
0
      } else {
1176
0
        e +=
1177
0
          cmStrCat("TARGET '", target, "' was not created in this directory.");
1178
0
      }
1179
0
    } else {
1180
0
      e += cmStrCat("No TARGET '", target,
1181
0
                    "' has been created in this directory.");
1182
0
    }
1183
0
    this->GetCMakeInstance()->IssueMessage(MessageType::FATAL_ERROR, e, lfbt);
1184
0
    return nullptr;
1185
0
  }
1186
1187
0
  cmTarget* t = &ti->second;
1188
0
  if (objLibCommands == cmObjectLibraryCommands::Reject &&
1189
0
      t->GetType() == cmStateEnums::OBJECT_LIBRARY) {
1190
0
    auto e = cmStrCat(
1191
0
      "Target \"", target,
1192
0
      "\" is an OBJECT library "
1193
0
      "that may not have PRE_BUILD, PRE_LINK, or POST_BUILD commands.");
1194
0
    this->GetCMakeInstance()->IssueMessage(MessageType::FATAL_ERROR, e, lfbt);
1195
0
    return nullptr;
1196
0
  }
1197
0
  if (t->GetType() == cmStateEnums::INTERFACE_LIBRARY) {
1198
0
    auto e = cmStrCat(
1199
0
      "Target \"", target,
1200
0
      "\" is an INTERFACE library "
1201
0
      "that may not have PRE_BUILD, PRE_LINK, or POST_BUILD commands.");
1202
0
    this->GetCMakeInstance()->IssueMessage(MessageType::FATAL_ERROR, e, lfbt);
1203
0
    return nullptr;
1204
0
  }
1205
1206
0
  return t;
1207
0
}
1208
1209
cmTarget* cmMakefile::AddCustomCommandToTarget(
1210
  std::string const& target, cmCustomCommandType type,
1211
  std::unique_ptr<cmCustomCommand> cc)
1212
0
{
1213
0
  auto const& byproducts = cc->GetByproducts();
1214
0
  auto const& commandLines = cc->GetCommandLines();
1215
1216
0
  cmTarget* t = this->GetCustomCommandTarget(
1217
0
    target, cmObjectLibraryCommands::Reject, this->Backtrace);
1218
1219
  // Validate custom commands.
1220
0
  if (!t || !this->ValidateCustomCommand(commandLines)) {
1221
0
    return t;
1222
0
  }
1223
1224
  // Always create the byproduct sources and mark them generated.
1225
0
  this->CreateGeneratedOutputs(byproducts);
1226
1227
0
  cc->RecordPolicyValues(this->GetStateSnapshot());
1228
1229
  // Dispatch command creation to allow generator expressions in outputs.
1230
0
  this->AddGeneratorAction(
1231
0
    std::move(cc),
1232
0
    [this, t, type](cmLocalGenerator& lg, cmListFileBacktrace const& lfbt,
1233
0
                    std::unique_ptr<cmCustomCommand> tcc) {
1234
0
      BacktraceGuard guard(this->Backtrace, lfbt);
1235
0
      tcc->SetBacktrace(lfbt);
1236
0
      detail::AddCustomCommandToTarget(lg, cmCommandOrigin::Project, t, type,
1237
0
                                       std::move(tcc));
1238
0
    });
1239
1240
0
  return t;
1241
0
}
1242
1243
void cmMakefile::AddCustomCommandToOutput(
1244
  std::unique_ptr<cmCustomCommand> cc, CommandSourceCallback const& callback,
1245
  bool replace)
1246
0
{
1247
0
  auto const& outputs = cc->GetOutputs();
1248
0
  auto const& byproducts = cc->GetByproducts();
1249
0
  auto const& commandLines = cc->GetCommandLines();
1250
1251
  // Make sure there is at least one output.
1252
0
  if (outputs.empty()) {
1253
0
    cmSystemTools::Error("Attempt to add a custom rule with no output!");
1254
0
    return;
1255
0
  }
1256
1257
  // Validate custom commands.
1258
0
  if (!this->ValidateCustomCommand(commandLines)) {
1259
0
    return;
1260
0
  }
1261
1262
  // Always create the output sources and mark them generated.
1263
0
  this->CreateGeneratedOutputs(outputs);
1264
0
  this->CreateGeneratedOutputs(byproducts);
1265
1266
0
  cc->RecordPolicyValues(this->GetStateSnapshot());
1267
1268
  // Dispatch command creation to allow generator expressions in outputs.
1269
0
  this->AddGeneratorAction(
1270
0
    std::move(cc),
1271
0
    [this, replace, callback](cmLocalGenerator& lg,
1272
0
                              cmListFileBacktrace const& lfbt,
1273
0
                              std::unique_ptr<cmCustomCommand> tcc) {
1274
0
      BacktraceGuard guard(this->Backtrace, lfbt);
1275
0
      tcc->SetBacktrace(lfbt);
1276
0
      cmSourceFile* sf = detail::AddCustomCommandToOutput(
1277
0
        lg, cmCommandOrigin::Project, std::move(tcc), replace);
1278
0
      if (callback && sf) {
1279
0
        callback(sf);
1280
0
      }
1281
0
    });
1282
0
}
1283
1284
void cmMakefile::AppendCustomCommandToOutput(
1285
  std::string const& output, std::vector<std::string> const& depends,
1286
  cmImplicitDependsList const& implicit_depends,
1287
  cmCustomCommandLines const& commandLines)
1288
0
{
1289
  // Validate custom commands.
1290
0
  if (this->ValidateCustomCommand(commandLines)) {
1291
    // Dispatch command creation to allow generator expressions in outputs.
1292
0
    this->AddGeneratorAction(
1293
0
      [this, output, depends, implicit_depends,
1294
0
       commandLines](cmLocalGenerator& lg, cmListFileBacktrace const& lfbt) {
1295
0
        BacktraceGuard guard(this->Backtrace, lfbt);
1296
0
        detail::AppendCustomCommandToOutput(lg, lfbt, output, depends,
1297
0
                                            implicit_depends, commandLines);
1298
0
      });
1299
0
  }
1300
0
}
1301
1302
cmTarget* cmMakefile::AddUtilityCommand(std::string const& utilityName,
1303
                                        bool excludeFromAll,
1304
                                        std::unique_ptr<cmCustomCommand> cc)
1305
0
{
1306
0
  auto const& depends = cc->GetDepends();
1307
0
  auto const& byproducts = cc->GetByproducts();
1308
0
  auto const& commandLines = cc->GetCommandLines();
1309
0
  cmTarget* target = this->AddNewUtilityTarget(utilityName, excludeFromAll);
1310
1311
  // Validate custom commands.
1312
0
  if ((commandLines.empty() && depends.empty()) ||
1313
0
      !this->ValidateCustomCommand(commandLines)) {
1314
0
    return target;
1315
0
  }
1316
1317
  // Always create the byproduct sources and mark them generated.
1318
0
  this->CreateGeneratedOutputs(byproducts);
1319
1320
0
  cc->RecordPolicyValues(this->GetStateSnapshot());
1321
1322
  // Dispatch command creation to allow generator expressions in outputs.
1323
0
  this->AddGeneratorAction(
1324
0
    std::move(cc),
1325
0
    [this, target](cmLocalGenerator& lg, cmListFileBacktrace const& lfbt,
1326
0
                   std::unique_ptr<cmCustomCommand> tcc) {
1327
0
      BacktraceGuard guard(this->Backtrace, lfbt);
1328
0
      tcc->SetBacktrace(lfbt);
1329
0
      detail::AddUtilityCommand(lg, cmCommandOrigin::Project, target,
1330
0
                                std::move(tcc));
1331
0
    });
1332
1333
0
  return target;
1334
0
}
1335
1336
static void s_AddDefineFlag(std::string const& flag, std::string& dflags)
1337
0
{
1338
  // remove any \n\r
1339
0
  std::string::size_type initSize = dflags.size();
1340
0
  dflags += ' ';
1341
0
  dflags += flag;
1342
0
  std::string::iterator flagStart = dflags.begin() + initSize + 1;
1343
0
  std::replace(flagStart, dflags.end(), '\n', ' ');
1344
0
  std::replace(flagStart, dflags.end(), '\r', ' ');
1345
0
}
1346
1347
void cmMakefile::AddDefineFlag(std::string const& flag)
1348
0
{
1349
0
  if (flag.empty()) {
1350
0
    return;
1351
0
  }
1352
1353
  // If this is really a definition, update COMPILE_DEFINITIONS.
1354
0
  if (this->ParseDefineFlag(flag, false)) {
1355
0
    return;
1356
0
  }
1357
1358
  // Add this flag that does not look like a definition.
1359
0
  s_AddDefineFlag(flag, this->DefineFlags);
1360
0
}
1361
1362
static void s_RemoveDefineFlag(std::string const& flag, std::string& dflags)
1363
0
{
1364
0
  std::string::size_type const len = flag.length();
1365
  // Remove all instances of the flag that are surrounded by
1366
  // whitespace or the beginning/end of the string.
1367
0
  for (std::string::size_type lpos = dflags.find(flag, 0);
1368
0
       lpos != std::string::npos; lpos = dflags.find(flag, lpos)) {
1369
0
    std::string::size_type rpos = lpos + len;
1370
0
    if ((lpos <= 0 || cmsysString_isspace(dflags[lpos - 1])) &&
1371
0
        (rpos >= dflags.size() || cmsysString_isspace(dflags[rpos]))) {
1372
0
      dflags.erase(lpos, len);
1373
0
    } else {
1374
0
      ++lpos;
1375
0
    }
1376
0
  }
1377
0
}
1378
1379
void cmMakefile::RemoveDefineFlag(std::string const& flag)
1380
0
{
1381
  // Check the length of the flag to remove.
1382
0
  if (flag.empty()) {
1383
0
    return;
1384
0
  }
1385
1386
  // If this is really a definition, update COMPILE_DEFINITIONS.
1387
0
  if (this->ParseDefineFlag(flag, true)) {
1388
0
    return;
1389
0
  }
1390
1391
  // Remove this flag that does not look like a definition.
1392
0
  s_RemoveDefineFlag(flag, this->DefineFlags);
1393
0
}
1394
1395
void cmMakefile::AddCompileDefinition(std::string const& option)
1396
0
{
1397
0
  this->AppendProperty("COMPILE_DEFINITIONS", option);
1398
0
}
1399
1400
void cmMakefile::AddCompileOption(std::string const& option)
1401
0
{
1402
0
  this->AppendProperty("COMPILE_OPTIONS", option);
1403
0
}
1404
1405
void cmMakefile::AddLinkOption(std::string const& option)
1406
0
{
1407
0
  this->AppendProperty("LINK_OPTIONS", option);
1408
0
}
1409
1410
void cmMakefile::AddLinkDirectory(std::string const& directory, bool before)
1411
0
{
1412
0
  if (before) {
1413
0
    this->StateSnapshot.GetDirectory().PrependLinkDirectoriesEntry(
1414
0
      BT<std::string>(directory, this->Backtrace));
1415
0
  } else {
1416
0
    this->StateSnapshot.GetDirectory().AppendLinkDirectoriesEntry(
1417
0
      BT<std::string>(directory, this->Backtrace));
1418
0
  }
1419
0
}
1420
1421
bool cmMakefile::ParseDefineFlag(std::string const& def, bool remove)
1422
0
{
1423
  // Create a regular expression to match valid definitions.
1424
0
  static cmsys::RegularExpression valid("^[-/]D[A-Za-z_][A-Za-z0-9_]*(=.*)?$");
1425
1426
  // Make sure the definition matches.
1427
0
  if (!valid.find(def)) {
1428
0
    return false;
1429
0
  }
1430
1431
  // Get the definition part after the flag.
1432
0
  char const* define = def.c_str() + 2;
1433
1434
0
  if (remove) {
1435
0
    if (cmValue cdefs = this->GetProperty("COMPILE_DEFINITIONS")) {
1436
      // Expand the list.
1437
0
      cmList defs{ *cdefs };
1438
1439
      // Recompose the list without the definition.
1440
0
      defs.remove_items({ define });
1441
1442
      // Store the new list.
1443
0
      this->SetProperty("COMPILE_DEFINITIONS", defs.to_string());
1444
0
    }
1445
0
  } else {
1446
    // Append the definition to the directory property.
1447
0
    this->AppendProperty("COMPILE_DEFINITIONS", define);
1448
0
  }
1449
1450
0
  return true;
1451
0
}
1452
1453
void cmMakefile::InitializeFromParent(cmMakefile* parent)
1454
0
{
1455
0
  this->SystemIncludeDirectories = parent->SystemIncludeDirectories;
1456
1457
  // define flags
1458
0
  this->DefineFlags = parent->DefineFlags;
1459
1460
  // Include transform property.  There is no per-config version.
1461
0
  {
1462
0
    char const* prop = "IMPLICIT_DEPENDS_INCLUDE_TRANSFORM";
1463
0
    this->SetProperty(prop, parent->GetProperty(prop));
1464
0
  }
1465
1466
  // labels
1467
0
  this->SetProperty("LABELS", parent->GetProperty("LABELS"));
1468
1469
  // link libraries
1470
0
  this->SetProperty("LINK_LIBRARIES", parent->GetProperty("LINK_LIBRARIES"));
1471
1472
  // the initial project name
1473
0
  this->StateSnapshot.SetProjectName(parent->StateSnapshot.GetProjectName());
1474
1475
  // Copy include regular expressions.
1476
0
  this->ComplainFileRegularExpression = parent->ComplainFileRegularExpression;
1477
1478
  // Imported targets.
1479
0
  this->ImportedTargets = parent->ImportedTargets;
1480
1481
  // Non-global Alias targets.
1482
0
  this->AliasTargets = parent->AliasTargets;
1483
1484
  // Recursion depth.
1485
0
  this->RecursionDepth = parent->RecursionDepth;
1486
0
}
1487
1488
void cmMakefile::AddInstallGenerator(std::unique_ptr<cmInstallGenerator> g)
1489
0
{
1490
0
  if (g) {
1491
0
    this->InstallGenerators.push_back(std::move(g));
1492
0
  }
1493
0
}
1494
1495
void cmMakefile::AddTestGenerator(std::unique_ptr<cmTestGenerator> g)
1496
0
{
1497
0
  if (g) {
1498
0
    this->TestGenerators.push_back(std::move(g));
1499
0
  }
1500
0
}
1501
1502
void cmMakefile::PushFunctionScope(std::string const& fileName,
1503
                                   cmPolicies::PolicyMap const& pm,
1504
                                   cmDiagnostics::DiagnosticMap dm)
1505
0
{
1506
0
  this->StateSnapshot = this->GetState()->CreateFunctionCallSnapshot(
1507
0
    this->StateSnapshot, fileName);
1508
0
  assert(this->StateSnapshot.IsValid());
1509
1510
0
  this->PushLoopBlockBarrier();
1511
1512
0
#if !defined(CMAKE_BOOTSTRAP)
1513
0
  this->GetGlobalGenerator()->GetFileLockPool().PushFunctionScope();
1514
0
#endif
1515
1516
0
  this->PushFunctionBlockerBarrier();
1517
1518
0
  this->PushPolicy(true, pm);
1519
0
  this->PushDiagnostic(true, dm);
1520
0
}
1521
1522
void cmMakefile::PopFunctionScope(bool reportError)
1523
0
{
1524
0
  this->PopDiagnostic();
1525
0
  this->PopPolicy();
1526
1527
0
  this->PopSnapshot(reportError);
1528
1529
0
  this->PopFunctionBlockerBarrier(reportError);
1530
1531
0
#if !defined(CMAKE_BOOTSTRAP)
1532
0
  this->GetGlobalGenerator()->GetFileLockPool().PopFunctionScope();
1533
0
#endif
1534
1535
0
  this->PopLoopBlockBarrier();
1536
0
}
1537
1538
void cmMakefile::PushMacroScope(std::string const& fileName,
1539
                                cmPolicies::PolicyMap const& pm,
1540
                                cmDiagnostics::DiagnosticMap dm)
1541
0
{
1542
0
  this->StateSnapshot =
1543
0
    this->GetState()->CreateMacroCallSnapshot(this->StateSnapshot, fileName);
1544
0
  assert(this->StateSnapshot.IsValid());
1545
1546
0
  this->PushFunctionBlockerBarrier();
1547
1548
0
  this->PushPolicy(true, pm);
1549
0
  this->PushDiagnostic(true, dm);
1550
0
}
1551
1552
void cmMakefile::PopMacroScope(bool reportError)
1553
0
{
1554
0
  this->PopDiagnostic();
1555
0
  this->PopPolicy();
1556
0
  this->PopSnapshot(reportError);
1557
1558
0
  this->PopFunctionBlockerBarrier(reportError);
1559
0
}
1560
1561
bool cmMakefile::IsRootMakefile() const
1562
0
{
1563
0
  return !this->StateSnapshot.GetBuildsystemDirectoryParent().IsValid();
1564
0
}
1565
1566
class cmMakefile::BuildsystemFileScope : public FileScopeBase
1567
{
1568
public:
1569
  BuildsystemFileScope(cmMakefile* mf)
1570
0
    : FileScopeBase(mf)
1571
0
  {
1572
0
    std::string currentStart =
1573
0
      this->Makefile->GetCMakeInstance()->GetCMakeListFile(
1574
0
        this->Makefile->StateSnapshot.GetDirectory().GetCurrentSource());
1575
0
    this->Makefile->StateSnapshot.SetListFile(currentStart);
1576
0
    this->Makefile->StateSnapshot =
1577
0
      this->Makefile->StateSnapshot.GetState()->CreatePolicyScopeSnapshot(
1578
0
        this->Makefile->StateSnapshot);
1579
0
    this->Makefile->PushFunctionBlockerBarrier();
1580
0
    this->PushListFileVars(currentStart);
1581
1582
0
    this->GG = mf->GetGlobalGenerator();
1583
0
    this->CurrentMakefile = this->GG->GetCurrentMakefile();
1584
0
    this->Snapshot = this->GG->GetCMakeInstance()->GetCurrentSnapshot();
1585
0
    this->GG->GetCMakeInstance()->SetCurrentSnapshot(this->Snapshot);
1586
0
    this->GG->SetCurrentMakefile(mf);
1587
0
  }
1588
1589
  ~BuildsystemFileScope()
1590
0
  {
1591
0
    this->PopListFileVars();
1592
0
    this->Makefile->PopFunctionBlockerBarrier(this->ReportError);
1593
0
    this->Makefile->PopSnapshot(this->ReportError);
1594
0
    this->GG->SetCurrentMakefile(this->CurrentMakefile);
1595
0
    this->GG->GetCMakeInstance()->SetCurrentSnapshot(this->Snapshot);
1596
0
  }
1597
1598
0
  void Quiet() { this->ReportError = false; }
1599
1600
  BuildsystemFileScope(BuildsystemFileScope const&) = delete;
1601
  BuildsystemFileScope& operator=(BuildsystemFileScope const&) = delete;
1602
1603
private:
1604
  cmGlobalGenerator* GG;
1605
  cmMakefile* CurrentMakefile;
1606
  cmStateSnapshot Snapshot;
1607
  bool ReportError = true;
1608
};
1609
1610
void cmMakefile::Configure()
1611
0
{
1612
0
  std::string currentStart = this->GetCMakeInstance()->GetCMakeListFile(
1613
0
    this->StateSnapshot.GetDirectory().GetCurrentSource());
1614
1615
  // Add the bottom of all backtraces within this directory.
1616
  // We will never pop this scope because it should be available
1617
  // for messages during the generate step too.
1618
0
  this->Backtrace =
1619
0
    this->Backtrace.Push(cmListFileContext::FromListFilePath(currentStart));
1620
1621
0
  BuildsystemFileScope scope(this);
1622
1623
  // make sure the CMakeFiles dir is there
1624
0
  std::string filesDir = cmStrCat(
1625
0
    this->StateSnapshot.GetDirectory().GetCurrentBinary(), "/CMakeFiles");
1626
0
  cmSystemTools::MakeDirectory(filesDir);
1627
1628
0
  assert(cmSystemTools::FileExists(currentStart, true));
1629
1630
  // In the top-most directory, cmake_minimum_required() may not have been
1631
  // called yet, so ApplyPolicyVersion() may not have handled the default
1632
  // policy value.  Check them here.
1633
0
  if (this->GetPolicyStatus(cmPolicies::CMP0198) == cmPolicies::WARN) {
1634
0
    if (cmValue defaultValue =
1635
0
          this->GetDefinition("CMAKE_POLICY_DEFAULT_CMP0198")) {
1636
0
      if (*defaultValue == "NEW") {
1637
0
        this->SetPolicy(cmPolicies::CMP0198, cmPolicies::NEW);
1638
0
      } else if (*defaultValue == "OLD") {
1639
0
        this->SetPolicy(cmPolicies::CMP0198, cmPolicies::OLD);
1640
0
      }
1641
0
    }
1642
0
  }
1643
1644
  // Set CMAKE_PARENT_LIST_FILE for CMakeLists.txt based on CMP0198 policy
1645
0
  this->UpdateParentListFileVariable();
1646
1647
0
#ifdef CMake_ENABLE_DEBUGGER
1648
0
  if (this->GetCMakeInstance()->GetDebugAdapter()) {
1649
0
    this->GetCMakeInstance()->GetDebugAdapter()->OnBeginFileParse(
1650
0
      this, currentStart);
1651
0
  }
1652
0
#endif
1653
1654
0
  cmListFile listFile;
1655
0
  if (!listFile.ParseFile(currentStart, this, this->Backtrace)) {
1656
0
#ifdef CMake_ENABLE_DEBUGGER
1657
0
    if (this->GetCMakeInstance()->GetDebugAdapter()) {
1658
0
      this->GetCMakeInstance()->GetDebugAdapter()->OnEndFileParse();
1659
0
    }
1660
0
#endif
1661
1662
0
    return;
1663
0
  }
1664
1665
0
#ifdef CMake_ENABLE_DEBUGGER
1666
0
  if (this->GetCMakeInstance()->GetDebugAdapter()) {
1667
0
    this->GetCMakeInstance()->GetDebugAdapter()->OnEndFileParse();
1668
0
    this->GetCMakeInstance()->GetDebugAdapter()->OnFileParsedSuccessfully(
1669
0
      currentStart, listFile.Functions);
1670
0
  }
1671
0
#endif
1672
1673
0
  if (this->IsRootMakefile()) {
1674
0
    bool hasVersion = false;
1675
    // search for the right policy command
1676
0
    for (cmListFileFunction const& func : listFile.Functions) {
1677
0
      if (func.LowerCaseName() == "cmake_minimum_required"_s) {
1678
0
        hasVersion = true;
1679
0
        break;
1680
0
      }
1681
0
    }
1682
    // if no policy command is found this is an error if they use any
1683
    // non advanced functions or a lot of functions
1684
0
    if (!hasVersion) {
1685
0
      bool isProblem = true;
1686
0
      if (listFile.Functions.size() < 30) {
1687
        // the list of simple commands DO NOT ADD TO THIS LIST!!!!!
1688
        // these commands must have backwards compatibility forever and
1689
        // and that is a lot longer than your tiny mind can comprehend mortal
1690
0
        std::set<std::string> allowedCommands;
1691
0
        allowedCommands.insert("project");
1692
0
        allowedCommands.insert("set");
1693
0
        allowedCommands.insert("if");
1694
0
        allowedCommands.insert("endif");
1695
0
        allowedCommands.insert("else");
1696
0
        allowedCommands.insert("elseif");
1697
0
        allowedCommands.insert("add_executable");
1698
0
        allowedCommands.insert("add_library");
1699
0
        allowedCommands.insert("target_link_libraries");
1700
0
        allowedCommands.insert("option");
1701
0
        allowedCommands.insert("message");
1702
0
        isProblem = false;
1703
0
        for (cmListFileFunction const& func : listFile.Functions) {
1704
0
          if (!cm::contains(allowedCommands, func.LowerCaseName())) {
1705
0
            isProblem = true;
1706
0
            break;
1707
0
          }
1708
0
        }
1709
0
      }
1710
1711
0
      if (isProblem) {
1712
        // Tell the top level cmMakefile to diagnose
1713
        // this violation of CMP0000.
1714
0
        this->SetCheckCMP0000(true);
1715
1716
        // Implicitly set the version for the user.
1717
0
        cmPolicies::ApplyPolicyVersion(this, 3, 5, 0,
1718
0
                                       cmPolicies::WarnCompat::Off);
1719
0
      }
1720
0
    }
1721
0
    bool hasProject = false;
1722
    // search for a project command
1723
0
    for (cmListFileFunction const& func : listFile.Functions) {
1724
0
      if (func.LowerCaseName() == "project"_s) {
1725
0
        hasProject = true;
1726
0
        break;
1727
0
      }
1728
0
    }
1729
    // if no project command is found, add one
1730
0
    if (!hasProject) {
1731
0
      this->IssueDiagnostic(
1732
0
        cmDiagnostics::CMD_AUTHOR,
1733
0
        "No project() command is present.  The top-level CMakeLists.txt "
1734
0
        "file must contain a literal, direct call to the project() command.  "
1735
0
        "Add a line of code such as\n"
1736
0
        "  project(ProjectName)\n"
1737
0
        "near the top of the file, but after cmake_minimum_required().\n"
1738
0
        "CMake is pretending there is a \"project(Project)\" command on "
1739
0
        "the first line.");
1740
0
      cmListFileFunction project{
1741
0
        "project", 0, 0, { { "Project", cmListFileArgument::Unquoted, 0 } }
1742
0
      };
1743
0
      listFile.Functions.insert(listFile.Functions.begin(), project);
1744
0
    }
1745
0
  }
1746
1747
0
  this->Defer = cm::make_unique<DeferCommands>();
1748
0
  this->RunListFile(listFile, currentStart, this->Defer.get());
1749
0
  this->Defer.reset();
1750
0
  if (cmSystemTools::GetFatalErrorOccurred()) {
1751
0
    scope.Quiet();
1752
0
  }
1753
1754
  // at the end handle any old style subdirs
1755
0
  std::vector<cmMakefile*> subdirs = this->UnConfiguredDirectories;
1756
1757
  // for each subdir recurse
1758
0
  auto sdi = subdirs.begin();
1759
0
  for (; sdi != subdirs.end(); ++sdi) {
1760
0
    (*sdi)->StateSnapshot.InitializeFromParent_ForSubdirsCommand();
1761
0
    this->ConfigureSubDirectory(*sdi);
1762
0
  }
1763
1764
0
  this->AddCMakeDependFilesFromUser();
1765
0
}
1766
1767
void cmMakefile::ConfigureSubDirectory(cmMakefile* mf)
1768
0
{
1769
0
  mf->InitializeFromParent(this);
1770
0
  std::string currentStart = mf->GetCurrentSourceDirectory();
1771
0
  if (this->GetCMakeInstance()->GetDebugOutput()) {
1772
0
    std::string msg = cmStrCat("   Entering             ", currentStart);
1773
0
    cmSystemTools::Message(msg);
1774
0
  }
1775
1776
0
  std::string currentStartFile =
1777
0
    this->GetCMakeInstance()->GetCMakeListFile(currentStart);
1778
0
  if (!cmSystemTools::FileExists(currentStartFile, true)) {
1779
0
    this->IssueMessage(MessageType::FATAL_ERROR,
1780
0
                       cmStrCat("The source directory\n  ", currentStart,
1781
0
                                "\n"
1782
0
                                "does not contain a CMakeLists.txt file."));
1783
0
    return;
1784
0
  }
1785
  // finally configure the subdir
1786
0
  mf->Configure();
1787
1788
0
  if (this->GetCMakeInstance()->GetDebugOutput()) {
1789
0
    auto msg =
1790
0
      cmStrCat("   Returning to         ", this->GetCurrentSourceDirectory());
1791
0
    cmSystemTools::Message(msg);
1792
0
  }
1793
0
}
1794
1795
void cmMakefile::AddSubDirectory(std::string const& srcPath,
1796
                                 std::string const& binPath,
1797
                                 bool excludeFromAll, bool immediate,
1798
                                 bool system)
1799
0
{
1800
0
  if (this->DeferRunning) {
1801
0
    this->IssueMessage(
1802
0
      MessageType::FATAL_ERROR,
1803
0
      "Subdirectories may not be created during deferred execution.");
1804
0
    return;
1805
0
  }
1806
1807
  // Make sure the binary directory is unique.
1808
0
  if (!this->EnforceUniqueDir(srcPath, binPath)) {
1809
0
    return;
1810
0
  }
1811
1812
0
  cmStateSnapshot newSnapshot =
1813
0
    this->GetState()->CreateBuildsystemDirectorySnapshot(this->StateSnapshot);
1814
1815
0
  newSnapshot.GetDirectory().SetCurrentSource(srcPath);
1816
0
  newSnapshot.GetDirectory().SetCurrentBinary(binPath);
1817
1818
0
  cmSystemTools::MakeDirectory(binPath);
1819
1820
0
  auto subMfu =
1821
0
    cm::make_unique<cmMakefile>(this->GlobalGenerator, newSnapshot);
1822
0
  auto* subMf = subMfu.get();
1823
0
  this->GetGlobalGenerator()->AddMakefile(std::move(subMfu));
1824
1825
0
  if (excludeFromAll) {
1826
0
    subMf->SetProperty("EXCLUDE_FROM_ALL", "TRUE");
1827
0
  }
1828
0
  if (system) {
1829
0
    subMf->SetProperty("SYSTEM", "TRUE");
1830
0
  }
1831
1832
0
  if (immediate) {
1833
0
    this->ConfigureSubDirectory(subMf);
1834
0
  } else {
1835
0
    this->UnConfiguredDirectories.push_back(subMf);
1836
0
  }
1837
1838
0
  this->AddInstallGenerator(cm::make_unique<cmInstallSubdirectoryGenerator>(
1839
0
    subMf, binPath, this->GetBacktrace()));
1840
0
}
1841
1842
std::string const& cmMakefile::GetCurrentSourceDirectory() const
1843
1
{
1844
1
  return this->StateSnapshot.GetDirectory().GetCurrentSource();
1845
1
}
1846
1847
std::string const& cmMakefile::GetCurrentBinaryDirectory() const
1848
0
{
1849
0
  return this->StateSnapshot.GetDirectory().GetCurrentBinary();
1850
0
}
1851
1852
cmTarget* cmMakefile::FindImportedTarget(std::string const& name) const
1853
0
{
1854
0
  auto const i = this->ImportedTargets.find(name);
1855
0
  if (i != this->ImportedTargets.end()) {
1856
0
    return i->second;
1857
0
  }
1858
0
  return nullptr;
1859
0
}
1860
1861
std::vector<cmTarget*> cmMakefile::GetImportedTargets() const
1862
0
{
1863
0
  std::vector<cmTarget*> tgts;
1864
0
  tgts.reserve(this->ImportedTargets.size());
1865
0
  for (auto const& impTarget : this->ImportedTargets) {
1866
0
    tgts.push_back(impTarget.second);
1867
0
  }
1868
0
  return tgts;
1869
0
}
1870
1871
void cmMakefile::AddIncludeDirectories(std::vector<std::string> const& incs,
1872
                                       bool before)
1873
0
{
1874
0
  if (incs.empty()) {
1875
0
    return;
1876
0
  }
1877
1878
0
  std::string entryString = cmList::to_string(incs);
1879
0
  if (before) {
1880
0
    this->StateSnapshot.GetDirectory().PrependIncludeDirectoriesEntry(
1881
0
      BT<std::string>(entryString, this->Backtrace));
1882
0
  } else {
1883
0
    this->StateSnapshot.GetDirectory().AppendIncludeDirectoriesEntry(
1884
0
      BT<std::string>(entryString, this->Backtrace));
1885
0
  }
1886
1887
  // Property on each target:
1888
0
  for (auto& target : this->Targets) {
1889
0
    cmTarget& t = target.second;
1890
0
    t.InsertInclude(BT<std::string>(entryString, this->Backtrace), before);
1891
0
  }
1892
0
}
1893
1894
void cmMakefile::AddSystemIncludeDirectories(std::set<std::string> const& incs)
1895
0
{
1896
0
  if (incs.empty()) {
1897
0
    return;
1898
0
  }
1899
1900
0
  this->SystemIncludeDirectories.insert(incs.begin(), incs.end());
1901
1902
0
  for (auto& target : this->Targets) {
1903
0
    cmTarget& t = target.second;
1904
0
    t.AddSystemIncludeDirectories(incs);
1905
0
  }
1906
0
}
1907
1908
void cmMakefile::AddDefinition(std::string const& name, cm::string_view value)
1909
9
{
1910
9
  this->StateSnapshot.SetDefinition(name, value);
1911
1912
9
#ifndef CMAKE_BOOTSTRAP
1913
9
  cmVariableWatch* vv = this->GetVariableWatch();
1914
9
  if (vv) {
1915
9
    vv->VariableAccessed(name, cmVariableWatch::VARIABLE_MODIFIED_ACCESS,
1916
9
                         value.data(), this);
1917
9
  }
1918
9
#endif
1919
9
}
1920
1921
void cmMakefile::AddDefinitionBool(std::string const& name, bool value)
1922
0
{
1923
0
  this->AddDefinition(name, value ? "ON" : "OFF");
1924
0
}
1925
1926
void cmMakefile::AddCacheDefinition(std::string const& name, cmValue value,
1927
                                    cmValue doc,
1928
                                    cmStateEnums::CacheEntryType type,
1929
                                    bool force)
1930
0
{
1931
0
  cmValue existingValue = this->GetState()->GetInitializedCacheValue(name);
1932
  // must be outside the following if() to keep it alive long enough
1933
0
  std::string nvalue;
1934
1935
0
  if (existingValue &&
1936
0
      (this->GetState()->GetCacheEntryType(name) ==
1937
0
       cmStateEnums::UNINITIALIZED)) {
1938
    // if this is not a force, then use the value from the cache
1939
    // if it is a force, then use the value being passed in
1940
0
    if (!force) {
1941
0
      value = existingValue;
1942
0
    }
1943
0
    if (type == cmStateEnums::PATH || type == cmStateEnums::FILEPATH) {
1944
0
      cmList files(value);
1945
0
      for (auto& file : files) {
1946
0
        if (!cmIsOff(file)) {
1947
0
          file = cmSystemTools::ToNormalizedPathOnDisk(file);
1948
0
        }
1949
0
      }
1950
0
      nvalue = files.to_string();
1951
0
      value = cmValue{ nvalue };
1952
1953
0
      this->GetCMakeInstance()->AddCacheEntry(name, value, doc, type);
1954
0
      value = this->GetState()->GetInitializedCacheValue(name);
1955
0
    }
1956
0
  }
1957
0
  this->GetCMakeInstance()->AddCacheEntry(name, value, doc, type);
1958
0
  switch (this->GetPolicyStatus(cmPolicies::CMP0126)) {
1959
0
    case cmPolicies::WARN:
1960
0
      if (this->PolicyOptionalWarningEnabled("CMAKE_POLICY_WARNING_CMP0126") &&
1961
0
          this->IsNormalDefinitionSet(name)) {
1962
0
        this->IssuePolicyWarning(
1963
0
          cmPolicies::CMP0126, {},
1964
0
          cmStrCat("For compatibility with older versions of CMake, "
1965
0
                   "normal variable \""_s,
1966
0
                   name, "\" will be removed from the current scope."_s));
1967
0
      }
1968
0
      CM_FALLTHROUGH;
1969
0
    case cmPolicies::OLD:
1970
      // if there was a definition then remove it
1971
0
      this->StateSnapshot.RemoveDefinition(name);
1972
0
      break;
1973
0
    case cmPolicies::NEW:
1974
0
      break;
1975
0
  }
1976
0
}
1977
1978
void cmMakefile::MarkVariableAsUsed(std::string const& var)
1979
4
{
1980
4
  this->StateSnapshot.GetDefinition(var);
1981
4
}
1982
1983
bool cmMakefile::VariableInitialized(std::string const& var) const
1984
0
{
1985
0
  return this->StateSnapshot.IsInitialized(var);
1986
0
}
1987
1988
void cmMakefile::MaybeWarnUninitialized(std::string const& variable,
1989
                                        char const* sourceFilename) const
1990
0
{
1991
  // check to see if we need to print a warning
1992
  // if strict mode is on and the variable has
1993
  // not been "cleared"/initialized with a set(foo ) call
1994
0
  cmDiagnosticAction const action =
1995
0
    this->GetDiagnosticAction(cmDiagnostics::CMD_UNINITIALIZED);
1996
0
  if (action != cmDiagnostics::Ignore &&
1997
0
      !this->VariableInitialized(variable)) {
1998
0
    if (this->CheckSystemVars ||
1999
0
        (sourceFilename && this->IsProjectFile(sourceFilename))) {
2000
0
      this->IssueDiagnostic(
2001
0
        cmDiagnostics::CMD_UNINITIALIZED,
2002
0
        cmStrCat("uninitialized variable '", variable, '\''));
2003
0
    }
2004
0
  }
2005
0
}
2006
2007
void cmMakefile::RemoveDefinition(std::string const& name)
2008
1
{
2009
1
  this->StateSnapshot.RemoveDefinition(name);
2010
1
#ifndef CMAKE_BOOTSTRAP
2011
1
  cmVariableWatch* vv = this->GetVariableWatch();
2012
1
  if (vv) {
2013
1
    vv->VariableAccessed(name, cmVariableWatch::VARIABLE_REMOVED_ACCESS,
2014
1
                         nullptr, this);
2015
1
  }
2016
1
#endif
2017
1
}
2018
2019
void cmMakefile::RemoveCacheDefinition(std::string const& name) const
2020
0
{
2021
0
  this->GetState()->RemoveCacheEntry(name);
2022
0
}
2023
2024
void cmMakefile::SetProjectName(std::string const& p)
2025
0
{
2026
0
  this->StateSnapshot.SetProjectName(p);
2027
0
}
2028
2029
void cmMakefile::AddGlobalLinkInformation(cmTarget& target)
2030
0
{
2031
  // for these targets do not add anything
2032
0
  switch (target.GetType()) {
2033
0
    case cmStateEnums::UTILITY:
2034
0
    case cmStateEnums::GLOBAL_TARGET:
2035
0
    case cmStateEnums::INTERFACE_LIBRARY:
2036
0
      return;
2037
0
    default:;
2038
0
  }
2039
2040
0
  if (cmValue linkLibsProp = this->GetProperty("LINK_LIBRARIES")) {
2041
0
    cmList linkLibs{ *linkLibsProp };
2042
2043
0
    for (auto j = linkLibs.begin(); j != linkLibs.end(); ++j) {
2044
0
      std::string libraryName = *j;
2045
0
      cmTargetLinkLibraryType libType = GENERAL_LibraryType;
2046
0
      if (libraryName == "optimized"_s) {
2047
0
        libType = OPTIMIZED_LibraryType;
2048
0
        ++j;
2049
0
        libraryName = *j;
2050
0
      } else if (libraryName == "debug"_s) {
2051
0
        libType = DEBUG_LibraryType;
2052
0
        ++j;
2053
0
        libraryName = *j;
2054
0
      }
2055
      // This is equivalent to the target_link_libraries plain signature.
2056
0
      target.AddLinkLibrary(*this, libraryName, libType);
2057
0
      target.AppendProperty(
2058
0
        "INTERFACE_LINK_LIBRARIES",
2059
0
        target.GetDebugGeneratorExpressions(libraryName, libType));
2060
0
    }
2061
0
  }
2062
0
}
2063
2064
void cmMakefile::AddAlias(std::string const& lname, std::string const& tgtName,
2065
                          bool globallyVisible)
2066
0
{
2067
0
  this->AliasTargets[lname] = tgtName;
2068
0
  if (globallyVisible) {
2069
0
    this->GetGlobalGenerator()->AddAlias(lname, tgtName);
2070
0
  }
2071
0
}
2072
2073
cmTarget* cmMakefile::AddLibrary(std::string const& lname,
2074
                                 cmStateEnums::TargetType type,
2075
                                 std::vector<std::string> const& srcs,
2076
                                 bool excludeFromAll)
2077
0
{
2078
0
  assert(type == cmStateEnums::STATIC_LIBRARY ||
2079
0
         type == cmStateEnums::SHARED_LIBRARY ||
2080
0
         type == cmStateEnums::MODULE_LIBRARY ||
2081
0
         type == cmStateEnums::OBJECT_LIBRARY ||
2082
0
         type == cmStateEnums::INTERFACE_LIBRARY);
2083
2084
0
  cmTarget* target = this->AddNewTarget(type, lname);
2085
  // Clear its dependencies. Otherwise, dependencies might persist
2086
  // over changes in CMakeLists.txt, making the information stale and
2087
  // hence useless.
2088
0
  target->ClearDependencyInformation(*this);
2089
0
  if (excludeFromAll) {
2090
0
    target->SetProperty("EXCLUDE_FROM_ALL", "TRUE");
2091
0
  }
2092
0
  target->AddSources(srcs);
2093
0
  this->AddGlobalLinkInformation(*target);
2094
0
  return target;
2095
0
}
2096
2097
cmTarget* cmMakefile::AddExecutable(std::string const& exeName,
2098
                                    std::vector<std::string> const& srcs,
2099
                                    bool excludeFromAll)
2100
0
{
2101
0
  cmTarget* target = this->AddNewTarget(cmStateEnums::EXECUTABLE, exeName);
2102
0
  if (excludeFromAll) {
2103
0
    target->SetProperty("EXCLUDE_FROM_ALL", "TRUE");
2104
0
  }
2105
0
  target->AddSources(srcs);
2106
0
  this->AddGlobalLinkInformation(*target);
2107
0
  return target;
2108
0
}
2109
2110
cmTarget* cmMakefile::AddNewTarget(cmStateEnums::TargetType type,
2111
                                   std::string const& name)
2112
0
{
2113
0
  return &this->CreateNewTarget(name, type).first;
2114
0
}
2115
2116
cmTarget* cmMakefile::AddSynthesizedTarget(cmStateEnums::TargetType type,
2117
                                           std::string const& name)
2118
0
{
2119
0
  return &this
2120
0
            ->CreateNewTarget(name, type, cmTarget::PerConfig::Yes,
2121
0
                              cmTarget::Visibility::Generated)
2122
0
            .first;
2123
0
}
2124
2125
std::pair<cmTarget&, bool> cmMakefile::CreateNewTarget(
2126
  std::string const& name, cmStateEnums::TargetType type,
2127
  cmTarget::PerConfig perConfig, cmTarget::Visibility vis)
2128
0
{
2129
0
  auto ib =
2130
0
    this->Targets.emplace(name, cmTarget(name, type, vis, this, perConfig));
2131
0
  auto it = ib.first;
2132
0
  if (!ib.second) {
2133
0
    return std::make_pair(std::ref(it->second), false);
2134
0
  }
2135
0
  this->OrderedTargets.push_back(&it->second);
2136
0
  this->GetGlobalGenerator()->IndexTarget(&it->second);
2137
0
  this->GetStateSnapshot().GetDirectory().AddNormalTargetName(name);
2138
0
  return std::make_pair(std::ref(it->second), true);
2139
0
}
2140
2141
cmTarget* cmMakefile::AddNewUtilityTarget(std::string const& utilityName,
2142
                                          bool excludeFromAll)
2143
0
{
2144
0
  cmTarget* target = this->AddNewTarget(cmStateEnums::UTILITY, utilityName);
2145
0
  if (excludeFromAll) {
2146
0
    target->SetProperty("EXCLUDE_FROM_ALL", "TRUE");
2147
0
  }
2148
0
  return target;
2149
0
}
2150
2151
namespace {
2152
}
2153
2154
#if !defined(CMAKE_BOOTSTRAP)
2155
2156
void cmMakefile::ResolveSourceGroupGenex(cmLocalGenerator* lg)
2157
0
{
2158
0
  for (auto const& sourceGroup : this->SourceGroups) {
2159
0
    sourceGroup->ResolveGenex(lg, {});
2160
0
  }
2161
0
}
2162
2163
cmSourceGroup* cmMakefile::GetSourceGroup(
2164
  std::vector<std::string> const& name) const
2165
14
{
2166
14
  cmSourceGroup* sg = nullptr;
2167
2168
  // first look for source group starting with the same as the one we want
2169
49
  for (auto const& srcGroup : this->SourceGroups) {
2170
49
    std::string const& sgName = srcGroup->GetName();
2171
49
    if (sgName == name[0]) {
2172
7
      sg = srcGroup.get();
2173
7
      break;
2174
7
    }
2175
49
  }
2176
2177
14
  if (sg) {
2178
    // iterate through its children to find match source group
2179
7
    for (unsigned int i = 1; i < name.size(); ++i) {
2180
0
      sg = sg->LookupChild(name[i]);
2181
0
      if (!sg) {
2182
0
        break;
2183
0
      }
2184
0
    }
2185
7
  }
2186
14
  return sg;
2187
14
}
2188
2189
void cmMakefile::AddSourceGroup(std::string const& name, char const* regex)
2190
7
{
2191
7
  std::vector<std::string> nameVector;
2192
7
  nameVector.push_back(name);
2193
7
  this->AddSourceGroup(nameVector, regex);
2194
7
}
2195
2196
void cmMakefile::AddSourceGroup(std::vector<std::string> const& name,
2197
                                char const* regex)
2198
7
{
2199
7
  cmSourceGroup* sg = nullptr;
2200
7
  std::vector<std::string> currentName;
2201
7
  int i = 0;
2202
7
  int const lastElement = static_cast<int>(name.size() - 1);
2203
14
  for (i = lastElement; i >= 0; --i) {
2204
7
    currentName.assign(name.begin(), name.begin() + i + 1);
2205
7
    sg = this->GetSourceGroup(currentName);
2206
7
    if (sg) {
2207
0
      break;
2208
0
    }
2209
7
  }
2210
2211
  // i now contains the index of the last found component
2212
7
  if (i == lastElement) {
2213
    // group already exists, replace its regular expression
2214
0
    if (regex && sg) {
2215
      // We only want to set the regular expression.  If there are already
2216
      // source files in the group, we don't want to remove them.
2217
0
      sg->SetGroupRegex(regex);
2218
0
    }
2219
0
    return;
2220
0
  }
2221
7
  if (i == -1) {
2222
    // group does not exist nor belong to any existing group
2223
    // add its first component
2224
7
    this->SourceGroups.emplace_back(
2225
7
      cm::make_unique<cmSourceGroup>(name[0], regex));
2226
7
    sg = this->GetSourceGroup(currentName);
2227
7
    i = 0; // last component found
2228
7
  }
2229
7
  if (!sg) {
2230
0
    cmSystemTools::Error("Could not create source group ");
2231
0
    return;
2232
0
  }
2233
  // build the whole source group path
2234
7
  for (++i; i <= lastElement; ++i) {
2235
0
    sg->AddChild(cm::make_unique<cmSourceGroup>(name[i], nullptr,
2236
0
                                                sg->GetFullName().c_str()));
2237
0
    sg = sg->LookupChild(name[i]);
2238
0
  }
2239
2240
7
  sg->SetGroupRegex(regex);
2241
7
}
2242
2243
cmSourceGroup* cmMakefile::GetOrCreateSourceGroup(
2244
  std::vector<std::string> const& folders)
2245
0
{
2246
0
  cmSourceGroup* sg = this->GetSourceGroup(folders);
2247
0
  if (!sg) {
2248
0
    this->AddSourceGroup(folders);
2249
0
    sg = this->GetSourceGroup(folders);
2250
0
  }
2251
0
  return sg;
2252
0
}
2253
2254
cmSourceGroup* cmMakefile::GetOrCreateSourceGroup(std::string const& name)
2255
0
{
2256
0
  auto p = this->GetDefinition("SOURCE_GROUP_DELIMITER");
2257
0
  return this->GetOrCreateSourceGroup(
2258
0
    cmTokenize(name, p ? cm::string_view(*p) : R"(\/)"_s));
2259
0
}
2260
#endif
2261
2262
bool cmMakefile::IsOn(std::string const& name) const
2263
0
{
2264
0
  return this->GetDefinition(name).IsOn();
2265
0
}
2266
2267
bool cmMakefile::IsSet(std::string const& name) const
2268
0
{
2269
0
  cmValue value = this->GetDefinition(name);
2270
0
  if (!value) {
2271
0
    return false;
2272
0
  }
2273
2274
0
  if (value->empty()) {
2275
0
    return false;
2276
0
  }
2277
2278
0
  if (cmIsNOTFOUND(*value)) {
2279
0
    return false;
2280
0
  }
2281
2282
0
  return true;
2283
0
}
2284
2285
bool cmMakefile::PlatformIs32Bit() const
2286
0
{
2287
0
  if (cmValue plat_abi = this->GetDefinition("CMAKE_INTERNAL_PLATFORM_ABI")) {
2288
0
    if (*plat_abi == "ELF X32"_s) {
2289
0
      return false;
2290
0
    }
2291
0
  }
2292
0
  if (cmValue sizeof_dptr = this->GetDefinition("CMAKE_SIZEOF_VOID_P")) {
2293
0
    return atoi(sizeof_dptr->c_str()) == 4;
2294
0
  }
2295
0
  return false;
2296
0
}
2297
2298
bool cmMakefile::PlatformIs64Bit() const
2299
0
{
2300
0
  if (cmValue sizeof_dptr = this->GetDefinition("CMAKE_SIZEOF_VOID_P")) {
2301
0
    return atoi(sizeof_dptr->c_str()) == 8;
2302
0
  }
2303
0
  return false;
2304
0
}
2305
2306
bool cmMakefile::PlatformIsx32() const
2307
0
{
2308
0
  if (cmValue plat_abi = this->GetDefinition("CMAKE_INTERNAL_PLATFORM_ABI")) {
2309
0
    if (*plat_abi == "ELF X32"_s) {
2310
0
      return true;
2311
0
    }
2312
0
  }
2313
0
  return false;
2314
0
}
2315
2316
cmMakefile::AppleSDK cmMakefile::GetAppleSDKType() const
2317
0
{
2318
0
  std::string sdkRoot;
2319
0
  sdkRoot = this->GetSafeDefinition("CMAKE_OSX_SYSROOT");
2320
0
  sdkRoot = cmSystemTools::LowerCase(sdkRoot);
2321
2322
0
  struct
2323
0
  {
2324
0
    std::string name;
2325
0
    AppleSDK sdk;
2326
0
  } const sdkDatabase[]{
2327
0
    { "appletvos", AppleSDK::AppleTVOS },
2328
0
    { "appletvsimulator", AppleSDK::AppleTVSimulator },
2329
0
    { "iphoneos", AppleSDK::IPhoneOS },
2330
0
    { "iphonesimulator", AppleSDK::IPhoneSimulator },
2331
0
    { "watchos", AppleSDK::WatchOS },
2332
0
    { "watchsimulator", AppleSDK::WatchSimulator },
2333
0
    { "xros", AppleSDK::XROS },
2334
0
    { "xrsimulator", AppleSDK::XRSimulator },
2335
0
  };
2336
2337
0
  for (auto const& entry : sdkDatabase) {
2338
0
    if (cmHasPrefix(sdkRoot, entry.name) ||
2339
0
        sdkRoot.find(cmStrCat('/', entry.name)) != std::string::npos) {
2340
0
      return entry.sdk;
2341
0
    }
2342
0
  }
2343
2344
0
  return AppleSDK::MacOS;
2345
0
}
2346
2347
bool cmMakefile::PlatformIsAppleEmbedded() const
2348
0
{
2349
0
  return this->GetAppleSDKType() != AppleSDK::MacOS;
2350
0
}
2351
2352
bool cmMakefile::PlatformIsAppleSimulator() const
2353
0
{
2354
0
  return std::set<AppleSDK>{
2355
0
    AppleSDK::AppleTVSimulator,
2356
0
    AppleSDK::IPhoneSimulator,
2357
0
    AppleSDK::WatchSimulator,
2358
0
    AppleSDK::XRSimulator,
2359
0
  }
2360
0
    .count(this->GetAppleSDKType());
2361
0
}
2362
2363
bool cmMakefile::PlatformIsAppleCatalyst() const
2364
0
{
2365
0
  std::string systemName;
2366
0
  systemName = this->GetSafeDefinition("CMAKE_SYSTEM_NAME");
2367
0
  systemName = cmSystemTools::LowerCase(systemName);
2368
0
  return systemName == "ios" && this->GetAppleSDKType() == AppleSDK::MacOS;
2369
0
}
2370
2371
bool cmMakefile::PlatformSupportsAppleTextStubs() const
2372
0
{
2373
0
  return this->IsOn("APPLE") && this->IsSet("CMAKE_TAPI");
2374
0
}
2375
2376
char const* cmMakefile::GetSONameFlag(std::string const& language) const
2377
0
{
2378
0
  std::string name = "CMAKE_SHARED_LIBRARY_SONAME";
2379
0
  if (!language.empty()) {
2380
0
    name += "_";
2381
0
    name += language;
2382
0
  }
2383
0
  name += "_FLAG";
2384
0
  return this->GetDefinition(name).GetCStr();
2385
0
}
2386
2387
bool cmMakefile::CanIWriteThisFile(std::string const& fileName) const
2388
0
{
2389
0
  if (!this->IsOn("CMAKE_DISABLE_SOURCE_CHANGES")) {
2390
0
    return true;
2391
0
  }
2392
  // If we are doing an in-source build, then the test will always fail
2393
0
  if (cmSystemTools::SameFile(this->GetHomeDirectory(),
2394
0
                              this->GetHomeOutputDirectory())) {
2395
0
    return !this->IsOn("CMAKE_DISABLE_IN_SOURCE_BUILD");
2396
0
  }
2397
2398
0
  return !cmSystemTools::IsSubDirectory(fileName, this->GetHomeDirectory()) ||
2399
0
    cmSystemTools::IsSubDirectory(fileName, this->GetHomeOutputDirectory()) ||
2400
0
    cmSystemTools::SameFile(fileName, this->GetHomeOutputDirectory());
2401
0
}
2402
2403
std::string const& cmMakefile::GetRequiredDefinition(
2404
  std::string const& name) const
2405
0
{
2406
0
  static std::string const empty;
2407
0
  cmValue def = this->GetDefinition(name);
2408
0
  if (!def) {
2409
0
    cmSystemTools::Error("Error required internal CMake variable not "
2410
0
                         "set, cmake may not be built correctly.\n"
2411
0
                         "Missing variable is:\n" +
2412
0
                         name);
2413
0
    return empty;
2414
0
  }
2415
0
  return *def;
2416
0
}
2417
2418
bool cmMakefile::IsDefinitionSet(std::string const& name) const
2419
0
{
2420
0
  cmValue def = this->StateSnapshot.GetDefinition(name);
2421
0
  if (!def) {
2422
0
    def = this->GetState()->GetInitializedCacheValue(name);
2423
0
  }
2424
0
#ifndef CMAKE_BOOTSTRAP
2425
0
  if (cmVariableWatch* vv = this->GetVariableWatch()) {
2426
0
    if (!def) {
2427
0
      vv->VariableAccessed(
2428
0
        name, cmVariableWatch::UNKNOWN_VARIABLE_DEFINED_ACCESS, nullptr, this);
2429
0
    }
2430
0
  }
2431
0
#endif
2432
0
  return def != nullptr;
2433
0
}
2434
2435
bool cmMakefile::IsNormalDefinitionSet(std::string const& name) const
2436
0
{
2437
0
  cmValue def = this->StateSnapshot.GetDefinition(name);
2438
0
#ifndef CMAKE_BOOTSTRAP
2439
0
  if (cmVariableWatch* vv = this->GetVariableWatch()) {
2440
0
    if (!def) {
2441
0
      vv->VariableAccessed(
2442
0
        name, cmVariableWatch::UNKNOWN_VARIABLE_DEFINED_ACCESS, nullptr, this);
2443
0
    }
2444
0
  }
2445
0
#endif
2446
0
  return def != nullptr;
2447
0
}
2448
2449
cmValue cmMakefile::GetDefinition(std::string const& name) const
2450
2
{
2451
2
  cmValue def = this->StateSnapshot.GetDefinition(name);
2452
2
  if (!def) {
2453
2
    def = this->GetState()->GetInitializedCacheValue(name);
2454
2
  }
2455
2
#ifndef CMAKE_BOOTSTRAP
2456
2
  cmVariableWatch* vv = this->GetVariableWatch();
2457
2
  if (vv) {
2458
2
    bool const watch_function_executed =
2459
2
      vv->VariableAccessed(name,
2460
2
                           def ? cmVariableWatch::VARIABLE_READ_ACCESS
2461
2
                               : cmVariableWatch::UNKNOWN_VARIABLE_READ_ACCESS,
2462
2
                           def.GetCStr(), this);
2463
2464
2
    if (watch_function_executed) {
2465
      // A callback was executed and may have caused re-allocation of the
2466
      // variable storage.  Look it up again for now.
2467
      // FIXME: Refactor variable storage to avoid this problem.
2468
0
      def = this->StateSnapshot.GetDefinition(name);
2469
0
      if (!def) {
2470
0
        def = this->GetState()->GetInitializedCacheValue(name);
2471
0
      }
2472
0
    }
2473
2
  }
2474
2
#endif
2475
2
  return def;
2476
2
}
2477
2478
std::string const& cmMakefile::GetSafeDefinition(std::string const& name) const
2479
0
{
2480
0
  return this->GetDefinition(name);
2481
0
}
2482
2483
std::vector<std::string> cmMakefile::GetDefinitions() const
2484
0
{
2485
0
  std::vector<std::string> res = this->StateSnapshot.ClosureKeys();
2486
0
  cm::append(res, this->GetState()->GetCacheEntryKeys());
2487
0
  std::sort(res.begin(), res.end());
2488
0
  return res;
2489
0
}
2490
2491
std::string const& cmMakefile::ExpandVariablesInString(
2492
  std::string& source) const
2493
0
{
2494
0
  return this->ExpandVariablesInString(source, false, false);
2495
0
}
2496
2497
std::string const& cmMakefile::ExpandVariablesInString(
2498
  std::string& source, bool escapeQuotes, bool noEscapes, bool atOnly,
2499
  char const* filename, long line, bool removeEmpty, bool replaceAt) const
2500
0
{
2501
  // Sanity check the @ONLY mode.
2502
0
  if (atOnly && (!noEscapes || !removeEmpty)) {
2503
    // This case should never be called.  At-only is for
2504
    // configure-file/string which always does no escapes.
2505
0
    this->IssueMessage(MessageType::INTERNAL_ERROR,
2506
0
                       "ExpandVariablesInString @ONLY called "
2507
0
                       "on something with escapes.");
2508
0
    return source;
2509
0
  }
2510
2511
0
  std::string errorstr;
2512
0
  MessageType mtype = this->ExpandVariablesInStringImpl(
2513
0
    errorstr, source, escapeQuotes, noEscapes, atOnly, filename, line,
2514
0
    replaceAt);
2515
0
  if (mtype != MessageType::LOG) {
2516
0
    if (mtype == MessageType::FATAL_ERROR) {
2517
0
      cmSystemTools::SetFatalErrorOccurred();
2518
0
    }
2519
0
    this->IssueMessage(mtype, errorstr);
2520
0
  }
2521
2522
0
  return source;
2523
0
}
2524
2525
enum t_domain
2526
{
2527
  NORMAL,
2528
  ENVIRONMENT,
2529
  CACHE
2530
};
2531
2532
struct t_lookup
2533
{
2534
  t_domain domain = NORMAL;
2535
  size_t loc = 0;
2536
};
2537
2538
bool cmMakefile::IsProjectFile(char const* filename) const
2539
0
{
2540
0
  return cmSystemTools::IsSubDirectory(filename, this->GetHomeDirectory()) ||
2541
0
    (cmSystemTools::IsSubDirectory(filename, this->GetHomeOutputDirectory()) &&
2542
0
     !cmSystemTools::IsSubDirectory(filename, "/CMakeFiles"));
2543
0
}
2544
2545
size_t cmMakefile::GetRecursionDepthLimit() const
2546
0
{
2547
0
  size_t depth = CMake_DEFAULT_RECURSION_LIMIT;
2548
0
  if (cmValue depthStr =
2549
0
        this->GetDefinition("CMAKE_MAXIMUM_RECURSION_DEPTH")) {
2550
0
    unsigned long depthUL;
2551
0
    if (cmStrToULong(depthStr.GetCStr(), &depthUL)) {
2552
0
      depth = depthUL;
2553
0
    }
2554
0
  } else if (cm::optional<std::string> depthEnv =
2555
0
               cmSystemTools::GetEnvVar("CMAKE_MAXIMUM_RECURSION_DEPTH")) {
2556
0
    unsigned long depthUL;
2557
0
    if (cmStrToULong(*depthEnv, &depthUL)) {
2558
0
      depth = depthUL;
2559
0
    }
2560
0
  }
2561
0
  return depth;
2562
0
}
2563
2564
size_t cmMakefile::GetRecursionDepth() const
2565
0
{
2566
0
  return this->RecursionDepth;
2567
0
}
2568
2569
void cmMakefile::SetRecursionDepth(size_t recursionDepth)
2570
0
{
2571
0
  this->RecursionDepth = recursionDepth;
2572
0
}
2573
2574
std::string cmMakefile::NewDeferId() const
2575
0
{
2576
0
  return this->GetGlobalGenerator()->NewDeferId();
2577
0
}
2578
2579
bool cmMakefile::DeferCall(std::string id, std::string file,
2580
                           cmListFileFunction lff)
2581
0
{
2582
0
  if (!this->Defer) {
2583
0
    return false;
2584
0
  }
2585
0
  this->Defer->Commands.emplace_back(
2586
0
    DeferCommand{ std::move(id), std::move(file), std::move(lff) });
2587
0
  return true;
2588
0
}
2589
2590
bool cmMakefile::DeferCancelCall(std::string const& id)
2591
0
{
2592
0
  if (!this->Defer) {
2593
0
    return false;
2594
0
  }
2595
0
  for (DeferCommand& dc : this->Defer->Commands) {
2596
0
    if (dc.Id == id) {
2597
0
      dc.Id.clear();
2598
0
    }
2599
0
  }
2600
0
  return true;
2601
0
}
2602
2603
cm::optional<std::string> cmMakefile::DeferGetCallIds() const
2604
0
{
2605
0
  cm::optional<std::string> ids;
2606
0
  if (this->Defer) {
2607
0
    ids = cmList::to_string(
2608
0
      cmMakeRange(this->Defer->Commands)
2609
0
        .filter([](DeferCommand const& dc) -> bool { return !dc.Id.empty(); })
2610
0
        .transform(
2611
0
          [](DeferCommand const& dc) -> std::string const& { return dc.Id; }));
2612
0
  }
2613
0
  return ids;
2614
0
}
2615
2616
cm::optional<std::string> cmMakefile::DeferGetCall(std::string const& id) const
2617
0
{
2618
0
  cm::optional<std::string> call;
2619
0
  if (this->Defer) {
2620
0
    std::string tmp;
2621
0
    for (DeferCommand const& dc : this->Defer->Commands) {
2622
0
      if (dc.Id == id) {
2623
0
        tmp = dc.Command.OriginalName();
2624
0
        for (cmListFileArgument const& arg : dc.Command.Arguments()) {
2625
0
          tmp = cmStrCat(tmp, ';', arg.Value);
2626
0
        }
2627
0
        break;
2628
0
      }
2629
0
    }
2630
0
    call = std::move(tmp);
2631
0
  }
2632
0
  return call;
2633
0
}
2634
2635
namespace {
2636
cmPolicies::PolicyStatus CheckCMP0219Impl(cmPolicies::PolicyStatus status,
2637
                                          std::string const& calleeName,
2638
                                          bool hasBackslashes,
2639
                                          std::set<std::string>& warned)
2640
0
{
2641
0
  if (status == cmPolicies::WARN && hasBackslashes &&
2642
0
      warned.insert(calleeName).second) {
2643
0
    return cmPolicies::WARN;
2644
0
  }
2645
  // Suppress WARN when there are no backslashes or already warned.
2646
0
  return status == cmPolicies::NEW ? cmPolicies::NEW : cmPolicies::OLD;
2647
0
}
2648
}
2649
2650
cmPolicies::PolicyStatus cmMakefile::CheckCMP0219(
2651
  std::string const& calleeName, std::vector<std::string> const& args)
2652
0
{
2653
0
  bool const hasBackslashes =
2654
0
    std::any_of(args.begin(), args.end(), [](std::string const& s) {
2655
0
      return s.find('\\') != std::string::npos;
2656
0
    });
2657
0
  return CheckCMP0219Impl(GetPolicyStatus(cmPolicies::CMP0219), calleeName,
2658
0
                          hasBackslashes, WarnedCMP0219);
2659
0
}
2660
2661
cmPolicies::PolicyStatus cmMakefile::CheckCMP0219(
2662
  std::string const& calleeName, std::vector<cmListFileArgument> const& args)
2663
0
{
2664
0
  bool const hasBackslashes =
2665
0
    std::any_of(args.begin(), args.end(), [](cmListFileArgument const& s) {
2666
0
      return s.Value.find('\\') != std::string::npos;
2667
0
    });
2668
0
  return CheckCMP0219Impl(GetPolicyStatus(cmPolicies::CMP0219), calleeName,
2669
0
                          hasBackslashes, WarnedCMP0219);
2670
0
}
2671
2672
void cmMakefile::IssueCMP0219Warning(
2673
  std::string const& calleeName, std::vector<std::string> const& args) const
2674
0
{
2675
0
  std::string oldArgs;
2676
0
  for (std::string const& arg : args) {
2677
0
    if (arg.find('\\') == std::string::npos) {
2678
0
      continue;
2679
0
    }
2680
0
    if (!oldArgs.empty()) {
2681
0
      oldArgs += '\n';
2682
0
    }
2683
0
    oldArgs += cmStrCat(" \"", arg, '"');
2684
0
  }
2685
2686
0
  std::string newArgs = oldArgs;
2687
0
  cmSystemTools::ReplaceString(newArgs, "\\", "\\\\");
2688
2689
0
  this->IssueDiagnostic(
2690
0
    cmDiagnostics::CMD_POLICY,
2691
0
    cmStrCat(
2692
0
      cmPolicies::GetPolicyWarning(cmPolicies::CMP0219), '\n', "Command \"",
2693
0
      calleeName, "\" called with arguments containing backslashes.\n",
2694
0
      "Since the policy is not set, backslashes in the arguments:\n", oldArgs,
2695
0
      "\n", "will be interpreted as escape sequences for compatibility.\n",
2696
0
      "Set the policy to NEW to instead pass\n", newArgs, "\n",
2697
0
      "so that argument parsing will preserve the original values."));
2698
0
}
2699
2700
void cmMakefile::IssueCMP0219Warning(
2701
  std::string const& calleeName,
2702
  std::vector<cmListFileArgument> const& args) const
2703
0
{
2704
0
  std::vector<std::string> stringArgs;
2705
0
  stringArgs.reserve(args.size());
2706
0
  for (cmListFileArgument const& arg : args) {
2707
0
    stringArgs.push_back(arg.Value);
2708
0
  }
2709
0
  this->IssueCMP0219Warning(calleeName, stringArgs);
2710
0
}
2711
2712
MessageType cmMakefile::ExpandVariablesInStringImpl(
2713
  std::string& errorstr, std::string& source, bool escapeQuotes,
2714
  bool noEscapes, bool atOnly, char const* filename, long line,
2715
  bool replaceAt) const
2716
0
{
2717
  // This method replaces ${VAR} and @VAR@ where VAR is looked up
2718
  // with GetDefinition(), if not found in the map, nothing is expanded.
2719
  // It also supports the $ENV{VAR} syntax where VAR is looked up in
2720
  // the current environment variables.
2721
2722
0
  char const* in = source.c_str();
2723
0
  char const* last = in;
2724
0
  std::string result;
2725
0
  result.reserve(source.size());
2726
0
  std::vector<t_lookup> openstack;
2727
0
  bool error = false;
2728
0
  bool done = false;
2729
0
  MessageType mtype = MessageType::LOG;
2730
2731
0
  cmState* state = this->GetCMakeInstance()->GetState();
2732
2733
0
  static std::string const lineVar = "CMAKE_CURRENT_LIST_LINE";
2734
0
  do {
2735
0
    char inc = *in;
2736
0
    switch (inc) {
2737
0
      case '}':
2738
0
        if (!openstack.empty()) {
2739
0
          t_lookup var = openstack.back();
2740
0
          openstack.pop_back();
2741
0
          result.append(last, in - last);
2742
0
          std::string const& lookup = result.substr(var.loc);
2743
0
          cmValue value = nullptr;
2744
0
          std::string varresult;
2745
0
          std::string svalue;
2746
0
          switch (var.domain) {
2747
0
            case NORMAL:
2748
0
              if (filename && lookup == lineVar) {
2749
0
                cmListFileContext const& top = this->Backtrace.Top();
2750
0
                if (top.DeferId) {
2751
0
                  varresult = cmStrCat("DEFERRED:"_s, *top.DeferId);
2752
0
                } else {
2753
0
                  varresult = std::to_string(line);
2754
0
                }
2755
0
              } else {
2756
0
                value = this->GetDefinition(lookup);
2757
0
              }
2758
0
              break;
2759
0
            case ENVIRONMENT:
2760
0
              if (cmSystemTools::GetEnv(lookup, svalue)) {
2761
0
                value = cmValue(svalue);
2762
0
              }
2763
0
              break;
2764
0
            case CACHE:
2765
0
              value = state->GetCacheEntryValue(lookup);
2766
0
              break;
2767
0
          }
2768
          // Get the string we're meant to append to.
2769
0
          if (value) {
2770
0
            if (escapeQuotes) {
2771
0
              varresult = cmEscapeQuotes(*value);
2772
0
            } else {
2773
0
              varresult = *value;
2774
0
            }
2775
0
          } else {
2776
0
            this->MaybeWarnUninitialized(lookup, filename);
2777
0
          }
2778
0
          result.replace(var.loc, result.size() - var.loc, varresult);
2779
          // Start looking from here on out.
2780
0
          last = in + 1;
2781
0
        }
2782
0
        break;
2783
0
      case '$':
2784
0
        if (!atOnly) {
2785
0
          t_lookup lookup;
2786
0
          char const* next = in + 1;
2787
0
          char const* start = nullptr;
2788
0
          char nextc = *next;
2789
0
          if (nextc == '{') {
2790
            // Looking for a variable.
2791
0
            start = in + 2;
2792
0
            lookup.domain = NORMAL;
2793
0
          } else if (nextc == '<') {
2794
0
          } else if (!nextc) {
2795
0
            result.append(last, next - last);
2796
0
            last = next;
2797
0
          } else if (cmHasLiteralPrefix(next, "ENV{")) {
2798
            // Looking for an environment variable.
2799
0
            start = in + 5;
2800
0
            lookup.domain = ENVIRONMENT;
2801
0
          } else if (cmHasLiteralPrefix(next, "CACHE{")) {
2802
            // Looking for a cache variable.
2803
0
            start = in + 7;
2804
0
            lookup.domain = CACHE;
2805
0
          } else {
2806
0
            if (this->cmNamedCurly.find(next)) {
2807
0
              errorstr = "Syntax $" +
2808
0
                std::string(next, this->cmNamedCurly.end()) +
2809
0
                "{} is not supported.  Only ${}, $ENV{}, "
2810
0
                "and $CACHE{} are allowed.";
2811
0
              mtype = MessageType::FATAL_ERROR;
2812
0
              error = true;
2813
0
            }
2814
0
          }
2815
0
          if (start) {
2816
0
            result.append(last, in - last);
2817
0
            last = start;
2818
0
            in = start - 1;
2819
0
            lookup.loc = result.size();
2820
0
            openstack.push_back(lookup);
2821
0
          }
2822
0
          break;
2823
0
        }
2824
0
        CM_FALLTHROUGH;
2825
0
      case '\\':
2826
0
        if (!noEscapes) {
2827
0
          char const* next = in + 1;
2828
0
          char nextc = *next;
2829
0
          if (nextc == 't') {
2830
0
            result.append(last, in - last);
2831
0
            result.push_back('\t');
2832
0
            last = next + 1;
2833
0
          } else if (nextc == 'n') {
2834
0
            result.append(last, in - last);
2835
0
            result.push_back('\n');
2836
0
            last = next + 1;
2837
0
          } else if (nextc == 'r') {
2838
0
            result.append(last, in - last);
2839
0
            result.push_back('\r');
2840
0
            last = next + 1;
2841
0
          } else if (nextc == ';' && openstack.empty()) {
2842
            // Handled in ExpandListArgument; pass the backslash literally.
2843
0
          } else if (cmsysString_isalnum(nextc) || nextc == '\0') {
2844
0
            errorstr += "Invalid character escape '\\";
2845
0
            if (nextc) {
2846
0
              errorstr += nextc;
2847
0
              errorstr += "'.";
2848
0
            } else {
2849
0
              errorstr += "' (at end of input).";
2850
0
            }
2851
0
            error = true;
2852
0
          } else {
2853
            // Take what we've found so far, skipping the escape character.
2854
0
            result.append(last, in - last);
2855
            // Start tracking from the next character.
2856
0
            last = in + 1;
2857
0
          }
2858
          // Skip the next character since it was escaped, but don't read past
2859
          // the end of the string.
2860
0
          if (*last) {
2861
0
            ++in;
2862
0
          }
2863
0
        }
2864
0
        break;
2865
0
      case '\n':
2866
        // Onto the next line.
2867
0
        ++line;
2868
0
        break;
2869
0
      case '\0':
2870
0
        done = true;
2871
0
        break;
2872
0
      case '@':
2873
0
        if (replaceAt) {
2874
0
          char const* nextAt = strchr(in + 1, '@');
2875
0
          if (nextAt && nextAt != in + 1 &&
2876
0
              nextAt ==
2877
0
                in + 1 +
2878
0
                  std::strspn(in + 1,
2879
0
                              "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
2880
0
                              "abcdefghijklmnopqrstuvwxyz"
2881
0
                              "0123456789/_.+-")) {
2882
0
            std::string variable(in + 1, nextAt - in - 1);
2883
2884
0
            std::string varresult;
2885
0
            if (filename && variable == lineVar) {
2886
0
              varresult = std::to_string(line);
2887
0
            } else {
2888
0
              cmValue def = this->GetDefinition(variable);
2889
0
              if (def) {
2890
0
                varresult = *def;
2891
0
              } else {
2892
0
                this->MaybeWarnUninitialized(variable, filename);
2893
0
              }
2894
0
            }
2895
2896
0
            if (escapeQuotes) {
2897
0
              varresult = cmEscapeQuotes(varresult);
2898
0
            }
2899
            // Skip over the variable.
2900
0
            result.append(last, in - last);
2901
0
            result.append(varresult);
2902
0
            in = nextAt;
2903
0
            last = in + 1;
2904
0
            break;
2905
0
          }
2906
0
        }
2907
        // Failed to find a valid @ expansion; treat it as literal.
2908
0
        CM_FALLTHROUGH;
2909
0
      default: {
2910
0
        if (!openstack.empty() &&
2911
0
            !(cmsysString_isalnum(inc) || inc == '_' || inc == '/' ||
2912
0
              inc == '.' || inc == '+' || inc == '-')) {
2913
0
          errorstr += cmStrCat("Invalid character ('", inc);
2914
0
          result.append(last, in - last);
2915
0
          errorstr += cmStrCat("') in a variable name: '",
2916
0
                               result.substr(openstack.back().loc), '\'');
2917
0
          mtype = MessageType::FATAL_ERROR;
2918
0
          error = true;
2919
0
        }
2920
0
        break;
2921
0
      }
2922
0
    }
2923
    // Look at the next character.
2924
0
  } while (!error && !done && *++in);
2925
2926
  // Check for open variable references yet.
2927
0
  if (!error && !openstack.empty()) {
2928
0
    errorstr += "There is an unterminated variable reference.";
2929
0
    error = true;
2930
0
  }
2931
2932
0
  if (error) {
2933
0
    std::string e = "Syntax error in cmake code ";
2934
0
    if (filename) {
2935
      // This filename and line number may be more specific than the
2936
      // command context because one command invocation can have
2937
      // arguments on multiple lines.
2938
0
      e += cmStrCat("at\n  ", filename, ':', line, '\n');
2939
0
    }
2940
0
    errorstr = cmStrCat(e, "when parsing string\n  ", source, '\n', errorstr);
2941
0
    mtype = MessageType::FATAL_ERROR;
2942
0
  } else {
2943
    // Append the rest of the unchanged part of the string.
2944
0
    result.append(last);
2945
2946
0
    source = result;
2947
0
  }
2948
2949
0
  return mtype;
2950
0
}
2951
2952
void cmMakefile::RemoveVariablesInString(std::string& source,
2953
                                         bool atOnly) const
2954
0
{
2955
0
  if (!atOnly) {
2956
0
    cmsys::RegularExpression var("(\\${[A-Za-z_0-9]*})");
2957
0
    while (var.find(source)) {
2958
0
      source.erase(var.start(), var.end() - var.start());
2959
0
    }
2960
0
  }
2961
2962
0
  if (!atOnly) {
2963
0
    cmsys::RegularExpression varb("(\\$ENV{[A-Za-z_0-9]*})");
2964
0
    while (varb.find(source)) {
2965
0
      source.erase(varb.start(), varb.end() - varb.start());
2966
0
    }
2967
0
  }
2968
0
  cmsys::RegularExpression var2("(@[A-Za-z_0-9]*@)");
2969
0
  while (var2.find(source)) {
2970
0
    source.erase(var2.start(), var2.end() - var2.start());
2971
0
  }
2972
0
}
2973
2974
void cmMakefile::InitCMAKE_CONFIGURATION_TYPES(std::string const& genDefault)
2975
0
{
2976
0
  if (this->GetDefinition("CMAKE_CONFIGURATION_TYPES")) {
2977
0
    return;
2978
0
  }
2979
0
  std::string initConfigs;
2980
0
  if (this->GetCMakeInstance()->GetIsInTryCompile() ||
2981
0
      !cmSystemTools::GetEnv("CMAKE_CONFIGURATION_TYPES", initConfigs)) {
2982
0
    initConfigs = genDefault;
2983
0
  }
2984
0
  this->AddCacheDefinition(
2985
0
    "CMAKE_CONFIGURATION_TYPES", initConfigs,
2986
0
    "Semicolon separated list of supported configuration types, "
2987
0
    "only supports Debug, Release, MinSizeRel, and RelWithDebInfo, "
2988
0
    "anything else will be ignored.",
2989
0
    cmStateEnums::STRING);
2990
0
}
2991
2992
std::string cmMakefile::GetDefaultConfiguration() const
2993
0
{
2994
0
  if (this->GetGlobalGenerator()->IsMultiConfig()) {
2995
0
    return std::string{};
2996
0
  }
2997
0
  return this->GetSafeDefinition("CMAKE_BUILD_TYPE");
2998
0
}
2999
3000
std::vector<std::string> cmMakefile::GetGeneratorConfigs(
3001
  GeneratorConfigQuery mode) const
3002
0
{
3003
0
  cmList configs;
3004
0
  if (this->GetGlobalGenerator()->IsMultiConfig()) {
3005
0
    configs.assign(this->GetDefinition("CMAKE_CONFIGURATION_TYPES"));
3006
0
  } else if (mode != cmMakefile::OnlyMultiConfig) {
3007
0
    std::string const& buildType = this->GetSafeDefinition("CMAKE_BUILD_TYPE");
3008
0
    if (!buildType.empty()) {
3009
0
      configs.emplace_back(buildType);
3010
0
    }
3011
0
  }
3012
0
  if (mode == cmMakefile::IncludeEmptyConfig && configs.empty()) {
3013
0
    configs.emplace_back();
3014
0
  }
3015
0
  return std::move(configs.data());
3016
0
}
3017
3018
bool cmMakefile::IsFunctionBlocked(cmListFileFunction const& lff,
3019
                                   cmExecutionStatus& status)
3020
0
{
3021
  // if there are no blockers get out of here
3022
0
  if (this->FunctionBlockers.empty()) {
3023
0
    return false;
3024
0
  }
3025
3026
0
  return this->FunctionBlockers.top()->IsFunctionBlocked(lff, status);
3027
0
}
3028
3029
void cmMakefile::PushFunctionBlockerBarrier()
3030
1
{
3031
1
  this->FunctionBlockerBarriers.push_back(this->FunctionBlockers.size());
3032
1
}
3033
3034
void cmMakefile::PopFunctionBlockerBarrier(bool reportError)
3035
1
{
3036
  // Remove any extra entries pushed on the barrier.
3037
1
  FunctionBlockersType::size_type barrier =
3038
1
    this->FunctionBlockerBarriers.back();
3039
1
  while (this->FunctionBlockers.size() > barrier) {
3040
0
    std::unique_ptr<cmFunctionBlocker> fb(
3041
0
      std::move(this->FunctionBlockers.top()));
3042
0
    this->FunctionBlockers.pop();
3043
0
    if (reportError) {
3044
      // Report the context in which the unclosed block was opened.
3045
0
      cmListFileContext const& lfc = fb->GetStartingContext();
3046
0
      std::ostringstream e;
3047
      /* clang-format off */
3048
0
      e << "A logical block opening on the line\n"
3049
0
           "  " << lfc << "\n"
3050
0
           "is not closed.";
3051
      /* clang-format on */
3052
0
      this->IssueMessage(MessageType::FATAL_ERROR, e.str());
3053
0
      reportError = false;
3054
0
    }
3055
0
  }
3056
3057
  // Remove the barrier.
3058
1
  this->FunctionBlockerBarriers.pop_back();
3059
1
}
3060
3061
void cmMakefile::PushLoopBlock()
3062
0
{
3063
0
  assert(!this->LoopBlockCounter.empty());
3064
0
  this->LoopBlockCounter.top()++;
3065
0
}
3066
3067
void cmMakefile::PopLoopBlock()
3068
0
{
3069
0
  assert(!this->LoopBlockCounter.empty());
3070
0
  assert(this->LoopBlockCounter.top() > 0);
3071
0
  this->LoopBlockCounter.top()--;
3072
0
}
3073
3074
void cmMakefile::PushLoopBlockBarrier()
3075
1
{
3076
1
  this->LoopBlockCounter.push(0);
3077
1
}
3078
3079
void cmMakefile::PopLoopBlockBarrier()
3080
0
{
3081
0
  assert(!this->LoopBlockCounter.empty());
3082
0
  assert(this->LoopBlockCounter.top() == 0);
3083
0
  this->LoopBlockCounter.pop();
3084
0
}
3085
3086
bool cmMakefile::IsLoopBlock() const
3087
0
{
3088
0
  assert(!this->LoopBlockCounter.empty());
3089
0
  return !this->LoopBlockCounter.empty() && this->LoopBlockCounter.top() > 0;
3090
0
}
3091
3092
bool cmMakefile::ExpandArguments(std::vector<cmListFileArgument> const& inArgs,
3093
                                 std::vector<std::string>& outArgs) const
3094
0
{
3095
0
  std::string const& filename = this->GetBacktrace().Top().FilePath;
3096
0
  std::string value;
3097
0
  outArgs.reserve(inArgs.size());
3098
0
  for (cmListFileArgument const& i : inArgs) {
3099
    // No expansion in a bracket argument.
3100
0
    if (i.Delim == cmListFileArgument::Bracket) {
3101
0
      outArgs.push_back(i.Value);
3102
0
      continue;
3103
0
    }
3104
    // Expand the variables in the argument.
3105
0
    value = i.Value;
3106
0
    this->ExpandVariablesInString(value, false, false, false, filename.c_str(),
3107
0
                                  i.Line, false, false);
3108
3109
    // If the argument is quoted, it should be one argument.
3110
    // Otherwise, it may be a list of arguments.
3111
0
    if (i.Delim == cmListFileArgument::Quoted) {
3112
0
      outArgs.push_back(value);
3113
0
    } else {
3114
0
      cmExpandList(value, outArgs);
3115
0
    }
3116
0
  }
3117
0
  return !cmSystemTools::GetFatalErrorOccurred();
3118
0
}
3119
3120
bool cmMakefile::ExpandArguments(
3121
  std::vector<cmListFileArgument> const& inArgs,
3122
  std::vector<cmExpandedCommandArgument>& outArgs) const
3123
0
{
3124
0
  std::string const& filename = this->GetBacktrace().Top().FilePath;
3125
0
  std::string value;
3126
0
  outArgs.reserve(inArgs.size());
3127
0
  for (cmListFileArgument const& i : inArgs) {
3128
    // No expansion in a bracket argument.
3129
0
    if (i.Delim == cmListFileArgument::Bracket) {
3130
0
      outArgs.emplace_back(i.Value, true);
3131
0
      continue;
3132
0
    }
3133
    // Expand the variables in the argument.
3134
0
    value = i.Value;
3135
0
    this->ExpandVariablesInString(value, false, false, false, filename.c_str(),
3136
0
                                  i.Line, false, false);
3137
3138
    // If the argument is quoted, it should be one argument.
3139
    // Otherwise, it may be a list of arguments.
3140
0
    if (i.Delim == cmListFileArgument::Quoted) {
3141
0
      outArgs.emplace_back(value, true);
3142
0
    } else {
3143
0
      cmList stringArgs{ value };
3144
0
      for (std::string const& stringArg : stringArgs) {
3145
0
        outArgs.emplace_back(stringArg, false);
3146
0
      }
3147
0
    }
3148
0
  }
3149
0
  return !cmSystemTools::GetFatalErrorOccurred();
3150
0
}
3151
3152
void cmMakefile::AddFunctionBlocker(std::unique_ptr<cmFunctionBlocker> fb)
3153
0
{
3154
0
  if (!this->ExecutionStatusStack.empty()) {
3155
    // Record the context in which the blocker is created.
3156
0
    fb->SetStartingContext(this->Backtrace.Top());
3157
0
  }
3158
3159
0
  this->FunctionBlockers.push(std::move(fb));
3160
0
}
3161
3162
std::unique_ptr<cmFunctionBlocker> cmMakefile::RemoveFunctionBlocker()
3163
0
{
3164
0
  assert(!this->FunctionBlockers.empty());
3165
0
  assert(this->FunctionBlockerBarriers.empty() ||
3166
0
         this->FunctionBlockers.size() > this->FunctionBlockerBarriers.back());
3167
3168
0
  auto b = std::move(this->FunctionBlockers.top());
3169
0
  this->FunctionBlockers.pop();
3170
0
  return b;
3171
0
}
3172
3173
std::string const& cmMakefile::GetHomeDirectory() const
3174
0
{
3175
0
  return this->GetCMakeInstance()->GetHomeDirectory();
3176
0
}
3177
3178
std::string const& cmMakefile::GetHomeOutputDirectory() const
3179
0
{
3180
0
  return this->GetCMakeInstance()->GetHomeOutputDirectory();
3181
0
}
3182
3183
void cmMakefile::SetScriptModeFile(std::string const& scriptfile)
3184
1
{
3185
1
  this->AddDefinition("CMAKE_SCRIPT_MODE_FILE", scriptfile);
3186
1
}
3187
3188
void cmMakefile::SetArgcArgv(std::vector<std::string> const& args)
3189
1
{
3190
1
  this->AddDefinition("CMAKE_ARGC", std::to_string(args.size()));
3191
3192
4
  for (auto i = 0u; i < args.size(); ++i) {
3193
3
    this->AddDefinition(cmStrCat("CMAKE_ARGV", i), args[i]);
3194
3
  }
3195
1
}
3196
3197
cmSourceFile* cmMakefile::GetSource(std::string const& sourceName,
3198
                                    cmSourceFileLocationKind kind) const
3199
0
{
3200
  // First check "Known" paths (avoids the creation of cmSourceFileLocation)
3201
0
  if (kind == cmSourceFileLocationKind::Known) {
3202
0
    auto sfsi = this->KnownFileSearchIndex.find(sourceName);
3203
0
    if (sfsi != this->KnownFileSearchIndex.end()) {
3204
0
      return sfsi->second;
3205
0
    }
3206
0
  }
3207
3208
0
  cmSourceFileLocation sfl(this, sourceName, kind);
3209
0
  auto name = this->GetCMakeInstance()->StripExtension(sfl.GetName());
3210
#if defined(_WIN32) || defined(__APPLE__)
3211
  name = cmSystemTools::LowerCase(name);
3212
#endif
3213
0
  auto sfsi = this->SourceFileSearchIndex.find(name);
3214
0
  if (sfsi != this->SourceFileSearchIndex.end()) {
3215
0
    for (auto* sf : sfsi->second) {
3216
0
      if (sf->Matches(sfl)) {
3217
0
        return sf;
3218
0
      }
3219
0
    }
3220
0
  }
3221
0
  return nullptr;
3222
0
}
3223
3224
cmSourceFile* cmMakefile::CreateSource(std::string const& sourceName,
3225
                                       bool generated,
3226
                                       cmSourceFileLocationKind kind)
3227
0
{
3228
0
  auto sf = cm::make_unique<cmSourceFile>(this, sourceName, generated, kind);
3229
0
  auto name =
3230
0
    this->GetCMakeInstance()->StripExtension(sf->GetLocation().GetName());
3231
#if defined(_WIN32) || defined(__APPLE__)
3232
  name = cmSystemTools::LowerCase(name);
3233
#endif
3234
0
  this->SourceFileSearchIndex[name].push_back(sf.get());
3235
  // for "Known" paths add direct lookup (used for faster lookup in GetSource)
3236
0
  if (kind == cmSourceFileLocationKind::Known) {
3237
0
    this->KnownFileSearchIndex[sourceName] = sf.get();
3238
0
  }
3239
3240
0
  this->SourceFiles.push_back(std::move(sf));
3241
3242
0
  return this->SourceFiles.back().get();
3243
0
}
3244
3245
cmSourceFile* cmMakefile::GetOrCreateSource(std::string const& sourceName,
3246
                                            bool generated,
3247
                                            cmSourceFileLocationKind kind)
3248
0
{
3249
0
  if (cmSourceFile* esf = this->GetSource(sourceName, kind)) {
3250
0
    return esf;
3251
0
  }
3252
0
  return this->CreateSource(sourceName, generated, kind);
3253
0
}
3254
3255
cmSourceFile* cmMakefile::GetOrCreateGeneratedSource(
3256
  std::string const& sourceName)
3257
0
{
3258
0
  cmSourceFile* sf =
3259
0
    this->GetOrCreateSource(sourceName, true, cmSourceFileLocationKind::Known);
3260
0
  sf->MarkAsGenerated(); // In case we did not create the source file.
3261
0
  return sf;
3262
0
}
3263
3264
void cmMakefile::CreateGeneratedOutputs(
3265
  std::vector<std::string> const& outputs)
3266
0
{
3267
0
  for (std::string const& o : outputs) {
3268
0
    if (cmGeneratorExpression::Find(o) == std::string::npos) {
3269
0
      this->GetOrCreateGeneratedSource(o);
3270
0
    }
3271
0
  }
3272
0
}
3273
3274
void cmMakefile::AddTargetObject(std::string const& tgtName,
3275
                                 std::string const& objFile)
3276
0
{
3277
0
  cmSourceFile* sf =
3278
0
    this->GetOrCreateSource(objFile, true, cmSourceFileLocationKind::Known);
3279
0
  sf->SetSpecialSourceType(cmSourceFile::SpecialSourceType::Object);
3280
0
  sf->SetObjectLibrary(tgtName);
3281
0
  sf->SetProperty("EXTERNAL_OBJECT", "1");
3282
  // TODO: Compute a language for this object based on the associated source
3283
  // file that compiles to it. Needs a policy as it likely affects link
3284
  // language selection if done unconditionally.
3285
0
#if !defined(CMAKE_BOOTSTRAP)
3286
0
  this->SourceGroups[this->ObjectLibrariesSourceGroupIndex]->AddGroupFile(
3287
0
    sf->ResolveFullPath());
3288
0
#endif
3289
0
}
3290
3291
void cmMakefile::EnableLanguage(std::vector<std::string> const& languages,
3292
                                bool optional)
3293
0
{
3294
0
  if (this->DeferRunning) {
3295
0
    this->IssueMessage(
3296
0
      MessageType::FATAL_ERROR,
3297
0
      "Languages may not be enabled during deferred execution.");
3298
0
    return;
3299
0
  }
3300
0
  if (char const* def = this->GetGlobalGenerator()->GetCMakeCFGIntDir()) {
3301
0
    this->AddDefinition("CMAKE_CFG_INTDIR", def);
3302
0
  }
3303
3304
0
  std::vector<std::string> unique_languages;
3305
0
  {
3306
0
    std::vector<std::string> duplicate_languages;
3307
0
    for (std::string const& language : languages) {
3308
0
      if (!cm::contains(unique_languages, language)) {
3309
0
        unique_languages.push_back(language);
3310
0
      } else if (!cm::contains(duplicate_languages, language)) {
3311
0
        duplicate_languages.push_back(language);
3312
0
      }
3313
0
    }
3314
0
    if (!duplicate_languages.empty()) {
3315
0
      auto quantity = duplicate_languages.size() == 1 ? " has"_s : "s have"_s;
3316
0
      this->IssueDiagnostic(
3317
0
        cmDiagnostics::CMD_AUTHOR,
3318
0
        cmStrCat("Languages to be enabled may not be specified more "
3319
0
                 "than once at the same time. The following language",
3320
0
                 quantity, " been specified multiple times: ",
3321
0
                 cmJoin(duplicate_languages, ", ")));
3322
0
    }
3323
0
  }
3324
3325
  // If RC is explicitly listed we need to do it after other languages.
3326
  // On some platforms we enable RC implicitly while enabling others.
3327
  // Do not let that look like recursive enable_language(RC).
3328
0
  std::vector<std::string> languages_without_RC;
3329
0
  std::vector<std::string> languages_for_RC;
3330
0
  languages_without_RC.reserve(unique_languages.size());
3331
0
  for (std::string const& language : unique_languages) {
3332
0
    if (language == "RC"_s) {
3333
0
      languages_for_RC.push_back(language);
3334
0
    } else {
3335
0
      languages_without_RC.push_back(language);
3336
0
    }
3337
0
  }
3338
0
  if (!languages_without_RC.empty()) {
3339
0
    this->GetGlobalGenerator()->EnableLanguage(languages_without_RC, this,
3340
0
                                               optional);
3341
0
  }
3342
0
  if (!languages_for_RC.empty()) {
3343
0
    this->GetGlobalGenerator()->EnableLanguage(languages_for_RC, this,
3344
0
                                               optional);
3345
0
  }
3346
0
}
3347
3348
int cmMakefile::TryCompile(std::string const& srcdir,
3349
                           std::string const& bindir,
3350
                           std::string const& projectName,
3351
                           std::string const& targetName, bool fast, int jobs,
3352
                           std::vector<std::string> const* cmakeArgs,
3353
                           std::string& output)
3354
0
{
3355
0
  this->IsSourceFileTryCompile = fast;
3356
  // does the binary directory exist ? If not create it...
3357
0
  if (!cmSystemTools::FileIsDirectory(bindir)) {
3358
0
    cmSystemTools::MakeDirectory(bindir);
3359
0
  }
3360
3361
  // change to the tests directory and run cmake
3362
  // use the cmake object instead of calling cmake
3363
0
  cmWorkingDirectory workdir(bindir);
3364
0
  if (workdir.Failed()) {
3365
0
    this->IssueMessage(MessageType::FATAL_ERROR, workdir.GetError());
3366
0
    cmSystemTools::SetFatalErrorOccurred();
3367
0
    this->IsSourceFileTryCompile = false;
3368
0
    return 1;
3369
0
  }
3370
3371
  // unset the NINJA_STATUS environment variable while running try compile.
3372
  // since we parse the output, we need to ensure there aren't any unexpected
3373
  // characters that will cause issues, such as ANSI color escape codes.
3374
0
  cm::optional<cmSystemTools::ScopedEnv> maybeNinjaStatus;
3375
0
  if (this->GetGlobalGenerator()->IsNinja()) {
3376
0
    maybeNinjaStatus.emplace("NINJA_STATUS=");
3377
0
  }
3378
3379
  // make sure the same generator is used
3380
  // use this program as the cmake to be run, it should not
3381
  // be run that way but the cmake object requires a valid path
3382
0
  cmake cm(cmState::Role::Project, cmState::TryCompile::Yes);
3383
0
  auto gg = cm.CreateGlobalGenerator(this->GetGlobalGenerator()->GetName());
3384
0
  if (!gg) {
3385
0
    this->IssueMessage(MessageType::INTERNAL_ERROR,
3386
0
                       "Global generator '" +
3387
0
                         this->GetGlobalGenerator()->GetName() +
3388
0
                         "' could not be created.");
3389
0
    cmSystemTools::SetFatalErrorOccurred();
3390
0
    this->IsSourceFileTryCompile = false;
3391
0
    return 1;
3392
0
  }
3393
0
  gg->RecursionDepth = this->RecursionDepth;
3394
0
  cm.SetGlobalGenerator(std::move(gg));
3395
3396
  // copy trace state
3397
0
  cm.SetTraceRedirect(this->GetCMakeInstance());
3398
3399
  // do a configure
3400
0
  cm.SetHomeDirectory(srcdir);
3401
0
  cm.SetHomeOutputDirectory(bindir);
3402
0
  cm.SetGeneratorInstance(this->GetSafeDefinition("CMAKE_GENERATOR_INSTANCE"));
3403
0
  cm.SetGeneratorPlatform(this->GetSafeDefinition("CMAKE_GENERATOR_PLATFORM"));
3404
0
  cm.SetGeneratorToolset(this->GetSafeDefinition("CMAKE_GENERATOR_TOOLSET"));
3405
0
  cm.LoadCache();
3406
0
  if (!cm.GetGlobalGenerator()->IsMultiConfig()) {
3407
0
    if (cmValue config =
3408
0
          this->GetDefinition("CMAKE_TRY_COMPILE_CONFIGURATION")) {
3409
      // Tell the single-configuration generator which one to use.
3410
      // Add this before the user-provided CMake arguments in case
3411
      // one of the arguments is -DCMAKE_BUILD_TYPE=...
3412
0
      cm.AddCacheEntry("CMAKE_BUILD_TYPE", config, "Build configuration",
3413
0
                       cmStateEnums::STRING);
3414
0
    }
3415
0
  }
3416
0
  cmValue recursionDepth =
3417
0
    this->GetDefinition("CMAKE_MAXIMUM_RECURSION_DEPTH");
3418
0
  if (recursionDepth) {
3419
0
    cm.AddCacheEntry("CMAKE_MAXIMUM_RECURSION_DEPTH", recursionDepth,
3420
0
                     "Maximum recursion depth", cmStateEnums::STRING);
3421
0
  }
3422
  // if cmake args were provided then pass them in
3423
0
  if (cmakeArgs) {
3424
    // FIXME: Workaround to ignore unused CLI variables in try-compile.
3425
    //
3426
    // Ideally we should use SetArgs for options like -Wno-unused-cli.
3427
    // However, there is a subtle problem when certain arguments are passed to
3428
    // a macro wrapping around try_compile or try_run that does not escape
3429
    // semicolons in its parameters but just passes ${ARGV} or ${ARGN}.  In
3430
    // this case a list argument like "-DVAR=a;b" gets split into multiple
3431
    // cmake arguments "-DVAR=a" and "b".  Currently SetCacheArgs ignores
3432
    // argument "b" and uses just "-DVAR=a", leading to a subtle bug in that
3433
    // the try_compile or try_run does not get the proper value of VAR.  If we
3434
    // call SetArgs here then it would treat "b" as the source directory and
3435
    // cause an error such as "The source directory .../CMakeFiles/CMakeTmp/b
3436
    // does not exist", thus breaking the try_compile or try_run completely.
3437
    //
3438
    // Strictly speaking the bug is in the wrapper macro because the CMake
3439
    // language has always flattened nested lists and the macro should escape
3440
    // the semicolons in its arguments before forwarding them.  However, this
3441
    // bug is so subtle that projects typically work anyway, usually because
3442
    // the value VAR=a is sufficient for the try_compile or try_run to get the
3443
    // correct result.  Calling SetArgs here would break such projects that
3444
    // previously built.  Instead we work around the issue by never reporting
3445
    // unused arguments and ignoring options such as -Wno-unused-cli.
3446
0
    cm.GetCurrentSnapshot().SetDiagnostic(cmDiagnostics::CMD_UNUSED_CLI,
3447
0
                                          cmDiagnostics::Ignore, true);
3448
    // cm.SetArgs(*cmakeArgs, true);
3449
3450
0
    cm.SetCacheArgs(*cmakeArgs);
3451
0
  }
3452
  // to save time we pass the EnableLanguage info directly
3453
0
  cm.GetGlobalGenerator()->SetupTryCompile(this->GetGlobalGenerator(), this);
3454
0
  for (unsigned dc = 1; dc < cmDiagnostics::CategoryCount; ++dc) {
3455
0
    auto const category = static_cast<cmDiagnosticCategory>(dc);
3456
0
    if (this->GetDiagnosticAction(category) == cmDiagnostics::Ignore) {
3457
0
      cm.GetCurrentSnapshot().SetDiagnostic(category, cmDiagnostics::Ignore,
3458
0
                                            false);
3459
0
    }
3460
0
  }
3461
0
  if (cm.Configure() != 0) {
3462
0
    this->IssueMessage(MessageType::FATAL_ERROR,
3463
0
                       "Failed to configure test project build system.");
3464
0
    cmSystemTools::SetFatalErrorOccurred();
3465
0
    this->IsSourceFileTryCompile = false;
3466
0
    return 1;
3467
0
  }
3468
3469
0
  if (cm.Generate() != 0) {
3470
0
    this->IssueMessage(MessageType::FATAL_ERROR,
3471
0
                       "Failed to generate test project build system.");
3472
0
    cmSystemTools::SetFatalErrorOccurred();
3473
0
    this->IsSourceFileTryCompile = false;
3474
0
    return 1;
3475
0
  }
3476
3477
  // finally call the generator to actually build the resulting project
3478
0
  int ret = this->GetGlobalGenerator()->TryCompile(
3479
0
    jobs, bindir, projectName, targetName, fast, output, this);
3480
3481
0
  this->IsSourceFileTryCompile = false;
3482
0
  return ret;
3483
0
}
3484
3485
bool cmMakefile::GetIsSourceFileTryCompile() const
3486
0
{
3487
0
  return this->IsSourceFileTryCompile;
3488
0
}
3489
3490
cmake* cmMakefile::GetCMakeInstance() const
3491
32
{
3492
32
  return this->GlobalGenerator->GetCMakeInstance();
3493
32
}
3494
3495
cmMessenger* cmMakefile::GetMessenger() const
3496
0
{
3497
0
  return this->GetCMakeInstance()->GetMessenger();
3498
0
}
3499
3500
cmGlobalGenerator* cmMakefile::GetGlobalGenerator() const
3501
2
{
3502
2
  return this->GlobalGenerator;
3503
2
}
3504
3505
#ifndef CMAKE_BOOTSTRAP
3506
cmVariableWatch* cmMakefile::GetVariableWatch() const
3507
12
{
3508
12
  if (this->GetCMakeInstance()) {
3509
12
    return this->GetCMakeInstance()->GetVariableWatch();
3510
12
  }
3511
0
  return nullptr;
3512
12
}
3513
#endif
3514
3515
cmState* cmMakefile::GetState() const
3516
4
{
3517
4
  return this->GetCMakeInstance()->GetState();
3518
4
}
3519
3520
void cmMakefile::DisplayStatus(std::string const& message, float s) const
3521
0
{
3522
0
  cmake* cm = this->GetCMakeInstance();
3523
0
  if (cm->GetState()->GetRole() == cmState::Role::FindPackage) {
3524
    // don't output any STATUS message in --find-package mode, since they will
3525
    // directly be fed to the compiler, which will be confused.
3526
0
    return;
3527
0
  }
3528
0
  cm->UpdateProgress(message, s);
3529
3530
0
#ifdef CMake_ENABLE_DEBUGGER
3531
0
  if (cm->GetDebugAdapter()) {
3532
0
    cm->GetDebugAdapter()->OnMessageOutput(MessageType::MESSAGE, message);
3533
0
  }
3534
0
#endif
3535
0
}
3536
3537
std::string cmMakefile::GetModulesFile(cm::string_view filename, bool& system,
3538
                                       bool debug,
3539
                                       std::string& debugBuffer) const
3540
0
{
3541
0
  std::string result;
3542
3543
0
  std::string moduleInCMakeRoot;
3544
0
  std::string moduleInCMakeModulePath;
3545
3546
  // Always search in CMAKE_MODULE_PATH:
3547
0
  cmValue cmakeModulePath = this->GetDefinition("CMAKE_MODULE_PATH");
3548
0
  if (cmakeModulePath) {
3549
0
    cmList modulePath{ *cmakeModulePath };
3550
3551
    // Look through the possible module directories.
3552
0
    for (std::string itempl : modulePath) {
3553
0
      cmSystemTools::ConvertToUnixSlashes(itempl);
3554
0
      itempl += "/";
3555
0
      itempl += filename;
3556
0
      if (cmSystemTools::FileExists(itempl)) {
3557
0
        moduleInCMakeModulePath = itempl;
3558
0
        break;
3559
0
      }
3560
0
      if (debug) {
3561
0
        debugBuffer = cmStrCat(debugBuffer, "  ", itempl, '\n');
3562
0
      }
3563
0
    }
3564
0
  }
3565
3566
  // Always search in the standard modules location.
3567
0
  moduleInCMakeRoot =
3568
0
    cmStrCat(cmSystemTools::GetCMakeRoot(), "/Modules/", filename);
3569
0
  cmSystemTools::ConvertToUnixSlashes(moduleInCMakeRoot);
3570
0
  if (!cmSystemTools::FileExists(moduleInCMakeRoot)) {
3571
0
    if (debug) {
3572
0
      debugBuffer = cmStrCat(debugBuffer, "  ", moduleInCMakeRoot, '\n');
3573
0
    }
3574
0
    moduleInCMakeRoot.clear();
3575
0
  }
3576
3577
  // Normally, prefer the files found in CMAKE_MODULE_PATH. Only when the file
3578
  // from which we are being called is located itself in CMAKE_ROOT, then
3579
  // prefer results from CMAKE_ROOT depending on the policy setting.
3580
0
  if (!moduleInCMakeModulePath.empty() && !moduleInCMakeRoot.empty()) {
3581
0
    cmValue currentFile = this->GetDefinition(kCMAKE_CURRENT_LIST_FILE);
3582
0
    std::string mods = cmStrCat(cmSystemTools::GetCMakeRoot(), "/Modules/");
3583
0
    if (currentFile && cmSystemTools::IsSubDirectory(*currentFile, mods)) {
3584
0
      system = true;
3585
0
      result = moduleInCMakeRoot;
3586
0
    } else {
3587
0
      system = false;
3588
0
      result = moduleInCMakeModulePath;
3589
0
    }
3590
0
  } else if (!moduleInCMakeModulePath.empty()) {
3591
0
    system = false;
3592
0
    result = moduleInCMakeModulePath;
3593
0
  } else {
3594
0
    system = true;
3595
0
    result = moduleInCMakeRoot;
3596
0
  }
3597
3598
#if defined(_WIN32) || defined(__APPLE__)
3599
  if (!result.empty()) {
3600
    std::string const requestedName =
3601
      cmSystemTools::GetFilenameName(std::string{ filename });
3602
    std::string actualName;
3603
    cmsys::Status const status =
3604
      cmSystemTools::ReadNameOnDisk(result, actualName);
3605
    if (status && actualName != requestedName) {
3606
      this->IssueDiagnostic(
3607
        cmDiagnostics::CMD_AUTHOR,
3608
        cmStrCat("The module name\n  ", requestedName, '\n',
3609
                 "does not match the case of the module file name on disk\n"
3610
                 "  ",
3611
                 cmSystemTools::GetFilenamePath(result), '/', actualName, '\n',
3612
                 "This may fail on case-sensitive file systems.  "
3613
                 "Use the module name\n  ",
3614
                 actualName, "\ninstead."));
3615
    }
3616
  }
3617
#endif
3618
3619
0
  return result;
3620
0
}
3621
3622
void cmMakefile::ConfigureString(std::string const& input, std::string& output,
3623
                                 bool atOnly, bool escapeQuotes) const
3624
0
{
3625
  // Split input to handle one line at a time.
3626
0
  std::string::const_iterator lineStart = input.begin();
3627
0
  while (lineStart != input.end()) {
3628
    // Find the end of this line.
3629
0
    std::string::const_iterator lineEnd = lineStart;
3630
0
    while (lineEnd != input.end() && *lineEnd != '\n') {
3631
0
      ++lineEnd;
3632
0
    }
3633
3634
    // Copy the line.
3635
0
    std::string line(lineStart, lineEnd);
3636
3637
    // Skip the newline character.
3638
0
    bool haveNewline = (lineEnd != input.end());
3639
0
    if (haveNewline) {
3640
0
      ++lineEnd;
3641
0
    }
3642
3643
    // Replace #cmakedefine instances.
3644
0
    if (this->cmDefineRegex.find(line)) {
3645
0
      cmValue def = this->GetDefinition(this->cmDefineRegex.match(2));
3646
0
      if (!def.IsOff()) {
3647
0
        std::string const indentation = this->cmDefineRegex.match(1);
3648
0
        cmSystemTools::ReplaceString(line,
3649
0
                                     cmStrCat('#', indentation, "cmakedefine"),
3650
0
                                     cmStrCat('#', indentation, "define"));
3651
0
        output += line;
3652
0
      } else {
3653
0
        output += "/* #undef ";
3654
0
        output += this->cmDefineRegex.match(2);
3655
0
        output += " */";
3656
0
      }
3657
0
    } else if (this->cmDefine01Regex.find(line)) {
3658
0
      std::string const indentation = this->cmDefine01Regex.match(1);
3659
0
      cmValue def = this->GetDefinition(this->cmDefine01Regex.match(2));
3660
0
      cmSystemTools::ReplaceString(line,
3661
0
                                   cmStrCat('#', indentation, "cmakedefine01"),
3662
0
                                   cmStrCat('#', indentation, "define"));
3663
0
      output += line;
3664
0
      if (!def.IsOff()) {
3665
0
        output += " 1";
3666
0
      } else {
3667
0
        output += " 0";
3668
0
      }
3669
0
    } else {
3670
0
      output += line;
3671
0
    }
3672
3673
0
    if (haveNewline) {
3674
0
      output += '\n';
3675
0
    }
3676
3677
    // Move to the next line.
3678
0
    lineStart = lineEnd;
3679
0
  }
3680
3681
  // Perform variable replacements.
3682
0
  char const* filename = nullptr;
3683
0
  long lineNumber = -1;
3684
0
  if (!this->Backtrace.Empty()) {
3685
0
    auto const& currentTrace = this->Backtrace.Top();
3686
0
    filename = currentTrace.FilePath.c_str();
3687
0
    lineNumber = currentTrace.Line;
3688
0
  }
3689
0
  this->ExpandVariablesInString(output, escapeQuotes, true, atOnly, filename,
3690
0
                                lineNumber, true, true);
3691
0
}
3692
3693
int cmMakefile::ConfigureFile(std::string const& infile,
3694
                              std::string const& outfile, bool copyonly,
3695
                              bool atOnly, bool escapeQuotes,
3696
                              mode_t permissions, cmNewLineStyle newLine)
3697
0
{
3698
0
  int res = 1;
3699
0
  if (!this->CanIWriteThisFile(outfile)) {
3700
0
    cmSystemTools::Error(cmStrCat("Attempt to write file: ", outfile,
3701
0
                                  " into a source directory."));
3702
0
    return 0;
3703
0
  }
3704
0
  if (!cmSystemTools::FileExists(infile)) {
3705
0
    cmSystemTools::Error(cmStrCat("File ", infile, " does not exist."));
3706
0
    return 0;
3707
0
  }
3708
0
  std::string soutfile = outfile;
3709
0
  std::string const& sinfile = infile;
3710
0
  this->AddCMakeDependFile(sinfile);
3711
0
  cmSystemTools::ConvertToUnixSlashes(soutfile);
3712
3713
  // Re-generate if non-temporary outputs are missing.
3714
  // when we finalize the configuration we will remove all
3715
  // output files that now don't exist.
3716
0
  this->AddCMakeOutputFile(soutfile);
3717
3718
0
  if (permissions == 0) {
3719
0
    cmSystemTools::GetPermissions(sinfile, permissions);
3720
0
  }
3721
3722
0
  std::string::size_type pos = soutfile.rfind('/');
3723
0
  if (pos != std::string::npos) {
3724
0
    std::string path = soutfile.substr(0, pos);
3725
0
    cmSystemTools::MakeDirectory(path);
3726
0
  }
3727
3728
0
  if (copyonly) {
3729
0
    auto const copy_status =
3730
0
      cmSystemTools::CopyFileIfDifferent(sinfile, soutfile);
3731
0
    if (!copy_status) {
3732
0
      this->IssueMessage(
3733
0
        MessageType::FATAL_ERROR,
3734
0
        cmStrCat("Fail to copy ",
3735
0
                 copy_status.Path == cmsys::SystemTools::CopyStatus::SourcePath
3736
0
                   ? "source"
3737
0
                   : "destination",
3738
0
                 "file: ", copy_status.GetString()));
3739
0
      res = 0;
3740
0
    } else {
3741
0
      auto const status = cmSystemTools::SetPermissions(soutfile, permissions);
3742
0
      if (!status) {
3743
0
        this->IssueMessage(MessageType::FATAL_ERROR, status.GetString());
3744
0
        res = 0;
3745
0
      }
3746
0
    }
3747
0
    return res;
3748
0
  }
3749
3750
0
  std::string newLineCharacters;
3751
0
  std::ios::openmode omode = std::ios::out | std::ios::trunc;
3752
0
  if (newLine.IsValid()) {
3753
0
    newLineCharacters = newLine.GetCharacters();
3754
0
    omode |= std::ios::binary;
3755
0
  } else {
3756
0
    newLineCharacters = "\n";
3757
0
  }
3758
0
  std::string tempOutputFile = cmStrCat(soutfile, ".tmp");
3759
0
  cmsys::ofstream fout(tempOutputFile.c_str(), omode);
3760
0
  if (!fout) {
3761
0
    cmSystemTools::Error("Could not open file for write in copy operation " +
3762
0
                         tempOutputFile);
3763
0
    cmSystemTools::ReportLastSystemError("");
3764
0
    return 0;
3765
0
  }
3766
0
  cmsys::ifstream fin(sinfile.c_str());
3767
0
  if (!fin) {
3768
0
    cmSystemTools::Error("Could not open file for read in copy operation " +
3769
0
                         sinfile);
3770
0
    return 0;
3771
0
  }
3772
3773
0
  cmsys::FStream::BOM bom = cmsys::FStream::ReadBOM(fin);
3774
0
  if (bom != cmsys::FStream::BOM_None && bom != cmsys::FStream::BOM_UTF8) {
3775
0
    this->IssueMessage(
3776
0
      MessageType::FATAL_ERROR,
3777
0
      cmStrCat("File starts with a Byte-Order-Mark that is not UTF-8:\n  ",
3778
0
               sinfile));
3779
0
    return 0;
3780
0
  }
3781
  // rewind to copy BOM to output file
3782
0
  fin.seekg(0);
3783
3784
  // now copy input to output and expand variables in the
3785
  // input file at the same time
3786
0
  std::string inLine;
3787
0
  std::string outLine;
3788
0
  while (cmSystemTools::GetLineFromStream(fin, inLine)) {
3789
0
    outLine.clear();
3790
0
    this->ConfigureString(inLine, outLine, atOnly, escapeQuotes);
3791
0
    fout << outLine << newLineCharacters;
3792
0
  }
3793
  // close the files before attempting to copy
3794
0
  fin.close();
3795
0
  fout.close();
3796
3797
0
  auto status = cmSystemTools::MoveFileIfDifferent(tempOutputFile, soutfile);
3798
0
  if (!status) {
3799
0
    this->IssueMessage(MessageType::FATAL_ERROR, status.GetString());
3800
0
    res = 0;
3801
0
  } else {
3802
0
    status = cmSystemTools::SetPermissions(soutfile, permissions);
3803
0
    if (!status) {
3804
0
      this->IssueMessage(MessageType::FATAL_ERROR, status.GetString());
3805
0
      res = 0;
3806
0
    }
3807
0
  }
3808
3809
0
  return res;
3810
0
}
3811
3812
void cmMakefile::SetProperty(std::string const& prop, cmValue value)
3813
0
{
3814
0
  this->StateSnapshot.GetDirectory().SetProperty(prop, value, this->Backtrace);
3815
0
}
3816
3817
void cmMakefile::AppendProperty(std::string const& prop,
3818
                                std::string const& value, bool asString)
3819
0
{
3820
0
  this->StateSnapshot.GetDirectory().AppendProperty(prop, value, asString,
3821
0
                                                    this->Backtrace);
3822
0
}
3823
3824
cmValue cmMakefile::GetProperty(std::string const& prop) const
3825
0
{
3826
  // Check for computed properties.
3827
0
  static std::string output;
3828
0
  if (prop == "TESTS"_s) {
3829
0
    std::vector<std::string> keys;
3830
    // get list of keys
3831
0
    auto const* t = this;
3832
0
    std::transform(
3833
0
      t->Tests.begin(), t->Tests.end(), std::back_inserter(keys),
3834
0
      [](decltype(t->Tests)::value_type const& pair) { return pair.first; });
3835
0
    output = cmList::to_string(keys);
3836
0
    return cmValue(output);
3837
0
  }
3838
3839
0
  return this->StateSnapshot.GetDirectory().GetProperty(prop);
3840
0
}
3841
3842
cmValue cmMakefile::GetProperty(std::string const& prop, bool chain) const
3843
0
{
3844
0
  return this->StateSnapshot.GetDirectory().GetProperty(prop, chain);
3845
0
}
3846
3847
bool cmMakefile::GetPropertyAsBool(std::string const& prop) const
3848
0
{
3849
0
  return this->GetProperty(prop).IsOn();
3850
0
}
3851
3852
std::vector<std::string> cmMakefile::GetPropertyKeys() const
3853
0
{
3854
0
  return this->StateSnapshot.GetDirectory().GetPropertyKeys();
3855
0
}
3856
3857
cmTarget* cmMakefile::FindLocalNonAliasTarget(std::string const& name) const
3858
0
{
3859
0
  auto i = this->Targets.find(name);
3860
0
  if (i != this->Targets.end()) {
3861
0
    return &i->second;
3862
0
  }
3863
0
  return nullptr;
3864
0
}
3865
3866
cmTest* cmMakefile::CreateTest(std::string const& testName)
3867
0
{
3868
0
  cmTest* test = this->GetTest(testName);
3869
0
  if (test) {
3870
0
    return test;
3871
0
  }
3872
0
  auto newTest = cm::make_unique<cmTest>(this);
3873
0
  test = newTest.get();
3874
0
  newTest->SetName(testName);
3875
0
  this->Tests[testName] = std::move(newTest);
3876
0
  return test;
3877
0
}
3878
3879
cmTest* cmMakefile::GetTest(std::string const& testName) const
3880
0
{
3881
0
  auto mi = this->Tests.find(testName);
3882
0
  if (mi != this->Tests.end()) {
3883
0
    return mi->second.get();
3884
0
  }
3885
0
  return nullptr;
3886
0
}
3887
3888
void cmMakefile::GetTests(std::string const& config,
3889
                          std::vector<cmTest*>& tests) const
3890
0
{
3891
0
  for (auto const& generator : this->GetTestGenerators()) {
3892
0
    if (generator->TestsForConfig(config)) {
3893
0
      tests.push_back(generator->GetTest());
3894
0
    }
3895
0
  }
3896
0
}
3897
3898
void cmMakefile::AddCMakeDependFilesFromUser()
3899
0
{
3900
0
  cmList deps;
3901
0
  if (cmValue deps_str = this->GetProperty("CMAKE_CONFIGURE_DEPENDS")) {
3902
0
    deps.assign(*deps_str);
3903
0
  }
3904
0
  for (auto const& dep : deps) {
3905
0
    if (cmSystemTools::FileIsFullPath(dep)) {
3906
0
      this->AddCMakeDependFile(dep);
3907
0
    } else {
3908
0
      std::string f = cmStrCat(this->GetCurrentSourceDirectory(), '/', dep);
3909
0
      this->AddCMakeDependFile(f);
3910
0
    }
3911
0
  }
3912
0
}
3913
3914
std::string cmMakefile::FormatListFileStack() const
3915
0
{
3916
0
  std::vector<std::string> listFiles;
3917
0
  for (auto snp = this->StateSnapshot; snp.IsValid();
3918
0
       snp = snp.GetCallStackParent()) {
3919
0
    listFiles.emplace_back(snp.GetExecutionListFile());
3920
0
  }
3921
3922
0
  if (listFiles.empty()) {
3923
0
    return {};
3924
0
  }
3925
3926
0
  auto depth = 1;
3927
0
  std::transform(listFiles.begin(), listFiles.end(), listFiles.begin(),
3928
0
                 [&depth](std::string const& file) {
3929
0
                   return cmStrCat('[', depth++, "]\t", file);
3930
0
                 });
3931
3932
0
  return cmJoinStrings(cmMakeRange(listFiles.rbegin(), listFiles.rend()),
3933
0
                       "\n                "_s, {});
3934
0
}
3935
3936
void cmMakefile::PushScope()
3937
0
{
3938
0
  this->StateSnapshot =
3939
0
    this->GetState()->CreateVariableScopeSnapshot(this->StateSnapshot);
3940
0
  this->PushLoopBlockBarrier();
3941
3942
0
#if !defined(CMAKE_BOOTSTRAP)
3943
0
  this->GetGlobalGenerator()->GetFileLockPool().PushFunctionScope();
3944
0
#endif
3945
0
}
3946
3947
void cmMakefile::PopScope()
3948
0
{
3949
0
#if !defined(CMAKE_BOOTSTRAP)
3950
0
  this->GetGlobalGenerator()->GetFileLockPool().PopFunctionScope();
3951
0
#endif
3952
3953
0
  this->PopLoopBlockBarrier();
3954
3955
0
  this->PopSnapshot();
3956
0
}
3957
3958
void cmMakefile::RaiseScope(std::string const& var, char const* varDef)
3959
0
{
3960
0
  if (var.empty()) {
3961
0
    return;
3962
0
  }
3963
3964
0
  if (!this->StateSnapshot.RaiseScope(var, varDef)) {
3965
0
    this->IssueDiagnostic(
3966
0
      cmDiagnostics::CMD_AUTHOR,
3967
0
      cmStrCat("Cannot set \"", var, "\": current scope has no parent."));
3968
0
    return;
3969
0
  }
3970
3971
0
#ifndef CMAKE_BOOTSTRAP
3972
0
  cmVariableWatch* vv = this->GetVariableWatch();
3973
0
  if (vv) {
3974
0
    vv->VariableAccessed(var, cmVariableWatch::VARIABLE_MODIFIED_ACCESS,
3975
0
                         varDef, this);
3976
0
  }
3977
0
#endif
3978
0
}
3979
3980
void cmMakefile::RaiseScope(std::vector<std::string> const& variables)
3981
0
{
3982
0
  for (auto const& varName : variables) {
3983
0
    if (this->IsNormalDefinitionSet(varName)) {
3984
0
      this->RaiseScope(varName, this->GetDefinition(varName));
3985
0
    } else {
3986
      // unset variable in parent scope
3987
0
      this->RaiseScope(varName, nullptr);
3988
0
    }
3989
0
  }
3990
0
}
3991
3992
cmTarget* cmMakefile::AddImportedTarget(std::string const& name,
3993
                                        cmStateEnums::TargetType type,
3994
                                        bool global)
3995
0
{
3996
  // Create the target.
3997
0
  auto target =
3998
0
    cm::make_unique<cmTarget>(name, type,
3999
0
                              global ? cmTarget::Visibility::ImportedGlobally
4000
0
                                     : cmTarget::Visibility::Imported,
4001
0
                              this, cmTarget::PerConfig::Yes);
4002
4003
  // Add to the set of available imported targets.
4004
0
  this->ImportedTargets[name] = target.get();
4005
0
  this->GetGlobalGenerator()->IndexTarget(target.get());
4006
0
  this->GetStateSnapshot().GetDirectory().AddImportedTargetName(name);
4007
4008
  // Transfer ownership to this cmMakefile object.
4009
0
  this->ImportedTargetsOwned.push_back(std::move(target));
4010
0
  return this->ImportedTargetsOwned.back().get();
4011
0
}
4012
4013
cmTarget* cmMakefile::AddForeignTarget(std::string const& origin,
4014
                                       std::string const& name)
4015
0
{
4016
0
  auto foreign_name = cmStrCat("@foreign_", origin, "::", name);
4017
0
  auto target = cm::make_unique<cmTarget>(
4018
0
    foreign_name, cmStateEnums::TargetType::INTERFACE_LIBRARY,
4019
0
    cmTarget::Visibility::Foreign, this, cmTarget::PerConfig::Yes);
4020
4021
0
  this->ImportedTargets[foreign_name] = target.get();
4022
0
  this->GetGlobalGenerator()->IndexTarget(target.get());
4023
0
  this->GetStateSnapshot().GetDirectory().AddImportedTargetName(foreign_name);
4024
4025
0
  this->ImportedTargetsOwned.push_back(std::move(target));
4026
0
  return this->ImportedTargetsOwned.back().get();
4027
0
}
4028
4029
cmTarget* cmMakefile::FindTargetToUse(
4030
  std::string const& name, cmStateEnums::TargetDomainSet domains) const
4031
0
{
4032
  // Look for an imported target.  These take priority because they
4033
  // are more local in scope and do not have to be globally unique.
4034
0
  auto targetName = name;
4035
0
  if (domains.contains(cmStateEnums::TargetDomain::ALIAS)) {
4036
    // Look for local alias targets.
4037
0
    auto alias = this->AliasTargets.find(name);
4038
0
    if (alias != this->AliasTargets.end()) {
4039
0
      targetName = alias->second;
4040
0
    }
4041
0
  }
4042
0
  auto const imported = this->ImportedTargets.find(targetName);
4043
4044
0
  bool const useForeign =
4045
0
    domains.contains(cmStateEnums::TargetDomain::FOREIGN);
4046
0
  bool const useNative = domains.contains(cmStateEnums::TargetDomain::NATIVE);
4047
4048
0
  if (imported != this->ImportedTargets.end()) {
4049
0
    if (imported->second->IsForeign() ? useForeign : useNative) {
4050
0
      return imported->second;
4051
0
    }
4052
0
  }
4053
4054
  // Look for a target built in this directory.
4055
0
  if (cmTarget* t = this->FindLocalNonAliasTarget(name)) {
4056
0
    if (t->IsForeign() ? useForeign : useNative) {
4057
0
      return t;
4058
0
    }
4059
0
  }
4060
4061
  // Look for a target built in this project.
4062
0
  return this->GetGlobalGenerator()->FindTarget(name, domains);
4063
0
}
4064
4065
bool cmMakefile::IsAlias(std::string const& name) const
4066
0
{
4067
0
  if (cm::contains(this->AliasTargets, name)) {
4068
0
    return true;
4069
0
  }
4070
0
  return this->GetGlobalGenerator()->IsAlias(name);
4071
0
}
4072
4073
bool cmMakefile::EnforceUniqueName(std::string const& name, std::string& msg,
4074
                                   bool isCustom) const
4075
0
{
4076
0
  if (this->IsAlias(name)) {
4077
0
    msg = cmStrCat("cannot create target \"", name,
4078
0
                   "\" because an alias with the same name already exists.");
4079
0
    return false;
4080
0
  }
4081
0
  if (cmTarget* existing = this->FindTargetToUse(name)) {
4082
    // The name given conflicts with an existing target.  Produce an
4083
    // error in a compatible way.
4084
0
    if (existing->IsImported()) {
4085
      // Imported targets were not supported in previous versions.
4086
      // This is new code, so we can make it an error.
4087
0
      msg = cmStrCat(
4088
0
        "cannot create target \"", name,
4089
0
        "\" because an imported target with the same name already exists.");
4090
0
      return false;
4091
0
    }
4092
4093
    // The conflict is with a non-imported target.
4094
    // Allow this if the user has requested support.
4095
0
    cmake* cm = this->GetCMakeInstance();
4096
0
    if (isCustom && existing->GetType() == cmStateEnums::UTILITY &&
4097
0
        this != existing->GetMakefile() &&
4098
0
        cm->GetState()->GetGlobalPropertyAsBool(
4099
0
          "ALLOW_DUPLICATE_CUSTOM_TARGETS")) {
4100
0
      return true;
4101
0
    }
4102
4103
    // Produce an error that tells the user how to work around the
4104
    // problem.
4105
0
    std::ostringstream e;
4106
0
    e << "cannot create target \"" << name
4107
0
      << "\" because another target with the same name already exists.  "
4108
0
         "The existing target is ";
4109
0
    switch (existing->GetType()) {
4110
0
      case cmStateEnums::EXECUTABLE:
4111
0
        e << "an executable ";
4112
0
        break;
4113
0
      case cmStateEnums::STATIC_LIBRARY:
4114
0
        e << "a static library ";
4115
0
        break;
4116
0
      case cmStateEnums::SHARED_LIBRARY:
4117
0
        e << "a shared library ";
4118
0
        break;
4119
0
      case cmStateEnums::MODULE_LIBRARY:
4120
0
        e << "a module library ";
4121
0
        break;
4122
0
      case cmStateEnums::UTILITY:
4123
0
        e << "a custom target ";
4124
0
        break;
4125
0
      case cmStateEnums::INTERFACE_LIBRARY:
4126
0
        e << "an interface library ";
4127
0
        break;
4128
0
      default:
4129
0
        break;
4130
0
    }
4131
0
    e << "created in source directory \""
4132
0
      << existing->GetMakefile()->GetCurrentSourceDirectory()
4133
0
      << "\".  "
4134
0
         "See documentation for policy CMP0002 for more details.";
4135
0
    msg = e.str();
4136
0
    return false;
4137
0
  }
4138
0
  return true;
4139
0
}
4140
4141
bool cmMakefile::EnforceUniqueDir(std::string const& srcPath,
4142
                                  std::string const& binPath) const
4143
0
{
4144
  // Make sure the binary directory is unique.
4145
0
  cmGlobalGenerator* gg = this->GetGlobalGenerator();
4146
0
  if (gg->BinaryDirectoryIsNew(binPath)) {
4147
0
    return true;
4148
0
  }
4149
0
  this->IssueMessage(MessageType::FATAL_ERROR,
4150
0
                     cmStrCat("The binary directory\n"
4151
0
                              "  ",
4152
0
                              binPath,
4153
0
                              "\n"
4154
0
                              "is already used to build a source directory.  "
4155
0
                              "It cannot be used to build source directory\n"
4156
0
                              "  ",
4157
0
                              srcPath,
4158
0
                              "\n"
4159
0
                              "Specify a unique binary directory name."));
4160
4161
0
  return false;
4162
0
}
4163
4164
static std::string const matchVariables[] = {
4165
  "CMAKE_MATCH_0", "CMAKE_MATCH_1", "CMAKE_MATCH_2", "CMAKE_MATCH_3",
4166
  "CMAKE_MATCH_4", "CMAKE_MATCH_5", "CMAKE_MATCH_6", "CMAKE_MATCH_7",
4167
  "CMAKE_MATCH_8", "CMAKE_MATCH_9"
4168
};
4169
4170
static std::string const nMatchesVariable = "CMAKE_MATCH_COUNT";
4171
4172
void cmMakefile::ClearMatches()
4173
0
{
4174
0
  cmValue nMatchesStr = this->GetDefinition(nMatchesVariable);
4175
0
  if (!nMatchesStr) {
4176
0
    return;
4177
0
  }
4178
0
  int nMatches = atoi(nMatchesStr->c_str());
4179
0
  for (int i = 0; i <= nMatches; i++) {
4180
0
    std::string const& var = matchVariables[i];
4181
0
    std::string const& s = this->GetSafeDefinition(var);
4182
0
    if (!s.empty()) {
4183
0
      this->AddDefinition(var, "");
4184
0
      this->MarkVariableAsUsed(var);
4185
0
    }
4186
0
  }
4187
0
  this->AddDefinition(nMatchesVariable, "0");
4188
0
  this->MarkVariableAsUsed(nMatchesVariable);
4189
0
}
4190
4191
void cmMakefile::StoreMatches(cmsys::RegularExpression& re)
4192
0
{
4193
0
  char highest = 0;
4194
0
  for (int i = 0; i < 10; i++) {
4195
0
    std::string const& m = re.match(i);
4196
0
    if (!m.empty()) {
4197
0
      std::string const& var = matchVariables[i];
4198
0
      this->AddDefinition(var, m);
4199
0
      this->MarkVariableAsUsed(var);
4200
0
      highest = static_cast<char>('0' + i);
4201
0
    }
4202
0
  }
4203
0
  char nMatches[] = { highest, '\0' };
4204
0
  this->AddDefinition(nMatchesVariable, nMatches);
4205
0
  this->MarkVariableAsUsed(nMatchesVariable);
4206
0
}
4207
4208
cmStateSnapshot cmMakefile::GetStateSnapshot() const
4209
0
{
4210
0
  return this->StateSnapshot;
4211
0
}
4212
4213
cmPolicies::PolicyStatus cmMakefile::GetPolicyStatus(cmPolicies::PolicyID id,
4214
                                                     bool parent_scope) const
4215
0
{
4216
0
  return this->StateSnapshot.GetPolicy(id, parent_scope);
4217
0
}
4218
4219
bool cmMakefile::PolicyOptionalWarningEnabled(std::string const& var) const
4220
0
{
4221
  // Check for an explicit CMAKE_POLICY_WARNING_CMP<NNNN> setting.
4222
0
  if (cmValue val = this->GetDefinition(var)) {
4223
0
    return val.IsOn();
4224
0
  }
4225
  // Enable optional policy warnings with --debug-output, --trace,
4226
  // or --trace-expand.
4227
0
  cmake* cm = this->GetCMakeInstance();
4228
0
  return cm->GetDebugOutput() || cm->GetTrace();
4229
0
}
4230
4231
bool cmMakefile::SetPolicy(char const* id, cmPolicies::PolicyStatus status)
4232
0
{
4233
0
  cmPolicies::PolicyID pid;
4234
0
  if (!cmPolicies::GetPolicyID(id, /* out */ pid)) {
4235
0
    this->IssueMessage(
4236
0
      MessageType::FATAL_ERROR,
4237
0
      cmStrCat("Policy \"", id, "\" is not known to this version of CMake."));
4238
0
    return false;
4239
0
  }
4240
0
  return this->SetPolicy(pid, status);
4241
0
}
4242
4243
bool cmMakefile::SetPolicy(cmPolicies::PolicyID id,
4244
                           cmPolicies::PolicyStatus status)
4245
0
{
4246
  // A removed policy may be set only to NEW.
4247
0
  if (cmPolicies::IsRemoved(id) && status != cmPolicies::NEW) {
4248
0
    std::string msg = cmPolicies::GetRemovedPolicyError(id);
4249
0
    this->IssueMessage(MessageType::FATAL_ERROR, msg);
4250
0
    return false;
4251
0
  }
4252
4253
  // Deprecate old policies.
4254
0
  if (status == cmPolicies::OLD && id <= cmPolicies::CMP0161 &&
4255
0
      !(this->GetCMakeInstance()->GetIsInTryCompile() &&
4256
0
        (
4257
          // Policies set by cmCoreTryCompile::TryCompileCode.
4258
0
          id == cmPolicies::CMP0083 || id == cmPolicies::CMP0091 ||
4259
0
          id == cmPolicies::CMP0104 || id == cmPolicies::CMP0123 ||
4260
0
          id == cmPolicies::CMP0126 || id == cmPolicies::CMP0128 ||
4261
0
          id == cmPolicies::CMP0136 || id == cmPolicies::CMP0141 ||
4262
0
          id == cmPolicies::CMP0155 || id == cmPolicies::CMP0157))) {
4263
0
    std::unique_ptr<PolicyPushPop> ps;
4264
0
    std::unique_ptr<DiagnosticPushPop> ds;
4265
4266
0
    cmPolicies::PolicyStatus const cmp0218 =
4267
0
      this->GetPolicyStatus(cmPolicies::CMP0218);
4268
0
    if (cmp0218 != cmPolicies::NEW) {
4269
0
      if (cmp0218 != cmPolicies::OLD) {
4270
        // Suppress warnings about using old variables.
4271
0
        ps = cm::make_unique<PolicyPushPop>(this);
4272
0
        this->SetPolicy(cmPolicies::CMP0218, cmPolicies::OLD);
4273
0
      }
4274
4275
0
      ds = cm::make_unique<DiagnosticPushPop>(this);
4276
4277
      // Use old variables to determine diagnostic action.
4278
0
      cmValue const warn = this->GetDefinition("CMAKE_WARN_DEPRECATED");
4279
0
      if (warn.IsSet() && !warn.IsOn()) {
4280
0
        this->SetDiagnostic(cmDiagnostics::CMD_DEPRECATED,
4281
0
                            cmDiagnostics::Ignore);
4282
0
      } else if (this->IsOn("CMAKE_ERROR_DEPRECATED")) {
4283
0
        this->SetDiagnostic(cmDiagnostics::CMD_DEPRECATED,
4284
0
                            cmDiagnostics::SendError);
4285
0
      } else {
4286
0
        this->SetDiagnostic(cmDiagnostics::CMD_DEPRECATED,
4287
0
                            cmDiagnostics::Warn);
4288
0
      }
4289
0
    }
4290
4291
0
    this->IssueDiagnostic(cmDiagnostics::CMD_DEPRECATED,
4292
0
                          cmPolicies::GetPolicyDeprecatedWarning(id));
4293
0
  }
4294
4295
0
  this->StateSnapshot.SetPolicy(id, status);
4296
4297
  // Handle CMAKE_PARENT_LIST_FILE for CMP0198 policy changes
4298
0
  if (id == cmPolicies::CMP0198 &&
4299
0
      this->GetCMakeInstance()->GetState()->GetRole() ==
4300
0
        cmState::Role::Project) {
4301
0
    this->UpdateParentListFileVariable();
4302
0
  }
4303
4304
0
  return true;
4305
0
}
4306
4307
cmMakefile::PolicyPushPop::PolicyPushPop(cmMakefile* m)
4308
0
  : Makefile(m)
4309
0
{
4310
0
  this->Makefile->PushPolicy();
4311
0
}
4312
4313
cmMakefile::PolicyPushPop::~PolicyPushPop()
4314
0
{
4315
0
  this->Makefile->PopPolicy();
4316
0
}
4317
4318
void cmMakefile::PushPolicy(bool weak, cmPolicies::PolicyMap const& pm)
4319
1
{
4320
1
  this->StateSnapshot.PushPolicy(pm, weak);
4321
1
}
4322
4323
void cmMakefile::PopPolicy()
4324
0
{
4325
0
  if (!this->StateSnapshot.PopPolicy()) {
4326
0
    this->IssueMessage(MessageType::FATAL_ERROR,
4327
0
                       "cmake_policy POP without matching PUSH");
4328
0
  }
4329
0
}
4330
4331
cmDiagnosticAction cmMakefile::GetDiagnosticAction(
4332
  cmDiagnosticCategory category) const
4333
0
{
4334
0
  return this->StateSnapshot.GetDiagnostic(category);
4335
0
}
4336
4337
bool cmMakefile::SetDiagnostic(cmDiagnosticCategory category,
4338
                               cmDiagnosticAction action, bool recursive)
4339
0
{
4340
0
  this->StateSnapshot.SetDiagnostic(category, action, recursive);
4341
0
  return true;
4342
0
}
4343
4344
bool cmMakefile::PromoteDiagnostic(cmDiagnosticCategory category,
4345
                                   cmDiagnosticAction action, bool recursive)
4346
0
{
4347
0
  this->StateSnapshot.PromoteDiagnostic(category, action, recursive);
4348
0
  return true;
4349
0
}
4350
4351
bool cmMakefile::DemoteDiagnostic(cmDiagnosticCategory category,
4352
                                  cmDiagnosticAction action, bool recursive)
4353
0
{
4354
0
  this->StateSnapshot.DemoteDiagnostic(category, action, recursive);
4355
0
  return true;
4356
0
}
4357
4358
cmMakefile::DiagnosticPushPop::DiagnosticPushPop(cmMakefile* m)
4359
0
  : Makefile(m)
4360
0
{
4361
0
  this->Makefile->PushDiagnostic();
4362
0
}
4363
4364
cmMakefile::DiagnosticPushPop::~DiagnosticPushPop()
4365
0
{
4366
0
  this->Makefile->PopDiagnostic();
4367
0
}
4368
4369
void cmMakefile::PushDiagnostic(bool weak, cmDiagnostics::DiagnosticMap dm)
4370
1
{
4371
1
  this->StateSnapshot.PushDiagnostic(dm, weak);
4372
1
}
4373
4374
void cmMakefile::PopDiagnostic()
4375
0
{
4376
0
  if (!this->StateSnapshot.PopDiagnostic()) {
4377
0
    this->IssueMessage(MessageType::FATAL_ERROR,
4378
0
                       "cmake_diagnostic POP without matching PUSH");
4379
0
  }
4380
0
}
4381
4382
void cmMakefile::PopSnapshot(bool reportError)
4383
1
{
4384
  // cmStateSnapshot manages nested policy/diagnostic scopes within it.
4385
  // Since the scope corresponding to the snapshot is closing,
4386
  // reject any still-open nested policy/diagnostic scopes with an error.
4387
1
  for (;;) {
4388
1
    if (this->StateSnapshot.CanPopPolicyScope()) {
4389
0
      if (reportError) {
4390
0
        this->IssueMessage(MessageType::FATAL_ERROR,
4391
0
                           "cmake_policy PUSH without matching POP");
4392
0
        reportError = false;
4393
0
      }
4394
0
      this->PopPolicy();
4395
1
    } else if (this->StateSnapshot.CanPopDiagnosticScope()) {
4396
0
      if (reportError) {
4397
0
        this->IssueMessage(MessageType::FATAL_ERROR,
4398
0
                           "cmake_diagnostic PUSH without matching POP");
4399
0
        reportError = false;
4400
0
      }
4401
0
      this->PopDiagnostic();
4402
1
    } else {
4403
1
      break;
4404
1
    }
4405
1
  }
4406
4407
1
  this->StateSnapshot = this->GetState()->Pop(this->StateSnapshot);
4408
1
  assert(this->StateSnapshot.IsValid());
4409
1
}
4410
4411
bool cmMakefile::SetPolicyVersion(std::string const& version_min,
4412
                                  std::string const& version_max)
4413
0
{
4414
0
  return cmPolicies::ApplyPolicyVersion(this, version_min, version_max,
4415
0
                                        cmPolicies::WarnCompat::On);
4416
0
}
4417
4418
void cmMakefile::UpdateParentListFileVariable()
4419
0
{
4420
  // CMP0198 determines CMAKE_PARENT_LIST_FILE behavior in CMakeLists.txt
4421
0
  if (this->GetPolicyStatus(cmPolicies::CMP0198) == cmPolicies::NEW) {
4422
0
    this->RemoveDefinition(kCMAKE_PARENT_LIST_FILE);
4423
0
  } else {
4424
0
    std::string currentSourceDir =
4425
0
      this->StateSnapshot.GetDirectory().GetCurrentSource();
4426
0
    std::string currentStart =
4427
0
      this->GetCMakeInstance()->GetCMakeListFile(currentSourceDir);
4428
4429
0
    this->AddDefinition(kCMAKE_PARENT_LIST_FILE, currentStart);
4430
0
  }
4431
0
}
4432
4433
cmMakefile::VariablePushPop::VariablePushPop(cmMakefile* m)
4434
0
  : Makefile(m)
4435
0
{
4436
0
  this->Makefile->StateSnapshot =
4437
0
    this->Makefile->GetState()->CreateVariableScopeSnapshot(
4438
0
      this->Makefile->StateSnapshot);
4439
0
}
4440
4441
cmMakefile::VariablePushPop::~VariablePushPop()
4442
0
{
4443
0
  this->Makefile->PopSnapshot();
4444
0
}
4445
4446
void cmMakefile::RecordPolicies(cmPolicies::PolicyMap& pm) const
4447
0
{
4448
  /* Record the setting of every policy.  */
4449
0
  using PolicyID = cmPolicies::PolicyID;
4450
0
  for (PolicyID pid = cmPolicies::CMP0000; pid != cmPolicies::CMPCOUNT;
4451
0
       pid = static_cast<PolicyID>(pid + 1)) {
4452
0
    pm.Set(pid, this->GetPolicyStatus(pid));
4453
0
  }
4454
0
}
4455
4456
void cmMakefile::RecordDiagnostics(cmDiagnostics::DiagnosticMap& dm) const
4457
0
{
4458
  /* Record the setting of every diagnostic category.  */
4459
0
  for (unsigned n = 0; n < cmDiagnostics::CategoryCount; ++n) {
4460
0
    cmDiagnosticCategory const dc = static_cast<cmDiagnosticCategory>(n);
4461
0
    dm[dc] = this->GetDiagnosticAction(dc);
4462
0
  }
4463
0
}
4464
4465
cmMakefile::FunctionPushPop::FunctionPushPop(cmMakefile* mf,
4466
                                             std::string const& fileName,
4467
                                             cmPolicies::PolicyMap const& pm,
4468
                                             cmDiagnostics::DiagnosticMap dm)
4469
0
  : Makefile(mf)
4470
0
{
4471
0
  this->Makefile->PushFunctionScope(fileName, pm, dm);
4472
0
}
4473
4474
cmMakefile::FunctionPushPop::~FunctionPushPop()
4475
0
{
4476
0
  this->Makefile->PopFunctionScope(this->ReportError);
4477
0
}
4478
4479
cmMakefile::MacroPushPop::MacroPushPop(cmMakefile* mf,
4480
                                       std::string const& fileName,
4481
                                       cmPolicies::PolicyMap const& pm,
4482
                                       cmDiagnostics::DiagnosticMap dm)
4483
0
  : Makefile(mf)
4484
0
{
4485
0
  this->Makefile->PushMacroScope(fileName, pm, dm);
4486
0
}
4487
4488
cmMakefile::MacroPushPop::~MacroPushPop()
4489
0
{
4490
0
  this->Makefile->PopMacroScope(this->ReportError);
4491
0
}
4492
4493
cmMakefile::FindPackageStackRAII::FindPackageStackRAII(
4494
  cmMakefile* mf, std::string const& name,
4495
  std::shared_ptr<cmPackageInformation const> pkgInfo)
4496
0
  : Makefile(mf)
4497
0
{
4498
0
  this->Makefile->FindPackageStack =
4499
0
    this->Makefile->FindPackageStack.Push(cmFindPackageCall{
4500
0
      name,
4501
0
      std::move(pkgInfo),
4502
0
      this->Makefile->FindPackageStackNextIndex,
4503
0
    });
4504
0
  this->Makefile->FindPackageStackNextIndex++;
4505
0
}
4506
4507
cmMakefile::FindPackageStackRAII::~FindPackageStackRAII()
4508
0
{
4509
0
  this->Makefile->FindPackageStackNextIndex =
4510
0
    this->Makefile->FindPackageStack.Top().Index + 1;
4511
0
  this->Makefile->FindPackageStack = this->Makefile->FindPackageStack.Pop();
4512
4513
0
  if (!this->Makefile->FindPackageStack.Empty()) {
4514
    // We have just finished an inner package found as a dependency of an
4515
    // outer package.  Targets created in the outer package after this
4516
    // point may depend on the inner package, so if they are exported,
4517
    // their find_dependency call for the outer package should be
4518
    // ordered after the find_dependency call for the inner package.
4519
    //
4520
    // Any targets created by the outer package before the inner package
4521
    // was loaded will have already saved a copy of the outer package
4522
    // stack with its original index.  Replace the top entry with a new
4523
    // one representing the same outer package with a new index.
4524
0
    cmFindPackageCall outer = this->Makefile->FindPackageStack.Top();
4525
0
    this->Makefile->FindPackageStack = this->Makefile->FindPackageStack.Pop();
4526
4527
0
    outer.Index = this->Makefile->FindPackageStackNextIndex;
4528
0
    this->Makefile->FindPackageStackNextIndex++;
4529
4530
0
    this->Makefile->FindPackageStack =
4531
0
      this->Makefile->FindPackageStack.Push(outer);
4532
0
  }
4533
0
}
4534
4535
cmMakefile::DebugFindPkgRAII::DebugFindPkgRAII(cmMakefile* mf,
4536
                                               std::string const& pkg)
4537
0
  : Makefile(mf)
4538
0
  , OldValue(this->Makefile->DebugFindPkg)
4539
0
{
4540
0
  this->Makefile->DebugFindPkg =
4541
0
    this->Makefile->GetCMakeInstance()->GetDebugFindPkgOutput(pkg);
4542
0
}
4543
4544
cmMakefile::DebugFindPkgRAII::~DebugFindPkgRAII()
4545
0
{
4546
0
  this->Makefile->DebugFindPkg = this->OldValue;
4547
0
}
4548
4549
bool cmMakefile::GetDebugFindPkgMode() const
4550
0
{
4551
0
  return this->DebugFindPkg;
4552
0
}