Coverage Report

Created: 2026-07-30 06:52

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 == cm::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() == cm::TargetType::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() == cm::TargetType::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 cm::TargetType::UTILITY:
2034
0
    case cm::TargetType::GLOBAL_TARGET:
2035
0
    case cm::TargetType::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, cm::TargetType type,
2074
                                 std::vector<std::string> const& srcs,
2075
                                 bool excludeFromAll)
2076
0
{
2077
0
  assert(type == cm::TargetType::STATIC_LIBRARY ||
2078
0
         type == cm::TargetType::SHARED_LIBRARY ||
2079
0
         type == cm::TargetType::MODULE_LIBRARY ||
2080
0
         type == cm::TargetType::OBJECT_LIBRARY ||
2081
0
         type == cm::TargetType::INTERFACE_LIBRARY);
2082
2083
0
  cmTarget* target = this->AddNewTarget(type, lname);
2084
  // Clear its dependencies. Otherwise, dependencies might persist
2085
  // over changes in CMakeLists.txt, making the information stale and
2086
  // hence useless.
2087
0
  target->ClearDependencyInformation(*this);
2088
0
  if (excludeFromAll) {
2089
0
    target->SetProperty("EXCLUDE_FROM_ALL", "TRUE");
2090
0
  }
2091
0
  target->AddSources(srcs);
2092
0
  this->AddGlobalLinkInformation(*target);
2093
0
  return target;
2094
0
}
2095
2096
cmTarget* cmMakefile::AddExecutable(std::string const& exeName,
2097
                                    std::vector<std::string> const& srcs,
2098
                                    bool excludeFromAll)
2099
0
{
2100
0
  cmTarget* target = this->AddNewTarget(cm::TargetType::EXECUTABLE, exeName);
2101
0
  if (excludeFromAll) {
2102
0
    target->SetProperty("EXCLUDE_FROM_ALL", "TRUE");
2103
0
  }
2104
0
  target->AddSources(srcs);
2105
0
  this->AddGlobalLinkInformation(*target);
2106
0
  return target;
2107
0
}
2108
2109
cmTarget* cmMakefile::AddNewTarget(cm::TargetType type,
2110
                                   std::string const& name)
2111
0
{
2112
0
  return &this->CreateNewTarget(name, type).first;
2113
0
}
2114
2115
cmTarget* cmMakefile::AddSynthesizedTarget(cm::TargetType type,
2116
                                           std::string const& name)
2117
0
{
2118
0
  return &this
2119
0
            ->CreateNewTarget(name, type, cmTarget::PerConfig::Yes,
2120
0
                              cmTarget::Visibility::Generated)
2121
0
            .first;
2122
0
}
2123
2124
std::pair<cmTarget&, bool> cmMakefile::CreateNewTarget(
2125
  std::string const& name, cm::TargetType type, cmTarget::PerConfig perConfig,
2126
  cmTarget::Visibility vis)
2127
0
{
2128
0
  auto ib =
2129
0
    this->Targets.emplace(name, cmTarget(name, type, vis, this, perConfig));
2130
0
  auto it = ib.first;
2131
0
  if (!ib.second) {
2132
0
    return std::make_pair(std::ref(it->second), false);
2133
0
  }
2134
0
  this->OrderedTargets.push_back(&it->second);
2135
0
  this->GetGlobalGenerator()->IndexTarget(&it->second);
2136
0
  this->GetStateSnapshot().GetDirectory().AddNormalTargetName(name);
2137
0
  return std::make_pair(std::ref(it->second), true);
2138
0
}
2139
2140
cmTarget* cmMakefile::AddNewUtilityTarget(std::string const& utilityName,
2141
                                          bool excludeFromAll)
2142
0
{
2143
0
  cmTarget* target = this->AddNewTarget(cm::TargetType::UTILITY, utilityName);
2144
0
  if (excludeFromAll) {
2145
0
    target->SetProperty("EXCLUDE_FROM_ALL", "TRUE");
2146
0
  }
2147
0
  return target;
2148
0
}
2149
2150
#if !defined(CMAKE_BOOTSTRAP)
2151
2152
void cmMakefile::ResolveSourceGroupGenex(cmLocalGenerator* lg)
2153
0
{
2154
0
  for (auto const& sourceGroup : this->SourceGroups) {
2155
0
    sourceGroup->ResolveGenex(lg, {});
2156
0
  }
2157
0
}
2158
2159
cmSourceGroup* cmMakefile::GetSourceGroup(
2160
  std::vector<std::string> const& name) const
2161
14
{
2162
14
  cmSourceGroup* sg = nullptr;
2163
2164
  // first look for source group starting with the same as the one we want
2165
49
  for (auto const& srcGroup : this->SourceGroups) {
2166
49
    std::string const& sgName = srcGroup->GetName();
2167
49
    if (sgName == name[0]) {
2168
7
      sg = srcGroup.get();
2169
7
      break;
2170
7
    }
2171
49
  }
2172
2173
14
  if (sg) {
2174
    // iterate through its children to find match source group
2175
7
    for (unsigned int i = 1; i < name.size(); ++i) {
2176
0
      sg = sg->LookupChild(name[i]);
2177
0
      if (!sg) {
2178
0
        break;
2179
0
      }
2180
0
    }
2181
7
  }
2182
14
  return sg;
2183
14
}
2184
2185
void cmMakefile::AddSourceGroup(std::string const& name, cm::string_view regex)
2186
7
{
2187
7
  std::vector<std::string> nameVector;
2188
7
  nameVector.push_back(name);
2189
7
  this->AddSourceGroup(nameVector, regex);
2190
7
}
2191
2192
void cmMakefile::AddSourceGroup(std::vector<std::string> const& name,
2193
                                cm::string_view regex)
2194
7
{
2195
7
  cmSourceGroup* sg = nullptr;
2196
7
  std::vector<std::string> currentName;
2197
7
  int i = 0;
2198
7
  int const lastElement = static_cast<int>(name.size() - 1);
2199
14
  for (i = lastElement; i >= 0; --i) {
2200
7
    currentName.assign(name.begin(), name.begin() + i + 1);
2201
7
    sg = this->GetSourceGroup(currentName);
2202
7
    if (sg) {
2203
0
      break;
2204
0
    }
2205
7
  }
2206
2207
  // i now contains the index of the last found component
2208
7
  if (i == lastElement) {
2209
    // group already exists, replace its regular expression
2210
0
    if (regex.data() && sg) {
2211
      // We only want to set the regular expression.  If there are already
2212
      // source files in the group, we don't want to remove them.
2213
0
      sg->SetGroupRegex(regex);
2214
0
    }
2215
0
    return;
2216
0
  }
2217
7
  if (i == -1) {
2218
    // group does not exist nor belong to any existing group
2219
    // add its first component
2220
7
    this->SourceGroups.emplace_back(
2221
7
      cm::make_unique<cmSourceGroup>(name[0], regex));
2222
7
    sg = this->GetSourceGroup(currentName);
2223
7
    i = 0; // last component found
2224
7
  }
2225
7
  if (!sg) {
2226
0
    cmSystemTools::Error("Could not create source group ");
2227
0
    return;
2228
0
  }
2229
  // build the whole source group path
2230
7
  for (++i; i <= lastElement; ++i) {
2231
0
    sg->AddChild(cm::make_unique<cmSourceGroup>(name[i], cm::string_view{},
2232
0
                                                sg->GetFullName()));
2233
0
    sg = sg->LookupChild(name[i]);
2234
0
  }
2235
2236
7
  sg->SetGroupRegex(regex);
2237
7
}
2238
2239
cmSourceGroup* cmMakefile::GetOrCreateSourceGroup(
2240
  std::vector<std::string> const& folders)
2241
0
{
2242
0
  cmSourceGroup* sg = this->GetSourceGroup(folders);
2243
0
  if (!sg) {
2244
0
    this->AddSourceGroup(folders);
2245
0
    sg = this->GetSourceGroup(folders);
2246
0
  }
2247
0
  return sg;
2248
0
}
2249
2250
cmSourceGroup* cmMakefile::GetOrCreateSourceGroup(std::string const& name)
2251
0
{
2252
0
  auto p = this->GetDefinition("SOURCE_GROUP_DELIMITER");
2253
0
  return this->GetOrCreateSourceGroup(
2254
0
    cmTokenize(name, p ? cm::string_view(*p) : R"(\/)"_s));
2255
0
}
2256
#endif
2257
2258
bool cmMakefile::IsOn(std::string const& name) const
2259
0
{
2260
0
  return this->GetDefinition(name).IsOn();
2261
0
}
2262
2263
bool cmMakefile::IsSet(std::string const& name) const
2264
0
{
2265
0
  cmValue value = this->GetDefinition(name);
2266
0
  if (!value) {
2267
0
    return false;
2268
0
  }
2269
2270
0
  if (value->empty()) {
2271
0
    return false;
2272
0
  }
2273
2274
0
  if (cmIsNOTFOUND(*value)) {
2275
0
    return false;
2276
0
  }
2277
2278
0
  return true;
2279
0
}
2280
2281
bool cmMakefile::PlatformIs32Bit() const
2282
0
{
2283
0
  if (cmValue plat_abi = this->GetDefinition("CMAKE_INTERNAL_PLATFORM_ABI")) {
2284
0
    if (*plat_abi == "ELF X32"_s) {
2285
0
      return false;
2286
0
    }
2287
0
  }
2288
0
  if (cmValue sizeof_dptr = this->GetDefinition("CMAKE_SIZEOF_VOID_P")) {
2289
0
    return atoi(sizeof_dptr->c_str()) == 4;
2290
0
  }
2291
0
  return false;
2292
0
}
2293
2294
bool cmMakefile::PlatformIs64Bit() const
2295
0
{
2296
0
  if (cmValue sizeof_dptr = this->GetDefinition("CMAKE_SIZEOF_VOID_P")) {
2297
0
    return atoi(sizeof_dptr->c_str()) == 8;
2298
0
  }
2299
0
  return false;
2300
0
}
2301
2302
bool cmMakefile::PlatformIsx32() const
2303
0
{
2304
0
  if (cmValue plat_abi = this->GetDefinition("CMAKE_INTERNAL_PLATFORM_ABI")) {
2305
0
    if (*plat_abi == "ELF X32"_s) {
2306
0
      return true;
2307
0
    }
2308
0
  }
2309
0
  return false;
2310
0
}
2311
2312
cmMakefile::AppleSDK cmMakefile::GetAppleSDKType() const
2313
0
{
2314
0
  std::string sdkRoot;
2315
0
  sdkRoot = this->GetSafeDefinition("CMAKE_OSX_SYSROOT");
2316
0
  sdkRoot = cmSystemTools::LowerCase(sdkRoot);
2317
2318
0
  struct
2319
0
  {
2320
0
    std::string name;
2321
0
    AppleSDK sdk;
2322
0
  } const sdkDatabase[]{
2323
0
    { "appletvos", AppleSDK::AppleTVOS },
2324
0
    { "appletvsimulator", AppleSDK::AppleTVSimulator },
2325
0
    { "iphoneos", AppleSDK::IPhoneOS },
2326
0
    { "iphonesimulator", AppleSDK::IPhoneSimulator },
2327
0
    { "watchos", AppleSDK::WatchOS },
2328
0
    { "watchsimulator", AppleSDK::WatchSimulator },
2329
0
    { "xros", AppleSDK::XROS },
2330
0
    { "xrsimulator", AppleSDK::XRSimulator },
2331
0
  };
2332
2333
0
  for (auto const& entry : sdkDatabase) {
2334
0
    if (cmHasPrefix(sdkRoot, entry.name) ||
2335
0
        sdkRoot.find(cmStrCat('/', entry.name)) != std::string::npos) {
2336
0
      return entry.sdk;
2337
0
    }
2338
0
  }
2339
2340
0
  return AppleSDK::MacOS;
2341
0
}
2342
2343
bool cmMakefile::PlatformIsAppleEmbedded() const
2344
0
{
2345
0
  return this->GetAppleSDKType() != AppleSDK::MacOS;
2346
0
}
2347
2348
bool cmMakefile::PlatformIsAppleSimulator() const
2349
0
{
2350
0
  return std::set<AppleSDK>{
2351
0
    AppleSDK::AppleTVSimulator,
2352
0
    AppleSDK::IPhoneSimulator,
2353
0
    AppleSDK::WatchSimulator,
2354
0
    AppleSDK::XRSimulator,
2355
0
  }
2356
0
    .count(this->GetAppleSDKType());
2357
0
}
2358
2359
bool cmMakefile::PlatformIsAppleCatalyst() const
2360
0
{
2361
0
  std::string systemName;
2362
0
  systemName = this->GetSafeDefinition("CMAKE_SYSTEM_NAME");
2363
0
  systemName = cmSystemTools::LowerCase(systemName);
2364
0
  return systemName == "ios" && this->GetAppleSDKType() == AppleSDK::MacOS;
2365
0
}
2366
2367
bool cmMakefile::PlatformSupportsAppleTextStubs() const
2368
0
{
2369
0
  return this->IsOn("APPLE") && this->IsSet("CMAKE_TAPI");
2370
0
}
2371
2372
char const* cmMakefile::GetSONameFlag(std::string const& language) const
2373
0
{
2374
0
  std::string name = "CMAKE_SHARED_LIBRARY_SONAME";
2375
0
  if (!language.empty()) {
2376
0
    name += "_";
2377
0
    name += language;
2378
0
  }
2379
0
  name += "_FLAG";
2380
0
  return this->GetDefinition(name).GetCStr();
2381
0
}
2382
2383
bool cmMakefile::CanIWriteThisFile(std::string const& fileName) const
2384
0
{
2385
0
  if (!this->IsOn("CMAKE_DISABLE_SOURCE_CHANGES")) {
2386
0
    return true;
2387
0
  }
2388
  // If we are doing an in-source build, then the test will always fail
2389
0
  if (cmSystemTools::SameFile(this->GetHomeDirectory(),
2390
0
                              this->GetHomeOutputDirectory())) {
2391
0
    return !this->IsOn("CMAKE_DISABLE_IN_SOURCE_BUILD");
2392
0
  }
2393
2394
0
  return !cmSystemTools::IsSubDirectory(fileName, this->GetHomeDirectory()) ||
2395
0
    cmSystemTools::IsSubDirectory(fileName, this->GetHomeOutputDirectory()) ||
2396
0
    cmSystemTools::SameFile(fileName, this->GetHomeOutputDirectory());
2397
0
}
2398
2399
std::string const& cmMakefile::GetRequiredDefinition(
2400
  std::string const& name) const
2401
0
{
2402
0
  static std::string const empty;
2403
0
  cmValue def = this->GetDefinition(name);
2404
0
  if (!def) {
2405
0
    cmSystemTools::Error("Error required internal CMake variable not "
2406
0
                         "set, cmake may not be built correctly.\n"
2407
0
                         "Missing variable is:\n" +
2408
0
                         name);
2409
0
    return empty;
2410
0
  }
2411
0
  return *def;
2412
0
}
2413
2414
bool cmMakefile::IsDefinitionSet(std::string const& name) const
2415
0
{
2416
0
  cmValue def = this->StateSnapshot.GetDefinition(name);
2417
0
  if (!def) {
2418
0
    def = this->GetState()->GetInitializedCacheValue(name);
2419
0
  }
2420
0
#ifndef CMAKE_BOOTSTRAP
2421
0
  if (cmVariableWatch* vv = this->GetVariableWatch()) {
2422
0
    if (!def) {
2423
0
      vv->VariableAccessed(
2424
0
        name, cmVariableWatch::UNKNOWN_VARIABLE_DEFINED_ACCESS, nullptr, this);
2425
0
    }
2426
0
  }
2427
0
#endif
2428
0
  return def != nullptr;
2429
0
}
2430
2431
bool cmMakefile::IsNormalDefinitionSet(std::string const& name) const
2432
0
{
2433
0
  cmValue def = this->StateSnapshot.GetDefinition(name);
2434
0
#ifndef CMAKE_BOOTSTRAP
2435
0
  if (cmVariableWatch* vv = this->GetVariableWatch()) {
2436
0
    if (!def) {
2437
0
      vv->VariableAccessed(
2438
0
        name, cmVariableWatch::UNKNOWN_VARIABLE_DEFINED_ACCESS, nullptr, this);
2439
0
    }
2440
0
  }
2441
0
#endif
2442
0
  return def != nullptr;
2443
0
}
2444
2445
cmValue cmMakefile::GetDefinition(std::string const& name) const
2446
2
{
2447
2
  cmValue def = this->StateSnapshot.GetDefinition(name);
2448
2
  if (!def) {
2449
2
    def = this->GetState()->GetInitializedCacheValue(name);
2450
2
  }
2451
2
#ifndef CMAKE_BOOTSTRAP
2452
2
  cmVariableWatch* vv = this->GetVariableWatch();
2453
2
  if (vv) {
2454
2
    bool const watch_function_executed =
2455
2
      vv->VariableAccessed(name,
2456
2
                           def ? cmVariableWatch::VARIABLE_READ_ACCESS
2457
2
                               : cmVariableWatch::UNKNOWN_VARIABLE_READ_ACCESS,
2458
2
                           def.GetCStr(), this);
2459
2460
2
    if (watch_function_executed) {
2461
      // A callback was executed and may have caused re-allocation of the
2462
      // variable storage.  Look it up again for now.
2463
      // FIXME: Refactor variable storage to avoid this problem.
2464
0
      def = this->StateSnapshot.GetDefinition(name);
2465
0
      if (!def) {
2466
0
        def = this->GetState()->GetInitializedCacheValue(name);
2467
0
      }
2468
0
    }
2469
2
  }
2470
2
#endif
2471
2
  return def;
2472
2
}
2473
2474
std::string const& cmMakefile::GetSafeDefinition(std::string const& name) const
2475
0
{
2476
0
  return this->GetDefinition(name);
2477
0
}
2478
2479
std::vector<std::string> cmMakefile::GetDefinitions() const
2480
0
{
2481
0
  std::vector<std::string> res = this->StateSnapshot.ClosureKeys();
2482
0
  cm::append(res, this->GetState()->GetCacheEntryKeys());
2483
0
  std::sort(res.begin(), res.end());
2484
0
  return res;
2485
0
}
2486
2487
std::string const& cmMakefile::ExpandVariablesInString(
2488
  std::string& source) const
2489
0
{
2490
0
  return this->ExpandVariablesInString(source, false, false);
2491
0
}
2492
2493
std::string const& cmMakefile::ExpandVariablesInString(
2494
  std::string& source, bool escapeQuotes, bool noEscapes, bool atOnly,
2495
  char const* filename, long line, bool removeEmpty, bool replaceAt) const
2496
0
{
2497
  // Sanity check the @ONLY mode.
2498
0
  if (atOnly && (!noEscapes || !removeEmpty)) {
2499
    // This case should never be called.  At-only is for
2500
    // configure-file/string which always does no escapes.
2501
0
    this->IssueMessage(MessageType::INTERNAL_ERROR,
2502
0
                       "ExpandVariablesInString @ONLY called "
2503
0
                       "on something with escapes.");
2504
0
    return source;
2505
0
  }
2506
2507
0
  std::string errorstr;
2508
0
  MessageType mtype = this->ExpandVariablesInStringImpl(
2509
0
    errorstr, source, escapeQuotes, noEscapes, atOnly, filename, line,
2510
0
    replaceAt);
2511
0
  if (mtype != MessageType::LOG) {
2512
0
    if (mtype == MessageType::FATAL_ERROR) {
2513
0
      cmSystemTools::SetFatalErrorOccurred();
2514
0
    }
2515
0
    this->IssueMessage(mtype, errorstr);
2516
0
  }
2517
2518
0
  return source;
2519
0
}
2520
2521
enum t_domain
2522
{
2523
  NORMAL,
2524
  ENVIRONMENT,
2525
  CACHE
2526
};
2527
2528
struct t_lookup
2529
{
2530
  t_domain domain = NORMAL;
2531
  size_t loc = 0;
2532
};
2533
2534
bool cmMakefile::IsProjectFile(char const* filename) const
2535
0
{
2536
0
  std::string const& cmakeRoot = cmSystemTools::GetCMakeRoot();
2537
0
  if (cmSystemTools::IsSubDirectory(filename, cmakeRoot) &&
2538
0
      (cmSystemTools::IsSubDirectory(cmakeRoot, this->GetHomeDirectory()) ||
2539
0
       cmSystemTools::IsSubDirectory(cmakeRoot,
2540
0
                                     this->GetHomeOutputDirectory()))) {
2541
0
    return false;
2542
0
  }
2543
0
  return cmSystemTools::IsSubDirectory(filename, this->GetHomeDirectory()) ||
2544
0
    (cmSystemTools::IsSubDirectory(filename, this->GetHomeOutputDirectory()) &&
2545
0
     !cmSystemTools::IsSubDirectory(filename, "/CMakeFiles"));
2546
0
}
2547
2548
size_t cmMakefile::GetRecursionDepthLimit() const
2549
0
{
2550
0
  size_t depth = CMake_DEFAULT_RECURSION_LIMIT;
2551
0
  if (cmValue depthStr =
2552
0
        this->GetDefinition("CMAKE_MAXIMUM_RECURSION_DEPTH")) {
2553
0
    unsigned long depthUL;
2554
0
    if (cmStrToULong(depthStr.GetCStr(), &depthUL)) {
2555
0
      depth = depthUL;
2556
0
    }
2557
0
  } else if (cm::optional<std::string> depthEnv =
2558
0
               cmSystemTools::GetEnvVar("CMAKE_MAXIMUM_RECURSION_DEPTH")) {
2559
0
    unsigned long depthUL;
2560
0
    if (cmStrToULong(*depthEnv, &depthUL)) {
2561
0
      depth = depthUL;
2562
0
    }
2563
0
  }
2564
0
  return depth;
2565
0
}
2566
2567
size_t cmMakefile::GetRecursionDepth() const
2568
0
{
2569
0
  return this->RecursionDepth;
2570
0
}
2571
2572
void cmMakefile::SetRecursionDepth(size_t recursionDepth)
2573
0
{
2574
0
  this->RecursionDepth = recursionDepth;
2575
0
}
2576
2577
std::string cmMakefile::NewDeferId() const
2578
0
{
2579
0
  return this->GetGlobalGenerator()->NewDeferId();
2580
0
}
2581
2582
bool cmMakefile::DeferCall(std::string id, std::string file,
2583
                           cmListFileFunction lff)
2584
0
{
2585
0
  if (!this->Defer) {
2586
0
    return false;
2587
0
  }
2588
0
  this->Defer->Commands.emplace_back(
2589
0
    DeferCommand{ std::move(id), std::move(file), std::move(lff) });
2590
0
  return true;
2591
0
}
2592
2593
bool cmMakefile::DeferCancelCall(std::string const& id)
2594
0
{
2595
0
  if (!this->Defer) {
2596
0
    return false;
2597
0
  }
2598
0
  for (DeferCommand& dc : this->Defer->Commands) {
2599
0
    if (dc.Id == id) {
2600
0
      dc.Id.clear();
2601
0
    }
2602
0
  }
2603
0
  return true;
2604
0
}
2605
2606
cm::optional<std::string> cmMakefile::DeferGetCallIds() const
2607
0
{
2608
0
  cm::optional<std::string> ids;
2609
0
  if (this->Defer) {
2610
0
    ids = cmList::to_string(
2611
0
      cmMakeRange(this->Defer->Commands)
2612
0
        .filter([](DeferCommand const& dc) -> bool { return !dc.Id.empty(); })
2613
0
        .transform(
2614
0
          [](DeferCommand const& dc) -> std::string const& { return dc.Id; }));
2615
0
  }
2616
0
  return ids;
2617
0
}
2618
2619
cm::optional<std::string> cmMakefile::DeferGetCall(std::string const& id) const
2620
0
{
2621
0
  cm::optional<std::string> call;
2622
0
  if (this->Defer) {
2623
0
    std::string tmp;
2624
0
    for (DeferCommand const& dc : this->Defer->Commands) {
2625
0
      if (dc.Id == id) {
2626
0
        tmp = dc.Command.OriginalName();
2627
0
        for (cmListFileArgument const& arg : dc.Command.Arguments()) {
2628
0
          tmp = cmStrCat(tmp, ';', arg.Value);
2629
0
        }
2630
0
        break;
2631
0
      }
2632
0
    }
2633
0
    call = std::move(tmp);
2634
0
  }
2635
0
  return call;
2636
0
}
2637
2638
namespace {
2639
cmPolicies::PolicyStatus CheckCMP0219Impl(cmPolicies::PolicyStatus status,
2640
                                          std::string const& calleeName,
2641
                                          bool hasBackslashes,
2642
                                          std::set<std::string>& warned)
2643
0
{
2644
0
  if (status == cmPolicies::WARN && hasBackslashes &&
2645
0
      warned.insert(calleeName).second) {
2646
0
    return cmPolicies::WARN;
2647
0
  }
2648
  // Suppress WARN when there are no backslashes or already warned.
2649
0
  return status == cmPolicies::NEW ? cmPolicies::NEW : cmPolicies::OLD;
2650
0
}
2651
}
2652
2653
cmPolicies::PolicyStatus cmMakefile::CheckCMP0219(
2654
  std::string const& calleeName, std::vector<std::string> const& args)
2655
0
{
2656
0
  bool const hasBackslashes =
2657
0
    std::any_of(args.begin(), args.end(), [](std::string const& s) {
2658
0
      return s.find('\\') != std::string::npos;
2659
0
    });
2660
0
  return CheckCMP0219Impl(GetPolicyStatus(cmPolicies::CMP0219), calleeName,
2661
0
                          hasBackslashes, WarnedCMP0219);
2662
0
}
2663
2664
cmPolicies::PolicyStatus cmMakefile::CheckCMP0219(
2665
  std::string const& calleeName, std::vector<cmListFileArgument> const& args)
2666
0
{
2667
0
  bool const hasBackslashes =
2668
0
    std::any_of(args.begin(), args.end(), [](cmListFileArgument const& s) {
2669
0
      return s.Value.find('\\') != std::string::npos;
2670
0
    });
2671
0
  return CheckCMP0219Impl(GetPolicyStatus(cmPolicies::CMP0219), calleeName,
2672
0
                          hasBackslashes, WarnedCMP0219);
2673
0
}
2674
2675
void cmMakefile::IssueCMP0219Warning(
2676
  std::string const& calleeName, std::vector<std::string> const& args) const
2677
0
{
2678
0
  std::string oldArgs;
2679
0
  for (std::string const& arg : args) {
2680
0
    if (arg.find('\\') == std::string::npos) {
2681
0
      continue;
2682
0
    }
2683
0
    if (!oldArgs.empty()) {
2684
0
      oldArgs += '\n';
2685
0
    }
2686
0
    oldArgs += cmStrCat(" \"", arg, '"');
2687
0
  }
2688
2689
0
  std::string newArgs = oldArgs;
2690
0
  cmSystemTools::ReplaceString(newArgs, "\\", "\\\\");
2691
2692
0
  this->IssueDiagnostic(
2693
0
    cmDiagnostics::CMD_POLICY,
2694
0
    cmStrCat(
2695
0
      cmPolicies::GetPolicyWarning(cmPolicies::CMP0219), '\n', "Command \"",
2696
0
      calleeName, "\" called with arguments containing backslashes.\n",
2697
0
      "Since the policy is not set, backslashes in the arguments:\n", oldArgs,
2698
0
      "\n", "will be interpreted as escape sequences for compatibility.\n",
2699
0
      "Set the policy to NEW to instead pass\n", newArgs, "\n",
2700
0
      "so that argument parsing will preserve the original values."));
2701
0
}
2702
2703
void cmMakefile::IssueCMP0219Warning(
2704
  std::string const& calleeName,
2705
  std::vector<cmListFileArgument> const& args) const
2706
0
{
2707
0
  std::vector<std::string> stringArgs;
2708
0
  stringArgs.reserve(args.size());
2709
0
  for (cmListFileArgument const& arg : args) {
2710
0
    stringArgs.push_back(arg.Value);
2711
0
  }
2712
0
  this->IssueCMP0219Warning(calleeName, stringArgs);
2713
0
}
2714
2715
MessageType cmMakefile::ExpandVariablesInStringImpl(
2716
  std::string& errorstr, std::string& source, bool escapeQuotes,
2717
  bool noEscapes, bool atOnly, char const* filename, long line,
2718
  bool replaceAt) const
2719
0
{
2720
  // This method replaces ${VAR} and @VAR@ where VAR is looked up
2721
  // with GetDefinition(), if not found in the map, nothing is expanded.
2722
  // It also supports the $ENV{VAR} syntax where VAR is looked up in
2723
  // the current environment variables.
2724
2725
0
  char const* in = source.c_str();
2726
0
  char const* last = in;
2727
0
  std::string result;
2728
0
  result.reserve(source.size());
2729
0
  std::vector<t_lookup> openstack;
2730
0
  bool error = false;
2731
0
  bool done = false;
2732
0
  MessageType mtype = MessageType::LOG;
2733
2734
0
  cmState* state = this->GetCMakeInstance()->GetState();
2735
2736
0
  static std::string const lineVar = "CMAKE_CURRENT_LIST_LINE";
2737
0
  do {
2738
0
    char inc = *in;
2739
0
    switch (inc) {
2740
0
      case '}':
2741
0
        if (!openstack.empty()) {
2742
0
          t_lookup var = openstack.back();
2743
0
          openstack.pop_back();
2744
0
          result.append(last, in - last);
2745
0
          std::string const& lookup = result.substr(var.loc);
2746
0
          cmValue value = nullptr;
2747
0
          std::string varresult;
2748
0
          std::string svalue;
2749
0
          switch (var.domain) {
2750
0
            case NORMAL:
2751
0
              if (filename && lookup == lineVar) {
2752
0
                cmListFileContext const& top = this->Backtrace.Top();
2753
0
                if (top.DeferId) {
2754
0
                  varresult = cmStrCat("DEFERRED:"_s, *top.DeferId);
2755
0
                } else {
2756
0
                  varresult = std::to_string(line);
2757
0
                }
2758
0
              } else {
2759
0
                value = this->GetDefinition(lookup);
2760
0
              }
2761
0
              break;
2762
0
            case ENVIRONMENT:
2763
0
              if (cmSystemTools::GetEnv(lookup, svalue)) {
2764
0
                value = cmValue(svalue);
2765
0
              }
2766
0
              break;
2767
0
            case CACHE:
2768
0
              value = state->GetCacheEntryValue(lookup);
2769
0
              break;
2770
0
          }
2771
          // Get the string we're meant to append to.
2772
0
          if (value) {
2773
0
            if (escapeQuotes) {
2774
0
              varresult = cmEscapeQuotes(*value);
2775
0
            } else {
2776
0
              varresult = *value;
2777
0
            }
2778
0
          } else {
2779
0
            this->MaybeWarnUninitialized(lookup, filename);
2780
0
          }
2781
0
          result.replace(var.loc, result.size() - var.loc, varresult);
2782
          // Start looking from here on out.
2783
0
          last = in + 1;
2784
0
        }
2785
0
        break;
2786
0
      case '$':
2787
0
        if (!atOnly) {
2788
0
          t_lookup lookup;
2789
0
          char const* next = in + 1;
2790
0
          char const* start = nullptr;
2791
0
          char nextc = *next;
2792
0
          if (nextc == '{') {
2793
            // Looking for a variable.
2794
0
            start = in + 2;
2795
0
            lookup.domain = NORMAL;
2796
0
          } else if (nextc == '<') {
2797
0
          } else if (!nextc) {
2798
0
            result.append(last, next - last);
2799
0
            last = next;
2800
0
          } else if (cmHasLiteralPrefix(next, "ENV{")) {
2801
            // Looking for an environment variable.
2802
0
            start = in + 5;
2803
0
            lookup.domain = ENVIRONMENT;
2804
0
          } else if (cmHasLiteralPrefix(next, "CACHE{")) {
2805
            // Looking for a cache variable.
2806
0
            start = in + 7;
2807
0
            lookup.domain = CACHE;
2808
0
          } else {
2809
0
            if (this->cmNamedCurly.find(next)) {
2810
0
              errorstr = "Syntax $" +
2811
0
                std::string(next, this->cmNamedCurly.end()) +
2812
0
                "{} is not supported.  Only ${}, $ENV{}, "
2813
0
                "and $CACHE{} are allowed.";
2814
0
              mtype = MessageType::FATAL_ERROR;
2815
0
              error = true;
2816
0
            }
2817
0
          }
2818
0
          if (start) {
2819
0
            result.append(last, in - last);
2820
0
            last = start;
2821
0
            in = start - 1;
2822
0
            lookup.loc = result.size();
2823
0
            openstack.push_back(lookup);
2824
0
          }
2825
0
          break;
2826
0
        }
2827
0
        CM_FALLTHROUGH;
2828
0
      case '\\':
2829
0
        if (!noEscapes) {
2830
0
          char const* next = in + 1;
2831
0
          char nextc = *next;
2832
0
          if (nextc == 't') {
2833
0
            result.append(last, in - last);
2834
0
            result.push_back('\t');
2835
0
            last = next + 1;
2836
0
          } else if (nextc == 'n') {
2837
0
            result.append(last, in - last);
2838
0
            result.push_back('\n');
2839
0
            last = next + 1;
2840
0
          } else if (nextc == 'r') {
2841
0
            result.append(last, in - last);
2842
0
            result.push_back('\r');
2843
0
            last = next + 1;
2844
0
          } else if (nextc == ';' && openstack.empty()) {
2845
            // Handled in ExpandListArgument; pass the backslash literally.
2846
0
          } else if (cmsysString_isalnum(nextc) || nextc == '\0') {
2847
0
            errorstr += "Invalid character escape '\\";
2848
0
            if (nextc) {
2849
0
              errorstr += nextc;
2850
0
              errorstr += "'.";
2851
0
            } else {
2852
0
              errorstr += "' (at end of input).";
2853
0
            }
2854
0
            error = true;
2855
0
          } else {
2856
            // Take what we've found so far, skipping the escape character.
2857
0
            result.append(last, in - last);
2858
            // Start tracking from the next character.
2859
0
            last = in + 1;
2860
0
          }
2861
          // Skip the next character since it was escaped, but don't read past
2862
          // the end of the string.
2863
0
          if (*last) {
2864
0
            ++in;
2865
0
          }
2866
0
        }
2867
0
        break;
2868
0
      case '\n':
2869
        // Onto the next line.
2870
0
        ++line;
2871
0
        break;
2872
0
      case '\0':
2873
0
        done = true;
2874
0
        break;
2875
0
      case '@':
2876
0
        if (replaceAt) {
2877
0
          char const* nextAt = strchr(in + 1, '@');
2878
0
          if (nextAt && nextAt != in + 1 &&
2879
0
              nextAt ==
2880
0
                in + 1 +
2881
0
                  std::strspn(in + 1,
2882
0
                              "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
2883
0
                              "abcdefghijklmnopqrstuvwxyz"
2884
0
                              "0123456789/_.+-")) {
2885
0
            std::string variable(in + 1, nextAt - in - 1);
2886
2887
0
            std::string varresult;
2888
0
            if (filename && variable == lineVar) {
2889
0
              varresult = std::to_string(line);
2890
0
            } else {
2891
0
              cmValue def = this->GetDefinition(variable);
2892
0
              if (def) {
2893
0
                varresult = *def;
2894
0
              } else {
2895
0
                this->MaybeWarnUninitialized(variable, filename);
2896
0
              }
2897
0
            }
2898
2899
0
            if (escapeQuotes) {
2900
0
              varresult = cmEscapeQuotes(varresult);
2901
0
            }
2902
            // Skip over the variable.
2903
0
            result.append(last, in - last);
2904
0
            result.append(varresult);
2905
0
            in = nextAt;
2906
0
            last = in + 1;
2907
0
            break;
2908
0
          }
2909
0
        }
2910
        // Failed to find a valid @ expansion; treat it as literal.
2911
0
        CM_FALLTHROUGH;
2912
0
      default: {
2913
0
        if (!openstack.empty() &&
2914
0
            !(cmsysString_isalnum(inc) || inc == '_' || inc == '/' ||
2915
0
              inc == '.' || inc == '+' || inc == '-')) {
2916
0
          errorstr += cmStrCat("Invalid character ('", inc);
2917
0
          result.append(last, in - last);
2918
0
          errorstr += cmStrCat("') in a variable name: '",
2919
0
                               result.substr(openstack.back().loc), '\'');
2920
0
          mtype = MessageType::FATAL_ERROR;
2921
0
          error = true;
2922
0
        }
2923
0
        break;
2924
0
      }
2925
0
    }
2926
    // Look at the next character.
2927
0
  } while (!error && !done && *++in);
2928
2929
  // Check for open variable references yet.
2930
0
  if (!error && !openstack.empty()) {
2931
0
    errorstr += "There is an unterminated variable reference.";
2932
0
    error = true;
2933
0
  }
2934
2935
0
  if (error) {
2936
0
    std::string e = "Syntax error in cmake code ";
2937
0
    if (filename) {
2938
      // This filename and line number may be more specific than the
2939
      // command context because one command invocation can have
2940
      // arguments on multiple lines.
2941
0
      e += cmStrCat("at\n  ", filename, ':', line, '\n');
2942
0
    }
2943
0
    errorstr = cmStrCat(e, "when parsing string\n  ", source, '\n', errorstr);
2944
0
    mtype = MessageType::FATAL_ERROR;
2945
0
  } else {
2946
    // Append the rest of the unchanged part of the string.
2947
0
    result.append(last);
2948
2949
0
    source = result;
2950
0
  }
2951
2952
0
  return mtype;
2953
0
}
2954
2955
void cmMakefile::RemoveVariablesInString(std::string& source,
2956
                                         bool atOnly) const
2957
0
{
2958
0
  if (!atOnly) {
2959
0
    cmsys::RegularExpression var("(\\${[A-Za-z_0-9]*})");
2960
0
    while (var.find(source)) {
2961
0
      source.erase(var.start(), var.end() - var.start());
2962
0
    }
2963
0
  }
2964
2965
0
  if (!atOnly) {
2966
0
    cmsys::RegularExpression varb("(\\$ENV{[A-Za-z_0-9]*})");
2967
0
    while (varb.find(source)) {
2968
0
      source.erase(varb.start(), varb.end() - varb.start());
2969
0
    }
2970
0
  }
2971
0
  cmsys::RegularExpression var2("(@[A-Za-z_0-9]*@)");
2972
0
  while (var2.find(source)) {
2973
0
    source.erase(var2.start(), var2.end() - var2.start());
2974
0
  }
2975
0
}
2976
2977
void cmMakefile::InitCMAKE_CONFIGURATION_TYPES(std::string const& genDefault)
2978
0
{
2979
0
  if (this->GetDefinition("CMAKE_CONFIGURATION_TYPES")) {
2980
0
    return;
2981
0
  }
2982
0
  std::string initConfigs;
2983
0
  if (this->GetCMakeInstance()->GetIsInTryCompile() ||
2984
0
      !cmSystemTools::GetEnv("CMAKE_CONFIGURATION_TYPES", initConfigs)) {
2985
0
    initConfigs = genDefault;
2986
0
  }
2987
0
  this->AddCacheDefinition(
2988
0
    "CMAKE_CONFIGURATION_TYPES", initConfigs,
2989
0
    "Semicolon separated list of supported configuration types, "
2990
0
    "only supports Debug, Release, MinSizeRel, and RelWithDebInfo, "
2991
0
    "anything else will be ignored.",
2992
0
    cmStateEnums::STRING);
2993
0
}
2994
2995
std::string cmMakefile::GetDefaultConfiguration() const
2996
0
{
2997
0
  if (this->GetGlobalGenerator()->IsMultiConfig()) {
2998
0
    return std::string{};
2999
0
  }
3000
0
  return this->GetSafeDefinition("CMAKE_BUILD_TYPE");
3001
0
}
3002
3003
std::vector<std::string> cmMakefile::GetGeneratorConfigs(
3004
  GeneratorConfigQuery mode) const
3005
0
{
3006
0
  cmList configs;
3007
0
  if (this->GetGlobalGenerator()->IsMultiConfig()) {
3008
0
    configs.assign(this->GetDefinition("CMAKE_CONFIGURATION_TYPES"));
3009
0
  } else if (mode != cmMakefile::OnlyMultiConfig) {
3010
0
    std::string const& buildType = this->GetSafeDefinition("CMAKE_BUILD_TYPE");
3011
0
    if (!buildType.empty()) {
3012
0
      configs.emplace_back(buildType);
3013
0
    }
3014
0
  }
3015
0
  if (mode == cmMakefile::IncludeEmptyConfig && configs.empty()) {
3016
0
    configs.emplace_back();
3017
0
  }
3018
0
  return std::move(configs.data());
3019
0
}
3020
3021
bool cmMakefile::IsFunctionBlocked(cmListFileFunction const& lff,
3022
                                   cmExecutionStatus& status)
3023
0
{
3024
  // if there are no blockers get out of here
3025
0
  if (this->FunctionBlockers.empty()) {
3026
0
    return false;
3027
0
  }
3028
3029
0
  return this->FunctionBlockers.top()->IsFunctionBlocked(lff, status);
3030
0
}
3031
3032
void cmMakefile::PushFunctionBlockerBarrier()
3033
1
{
3034
1
  this->FunctionBlockerBarriers.push_back(this->FunctionBlockers.size());
3035
1
}
3036
3037
void cmMakefile::PopFunctionBlockerBarrier(bool reportError)
3038
1
{
3039
  // Remove any extra entries pushed on the barrier.
3040
1
  FunctionBlockersType::size_type barrier =
3041
1
    this->FunctionBlockerBarriers.back();
3042
1
  while (this->FunctionBlockers.size() > barrier) {
3043
0
    std::unique_ptr<cmFunctionBlocker> fb(
3044
0
      std::move(this->FunctionBlockers.top()));
3045
0
    this->FunctionBlockers.pop();
3046
0
    if (reportError) {
3047
      // Report the context in which the unclosed block was opened.
3048
0
      cmListFileContext const& lfc = fb->GetStartingContext();
3049
0
      std::ostringstream e;
3050
      /* clang-format off */
3051
0
      e << "A logical block opening on the line\n"
3052
0
           "  " << lfc << "\n"
3053
0
           "is not closed.";
3054
      /* clang-format on */
3055
0
      this->IssueMessage(MessageType::FATAL_ERROR, e.str());
3056
0
      reportError = false;
3057
0
    }
3058
0
  }
3059
3060
  // Remove the barrier.
3061
1
  this->FunctionBlockerBarriers.pop_back();
3062
1
}
3063
3064
void cmMakefile::PushLoopBlock()
3065
0
{
3066
0
  assert(!this->LoopBlockCounter.empty());
3067
0
  this->LoopBlockCounter.top()++;
3068
0
}
3069
3070
void cmMakefile::PopLoopBlock()
3071
0
{
3072
0
  assert(!this->LoopBlockCounter.empty());
3073
0
  assert(this->LoopBlockCounter.top() > 0);
3074
0
  this->LoopBlockCounter.top()--;
3075
0
}
3076
3077
void cmMakefile::PushLoopBlockBarrier()
3078
1
{
3079
1
  this->LoopBlockCounter.push(0);
3080
1
}
3081
3082
void cmMakefile::PopLoopBlockBarrier()
3083
0
{
3084
0
  assert(!this->LoopBlockCounter.empty());
3085
0
  assert(this->LoopBlockCounter.top() == 0);
3086
0
  this->LoopBlockCounter.pop();
3087
0
}
3088
3089
bool cmMakefile::IsLoopBlock() const
3090
0
{
3091
0
  assert(!this->LoopBlockCounter.empty());
3092
0
  return !this->LoopBlockCounter.empty() && this->LoopBlockCounter.top() > 0;
3093
0
}
3094
3095
bool cmMakefile::ExpandArguments(std::vector<cmListFileArgument> const& inArgs,
3096
                                 std::vector<std::string>& outArgs) const
3097
0
{
3098
0
  std::string const& filename = this->GetBacktrace().Top().FilePath;
3099
0
  std::string value;
3100
0
  outArgs.reserve(inArgs.size());
3101
0
  for (cmListFileArgument const& i : inArgs) {
3102
    // No expansion in a bracket argument.
3103
0
    if (i.Delim == cmListFileArgument::Bracket) {
3104
0
      outArgs.push_back(i.Value);
3105
0
      continue;
3106
0
    }
3107
    // Expand the variables in the argument.
3108
0
    value = i.Value;
3109
0
    this->ExpandVariablesInString(value, false, false, false, filename.c_str(),
3110
0
                                  i.Line, false, false);
3111
3112
    // If the argument is quoted, it should be one argument.
3113
    // Otherwise, it may be a list of arguments.
3114
0
    if (i.Delim == cmListFileArgument::Quoted) {
3115
0
      outArgs.push_back(value);
3116
0
    } else {
3117
0
      cmExpandList(value, outArgs);
3118
0
    }
3119
0
  }
3120
0
  return !cmSystemTools::GetFatalErrorOccurred();
3121
0
}
3122
3123
bool cmMakefile::ExpandArguments(
3124
  std::vector<cmListFileArgument> const& inArgs,
3125
  std::vector<cmExpandedCommandArgument>& outArgs) const
3126
0
{
3127
0
  std::string const& filename = this->GetBacktrace().Top().FilePath;
3128
0
  std::string value;
3129
0
  outArgs.reserve(inArgs.size());
3130
0
  for (cmListFileArgument const& i : inArgs) {
3131
    // No expansion in a bracket argument.
3132
0
    if (i.Delim == cmListFileArgument::Bracket) {
3133
0
      outArgs.emplace_back(i.Value, true);
3134
0
      continue;
3135
0
    }
3136
    // Expand the variables in the argument.
3137
0
    value = i.Value;
3138
0
    this->ExpandVariablesInString(value, false, false, false, filename.c_str(),
3139
0
                                  i.Line, false, false);
3140
3141
    // If the argument is quoted, it should be one argument.
3142
    // Otherwise, it may be a list of arguments.
3143
0
    if (i.Delim == cmListFileArgument::Quoted) {
3144
0
      outArgs.emplace_back(value, true);
3145
0
    } else {
3146
0
      cmList stringArgs{ value };
3147
0
      for (std::string const& stringArg : stringArgs) {
3148
0
        outArgs.emplace_back(stringArg, false);
3149
0
      }
3150
0
    }
3151
0
  }
3152
0
  return !cmSystemTools::GetFatalErrorOccurred();
3153
0
}
3154
3155
void cmMakefile::AddFunctionBlocker(std::unique_ptr<cmFunctionBlocker> fb)
3156
0
{
3157
0
  if (!this->ExecutionStatusStack.empty()) {
3158
    // Record the context in which the blocker is created.
3159
0
    fb->SetStartingContext(this->Backtrace.Top());
3160
0
  }
3161
3162
0
  this->FunctionBlockers.push(std::move(fb));
3163
0
}
3164
3165
std::unique_ptr<cmFunctionBlocker> cmMakefile::RemoveFunctionBlocker()
3166
0
{
3167
0
  assert(!this->FunctionBlockers.empty());
3168
0
  assert(this->FunctionBlockerBarriers.empty() ||
3169
0
         this->FunctionBlockers.size() > this->FunctionBlockerBarriers.back());
3170
3171
0
  auto b = std::move(this->FunctionBlockers.top());
3172
0
  this->FunctionBlockers.pop();
3173
0
  return b;
3174
0
}
3175
3176
std::string const& cmMakefile::GetHomeDirectory() const
3177
0
{
3178
0
  return this->GetCMakeInstance()->GetHomeDirectory();
3179
0
}
3180
3181
std::string const& cmMakefile::GetHomeOutputDirectory() const
3182
0
{
3183
0
  return this->GetCMakeInstance()->GetHomeOutputDirectory();
3184
0
}
3185
3186
void cmMakefile::SetScriptModeFile(std::string const& scriptfile)
3187
1
{
3188
1
  this->AddDefinition("CMAKE_SCRIPT_MODE_FILE", scriptfile);
3189
1
}
3190
3191
void cmMakefile::SetArgcArgv(std::vector<std::string> const& args)
3192
1
{
3193
1
  this->AddDefinition("CMAKE_ARGC", std::to_string(args.size()));
3194
3195
4
  for (auto i = 0u; i < args.size(); ++i) {
3196
3
    this->AddDefinition(cmStrCat("CMAKE_ARGV", i), args[i]);
3197
3
  }
3198
1
}
3199
3200
cmSourceFile* cmMakefile::GetSource(std::string const& sourceName,
3201
                                    cmSourceFileLocationKind kind) const
3202
0
{
3203
  // First check "Known" paths (avoids the creation of cmSourceFileLocation)
3204
0
  if (kind == cmSourceFileLocationKind::Known) {
3205
0
    auto sfsi = this->KnownFileSearchIndex.find(sourceName);
3206
0
    if (sfsi != this->KnownFileSearchIndex.end()) {
3207
0
      return sfsi->second;
3208
0
    }
3209
0
  }
3210
3211
0
  cmSourceFileLocation sfl(this, sourceName, kind);
3212
0
  auto name = this->GetCMakeInstance()->StripExtension(sfl.GetName());
3213
#if defined(_WIN32) || defined(__APPLE__)
3214
  name = cmSystemTools::LowerCase(name);
3215
#endif
3216
0
  auto sfsi = this->SourceFileSearchIndex.find(name);
3217
0
  if (sfsi != this->SourceFileSearchIndex.end()) {
3218
0
    for (auto* sf : sfsi->second) {
3219
0
      if (sf->Matches(sfl)) {
3220
0
        return sf;
3221
0
      }
3222
0
    }
3223
0
  }
3224
0
  return nullptr;
3225
0
}
3226
3227
cmSourceFile* cmMakefile::CreateSource(std::string const& sourceName,
3228
                                       bool generated,
3229
                                       cmSourceFileLocationKind kind)
3230
0
{
3231
0
  auto sf = cm::make_unique<cmSourceFile>(this, sourceName, generated, kind);
3232
0
  auto name =
3233
0
    this->GetCMakeInstance()->StripExtension(sf->GetLocation().GetName());
3234
#if defined(_WIN32) || defined(__APPLE__)
3235
  name = cmSystemTools::LowerCase(name);
3236
#endif
3237
0
  this->SourceFileSearchIndex[name].push_back(sf.get());
3238
  // for "Known" paths add direct lookup (used for faster lookup in GetSource)
3239
0
  if (kind == cmSourceFileLocationKind::Known) {
3240
0
    this->KnownFileSearchIndex[sourceName] = sf.get();
3241
0
  }
3242
3243
0
  this->SourceFiles.push_back(std::move(sf));
3244
3245
0
  return this->SourceFiles.back().get();
3246
0
}
3247
3248
cmSourceFile* cmMakefile::GetOrCreateSource(std::string const& sourceName,
3249
                                            bool generated,
3250
                                            cmSourceFileLocationKind kind)
3251
0
{
3252
0
  if (cmSourceFile* esf = this->GetSource(sourceName, kind)) {
3253
0
    return esf;
3254
0
  }
3255
0
  return this->CreateSource(sourceName, generated, kind);
3256
0
}
3257
3258
cmSourceFile* cmMakefile::GetOrCreateGeneratedSource(
3259
  std::string const& sourceName)
3260
0
{
3261
0
  cmSourceFile* sf =
3262
0
    this->GetOrCreateSource(sourceName, true, cmSourceFileLocationKind::Known);
3263
0
  sf->MarkAsGenerated(); // In case we did not create the source file.
3264
0
  return sf;
3265
0
}
3266
3267
void cmMakefile::CreateGeneratedOutputs(
3268
  std::vector<std::string> const& outputs)
3269
0
{
3270
0
  for (std::string const& o : outputs) {
3271
0
    if (cmGeneratorExpression::Find(o) == std::string::npos) {
3272
0
      this->GetOrCreateGeneratedSource(o);
3273
0
    }
3274
0
  }
3275
0
}
3276
3277
void cmMakefile::AddTargetObject(std::string const& tgtName,
3278
                                 std::string const& objFile)
3279
0
{
3280
0
  cmSourceFile* sf =
3281
0
    this->GetOrCreateSource(objFile, true, cmSourceFileLocationKind::Known);
3282
0
  sf->SetSpecialSourceType(cmSourceFile::SpecialSourceType::Object);
3283
0
  sf->SetObjectLibrary(tgtName);
3284
0
  sf->SetProperty("EXTERNAL_OBJECT", "1");
3285
  // TODO: Compute a language for this object based on the associated source
3286
  // file that compiles to it. Needs a policy as it likely affects link
3287
  // language selection if done unconditionally.
3288
0
#if !defined(CMAKE_BOOTSTRAP)
3289
0
  this->SourceGroups[this->ObjectLibrariesSourceGroupIndex]->AddGroupFile(
3290
0
    sf->ResolveFullPath());
3291
0
#endif
3292
0
}
3293
3294
void cmMakefile::EnableLanguage(std::vector<std::string> const& languages,
3295
                                bool optional)
3296
0
{
3297
0
  if (this->DeferRunning) {
3298
0
    this->IssueMessage(
3299
0
      MessageType::FATAL_ERROR,
3300
0
      "Languages may not be enabled during deferred execution.");
3301
0
    return;
3302
0
  }
3303
0
  if (char const* def = this->GetGlobalGenerator()->GetCMakeCFGIntDir()) {
3304
0
    this->AddDefinition("CMAKE_CFG_INTDIR", def);
3305
0
  }
3306
3307
0
  std::vector<std::string> unique_languages;
3308
0
  {
3309
0
    std::vector<std::string> duplicate_languages;
3310
0
    for (std::string const& language : languages) {
3311
0
      if (!cm::contains(unique_languages, language)) {
3312
0
        unique_languages.push_back(language);
3313
0
      } else if (!cm::contains(duplicate_languages, language)) {
3314
0
        duplicate_languages.push_back(language);
3315
0
      }
3316
0
    }
3317
0
    if (!duplicate_languages.empty()) {
3318
0
      auto quantity = duplicate_languages.size() == 1 ? " has"_s : "s have"_s;
3319
0
      this->IssueDiagnostic(
3320
0
        cmDiagnostics::CMD_AUTHOR,
3321
0
        cmStrCat("Languages to be enabled may not be specified more "
3322
0
                 "than once at the same time. The following language",
3323
0
                 quantity, " been specified multiple times: ",
3324
0
                 cmJoin(duplicate_languages, ", ")));
3325
0
    }
3326
0
  }
3327
3328
  // If RC is explicitly listed we need to do it after other languages.
3329
  // On some platforms we enable RC implicitly while enabling others.
3330
  // Do not let that look like recursive enable_language(RC).
3331
0
  std::vector<std::string> languages_without_RC;
3332
0
  std::vector<std::string> languages_for_RC;
3333
0
  languages_without_RC.reserve(unique_languages.size());
3334
0
  for (std::string const& language : unique_languages) {
3335
0
    if (language == "RC"_s) {
3336
0
      languages_for_RC.push_back(language);
3337
0
    } else {
3338
0
      languages_without_RC.push_back(language);
3339
0
    }
3340
0
  }
3341
0
  if (!languages_without_RC.empty()) {
3342
0
    this->GetGlobalGenerator()->EnableLanguage(languages_without_RC, this,
3343
0
                                               optional);
3344
0
  }
3345
0
  if (!languages_for_RC.empty()) {
3346
0
    this->GetGlobalGenerator()->EnableLanguage(languages_for_RC, this,
3347
0
                                               optional);
3348
0
  }
3349
0
}
3350
3351
int cmMakefile::TryCompile(std::string const& srcdir,
3352
                           std::string const& bindir,
3353
                           std::string const& projectName,
3354
                           std::string const& targetName, bool fast, int jobs,
3355
                           std::vector<std::string> const* cmakeArgs,
3356
                           std::string& output)
3357
0
{
3358
0
  this->IsSourceFileTryCompile = fast;
3359
  // does the binary directory exist ? If not create it...
3360
0
  if (!cmSystemTools::FileIsDirectory(bindir)) {
3361
0
    cmSystemTools::MakeDirectory(bindir);
3362
0
  }
3363
3364
  // change to the tests directory and run cmake
3365
  // use the cmake object instead of calling cmake
3366
0
  cmWorkingDirectory workdir(bindir);
3367
0
  if (workdir.Failed()) {
3368
0
    this->IssueMessage(MessageType::FATAL_ERROR, workdir.GetError());
3369
0
    cmSystemTools::SetFatalErrorOccurred();
3370
0
    this->IsSourceFileTryCompile = false;
3371
0
    return 1;
3372
0
  }
3373
3374
  // unset the NINJA_STATUS environment variable while running try compile.
3375
  // since we parse the output, we need to ensure there aren't any unexpected
3376
  // characters that will cause issues, such as ANSI color escape codes.
3377
0
  cm::optional<cmSystemTools::ScopedEnv> maybeNinjaStatus;
3378
0
  if (this->GetGlobalGenerator()->IsNinja()) {
3379
0
    maybeNinjaStatus.emplace("NINJA_STATUS=");
3380
0
  }
3381
3382
  // make sure the same generator is used
3383
  // use this program as the cmake to be run, it should not
3384
  // be run that way but the cmake object requires a valid path
3385
0
  cmake cm(cmState::Role::Project, cmState::TryCompile::Yes);
3386
0
  auto gg = cm.CreateGlobalGenerator(this->GetGlobalGenerator()->GetName());
3387
0
  if (!gg) {
3388
0
    this->IssueMessage(MessageType::INTERNAL_ERROR,
3389
0
                       "Global generator '" +
3390
0
                         this->GetGlobalGenerator()->GetName() +
3391
0
                         "' could not be created.");
3392
0
    cmSystemTools::SetFatalErrorOccurred();
3393
0
    this->IsSourceFileTryCompile = false;
3394
0
    return 1;
3395
0
  }
3396
0
  gg->RecursionDepth = this->RecursionDepth;
3397
0
  cm.SetGlobalGenerator(std::move(gg));
3398
3399
  // copy trace state
3400
0
  cm.SetTraceRedirect(this->GetCMakeInstance());
3401
3402
  // do a configure
3403
0
  cm.SetHomeDirectory(srcdir);
3404
0
  cm.SetHomeOutputDirectory(bindir);
3405
0
  cm.SetGeneratorInstance(this->GetSafeDefinition("CMAKE_GENERATOR_INSTANCE"));
3406
0
  cm.SetGeneratorPlatform(this->GetSafeDefinition("CMAKE_GENERATOR_PLATFORM"));
3407
0
  cm.SetGeneratorToolset(this->GetSafeDefinition("CMAKE_GENERATOR_TOOLSET"));
3408
0
  cm.LoadCache();
3409
0
  if (!cm.GetGlobalGenerator()->IsMultiConfig()) {
3410
0
    if (cmValue config =
3411
0
          this->GetDefinition("CMAKE_TRY_COMPILE_CONFIGURATION")) {
3412
      // Tell the single-configuration generator which one to use.
3413
      // Add this before the user-provided CMake arguments in case
3414
      // one of the arguments is -DCMAKE_BUILD_TYPE=...
3415
0
      cm.AddCacheEntry("CMAKE_BUILD_TYPE", config, "Build configuration",
3416
0
                       cmStateEnums::STRING);
3417
0
    }
3418
0
  }
3419
0
  cmValue recursionDepth =
3420
0
    this->GetDefinition("CMAKE_MAXIMUM_RECURSION_DEPTH");
3421
0
  if (recursionDepth) {
3422
0
    cm.AddCacheEntry("CMAKE_MAXIMUM_RECURSION_DEPTH", recursionDepth,
3423
0
                     "Maximum recursion depth", cmStateEnums::STRING);
3424
0
  }
3425
  // if cmake args were provided then pass them in
3426
0
  if (cmakeArgs) {
3427
    // FIXME: Workaround to ignore unused CLI variables in try-compile.
3428
    //
3429
    // Ideally we should use SetArgs for options like -Wno-unused-cli.
3430
    // However, there is a subtle problem when certain arguments are passed to
3431
    // a macro wrapping around try_compile or try_run that does not escape
3432
    // semicolons in its parameters but just passes ${ARGV} or ${ARGN}.  In
3433
    // this case a list argument like "-DVAR=a;b" gets split into multiple
3434
    // cmake arguments "-DVAR=a" and "b".  Currently SetCacheArgs ignores
3435
    // argument "b" and uses just "-DVAR=a", leading to a subtle bug in that
3436
    // the try_compile or try_run does not get the proper value of VAR.  If we
3437
    // call SetArgs here then it would treat "b" as the source directory and
3438
    // cause an error such as "The source directory .../CMakeFiles/CMakeTmp/b
3439
    // does not exist", thus breaking the try_compile or try_run completely.
3440
    //
3441
    // Strictly speaking the bug is in the wrapper macro because the CMake
3442
    // language has always flattened nested lists and the macro should escape
3443
    // the semicolons in its arguments before forwarding them.  However, this
3444
    // bug is so subtle that projects typically work anyway, usually because
3445
    // the value VAR=a is sufficient for the try_compile or try_run to get the
3446
    // correct result.  Calling SetArgs here would break such projects that
3447
    // previously built.  Instead we work around the issue by never reporting
3448
    // unused arguments and ignoring options such as -Wno-unused-cli.
3449
0
    cm.GetCurrentSnapshot().SetDiagnostic(cmDiagnostics::CMD_UNUSED_CLI,
3450
0
                                          cmDiagnostics::Ignore, true);
3451
    // cm.SetArgs(*cmakeArgs, true);
3452
3453
0
    cm.SetCacheArgs(*cmakeArgs);
3454
0
  }
3455
  // to save time we pass the EnableLanguage info directly
3456
0
  cm.GetGlobalGenerator()->SetupTryCompile(this->GetGlobalGenerator(), this);
3457
0
  for (unsigned dc = 1; dc < cmDiagnostics::CategoryCount; ++dc) {
3458
0
    auto const category = static_cast<cmDiagnosticCategory>(dc);
3459
0
    if (this->GetDiagnosticAction(category) == cmDiagnostics::Ignore) {
3460
0
      cm.GetCurrentSnapshot().SetDiagnostic(category, cmDiagnostics::Ignore,
3461
0
                                            false);
3462
0
    }
3463
0
  }
3464
0
  if (cm.Configure() != 0) {
3465
0
    this->IssueMessage(MessageType::FATAL_ERROR,
3466
0
                       "Failed to configure test project build system.");
3467
0
    cmSystemTools::SetFatalErrorOccurred();
3468
0
    this->IsSourceFileTryCompile = false;
3469
0
    return 1;
3470
0
  }
3471
3472
0
  if (cm.Generate() != 0) {
3473
0
    this->IssueMessage(MessageType::FATAL_ERROR,
3474
0
                       "Failed to generate test project build system.");
3475
0
    cmSystemTools::SetFatalErrorOccurred();
3476
0
    this->IsSourceFileTryCompile = false;
3477
0
    return 1;
3478
0
  }
3479
3480
  // finally call the generator to actually build the resulting project
3481
0
  int ret = this->GetGlobalGenerator()->TryCompile(
3482
0
    jobs, bindir, projectName, targetName, fast, output, this);
3483
3484
0
  this->IsSourceFileTryCompile = false;
3485
0
  return ret;
3486
0
}
3487
3488
bool cmMakefile::GetIsSourceFileTryCompile() const
3489
0
{
3490
0
  return this->IsSourceFileTryCompile;
3491
0
}
3492
3493
cmake* cmMakefile::GetCMakeInstance() const
3494
32
{
3495
32
  return this->GlobalGenerator->GetCMakeInstance();
3496
32
}
3497
3498
cmMessenger* cmMakefile::GetMessenger() const
3499
0
{
3500
0
  return this->GetCMakeInstance()->GetMessenger();
3501
0
}
3502
3503
cmGlobalGenerator* cmMakefile::GetGlobalGenerator() const
3504
2
{
3505
2
  return this->GlobalGenerator;
3506
2
}
3507
3508
#ifndef CMAKE_BOOTSTRAP
3509
cmVariableWatch* cmMakefile::GetVariableWatch() const
3510
12
{
3511
12
  if (this->GetCMakeInstance()) {
3512
12
    return this->GetCMakeInstance()->GetVariableWatch();
3513
12
  }
3514
0
  return nullptr;
3515
12
}
3516
#endif
3517
3518
cmState* cmMakefile::GetState() const
3519
4
{
3520
4
  return this->GetCMakeInstance()->GetState();
3521
4
}
3522
3523
void cmMakefile::DisplayStatus(std::string const& message, float s) const
3524
0
{
3525
0
  cmake* cm = this->GetCMakeInstance();
3526
0
  if (cm->GetState()->GetRole() == cmState::Role::FindPackage) {
3527
    // don't output any STATUS message in --find-package mode, since they will
3528
    // directly be fed to the compiler, which will be confused.
3529
0
    return;
3530
0
  }
3531
0
  cm->UpdateProgress(message, s);
3532
3533
0
#ifdef CMake_ENABLE_DEBUGGER
3534
0
  if (cm->GetDebugAdapter()) {
3535
0
    cm->GetDebugAdapter()->OnMessageOutput(MessageType::MESSAGE, message);
3536
0
  }
3537
0
#endif
3538
0
}
3539
3540
std::string cmMakefile::GetModulesFile(cm::string_view filename, bool& system,
3541
                                       bool debug,
3542
                                       std::string& debugBuffer) const
3543
0
{
3544
0
  std::string result;
3545
3546
0
  std::string moduleInCMakeRoot;
3547
0
  std::string moduleInCMakeModulePath;
3548
3549
  // Always search in CMAKE_MODULE_PATH:
3550
0
  cmValue cmakeModulePath = this->GetDefinition("CMAKE_MODULE_PATH");
3551
0
  if (cmakeModulePath) {
3552
0
    cmList modulePath{ *cmakeModulePath };
3553
3554
    // Look through the possible module directories.
3555
0
    for (std::string itempl : modulePath) {
3556
0
      cmSystemTools::ConvertToUnixSlashes(itempl);
3557
0
      itempl += "/";
3558
0
      itempl += filename;
3559
0
      if (cmSystemTools::FileExists(itempl)) {
3560
0
        moduleInCMakeModulePath = itempl;
3561
0
        break;
3562
0
      }
3563
0
      if (debug) {
3564
0
        debugBuffer = cmStrCat(debugBuffer, "  ", itempl, '\n');
3565
0
      }
3566
0
    }
3567
0
  }
3568
3569
  // Always search in the standard modules location.
3570
0
  moduleInCMakeRoot =
3571
0
    cmStrCat(cmSystemTools::GetCMakeRoot(), "/Modules/", filename);
3572
0
  cmSystemTools::ConvertToUnixSlashes(moduleInCMakeRoot);
3573
0
  if (!cmSystemTools::FileExists(moduleInCMakeRoot)) {
3574
0
    if (debug) {
3575
0
      debugBuffer = cmStrCat(debugBuffer, "  ", moduleInCMakeRoot, '\n');
3576
0
    }
3577
0
    moduleInCMakeRoot.clear();
3578
0
  }
3579
3580
  // Normally, prefer the files found in CMAKE_MODULE_PATH. Only when the file
3581
  // from which we are being called is located itself in CMAKE_ROOT, then
3582
  // prefer results from CMAKE_ROOT depending on the policy setting.
3583
0
  if (!moduleInCMakeModulePath.empty() && !moduleInCMakeRoot.empty()) {
3584
0
    cmValue currentFile = this->GetDefinition(kCMAKE_CURRENT_LIST_FILE);
3585
0
    std::string mods = cmStrCat(cmSystemTools::GetCMakeRoot(), "/Modules/");
3586
0
    if (currentFile && cmSystemTools::IsSubDirectory(*currentFile, mods)) {
3587
0
      system = true;
3588
0
      result = moduleInCMakeRoot;
3589
0
    } else {
3590
0
      system = false;
3591
0
      result = moduleInCMakeModulePath;
3592
0
    }
3593
0
  } else if (!moduleInCMakeModulePath.empty()) {
3594
0
    system = false;
3595
0
    result = moduleInCMakeModulePath;
3596
0
  } else {
3597
0
    system = true;
3598
0
    result = moduleInCMakeRoot;
3599
0
  }
3600
3601
#if defined(_WIN32) || defined(__APPLE__)
3602
  if (!result.empty()) {
3603
    std::string const requestedName =
3604
      cmSystemTools::GetFilenameName(std::string{ filename });
3605
    std::string actualName;
3606
    cmsys::Status const status =
3607
      cmSystemTools::ReadNameOnDisk(result, actualName);
3608
    if (status && actualName != requestedName) {
3609
      this->IssueDiagnostic(
3610
        cmDiagnostics::CMD_AUTHOR,
3611
        cmStrCat("The module name\n  ", requestedName, '\n',
3612
                 "does not match the case of the module file name on disk\n"
3613
                 "  ",
3614
                 cmSystemTools::GetFilenamePath(result), '/', actualName, '\n',
3615
                 "This may fail on case-sensitive file systems.  "
3616
                 "Use the module name\n  ",
3617
                 actualName, "\ninstead."));
3618
    }
3619
  }
3620
#endif
3621
3622
0
  return result;
3623
0
}
3624
3625
void cmMakefile::ConfigureString(std::string const& input, std::string& output,
3626
                                 bool atOnly, bool escapeQuotes) const
3627
0
{
3628
  // Split input to handle one line at a time.
3629
0
  std::string::const_iterator lineStart = input.begin();
3630
0
  while (lineStart != input.end()) {
3631
    // Find the end of this line.
3632
0
    std::string::const_iterator lineEnd = lineStart;
3633
0
    while (lineEnd != input.end() && *lineEnd != '\n') {
3634
0
      ++lineEnd;
3635
0
    }
3636
3637
    // Copy the line.
3638
0
    std::string line(lineStart, lineEnd);
3639
3640
    // Skip the newline character.
3641
0
    bool haveNewline = (lineEnd != input.end());
3642
0
    if (haveNewline) {
3643
0
      ++lineEnd;
3644
0
    }
3645
3646
    // Replace #cmakedefine instances.
3647
0
    if (this->cmDefineRegex.find(line)) {
3648
0
      cmValue def = this->GetDefinition(this->cmDefineRegex.match(2));
3649
0
      if (!def.IsOff()) {
3650
0
        std::string const indentation = this->cmDefineRegex.match(1);
3651
0
        cmSystemTools::ReplaceString(line,
3652
0
                                     cmStrCat('#', indentation, "cmakedefine"),
3653
0
                                     cmStrCat('#', indentation, "define"));
3654
0
        output += line;
3655
0
      } else {
3656
0
        output += "/* #undef ";
3657
0
        output += this->cmDefineRegex.match(2);
3658
0
        output += " */";
3659
0
      }
3660
0
    } else if (this->cmDefine01Regex.find(line)) {
3661
0
      std::string const indentation = this->cmDefine01Regex.match(1);
3662
0
      cmValue def = this->GetDefinition(this->cmDefine01Regex.match(2));
3663
0
      cmSystemTools::ReplaceString(line,
3664
0
                                   cmStrCat('#', indentation, "cmakedefine01"),
3665
0
                                   cmStrCat('#', indentation, "define"));
3666
0
      output += line;
3667
0
      if (!def.IsOff()) {
3668
0
        output += " 1";
3669
0
      } else {
3670
0
        output += " 0";
3671
0
      }
3672
0
    } else {
3673
0
      output += line;
3674
0
    }
3675
3676
0
    if (haveNewline) {
3677
0
      output += '\n';
3678
0
    }
3679
3680
    // Move to the next line.
3681
0
    lineStart = lineEnd;
3682
0
  }
3683
3684
  // Perform variable replacements.
3685
0
  char const* filename = nullptr;
3686
0
  long lineNumber = -1;
3687
0
  if (!this->Backtrace.Empty()) {
3688
0
    auto const& currentTrace = this->Backtrace.Top();
3689
0
    filename = currentTrace.FilePath.c_str();
3690
0
    lineNumber = currentTrace.Line;
3691
0
  }
3692
0
  this->ExpandVariablesInString(output, escapeQuotes, true, atOnly, filename,
3693
0
                                lineNumber, true, true);
3694
0
}
3695
3696
int cmMakefile::ConfigureFile(std::string const& infile,
3697
                              std::string const& outfile, bool copyonly,
3698
                              bool atOnly, bool escapeQuotes,
3699
                              mode_t permissions, cmNewLineStyle newLine)
3700
0
{
3701
0
  int res = 1;
3702
0
  if (!this->CanIWriteThisFile(outfile)) {
3703
0
    cmSystemTools::Error(cmStrCat("Attempt to write file: ", outfile,
3704
0
                                  " into a source directory."));
3705
0
    return 0;
3706
0
  }
3707
0
  if (!cmSystemTools::FileExists(infile)) {
3708
0
    cmSystemTools::Error(cmStrCat("File ", infile, " does not exist."));
3709
0
    return 0;
3710
0
  }
3711
0
  std::string soutfile = outfile;
3712
0
  std::string const& sinfile = infile;
3713
0
  this->AddCMakeDependFile(sinfile);
3714
0
  cmSystemTools::ConvertToUnixSlashes(soutfile);
3715
3716
  // Re-generate if non-temporary outputs are missing.
3717
  // when we finalize the configuration we will remove all
3718
  // output files that now don't exist.
3719
0
  this->AddCMakeOutputFile(soutfile);
3720
3721
0
  if (permissions == 0) {
3722
0
    cmSystemTools::GetPermissions(sinfile, permissions);
3723
0
  }
3724
3725
0
  std::string::size_type pos = soutfile.rfind('/');
3726
0
  if (pos != std::string::npos) {
3727
0
    std::string path = soutfile.substr(0, pos);
3728
0
    cmSystemTools::MakeDirectory(path);
3729
0
  }
3730
3731
0
  if (copyonly) {
3732
0
    auto const copy_status =
3733
0
      cmSystemTools::CopyFileIfDifferent(sinfile, soutfile);
3734
0
    if (!copy_status) {
3735
0
      this->IssueMessage(
3736
0
        MessageType::FATAL_ERROR,
3737
0
        cmStrCat("Fail to copy ",
3738
0
                 copy_status.Path == cmsys::SystemTools::CopyStatus::SourcePath
3739
0
                   ? "source"
3740
0
                   : "destination",
3741
0
                 "file: ", copy_status.GetString()));
3742
0
      res = 0;
3743
0
    } else {
3744
0
      auto const status = cmSystemTools::SetPermissions(soutfile, permissions);
3745
0
      if (!status) {
3746
0
        this->IssueMessage(MessageType::FATAL_ERROR, status.GetString());
3747
0
        res = 0;
3748
0
      }
3749
0
    }
3750
0
    return res;
3751
0
  }
3752
3753
0
  std::string newLineCharacters;
3754
0
  std::ios::openmode omode = std::ios::out | std::ios::trunc;
3755
0
  if (newLine.IsValid()) {
3756
0
    newLineCharacters = newLine.GetCharacters();
3757
0
    omode |= std::ios::binary;
3758
0
  } else {
3759
0
    newLineCharacters = "\n";
3760
0
  }
3761
0
  std::string tempOutputFile = cmStrCat(soutfile, ".tmp");
3762
0
  cmsys::ofstream fout(tempOutputFile.c_str(), omode);
3763
0
  if (!fout) {
3764
0
    cmSystemTools::Error("Could not open file for write in copy operation " +
3765
0
                         tempOutputFile);
3766
0
    cmSystemTools::ReportLastSystemError("");
3767
0
    return 0;
3768
0
  }
3769
0
  cmsys::ifstream fin(sinfile.c_str());
3770
0
  if (!fin) {
3771
0
    cmSystemTools::Error("Could not open file for read in copy operation " +
3772
0
                         sinfile);
3773
0
    return 0;
3774
0
  }
3775
3776
0
  cmsys::FStream::BOM bom = cmsys::FStream::ReadBOM(fin);
3777
0
  if (bom != cmsys::FStream::BOM_None && bom != cmsys::FStream::BOM_UTF8) {
3778
0
    this->IssueMessage(
3779
0
      MessageType::FATAL_ERROR,
3780
0
      cmStrCat("File starts with a Byte-Order-Mark that is not UTF-8:\n  ",
3781
0
               sinfile));
3782
0
    return 0;
3783
0
  }
3784
  // rewind to copy BOM to output file
3785
0
  fin.seekg(0);
3786
3787
  // now copy input to output and expand variables in the
3788
  // input file at the same time
3789
0
  std::string inLine;
3790
0
  std::string outLine;
3791
0
  while (cmSystemTools::GetLineFromStream(fin, inLine)) {
3792
0
    outLine.clear();
3793
0
    this->ConfigureString(inLine, outLine, atOnly, escapeQuotes);
3794
0
    fout << outLine << newLineCharacters;
3795
0
  }
3796
  // close the files before attempting to copy
3797
0
  fin.close();
3798
0
  fout.close();
3799
3800
0
  auto status = cmSystemTools::MoveFileIfDifferent(tempOutputFile, soutfile);
3801
0
  if (!status) {
3802
0
    this->IssueMessage(MessageType::FATAL_ERROR, status.GetString());
3803
0
    res = 0;
3804
0
  } else {
3805
0
    status = cmSystemTools::SetPermissions(soutfile, permissions);
3806
0
    if (!status) {
3807
0
      this->IssueMessage(MessageType::FATAL_ERROR, status.GetString());
3808
0
      res = 0;
3809
0
    }
3810
0
  }
3811
3812
0
  return res;
3813
0
}
3814
3815
void cmMakefile::SetProperty(std::string const& prop, cmValue value)
3816
0
{
3817
0
  this->StateSnapshot.GetDirectory().SetProperty(prop, value, this->Backtrace);
3818
0
}
3819
3820
void cmMakefile::AppendProperty(std::string const& prop,
3821
                                std::string const& value, bool asString)
3822
0
{
3823
0
  this->StateSnapshot.GetDirectory().AppendProperty(prop, value, asString,
3824
0
                                                    this->Backtrace);
3825
0
}
3826
3827
cmValue cmMakefile::GetProperty(std::string const& prop) const
3828
0
{
3829
  // Check for computed properties.
3830
0
  static std::string output;
3831
0
  if (prop == "TESTS"_s) {
3832
0
    std::vector<std::string> keys;
3833
    // get list of keys
3834
0
    auto const* t = this;
3835
0
    std::transform(
3836
0
      t->Tests.begin(), t->Tests.end(), std::back_inserter(keys),
3837
0
      [](decltype(t->Tests)::value_type const& pair) { return pair.first; });
3838
0
    output = cmList::to_string(keys);
3839
0
    return cmValue(output);
3840
0
  }
3841
3842
0
  return this->StateSnapshot.GetDirectory().GetProperty(prop);
3843
0
}
3844
3845
cmValue cmMakefile::GetProperty(std::string const& prop, bool chain) const
3846
0
{
3847
0
  return this->StateSnapshot.GetDirectory().GetProperty(prop, chain);
3848
0
}
3849
3850
bool cmMakefile::GetPropertyAsBool(std::string const& prop) const
3851
0
{
3852
0
  return this->GetProperty(prop).IsOn();
3853
0
}
3854
3855
std::vector<std::string> cmMakefile::GetPropertyKeys() const
3856
0
{
3857
0
  return this->StateSnapshot.GetDirectory().GetPropertyKeys();
3858
0
}
3859
3860
cmTarget* cmMakefile::FindLocalNonAliasTarget(std::string const& name) const
3861
0
{
3862
0
  auto i = this->Targets.find(name);
3863
0
  if (i != this->Targets.end()) {
3864
0
    return &i->second;
3865
0
  }
3866
0
  return nullptr;
3867
0
}
3868
3869
cmTest* cmMakefile::CreateTest(std::string const& testName)
3870
0
{
3871
0
  cmTest* test = this->GetTest(testName);
3872
0
  if (test) {
3873
0
    return test;
3874
0
  }
3875
0
  auto newTest = cm::make_unique<cmTest>(this);
3876
0
  test = newTest.get();
3877
0
  newTest->SetName(testName);
3878
0
  this->Tests[testName] = std::move(newTest);
3879
0
  return test;
3880
0
}
3881
3882
cmTest* cmMakefile::GetTest(std::string const& testName) const
3883
0
{
3884
0
  auto mi = this->Tests.find(testName);
3885
0
  if (mi != this->Tests.end()) {
3886
0
    return mi->second.get();
3887
0
  }
3888
0
  return nullptr;
3889
0
}
3890
3891
void cmMakefile::GetTests(std::string const& config,
3892
                          std::vector<cmTest*>& tests) const
3893
0
{
3894
0
  for (auto const& generator : this->GetTestGenerators()) {
3895
0
    if (generator->TestsForConfig(config)) {
3896
0
      tests.push_back(generator->GetTest());
3897
0
    }
3898
0
  }
3899
0
}
3900
3901
void cmMakefile::AddCMakeDependFilesFromUser()
3902
0
{
3903
0
  cmList deps;
3904
0
  if (cmValue deps_str = this->GetProperty("CMAKE_CONFIGURE_DEPENDS")) {
3905
0
    deps.assign(*deps_str);
3906
0
  }
3907
0
  for (auto const& dep : deps) {
3908
0
    if (cmSystemTools::FileIsFullPath(dep)) {
3909
0
      this->AddCMakeDependFile(dep);
3910
0
    } else {
3911
0
      std::string f = cmStrCat(this->GetCurrentSourceDirectory(), '/', dep);
3912
0
      this->AddCMakeDependFile(f);
3913
0
    }
3914
0
  }
3915
0
}
3916
3917
std::string cmMakefile::FormatListFileStack() const
3918
0
{
3919
0
  std::vector<std::string> listFiles;
3920
0
  for (auto snp = this->StateSnapshot; snp.IsValid();
3921
0
       snp = snp.GetCallStackParent()) {
3922
0
    listFiles.emplace_back(snp.GetExecutionListFile());
3923
0
  }
3924
3925
0
  if (listFiles.empty()) {
3926
0
    return {};
3927
0
  }
3928
3929
0
  auto depth = 1;
3930
0
  std::transform(listFiles.begin(), listFiles.end(), listFiles.begin(),
3931
0
                 [&depth](std::string const& file) {
3932
0
                   return cmStrCat('[', depth++, "]\t", file);
3933
0
                 });
3934
3935
0
  return cmJoinStrings(cmMakeRange(listFiles.rbegin(), listFiles.rend()),
3936
0
                       "\n                "_s, {});
3937
0
}
3938
3939
void cmMakefile::PushScope()
3940
0
{
3941
0
  this->StateSnapshot =
3942
0
    this->GetState()->CreateVariableScopeSnapshot(this->StateSnapshot);
3943
0
  this->PushLoopBlockBarrier();
3944
3945
0
#if !defined(CMAKE_BOOTSTRAP)
3946
0
  this->GetGlobalGenerator()->GetFileLockPool().PushFunctionScope();
3947
0
#endif
3948
0
}
3949
3950
void cmMakefile::PopScope()
3951
0
{
3952
0
#if !defined(CMAKE_BOOTSTRAP)
3953
0
  this->GetGlobalGenerator()->GetFileLockPool().PopFunctionScope();
3954
0
#endif
3955
3956
0
  this->PopLoopBlockBarrier();
3957
3958
0
  this->PopSnapshot();
3959
0
}
3960
3961
void cmMakefile::RaiseScope(std::string const& var, char const* varDef)
3962
0
{
3963
0
  if (var.empty()) {
3964
0
    return;
3965
0
  }
3966
3967
0
  if (!this->StateSnapshot.RaiseScope(var, varDef)) {
3968
0
    this->IssueDiagnostic(
3969
0
      cmDiagnostics::CMD_AUTHOR,
3970
0
      cmStrCat("Cannot set \"", var, "\": current scope has no parent."));
3971
0
    return;
3972
0
  }
3973
3974
0
#ifndef CMAKE_BOOTSTRAP
3975
0
  cmVariableWatch* vv = this->GetVariableWatch();
3976
0
  if (vv) {
3977
0
    vv->VariableAccessed(var, cmVariableWatch::VARIABLE_MODIFIED_ACCESS,
3978
0
                         varDef, this);
3979
0
  }
3980
0
#endif
3981
0
}
3982
3983
void cmMakefile::RaiseScope(std::vector<std::string> const& variables)
3984
0
{
3985
0
  for (auto const& varName : variables) {
3986
0
    if (this->IsNormalDefinitionSet(varName)) {
3987
0
      this->RaiseScope(varName, this->GetDefinition(varName));
3988
0
    } else {
3989
      // unset variable in parent scope
3990
0
      this->RaiseScope(varName, nullptr);
3991
0
    }
3992
0
  }
3993
0
}
3994
3995
cmTarget* cmMakefile::AddImportedTarget(std::string const& name,
3996
                                        cm::TargetType type,
3997
                                        cm::ImportedTargetScope scope)
3998
0
{
3999
  // Create the target.
4000
0
  auto target =
4001
0
    cm::make_unique<cmTarget>(name, type, cmTarget::ImportedVisibility(scope),
4002
0
                              this, cmTarget::PerConfig::Yes);
4003
4004
  // Add to the set of available imported targets.
4005
0
  this->ImportedTargets[name] = target.get();
4006
0
  this->GetGlobalGenerator()->IndexTarget(target.get());
4007
0
  this->GetStateSnapshot().GetDirectory().AddImportedTargetName(name);
4008
4009
  // Transfer ownership to this cmMakefile object.
4010
0
  this->ImportedTargetsOwned.push_back(std::move(target));
4011
0
  return this->ImportedTargetsOwned.back().get();
4012
0
}
4013
4014
cmTarget* cmMakefile::AddForeignTarget(std::string const& origin,
4015
                                       std::string const& name)
4016
0
{
4017
0
  auto foreign_name = cmStrCat("@foreign_", origin, "::", name);
4018
0
  auto target = cm::make_unique<cmTarget>(
4019
0
    foreign_name, cm::TargetType::INTERFACE_LIBRARY,
4020
0
    cmTarget::Visibility::Foreign, this, cmTarget::PerConfig::Yes);
4021
4022
0
  this->ImportedTargets[foreign_name] = target.get();
4023
0
  this->GetGlobalGenerator()->IndexTarget(target.get());
4024
0
  this->GetStateSnapshot().GetDirectory().AddImportedTargetName(foreign_name);
4025
4026
0
  this->ImportedTargetsOwned.push_back(std::move(target));
4027
0
  return this->ImportedTargetsOwned.back().get();
4028
0
}
4029
4030
cmTarget* cmMakefile::FindTargetToUse(std::string const& name,
4031
                                      cm::TargetDomainSet domains) const
4032
0
{
4033
  // Look for an imported target.  These take priority because they
4034
  // are more local in scope and do not have to be globally unique.
4035
0
  auto targetName = name;
4036
0
  if (domains.contains(cm::TargetDomain::ALIAS)) {
4037
    // Look for local alias targets.
4038
0
    auto alias = this->AliasTargets.find(name);
4039
0
    if (alias != this->AliasTargets.end()) {
4040
0
      targetName = alias->second;
4041
0
    }
4042
0
  }
4043
0
  auto const imported = this->ImportedTargets.find(targetName);
4044
4045
0
  bool const useForeign = domains.contains(cm::TargetDomain::FOREIGN);
4046
0
  bool const useNative = domains.contains(cm::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() == cm::TargetType::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 cm::TargetType::EXECUTABLE:
4111
0
        e << "an executable ";
4112
0
        break;
4113
0
      case cm::TargetType::STATIC_LIBRARY:
4114
0
        e << "a static library ";
4115
0
        break;
4116
0
      case cm::TargetType::SHARED_LIBRARY:
4117
0
        e << "a shared library ";
4118
0
        break;
4119
0
      case cm::TargetType::MODULE_LIBRARY:
4120
0
        e << "a module library ";
4121
0
        break;
4122
0
      case cm::TargetType::UTILITY:
4123
0
        e << "a custom target ";
4124
0
        break;
4125
0
      case cm::TargetType::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
}