Coverage Report

Created: 2026-07-14 07:09

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
  return cmSystemTools::IsSubDirectory(filename, this->GetHomeDirectory()) ||
2537
0
    (cmSystemTools::IsSubDirectory(filename, this->GetHomeOutputDirectory()) &&
2538
0
     !cmSystemTools::IsSubDirectory(filename, "/CMakeFiles"));
2539
0
}
2540
2541
size_t cmMakefile::GetRecursionDepthLimit() const
2542
0
{
2543
0
  size_t depth = CMake_DEFAULT_RECURSION_LIMIT;
2544
0
  if (cmValue depthStr =
2545
0
        this->GetDefinition("CMAKE_MAXIMUM_RECURSION_DEPTH")) {
2546
0
    unsigned long depthUL;
2547
0
    if (cmStrToULong(depthStr.GetCStr(), &depthUL)) {
2548
0
      depth = depthUL;
2549
0
    }
2550
0
  } else if (cm::optional<std::string> depthEnv =
2551
0
               cmSystemTools::GetEnvVar("CMAKE_MAXIMUM_RECURSION_DEPTH")) {
2552
0
    unsigned long depthUL;
2553
0
    if (cmStrToULong(*depthEnv, &depthUL)) {
2554
0
      depth = depthUL;
2555
0
    }
2556
0
  }
2557
0
  return depth;
2558
0
}
2559
2560
size_t cmMakefile::GetRecursionDepth() const
2561
0
{
2562
0
  return this->RecursionDepth;
2563
0
}
2564
2565
void cmMakefile::SetRecursionDepth(size_t recursionDepth)
2566
0
{
2567
0
  this->RecursionDepth = recursionDepth;
2568
0
}
2569
2570
std::string cmMakefile::NewDeferId() const
2571
0
{
2572
0
  return this->GetGlobalGenerator()->NewDeferId();
2573
0
}
2574
2575
bool cmMakefile::DeferCall(std::string id, std::string file,
2576
                           cmListFileFunction lff)
2577
0
{
2578
0
  if (!this->Defer) {
2579
0
    return false;
2580
0
  }
2581
0
  this->Defer->Commands.emplace_back(
2582
0
    DeferCommand{ std::move(id), std::move(file), std::move(lff) });
2583
0
  return true;
2584
0
}
2585
2586
bool cmMakefile::DeferCancelCall(std::string const& id)
2587
0
{
2588
0
  if (!this->Defer) {
2589
0
    return false;
2590
0
  }
2591
0
  for (DeferCommand& dc : this->Defer->Commands) {
2592
0
    if (dc.Id == id) {
2593
0
      dc.Id.clear();
2594
0
    }
2595
0
  }
2596
0
  return true;
2597
0
}
2598
2599
cm::optional<std::string> cmMakefile::DeferGetCallIds() const
2600
0
{
2601
0
  cm::optional<std::string> ids;
2602
0
  if (this->Defer) {
2603
0
    ids = cmList::to_string(
2604
0
      cmMakeRange(this->Defer->Commands)
2605
0
        .filter([](DeferCommand const& dc) -> bool { return !dc.Id.empty(); })
2606
0
        .transform(
2607
0
          [](DeferCommand const& dc) -> std::string const& { return dc.Id; }));
2608
0
  }
2609
0
  return ids;
2610
0
}
2611
2612
cm::optional<std::string> cmMakefile::DeferGetCall(std::string const& id) const
2613
0
{
2614
0
  cm::optional<std::string> call;
2615
0
  if (this->Defer) {
2616
0
    std::string tmp;
2617
0
    for (DeferCommand const& dc : this->Defer->Commands) {
2618
0
      if (dc.Id == id) {
2619
0
        tmp = dc.Command.OriginalName();
2620
0
        for (cmListFileArgument const& arg : dc.Command.Arguments()) {
2621
0
          tmp = cmStrCat(tmp, ';', arg.Value);
2622
0
        }
2623
0
        break;
2624
0
      }
2625
0
    }
2626
0
    call = std::move(tmp);
2627
0
  }
2628
0
  return call;
2629
0
}
2630
2631
namespace {
2632
cmPolicies::PolicyStatus CheckCMP0219Impl(cmPolicies::PolicyStatus status,
2633
                                          std::string const& calleeName,
2634
                                          bool hasBackslashes,
2635
                                          std::set<std::string>& warned)
2636
0
{
2637
0
  if (status == cmPolicies::WARN && hasBackslashes &&
2638
0
      warned.insert(calleeName).second) {
2639
0
    return cmPolicies::WARN;
2640
0
  }
2641
  // Suppress WARN when there are no backslashes or already warned.
2642
0
  return status == cmPolicies::NEW ? cmPolicies::NEW : cmPolicies::OLD;
2643
0
}
2644
}
2645
2646
cmPolicies::PolicyStatus cmMakefile::CheckCMP0219(
2647
  std::string const& calleeName, std::vector<std::string> const& args)
2648
0
{
2649
0
  bool const hasBackslashes =
2650
0
    std::any_of(args.begin(), args.end(), [](std::string const& s) {
2651
0
      return s.find('\\') != std::string::npos;
2652
0
    });
2653
0
  return CheckCMP0219Impl(GetPolicyStatus(cmPolicies::CMP0219), calleeName,
2654
0
                          hasBackslashes, WarnedCMP0219);
2655
0
}
2656
2657
cmPolicies::PolicyStatus cmMakefile::CheckCMP0219(
2658
  std::string const& calleeName, std::vector<cmListFileArgument> const& args)
2659
0
{
2660
0
  bool const hasBackslashes =
2661
0
    std::any_of(args.begin(), args.end(), [](cmListFileArgument const& s) {
2662
0
      return s.Value.find('\\') != std::string::npos;
2663
0
    });
2664
0
  return CheckCMP0219Impl(GetPolicyStatus(cmPolicies::CMP0219), calleeName,
2665
0
                          hasBackslashes, WarnedCMP0219);
2666
0
}
2667
2668
void cmMakefile::IssueCMP0219Warning(
2669
  std::string const& calleeName, std::vector<std::string> const& args) const
2670
0
{
2671
0
  std::string oldArgs;
2672
0
  for (std::string const& arg : args) {
2673
0
    if (arg.find('\\') == std::string::npos) {
2674
0
      continue;
2675
0
    }
2676
0
    if (!oldArgs.empty()) {
2677
0
      oldArgs += '\n';
2678
0
    }
2679
0
    oldArgs += cmStrCat(" \"", arg, '"');
2680
0
  }
2681
2682
0
  std::string newArgs = oldArgs;
2683
0
  cmSystemTools::ReplaceString(newArgs, "\\", "\\\\");
2684
2685
0
  this->IssueDiagnostic(
2686
0
    cmDiagnostics::CMD_POLICY,
2687
0
    cmStrCat(
2688
0
      cmPolicies::GetPolicyWarning(cmPolicies::CMP0219), '\n', "Command \"",
2689
0
      calleeName, "\" called with arguments containing backslashes.\n",
2690
0
      "Since the policy is not set, backslashes in the arguments:\n", oldArgs,
2691
0
      "\n", "will be interpreted as escape sequences for compatibility.\n",
2692
0
      "Set the policy to NEW to instead pass\n", newArgs, "\n",
2693
0
      "so that argument parsing will preserve the original values."));
2694
0
}
2695
2696
void cmMakefile::IssueCMP0219Warning(
2697
  std::string const& calleeName,
2698
  std::vector<cmListFileArgument> const& args) const
2699
0
{
2700
0
  std::vector<std::string> stringArgs;
2701
0
  stringArgs.reserve(args.size());
2702
0
  for (cmListFileArgument const& arg : args) {
2703
0
    stringArgs.push_back(arg.Value);
2704
0
  }
2705
0
  this->IssueCMP0219Warning(calleeName, stringArgs);
2706
0
}
2707
2708
MessageType cmMakefile::ExpandVariablesInStringImpl(
2709
  std::string& errorstr, std::string& source, bool escapeQuotes,
2710
  bool noEscapes, bool atOnly, char const* filename, long line,
2711
  bool replaceAt) const
2712
0
{
2713
  // This method replaces ${VAR} and @VAR@ where VAR is looked up
2714
  // with GetDefinition(), if not found in the map, nothing is expanded.
2715
  // It also supports the $ENV{VAR} syntax where VAR is looked up in
2716
  // the current environment variables.
2717
2718
0
  char const* in = source.c_str();
2719
0
  char const* last = in;
2720
0
  std::string result;
2721
0
  result.reserve(source.size());
2722
0
  std::vector<t_lookup> openstack;
2723
0
  bool error = false;
2724
0
  bool done = false;
2725
0
  MessageType mtype = MessageType::LOG;
2726
2727
0
  cmState* state = this->GetCMakeInstance()->GetState();
2728
2729
0
  static std::string const lineVar = "CMAKE_CURRENT_LIST_LINE";
2730
0
  do {
2731
0
    char inc = *in;
2732
0
    switch (inc) {
2733
0
      case '}':
2734
0
        if (!openstack.empty()) {
2735
0
          t_lookup var = openstack.back();
2736
0
          openstack.pop_back();
2737
0
          result.append(last, in - last);
2738
0
          std::string const& lookup = result.substr(var.loc);
2739
0
          cmValue value = nullptr;
2740
0
          std::string varresult;
2741
0
          std::string svalue;
2742
0
          switch (var.domain) {
2743
0
            case NORMAL:
2744
0
              if (filename && lookup == lineVar) {
2745
0
                cmListFileContext const& top = this->Backtrace.Top();
2746
0
                if (top.DeferId) {
2747
0
                  varresult = cmStrCat("DEFERRED:"_s, *top.DeferId);
2748
0
                } else {
2749
0
                  varresult = std::to_string(line);
2750
0
                }
2751
0
              } else {
2752
0
                value = this->GetDefinition(lookup);
2753
0
              }
2754
0
              break;
2755
0
            case ENVIRONMENT:
2756
0
              if (cmSystemTools::GetEnv(lookup, svalue)) {
2757
0
                value = cmValue(svalue);
2758
0
              }
2759
0
              break;
2760
0
            case CACHE:
2761
0
              value = state->GetCacheEntryValue(lookup);
2762
0
              break;
2763
0
          }
2764
          // Get the string we're meant to append to.
2765
0
          if (value) {
2766
0
            if (escapeQuotes) {
2767
0
              varresult = cmEscapeQuotes(*value);
2768
0
            } else {
2769
0
              varresult = *value;
2770
0
            }
2771
0
          } else {
2772
0
            this->MaybeWarnUninitialized(lookup, filename);
2773
0
          }
2774
0
          result.replace(var.loc, result.size() - var.loc, varresult);
2775
          // Start looking from here on out.
2776
0
          last = in + 1;
2777
0
        }
2778
0
        break;
2779
0
      case '$':
2780
0
        if (!atOnly) {
2781
0
          t_lookup lookup;
2782
0
          char const* next = in + 1;
2783
0
          char const* start = nullptr;
2784
0
          char nextc = *next;
2785
0
          if (nextc == '{') {
2786
            // Looking for a variable.
2787
0
            start = in + 2;
2788
0
            lookup.domain = NORMAL;
2789
0
          } else if (nextc == '<') {
2790
0
          } else if (!nextc) {
2791
0
            result.append(last, next - last);
2792
0
            last = next;
2793
0
          } else if (cmHasLiteralPrefix(next, "ENV{")) {
2794
            // Looking for an environment variable.
2795
0
            start = in + 5;
2796
0
            lookup.domain = ENVIRONMENT;
2797
0
          } else if (cmHasLiteralPrefix(next, "CACHE{")) {
2798
            // Looking for a cache variable.
2799
0
            start = in + 7;
2800
0
            lookup.domain = CACHE;
2801
0
          } else {
2802
0
            if (this->cmNamedCurly.find(next)) {
2803
0
              errorstr = "Syntax $" +
2804
0
                std::string(next, this->cmNamedCurly.end()) +
2805
0
                "{} is not supported.  Only ${}, $ENV{}, "
2806
0
                "and $CACHE{} are allowed.";
2807
0
              mtype = MessageType::FATAL_ERROR;
2808
0
              error = true;
2809
0
            }
2810
0
          }
2811
0
          if (start) {
2812
0
            result.append(last, in - last);
2813
0
            last = start;
2814
0
            in = start - 1;
2815
0
            lookup.loc = result.size();
2816
0
            openstack.push_back(lookup);
2817
0
          }
2818
0
          break;
2819
0
        }
2820
0
        CM_FALLTHROUGH;
2821
0
      case '\\':
2822
0
        if (!noEscapes) {
2823
0
          char const* next = in + 1;
2824
0
          char nextc = *next;
2825
0
          if (nextc == 't') {
2826
0
            result.append(last, in - last);
2827
0
            result.push_back('\t');
2828
0
            last = next + 1;
2829
0
          } else if (nextc == 'n') {
2830
0
            result.append(last, in - last);
2831
0
            result.push_back('\n');
2832
0
            last = next + 1;
2833
0
          } else if (nextc == 'r') {
2834
0
            result.append(last, in - last);
2835
0
            result.push_back('\r');
2836
0
            last = next + 1;
2837
0
          } else if (nextc == ';' && openstack.empty()) {
2838
            // Handled in ExpandListArgument; pass the backslash literally.
2839
0
          } else if (cmsysString_isalnum(nextc) || nextc == '\0') {
2840
0
            errorstr += "Invalid character escape '\\";
2841
0
            if (nextc) {
2842
0
              errorstr += nextc;
2843
0
              errorstr += "'.";
2844
0
            } else {
2845
0
              errorstr += "' (at end of input).";
2846
0
            }
2847
0
            error = true;
2848
0
          } else {
2849
            // Take what we've found so far, skipping the escape character.
2850
0
            result.append(last, in - last);
2851
            // Start tracking from the next character.
2852
0
            last = in + 1;
2853
0
          }
2854
          // Skip the next character since it was escaped, but don't read past
2855
          // the end of the string.
2856
0
          if (*last) {
2857
0
            ++in;
2858
0
          }
2859
0
        }
2860
0
        break;
2861
0
      case '\n':
2862
        // Onto the next line.
2863
0
        ++line;
2864
0
        break;
2865
0
      case '\0':
2866
0
        done = true;
2867
0
        break;
2868
0
      case '@':
2869
0
        if (replaceAt) {
2870
0
          char const* nextAt = strchr(in + 1, '@');
2871
0
          if (nextAt && nextAt != in + 1 &&
2872
0
              nextAt ==
2873
0
                in + 1 +
2874
0
                  std::strspn(in + 1,
2875
0
                              "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
2876
0
                              "abcdefghijklmnopqrstuvwxyz"
2877
0
                              "0123456789/_.+-")) {
2878
0
            std::string variable(in + 1, nextAt - in - 1);
2879
2880
0
            std::string varresult;
2881
0
            if (filename && variable == lineVar) {
2882
0
              varresult = std::to_string(line);
2883
0
            } else {
2884
0
              cmValue def = this->GetDefinition(variable);
2885
0
              if (def) {
2886
0
                varresult = *def;
2887
0
              } else {
2888
0
                this->MaybeWarnUninitialized(variable, filename);
2889
0
              }
2890
0
            }
2891
2892
0
            if (escapeQuotes) {
2893
0
              varresult = cmEscapeQuotes(varresult);
2894
0
            }
2895
            // Skip over the variable.
2896
0
            result.append(last, in - last);
2897
0
            result.append(varresult);
2898
0
            in = nextAt;
2899
0
            last = in + 1;
2900
0
            break;
2901
0
          }
2902
0
        }
2903
        // Failed to find a valid @ expansion; treat it as literal.
2904
0
        CM_FALLTHROUGH;
2905
0
      default: {
2906
0
        if (!openstack.empty() &&
2907
0
            !(cmsysString_isalnum(inc) || inc == '_' || inc == '/' ||
2908
0
              inc == '.' || inc == '+' || inc == '-')) {
2909
0
          errorstr += cmStrCat("Invalid character ('", inc);
2910
0
          result.append(last, in - last);
2911
0
          errorstr += cmStrCat("') in a variable name: '",
2912
0
                               result.substr(openstack.back().loc), '\'');
2913
0
          mtype = MessageType::FATAL_ERROR;
2914
0
          error = true;
2915
0
        }
2916
0
        break;
2917
0
      }
2918
0
    }
2919
    // Look at the next character.
2920
0
  } while (!error && !done && *++in);
2921
2922
  // Check for open variable references yet.
2923
0
  if (!error && !openstack.empty()) {
2924
0
    errorstr += "There is an unterminated variable reference.";
2925
0
    error = true;
2926
0
  }
2927
2928
0
  if (error) {
2929
0
    std::string e = "Syntax error in cmake code ";
2930
0
    if (filename) {
2931
      // This filename and line number may be more specific than the
2932
      // command context because one command invocation can have
2933
      // arguments on multiple lines.
2934
0
      e += cmStrCat("at\n  ", filename, ':', line, '\n');
2935
0
    }
2936
0
    errorstr = cmStrCat(e, "when parsing string\n  ", source, '\n', errorstr);
2937
0
    mtype = MessageType::FATAL_ERROR;
2938
0
  } else {
2939
    // Append the rest of the unchanged part of the string.
2940
0
    result.append(last);
2941
2942
0
    source = result;
2943
0
  }
2944
2945
0
  return mtype;
2946
0
}
2947
2948
void cmMakefile::RemoveVariablesInString(std::string& source,
2949
                                         bool atOnly) const
2950
0
{
2951
0
  if (!atOnly) {
2952
0
    cmsys::RegularExpression var("(\\${[A-Za-z_0-9]*})");
2953
0
    while (var.find(source)) {
2954
0
      source.erase(var.start(), var.end() - var.start());
2955
0
    }
2956
0
  }
2957
2958
0
  if (!atOnly) {
2959
0
    cmsys::RegularExpression varb("(\\$ENV{[A-Za-z_0-9]*})");
2960
0
    while (varb.find(source)) {
2961
0
      source.erase(varb.start(), varb.end() - varb.start());
2962
0
    }
2963
0
  }
2964
0
  cmsys::RegularExpression var2("(@[A-Za-z_0-9]*@)");
2965
0
  while (var2.find(source)) {
2966
0
    source.erase(var2.start(), var2.end() - var2.start());
2967
0
  }
2968
0
}
2969
2970
void cmMakefile::InitCMAKE_CONFIGURATION_TYPES(std::string const& genDefault)
2971
0
{
2972
0
  if (this->GetDefinition("CMAKE_CONFIGURATION_TYPES")) {
2973
0
    return;
2974
0
  }
2975
0
  std::string initConfigs;
2976
0
  if (this->GetCMakeInstance()->GetIsInTryCompile() ||
2977
0
      !cmSystemTools::GetEnv("CMAKE_CONFIGURATION_TYPES", initConfigs)) {
2978
0
    initConfigs = genDefault;
2979
0
  }
2980
0
  this->AddCacheDefinition(
2981
0
    "CMAKE_CONFIGURATION_TYPES", initConfigs,
2982
0
    "Semicolon separated list of supported configuration types, "
2983
0
    "only supports Debug, Release, MinSizeRel, and RelWithDebInfo, "
2984
0
    "anything else will be ignored.",
2985
0
    cmStateEnums::STRING);
2986
0
}
2987
2988
std::string cmMakefile::GetDefaultConfiguration() const
2989
0
{
2990
0
  if (this->GetGlobalGenerator()->IsMultiConfig()) {
2991
0
    return std::string{};
2992
0
  }
2993
0
  return this->GetSafeDefinition("CMAKE_BUILD_TYPE");
2994
0
}
2995
2996
std::vector<std::string> cmMakefile::GetGeneratorConfigs(
2997
  GeneratorConfigQuery mode) const
2998
0
{
2999
0
  cmList configs;
3000
0
  if (this->GetGlobalGenerator()->IsMultiConfig()) {
3001
0
    configs.assign(this->GetDefinition("CMAKE_CONFIGURATION_TYPES"));
3002
0
  } else if (mode != cmMakefile::OnlyMultiConfig) {
3003
0
    std::string const& buildType = this->GetSafeDefinition("CMAKE_BUILD_TYPE");
3004
0
    if (!buildType.empty()) {
3005
0
      configs.emplace_back(buildType);
3006
0
    }
3007
0
  }
3008
0
  if (mode == cmMakefile::IncludeEmptyConfig && configs.empty()) {
3009
0
    configs.emplace_back();
3010
0
  }
3011
0
  return std::move(configs.data());
3012
0
}
3013
3014
bool cmMakefile::IsFunctionBlocked(cmListFileFunction const& lff,
3015
                                   cmExecutionStatus& status)
3016
0
{
3017
  // if there are no blockers get out of here
3018
0
  if (this->FunctionBlockers.empty()) {
3019
0
    return false;
3020
0
  }
3021
3022
0
  return this->FunctionBlockers.top()->IsFunctionBlocked(lff, status);
3023
0
}
3024
3025
void cmMakefile::PushFunctionBlockerBarrier()
3026
1
{
3027
1
  this->FunctionBlockerBarriers.push_back(this->FunctionBlockers.size());
3028
1
}
3029
3030
void cmMakefile::PopFunctionBlockerBarrier(bool reportError)
3031
1
{
3032
  // Remove any extra entries pushed on the barrier.
3033
1
  FunctionBlockersType::size_type barrier =
3034
1
    this->FunctionBlockerBarriers.back();
3035
1
  while (this->FunctionBlockers.size() > barrier) {
3036
0
    std::unique_ptr<cmFunctionBlocker> fb(
3037
0
      std::move(this->FunctionBlockers.top()));
3038
0
    this->FunctionBlockers.pop();
3039
0
    if (reportError) {
3040
      // Report the context in which the unclosed block was opened.
3041
0
      cmListFileContext const& lfc = fb->GetStartingContext();
3042
0
      std::ostringstream e;
3043
      /* clang-format off */
3044
0
      e << "A logical block opening on the line\n"
3045
0
           "  " << lfc << "\n"
3046
0
           "is not closed.";
3047
      /* clang-format on */
3048
0
      this->IssueMessage(MessageType::FATAL_ERROR, e.str());
3049
0
      reportError = false;
3050
0
    }
3051
0
  }
3052
3053
  // Remove the barrier.
3054
1
  this->FunctionBlockerBarriers.pop_back();
3055
1
}
3056
3057
void cmMakefile::PushLoopBlock()
3058
0
{
3059
0
  assert(!this->LoopBlockCounter.empty());
3060
0
  this->LoopBlockCounter.top()++;
3061
0
}
3062
3063
void cmMakefile::PopLoopBlock()
3064
0
{
3065
0
  assert(!this->LoopBlockCounter.empty());
3066
0
  assert(this->LoopBlockCounter.top() > 0);
3067
0
  this->LoopBlockCounter.top()--;
3068
0
}
3069
3070
void cmMakefile::PushLoopBlockBarrier()
3071
1
{
3072
1
  this->LoopBlockCounter.push(0);
3073
1
}
3074
3075
void cmMakefile::PopLoopBlockBarrier()
3076
0
{
3077
0
  assert(!this->LoopBlockCounter.empty());
3078
0
  assert(this->LoopBlockCounter.top() == 0);
3079
0
  this->LoopBlockCounter.pop();
3080
0
}
3081
3082
bool cmMakefile::IsLoopBlock() const
3083
0
{
3084
0
  assert(!this->LoopBlockCounter.empty());
3085
0
  return !this->LoopBlockCounter.empty() && this->LoopBlockCounter.top() > 0;
3086
0
}
3087
3088
bool cmMakefile::ExpandArguments(std::vector<cmListFileArgument> const& inArgs,
3089
                                 std::vector<std::string>& outArgs) const
3090
0
{
3091
0
  std::string const& filename = this->GetBacktrace().Top().FilePath;
3092
0
  std::string value;
3093
0
  outArgs.reserve(inArgs.size());
3094
0
  for (cmListFileArgument const& i : inArgs) {
3095
    // No expansion in a bracket argument.
3096
0
    if (i.Delim == cmListFileArgument::Bracket) {
3097
0
      outArgs.push_back(i.Value);
3098
0
      continue;
3099
0
    }
3100
    // Expand the variables in the argument.
3101
0
    value = i.Value;
3102
0
    this->ExpandVariablesInString(value, false, false, false, filename.c_str(),
3103
0
                                  i.Line, false, false);
3104
3105
    // If the argument is quoted, it should be one argument.
3106
    // Otherwise, it may be a list of arguments.
3107
0
    if (i.Delim == cmListFileArgument::Quoted) {
3108
0
      outArgs.push_back(value);
3109
0
    } else {
3110
0
      cmExpandList(value, outArgs);
3111
0
    }
3112
0
  }
3113
0
  return !cmSystemTools::GetFatalErrorOccurred();
3114
0
}
3115
3116
bool cmMakefile::ExpandArguments(
3117
  std::vector<cmListFileArgument> const& inArgs,
3118
  std::vector<cmExpandedCommandArgument>& outArgs) const
3119
0
{
3120
0
  std::string const& filename = this->GetBacktrace().Top().FilePath;
3121
0
  std::string value;
3122
0
  outArgs.reserve(inArgs.size());
3123
0
  for (cmListFileArgument const& i : inArgs) {
3124
    // No expansion in a bracket argument.
3125
0
    if (i.Delim == cmListFileArgument::Bracket) {
3126
0
      outArgs.emplace_back(i.Value, true);
3127
0
      continue;
3128
0
    }
3129
    // Expand the variables in the argument.
3130
0
    value = i.Value;
3131
0
    this->ExpandVariablesInString(value, false, false, false, filename.c_str(),
3132
0
                                  i.Line, false, false);
3133
3134
    // If the argument is quoted, it should be one argument.
3135
    // Otherwise, it may be a list of arguments.
3136
0
    if (i.Delim == cmListFileArgument::Quoted) {
3137
0
      outArgs.emplace_back(value, true);
3138
0
    } else {
3139
0
      cmList stringArgs{ value };
3140
0
      for (std::string const& stringArg : stringArgs) {
3141
0
        outArgs.emplace_back(stringArg, false);
3142
0
      }
3143
0
    }
3144
0
  }
3145
0
  return !cmSystemTools::GetFatalErrorOccurred();
3146
0
}
3147
3148
void cmMakefile::AddFunctionBlocker(std::unique_ptr<cmFunctionBlocker> fb)
3149
0
{
3150
0
  if (!this->ExecutionStatusStack.empty()) {
3151
    // Record the context in which the blocker is created.
3152
0
    fb->SetStartingContext(this->Backtrace.Top());
3153
0
  }
3154
3155
0
  this->FunctionBlockers.push(std::move(fb));
3156
0
}
3157
3158
std::unique_ptr<cmFunctionBlocker> cmMakefile::RemoveFunctionBlocker()
3159
0
{
3160
0
  assert(!this->FunctionBlockers.empty());
3161
0
  assert(this->FunctionBlockerBarriers.empty() ||
3162
0
         this->FunctionBlockers.size() > this->FunctionBlockerBarriers.back());
3163
3164
0
  auto b = std::move(this->FunctionBlockers.top());
3165
0
  this->FunctionBlockers.pop();
3166
0
  return b;
3167
0
}
3168
3169
std::string const& cmMakefile::GetHomeDirectory() const
3170
0
{
3171
0
  return this->GetCMakeInstance()->GetHomeDirectory();
3172
0
}
3173
3174
std::string const& cmMakefile::GetHomeOutputDirectory() const
3175
0
{
3176
0
  return this->GetCMakeInstance()->GetHomeOutputDirectory();
3177
0
}
3178
3179
void cmMakefile::SetScriptModeFile(std::string const& scriptfile)
3180
1
{
3181
1
  this->AddDefinition("CMAKE_SCRIPT_MODE_FILE", scriptfile);
3182
1
}
3183
3184
void cmMakefile::SetArgcArgv(std::vector<std::string> const& args)
3185
1
{
3186
1
  this->AddDefinition("CMAKE_ARGC", std::to_string(args.size()));
3187
3188
4
  for (auto i = 0u; i < args.size(); ++i) {
3189
3
    this->AddDefinition(cmStrCat("CMAKE_ARGV", i), args[i]);
3190
3
  }
3191
1
}
3192
3193
cmSourceFile* cmMakefile::GetSource(std::string const& sourceName,
3194
                                    cmSourceFileLocationKind kind) const
3195
0
{
3196
  // First check "Known" paths (avoids the creation of cmSourceFileLocation)
3197
0
  if (kind == cmSourceFileLocationKind::Known) {
3198
0
    auto sfsi = this->KnownFileSearchIndex.find(sourceName);
3199
0
    if (sfsi != this->KnownFileSearchIndex.end()) {
3200
0
      return sfsi->second;
3201
0
    }
3202
0
  }
3203
3204
0
  cmSourceFileLocation sfl(this, sourceName, kind);
3205
0
  auto name = this->GetCMakeInstance()->StripExtension(sfl.GetName());
3206
#if defined(_WIN32) || defined(__APPLE__)
3207
  name = cmSystemTools::LowerCase(name);
3208
#endif
3209
0
  auto sfsi = this->SourceFileSearchIndex.find(name);
3210
0
  if (sfsi != this->SourceFileSearchIndex.end()) {
3211
0
    for (auto* sf : sfsi->second) {
3212
0
      if (sf->Matches(sfl)) {
3213
0
        return sf;
3214
0
      }
3215
0
    }
3216
0
  }
3217
0
  return nullptr;
3218
0
}
3219
3220
cmSourceFile* cmMakefile::CreateSource(std::string const& sourceName,
3221
                                       bool generated,
3222
                                       cmSourceFileLocationKind kind)
3223
0
{
3224
0
  auto sf = cm::make_unique<cmSourceFile>(this, sourceName, generated, kind);
3225
0
  auto name =
3226
0
    this->GetCMakeInstance()->StripExtension(sf->GetLocation().GetName());
3227
#if defined(_WIN32) || defined(__APPLE__)
3228
  name = cmSystemTools::LowerCase(name);
3229
#endif
3230
0
  this->SourceFileSearchIndex[name].push_back(sf.get());
3231
  // for "Known" paths add direct lookup (used for faster lookup in GetSource)
3232
0
  if (kind == cmSourceFileLocationKind::Known) {
3233
0
    this->KnownFileSearchIndex[sourceName] = sf.get();
3234
0
  }
3235
3236
0
  this->SourceFiles.push_back(std::move(sf));
3237
3238
0
  return this->SourceFiles.back().get();
3239
0
}
3240
3241
cmSourceFile* cmMakefile::GetOrCreateSource(std::string const& sourceName,
3242
                                            bool generated,
3243
                                            cmSourceFileLocationKind kind)
3244
0
{
3245
0
  if (cmSourceFile* esf = this->GetSource(sourceName, kind)) {
3246
0
    return esf;
3247
0
  }
3248
0
  return this->CreateSource(sourceName, generated, kind);
3249
0
}
3250
3251
cmSourceFile* cmMakefile::GetOrCreateGeneratedSource(
3252
  std::string const& sourceName)
3253
0
{
3254
0
  cmSourceFile* sf =
3255
0
    this->GetOrCreateSource(sourceName, true, cmSourceFileLocationKind::Known);
3256
0
  sf->MarkAsGenerated(); // In case we did not create the source file.
3257
0
  return sf;
3258
0
}
3259
3260
void cmMakefile::CreateGeneratedOutputs(
3261
  std::vector<std::string> const& outputs)
3262
0
{
3263
0
  for (std::string const& o : outputs) {
3264
0
    if (cmGeneratorExpression::Find(o) == std::string::npos) {
3265
0
      this->GetOrCreateGeneratedSource(o);
3266
0
    }
3267
0
  }
3268
0
}
3269
3270
void cmMakefile::AddTargetObject(std::string const& tgtName,
3271
                                 std::string const& objFile)
3272
0
{
3273
0
  cmSourceFile* sf =
3274
0
    this->GetOrCreateSource(objFile, true, cmSourceFileLocationKind::Known);
3275
0
  sf->SetSpecialSourceType(cmSourceFile::SpecialSourceType::Object);
3276
0
  sf->SetObjectLibrary(tgtName);
3277
0
  sf->SetProperty("EXTERNAL_OBJECT", "1");
3278
  // TODO: Compute a language for this object based on the associated source
3279
  // file that compiles to it. Needs a policy as it likely affects link
3280
  // language selection if done unconditionally.
3281
0
#if !defined(CMAKE_BOOTSTRAP)
3282
0
  this->SourceGroups[this->ObjectLibrariesSourceGroupIndex]->AddGroupFile(
3283
0
    sf->ResolveFullPath());
3284
0
#endif
3285
0
}
3286
3287
void cmMakefile::EnableLanguage(std::vector<std::string> const& languages,
3288
                                bool optional)
3289
0
{
3290
0
  if (this->DeferRunning) {
3291
0
    this->IssueMessage(
3292
0
      MessageType::FATAL_ERROR,
3293
0
      "Languages may not be enabled during deferred execution.");
3294
0
    return;
3295
0
  }
3296
0
  if (char const* def = this->GetGlobalGenerator()->GetCMakeCFGIntDir()) {
3297
0
    this->AddDefinition("CMAKE_CFG_INTDIR", def);
3298
0
  }
3299
3300
0
  std::vector<std::string> unique_languages;
3301
0
  {
3302
0
    std::vector<std::string> duplicate_languages;
3303
0
    for (std::string const& language : languages) {
3304
0
      if (!cm::contains(unique_languages, language)) {
3305
0
        unique_languages.push_back(language);
3306
0
      } else if (!cm::contains(duplicate_languages, language)) {
3307
0
        duplicate_languages.push_back(language);
3308
0
      }
3309
0
    }
3310
0
    if (!duplicate_languages.empty()) {
3311
0
      auto quantity = duplicate_languages.size() == 1 ? " has"_s : "s have"_s;
3312
0
      this->IssueDiagnostic(
3313
0
        cmDiagnostics::CMD_AUTHOR,
3314
0
        cmStrCat("Languages to be enabled may not be specified more "
3315
0
                 "than once at the same time. The following language",
3316
0
                 quantity, " been specified multiple times: ",
3317
0
                 cmJoin(duplicate_languages, ", ")));
3318
0
    }
3319
0
  }
3320
3321
  // If RC is explicitly listed we need to do it after other languages.
3322
  // On some platforms we enable RC implicitly while enabling others.
3323
  // Do not let that look like recursive enable_language(RC).
3324
0
  std::vector<std::string> languages_without_RC;
3325
0
  std::vector<std::string> languages_for_RC;
3326
0
  languages_without_RC.reserve(unique_languages.size());
3327
0
  for (std::string const& language : unique_languages) {
3328
0
    if (language == "RC"_s) {
3329
0
      languages_for_RC.push_back(language);
3330
0
    } else {
3331
0
      languages_without_RC.push_back(language);
3332
0
    }
3333
0
  }
3334
0
  if (!languages_without_RC.empty()) {
3335
0
    this->GetGlobalGenerator()->EnableLanguage(languages_without_RC, this,
3336
0
                                               optional);
3337
0
  }
3338
0
  if (!languages_for_RC.empty()) {
3339
0
    this->GetGlobalGenerator()->EnableLanguage(languages_for_RC, this,
3340
0
                                               optional);
3341
0
  }
3342
0
}
3343
3344
int cmMakefile::TryCompile(std::string const& srcdir,
3345
                           std::string const& bindir,
3346
                           std::string const& projectName,
3347
                           std::string const& targetName, bool fast, int jobs,
3348
                           std::vector<std::string> const* cmakeArgs,
3349
                           std::string& output)
3350
0
{
3351
0
  this->IsSourceFileTryCompile = fast;
3352
  // does the binary directory exist ? If not create it...
3353
0
  if (!cmSystemTools::FileIsDirectory(bindir)) {
3354
0
    cmSystemTools::MakeDirectory(bindir);
3355
0
  }
3356
3357
  // change to the tests directory and run cmake
3358
  // use the cmake object instead of calling cmake
3359
0
  cmWorkingDirectory workdir(bindir);
3360
0
  if (workdir.Failed()) {
3361
0
    this->IssueMessage(MessageType::FATAL_ERROR, workdir.GetError());
3362
0
    cmSystemTools::SetFatalErrorOccurred();
3363
0
    this->IsSourceFileTryCompile = false;
3364
0
    return 1;
3365
0
  }
3366
3367
  // unset the NINJA_STATUS environment variable while running try compile.
3368
  // since we parse the output, we need to ensure there aren't any unexpected
3369
  // characters that will cause issues, such as ANSI color escape codes.
3370
0
  cm::optional<cmSystemTools::ScopedEnv> maybeNinjaStatus;
3371
0
  if (this->GetGlobalGenerator()->IsNinja()) {
3372
0
    maybeNinjaStatus.emplace("NINJA_STATUS=");
3373
0
  }
3374
3375
  // make sure the same generator is used
3376
  // use this program as the cmake to be run, it should not
3377
  // be run that way but the cmake object requires a valid path
3378
0
  cmake cm(cmState::Role::Project, cmState::TryCompile::Yes);
3379
0
  auto gg = cm.CreateGlobalGenerator(this->GetGlobalGenerator()->GetName());
3380
0
  if (!gg) {
3381
0
    this->IssueMessage(MessageType::INTERNAL_ERROR,
3382
0
                       "Global generator '" +
3383
0
                         this->GetGlobalGenerator()->GetName() +
3384
0
                         "' could not be created.");
3385
0
    cmSystemTools::SetFatalErrorOccurred();
3386
0
    this->IsSourceFileTryCompile = false;
3387
0
    return 1;
3388
0
  }
3389
0
  gg->RecursionDepth = this->RecursionDepth;
3390
0
  cm.SetGlobalGenerator(std::move(gg));
3391
3392
  // copy trace state
3393
0
  cm.SetTraceRedirect(this->GetCMakeInstance());
3394
3395
  // do a configure
3396
0
  cm.SetHomeDirectory(srcdir);
3397
0
  cm.SetHomeOutputDirectory(bindir);
3398
0
  cm.SetGeneratorInstance(this->GetSafeDefinition("CMAKE_GENERATOR_INSTANCE"));
3399
0
  cm.SetGeneratorPlatform(this->GetSafeDefinition("CMAKE_GENERATOR_PLATFORM"));
3400
0
  cm.SetGeneratorToolset(this->GetSafeDefinition("CMAKE_GENERATOR_TOOLSET"));
3401
0
  cm.LoadCache();
3402
0
  if (!cm.GetGlobalGenerator()->IsMultiConfig()) {
3403
0
    if (cmValue config =
3404
0
          this->GetDefinition("CMAKE_TRY_COMPILE_CONFIGURATION")) {
3405
      // Tell the single-configuration generator which one to use.
3406
      // Add this before the user-provided CMake arguments in case
3407
      // one of the arguments is -DCMAKE_BUILD_TYPE=...
3408
0
      cm.AddCacheEntry("CMAKE_BUILD_TYPE", config, "Build configuration",
3409
0
                       cmStateEnums::STRING);
3410
0
    }
3411
0
  }
3412
0
  cmValue recursionDepth =
3413
0
    this->GetDefinition("CMAKE_MAXIMUM_RECURSION_DEPTH");
3414
0
  if (recursionDepth) {
3415
0
    cm.AddCacheEntry("CMAKE_MAXIMUM_RECURSION_DEPTH", recursionDepth,
3416
0
                     "Maximum recursion depth", cmStateEnums::STRING);
3417
0
  }
3418
  // if cmake args were provided then pass them in
3419
0
  if (cmakeArgs) {
3420
    // FIXME: Workaround to ignore unused CLI variables in try-compile.
3421
    //
3422
    // Ideally we should use SetArgs for options like -Wno-unused-cli.
3423
    // However, there is a subtle problem when certain arguments are passed to
3424
    // a macro wrapping around try_compile or try_run that does not escape
3425
    // semicolons in its parameters but just passes ${ARGV} or ${ARGN}.  In
3426
    // this case a list argument like "-DVAR=a;b" gets split into multiple
3427
    // cmake arguments "-DVAR=a" and "b".  Currently SetCacheArgs ignores
3428
    // argument "b" and uses just "-DVAR=a", leading to a subtle bug in that
3429
    // the try_compile or try_run does not get the proper value of VAR.  If we
3430
    // call SetArgs here then it would treat "b" as the source directory and
3431
    // cause an error such as "The source directory .../CMakeFiles/CMakeTmp/b
3432
    // does not exist", thus breaking the try_compile or try_run completely.
3433
    //
3434
    // Strictly speaking the bug is in the wrapper macro because the CMake
3435
    // language has always flattened nested lists and the macro should escape
3436
    // the semicolons in its arguments before forwarding them.  However, this
3437
    // bug is so subtle that projects typically work anyway, usually because
3438
    // the value VAR=a is sufficient for the try_compile or try_run to get the
3439
    // correct result.  Calling SetArgs here would break such projects that
3440
    // previously built.  Instead we work around the issue by never reporting
3441
    // unused arguments and ignoring options such as -Wno-unused-cli.
3442
0
    cm.GetCurrentSnapshot().SetDiagnostic(cmDiagnostics::CMD_UNUSED_CLI,
3443
0
                                          cmDiagnostics::Ignore, true);
3444
    // cm.SetArgs(*cmakeArgs, true);
3445
3446
0
    cm.SetCacheArgs(*cmakeArgs);
3447
0
  }
3448
  // to save time we pass the EnableLanguage info directly
3449
0
  cm.GetGlobalGenerator()->SetupTryCompile(this->GetGlobalGenerator(), this);
3450
0
  for (unsigned dc = 1; dc < cmDiagnostics::CategoryCount; ++dc) {
3451
0
    auto const category = static_cast<cmDiagnosticCategory>(dc);
3452
0
    if (this->GetDiagnosticAction(category) == cmDiagnostics::Ignore) {
3453
0
      cm.GetCurrentSnapshot().SetDiagnostic(category, cmDiagnostics::Ignore,
3454
0
                                            false);
3455
0
    }
3456
0
  }
3457
0
  if (cm.Configure() != 0) {
3458
0
    this->IssueMessage(MessageType::FATAL_ERROR,
3459
0
                       "Failed to configure test project build system.");
3460
0
    cmSystemTools::SetFatalErrorOccurred();
3461
0
    this->IsSourceFileTryCompile = false;
3462
0
    return 1;
3463
0
  }
3464
3465
0
  if (cm.Generate() != 0) {
3466
0
    this->IssueMessage(MessageType::FATAL_ERROR,
3467
0
                       "Failed to generate test project build system.");
3468
0
    cmSystemTools::SetFatalErrorOccurred();
3469
0
    this->IsSourceFileTryCompile = false;
3470
0
    return 1;
3471
0
  }
3472
3473
  // finally call the generator to actually build the resulting project
3474
0
  int ret = this->GetGlobalGenerator()->TryCompile(
3475
0
    jobs, bindir, projectName, targetName, fast, output, this);
3476
3477
0
  this->IsSourceFileTryCompile = false;
3478
0
  return ret;
3479
0
}
3480
3481
bool cmMakefile::GetIsSourceFileTryCompile() const
3482
0
{
3483
0
  return this->IsSourceFileTryCompile;
3484
0
}
3485
3486
cmake* cmMakefile::GetCMakeInstance() const
3487
32
{
3488
32
  return this->GlobalGenerator->GetCMakeInstance();
3489
32
}
3490
3491
cmMessenger* cmMakefile::GetMessenger() const
3492
0
{
3493
0
  return this->GetCMakeInstance()->GetMessenger();
3494
0
}
3495
3496
cmGlobalGenerator* cmMakefile::GetGlobalGenerator() const
3497
2
{
3498
2
  return this->GlobalGenerator;
3499
2
}
3500
3501
#ifndef CMAKE_BOOTSTRAP
3502
cmVariableWatch* cmMakefile::GetVariableWatch() const
3503
12
{
3504
12
  if (this->GetCMakeInstance()) {
3505
12
    return this->GetCMakeInstance()->GetVariableWatch();
3506
12
  }
3507
0
  return nullptr;
3508
12
}
3509
#endif
3510
3511
cmState* cmMakefile::GetState() const
3512
4
{
3513
4
  return this->GetCMakeInstance()->GetState();
3514
4
}
3515
3516
void cmMakefile::DisplayStatus(std::string const& message, float s) const
3517
0
{
3518
0
  cmake* cm = this->GetCMakeInstance();
3519
0
  if (cm->GetState()->GetRole() == cmState::Role::FindPackage) {
3520
    // don't output any STATUS message in --find-package mode, since they will
3521
    // directly be fed to the compiler, which will be confused.
3522
0
    return;
3523
0
  }
3524
0
  cm->UpdateProgress(message, s);
3525
3526
0
#ifdef CMake_ENABLE_DEBUGGER
3527
0
  if (cm->GetDebugAdapter()) {
3528
0
    cm->GetDebugAdapter()->OnMessageOutput(MessageType::MESSAGE, message);
3529
0
  }
3530
0
#endif
3531
0
}
3532
3533
std::string cmMakefile::GetModulesFile(cm::string_view filename, bool& system,
3534
                                       bool debug,
3535
                                       std::string& debugBuffer) const
3536
0
{
3537
0
  std::string result;
3538
3539
0
  std::string moduleInCMakeRoot;
3540
0
  std::string moduleInCMakeModulePath;
3541
3542
  // Always search in CMAKE_MODULE_PATH:
3543
0
  cmValue cmakeModulePath = this->GetDefinition("CMAKE_MODULE_PATH");
3544
0
  if (cmakeModulePath) {
3545
0
    cmList modulePath{ *cmakeModulePath };
3546
3547
    // Look through the possible module directories.
3548
0
    for (std::string itempl : modulePath) {
3549
0
      cmSystemTools::ConvertToUnixSlashes(itempl);
3550
0
      itempl += "/";
3551
0
      itempl += filename;
3552
0
      if (cmSystemTools::FileExists(itempl)) {
3553
0
        moduleInCMakeModulePath = itempl;
3554
0
        break;
3555
0
      }
3556
0
      if (debug) {
3557
0
        debugBuffer = cmStrCat(debugBuffer, "  ", itempl, '\n');
3558
0
      }
3559
0
    }
3560
0
  }
3561
3562
  // Always search in the standard modules location.
3563
0
  moduleInCMakeRoot =
3564
0
    cmStrCat(cmSystemTools::GetCMakeRoot(), "/Modules/", filename);
3565
0
  cmSystemTools::ConvertToUnixSlashes(moduleInCMakeRoot);
3566
0
  if (!cmSystemTools::FileExists(moduleInCMakeRoot)) {
3567
0
    if (debug) {
3568
0
      debugBuffer = cmStrCat(debugBuffer, "  ", moduleInCMakeRoot, '\n');
3569
0
    }
3570
0
    moduleInCMakeRoot.clear();
3571
0
  }
3572
3573
  // Normally, prefer the files found in CMAKE_MODULE_PATH. Only when the file
3574
  // from which we are being called is located itself in CMAKE_ROOT, then
3575
  // prefer results from CMAKE_ROOT depending on the policy setting.
3576
0
  if (!moduleInCMakeModulePath.empty() && !moduleInCMakeRoot.empty()) {
3577
0
    cmValue currentFile = this->GetDefinition(kCMAKE_CURRENT_LIST_FILE);
3578
0
    std::string mods = cmStrCat(cmSystemTools::GetCMakeRoot(), "/Modules/");
3579
0
    if (currentFile && cmSystemTools::IsSubDirectory(*currentFile, mods)) {
3580
0
      system = true;
3581
0
      result = moduleInCMakeRoot;
3582
0
    } else {
3583
0
      system = false;
3584
0
      result = moduleInCMakeModulePath;
3585
0
    }
3586
0
  } else if (!moduleInCMakeModulePath.empty()) {
3587
0
    system = false;
3588
0
    result = moduleInCMakeModulePath;
3589
0
  } else {
3590
0
    system = true;
3591
0
    result = moduleInCMakeRoot;
3592
0
  }
3593
3594
#if defined(_WIN32) || defined(__APPLE__)
3595
  if (!result.empty()) {
3596
    std::string const requestedName =
3597
      cmSystemTools::GetFilenameName(std::string{ filename });
3598
    std::string actualName;
3599
    cmsys::Status const status =
3600
      cmSystemTools::ReadNameOnDisk(result, actualName);
3601
    if (status && actualName != requestedName) {
3602
      this->IssueDiagnostic(
3603
        cmDiagnostics::CMD_AUTHOR,
3604
        cmStrCat("The module name\n  ", requestedName, '\n',
3605
                 "does not match the case of the module file name on disk\n"
3606
                 "  ",
3607
                 cmSystemTools::GetFilenamePath(result), '/', actualName, '\n',
3608
                 "This may fail on case-sensitive file systems.  "
3609
                 "Use the module name\n  ",
3610
                 actualName, "\ninstead."));
3611
    }
3612
  }
3613
#endif
3614
3615
0
  return result;
3616
0
}
3617
3618
void cmMakefile::ConfigureString(std::string const& input, std::string& output,
3619
                                 bool atOnly, bool escapeQuotes) const
3620
0
{
3621
  // Split input to handle one line at a time.
3622
0
  std::string::const_iterator lineStart = input.begin();
3623
0
  while (lineStart != input.end()) {
3624
    // Find the end of this line.
3625
0
    std::string::const_iterator lineEnd = lineStart;
3626
0
    while (lineEnd != input.end() && *lineEnd != '\n') {
3627
0
      ++lineEnd;
3628
0
    }
3629
3630
    // Copy the line.
3631
0
    std::string line(lineStart, lineEnd);
3632
3633
    // Skip the newline character.
3634
0
    bool haveNewline = (lineEnd != input.end());
3635
0
    if (haveNewline) {
3636
0
      ++lineEnd;
3637
0
    }
3638
3639
    // Replace #cmakedefine instances.
3640
0
    if (this->cmDefineRegex.find(line)) {
3641
0
      cmValue def = this->GetDefinition(this->cmDefineRegex.match(2));
3642
0
      if (!def.IsOff()) {
3643
0
        std::string const indentation = this->cmDefineRegex.match(1);
3644
0
        cmSystemTools::ReplaceString(line,
3645
0
                                     cmStrCat('#', indentation, "cmakedefine"),
3646
0
                                     cmStrCat('#', indentation, "define"));
3647
0
        output += line;
3648
0
      } else {
3649
0
        output += "/* #undef ";
3650
0
        output += this->cmDefineRegex.match(2);
3651
0
        output += " */";
3652
0
      }
3653
0
    } else if (this->cmDefine01Regex.find(line)) {
3654
0
      std::string const indentation = this->cmDefine01Regex.match(1);
3655
0
      cmValue def = this->GetDefinition(this->cmDefine01Regex.match(2));
3656
0
      cmSystemTools::ReplaceString(line,
3657
0
                                   cmStrCat('#', indentation, "cmakedefine01"),
3658
0
                                   cmStrCat('#', indentation, "define"));
3659
0
      output += line;
3660
0
      if (!def.IsOff()) {
3661
0
        output += " 1";
3662
0
      } else {
3663
0
        output += " 0";
3664
0
      }
3665
0
    } else {
3666
0
      output += line;
3667
0
    }
3668
3669
0
    if (haveNewline) {
3670
0
      output += '\n';
3671
0
    }
3672
3673
    // Move to the next line.
3674
0
    lineStart = lineEnd;
3675
0
  }
3676
3677
  // Perform variable replacements.
3678
0
  char const* filename = nullptr;
3679
0
  long lineNumber = -1;
3680
0
  if (!this->Backtrace.Empty()) {
3681
0
    auto const& currentTrace = this->Backtrace.Top();
3682
0
    filename = currentTrace.FilePath.c_str();
3683
0
    lineNumber = currentTrace.Line;
3684
0
  }
3685
0
  this->ExpandVariablesInString(output, escapeQuotes, true, atOnly, filename,
3686
0
                                lineNumber, true, true);
3687
0
}
3688
3689
int cmMakefile::ConfigureFile(std::string const& infile,
3690
                              std::string const& outfile, bool copyonly,
3691
                              bool atOnly, bool escapeQuotes,
3692
                              mode_t permissions, cmNewLineStyle newLine)
3693
0
{
3694
0
  int res = 1;
3695
0
  if (!this->CanIWriteThisFile(outfile)) {
3696
0
    cmSystemTools::Error(cmStrCat("Attempt to write file: ", outfile,
3697
0
                                  " into a source directory."));
3698
0
    return 0;
3699
0
  }
3700
0
  if (!cmSystemTools::FileExists(infile)) {
3701
0
    cmSystemTools::Error(cmStrCat("File ", infile, " does not exist."));
3702
0
    return 0;
3703
0
  }
3704
0
  std::string soutfile = outfile;
3705
0
  std::string const& sinfile = infile;
3706
0
  this->AddCMakeDependFile(sinfile);
3707
0
  cmSystemTools::ConvertToUnixSlashes(soutfile);
3708
3709
  // Re-generate if non-temporary outputs are missing.
3710
  // when we finalize the configuration we will remove all
3711
  // output files that now don't exist.
3712
0
  this->AddCMakeOutputFile(soutfile);
3713
3714
0
  if (permissions == 0) {
3715
0
    cmSystemTools::GetPermissions(sinfile, permissions);
3716
0
  }
3717
3718
0
  std::string::size_type pos = soutfile.rfind('/');
3719
0
  if (pos != std::string::npos) {
3720
0
    std::string path = soutfile.substr(0, pos);
3721
0
    cmSystemTools::MakeDirectory(path);
3722
0
  }
3723
3724
0
  if (copyonly) {
3725
0
    auto const copy_status =
3726
0
      cmSystemTools::CopyFileIfDifferent(sinfile, soutfile);
3727
0
    if (!copy_status) {
3728
0
      this->IssueMessage(
3729
0
        MessageType::FATAL_ERROR,
3730
0
        cmStrCat("Fail to copy ",
3731
0
                 copy_status.Path == cmsys::SystemTools::CopyStatus::SourcePath
3732
0
                   ? "source"
3733
0
                   : "destination",
3734
0
                 "file: ", copy_status.GetString()));
3735
0
      res = 0;
3736
0
    } else {
3737
0
      auto const status = cmSystemTools::SetPermissions(soutfile, permissions);
3738
0
      if (!status) {
3739
0
        this->IssueMessage(MessageType::FATAL_ERROR, status.GetString());
3740
0
        res = 0;
3741
0
      }
3742
0
    }
3743
0
    return res;
3744
0
  }
3745
3746
0
  std::string newLineCharacters;
3747
0
  std::ios::openmode omode = std::ios::out | std::ios::trunc;
3748
0
  if (newLine.IsValid()) {
3749
0
    newLineCharacters = newLine.GetCharacters();
3750
0
    omode |= std::ios::binary;
3751
0
  } else {
3752
0
    newLineCharacters = "\n";
3753
0
  }
3754
0
  std::string tempOutputFile = cmStrCat(soutfile, ".tmp");
3755
0
  cmsys::ofstream fout(tempOutputFile.c_str(), omode);
3756
0
  if (!fout) {
3757
0
    cmSystemTools::Error("Could not open file for write in copy operation " +
3758
0
                         tempOutputFile);
3759
0
    cmSystemTools::ReportLastSystemError("");
3760
0
    return 0;
3761
0
  }
3762
0
  cmsys::ifstream fin(sinfile.c_str());
3763
0
  if (!fin) {
3764
0
    cmSystemTools::Error("Could not open file for read in copy operation " +
3765
0
                         sinfile);
3766
0
    return 0;
3767
0
  }
3768
3769
0
  cmsys::FStream::BOM bom = cmsys::FStream::ReadBOM(fin);
3770
0
  if (bom != cmsys::FStream::BOM_None && bom != cmsys::FStream::BOM_UTF8) {
3771
0
    this->IssueMessage(
3772
0
      MessageType::FATAL_ERROR,
3773
0
      cmStrCat("File starts with a Byte-Order-Mark that is not UTF-8:\n  ",
3774
0
               sinfile));
3775
0
    return 0;
3776
0
  }
3777
  // rewind to copy BOM to output file
3778
0
  fin.seekg(0);
3779
3780
  // now copy input to output and expand variables in the
3781
  // input file at the same time
3782
0
  std::string inLine;
3783
0
  std::string outLine;
3784
0
  while (cmSystemTools::GetLineFromStream(fin, inLine)) {
3785
0
    outLine.clear();
3786
0
    this->ConfigureString(inLine, outLine, atOnly, escapeQuotes);
3787
0
    fout << outLine << newLineCharacters;
3788
0
  }
3789
  // close the files before attempting to copy
3790
0
  fin.close();
3791
0
  fout.close();
3792
3793
0
  auto status = cmSystemTools::MoveFileIfDifferent(tempOutputFile, soutfile);
3794
0
  if (!status) {
3795
0
    this->IssueMessage(MessageType::FATAL_ERROR, status.GetString());
3796
0
    res = 0;
3797
0
  } else {
3798
0
    status = cmSystemTools::SetPermissions(soutfile, permissions);
3799
0
    if (!status) {
3800
0
      this->IssueMessage(MessageType::FATAL_ERROR, status.GetString());
3801
0
      res = 0;
3802
0
    }
3803
0
  }
3804
3805
0
  return res;
3806
0
}
3807
3808
void cmMakefile::SetProperty(std::string const& prop, cmValue value)
3809
0
{
3810
0
  this->StateSnapshot.GetDirectory().SetProperty(prop, value, this->Backtrace);
3811
0
}
3812
3813
void cmMakefile::AppendProperty(std::string const& prop,
3814
                                std::string const& value, bool asString)
3815
0
{
3816
0
  this->StateSnapshot.GetDirectory().AppendProperty(prop, value, asString,
3817
0
                                                    this->Backtrace);
3818
0
}
3819
3820
cmValue cmMakefile::GetProperty(std::string const& prop) const
3821
0
{
3822
  // Check for computed properties.
3823
0
  static std::string output;
3824
0
  if (prop == "TESTS"_s) {
3825
0
    std::vector<std::string> keys;
3826
    // get list of keys
3827
0
    auto const* t = this;
3828
0
    std::transform(
3829
0
      t->Tests.begin(), t->Tests.end(), std::back_inserter(keys),
3830
0
      [](decltype(t->Tests)::value_type const& pair) { return pair.first; });
3831
0
    output = cmList::to_string(keys);
3832
0
    return cmValue(output);
3833
0
  }
3834
3835
0
  return this->StateSnapshot.GetDirectory().GetProperty(prop);
3836
0
}
3837
3838
cmValue cmMakefile::GetProperty(std::string const& prop, bool chain) const
3839
0
{
3840
0
  return this->StateSnapshot.GetDirectory().GetProperty(prop, chain);
3841
0
}
3842
3843
bool cmMakefile::GetPropertyAsBool(std::string const& prop) const
3844
0
{
3845
0
  return this->GetProperty(prop).IsOn();
3846
0
}
3847
3848
std::vector<std::string> cmMakefile::GetPropertyKeys() const
3849
0
{
3850
0
  return this->StateSnapshot.GetDirectory().GetPropertyKeys();
3851
0
}
3852
3853
cmTarget* cmMakefile::FindLocalNonAliasTarget(std::string const& name) const
3854
0
{
3855
0
  auto i = this->Targets.find(name);
3856
0
  if (i != this->Targets.end()) {
3857
0
    return &i->second;
3858
0
  }
3859
0
  return nullptr;
3860
0
}
3861
3862
cmTest* cmMakefile::CreateTest(std::string const& testName)
3863
0
{
3864
0
  cmTest* test = this->GetTest(testName);
3865
0
  if (test) {
3866
0
    return test;
3867
0
  }
3868
0
  auto newTest = cm::make_unique<cmTest>(this);
3869
0
  test = newTest.get();
3870
0
  newTest->SetName(testName);
3871
0
  this->Tests[testName] = std::move(newTest);
3872
0
  return test;
3873
0
}
3874
3875
cmTest* cmMakefile::GetTest(std::string const& testName) const
3876
0
{
3877
0
  auto mi = this->Tests.find(testName);
3878
0
  if (mi != this->Tests.end()) {
3879
0
    return mi->second.get();
3880
0
  }
3881
0
  return nullptr;
3882
0
}
3883
3884
void cmMakefile::GetTests(std::string const& config,
3885
                          std::vector<cmTest*>& tests) const
3886
0
{
3887
0
  for (auto const& generator : this->GetTestGenerators()) {
3888
0
    if (generator->TestsForConfig(config)) {
3889
0
      tests.push_back(generator->GetTest());
3890
0
    }
3891
0
  }
3892
0
}
3893
3894
void cmMakefile::AddCMakeDependFilesFromUser()
3895
0
{
3896
0
  cmList deps;
3897
0
  if (cmValue deps_str = this->GetProperty("CMAKE_CONFIGURE_DEPENDS")) {
3898
0
    deps.assign(*deps_str);
3899
0
  }
3900
0
  for (auto const& dep : deps) {
3901
0
    if (cmSystemTools::FileIsFullPath(dep)) {
3902
0
      this->AddCMakeDependFile(dep);
3903
0
    } else {
3904
0
      std::string f = cmStrCat(this->GetCurrentSourceDirectory(), '/', dep);
3905
0
      this->AddCMakeDependFile(f);
3906
0
    }
3907
0
  }
3908
0
}
3909
3910
std::string cmMakefile::FormatListFileStack() const
3911
0
{
3912
0
  std::vector<std::string> listFiles;
3913
0
  for (auto snp = this->StateSnapshot; snp.IsValid();
3914
0
       snp = snp.GetCallStackParent()) {
3915
0
    listFiles.emplace_back(snp.GetExecutionListFile());
3916
0
  }
3917
3918
0
  if (listFiles.empty()) {
3919
0
    return {};
3920
0
  }
3921
3922
0
  auto depth = 1;
3923
0
  std::transform(listFiles.begin(), listFiles.end(), listFiles.begin(),
3924
0
                 [&depth](std::string const& file) {
3925
0
                   return cmStrCat('[', depth++, "]\t", file);
3926
0
                 });
3927
3928
0
  return cmJoinStrings(cmMakeRange(listFiles.rbegin(), listFiles.rend()),
3929
0
                       "\n                "_s, {});
3930
0
}
3931
3932
void cmMakefile::PushScope()
3933
0
{
3934
0
  this->StateSnapshot =
3935
0
    this->GetState()->CreateVariableScopeSnapshot(this->StateSnapshot);
3936
0
  this->PushLoopBlockBarrier();
3937
3938
0
#if !defined(CMAKE_BOOTSTRAP)
3939
0
  this->GetGlobalGenerator()->GetFileLockPool().PushFunctionScope();
3940
0
#endif
3941
0
}
3942
3943
void cmMakefile::PopScope()
3944
0
{
3945
0
#if !defined(CMAKE_BOOTSTRAP)
3946
0
  this->GetGlobalGenerator()->GetFileLockPool().PopFunctionScope();
3947
0
#endif
3948
3949
0
  this->PopLoopBlockBarrier();
3950
3951
0
  this->PopSnapshot();
3952
0
}
3953
3954
void cmMakefile::RaiseScope(std::string const& var, char const* varDef)
3955
0
{
3956
0
  if (var.empty()) {
3957
0
    return;
3958
0
  }
3959
3960
0
  if (!this->StateSnapshot.RaiseScope(var, varDef)) {
3961
0
    this->IssueDiagnostic(
3962
0
      cmDiagnostics::CMD_AUTHOR,
3963
0
      cmStrCat("Cannot set \"", var, "\": current scope has no parent."));
3964
0
    return;
3965
0
  }
3966
3967
0
#ifndef CMAKE_BOOTSTRAP
3968
0
  cmVariableWatch* vv = this->GetVariableWatch();
3969
0
  if (vv) {
3970
0
    vv->VariableAccessed(var, cmVariableWatch::VARIABLE_MODIFIED_ACCESS,
3971
0
                         varDef, this);
3972
0
  }
3973
0
#endif
3974
0
}
3975
3976
void cmMakefile::RaiseScope(std::vector<std::string> const& variables)
3977
0
{
3978
0
  for (auto const& varName : variables) {
3979
0
    if (this->IsNormalDefinitionSet(varName)) {
3980
0
      this->RaiseScope(varName, this->GetDefinition(varName));
3981
0
    } else {
3982
      // unset variable in parent scope
3983
0
      this->RaiseScope(varName, nullptr);
3984
0
    }
3985
0
  }
3986
0
}
3987
3988
cmTarget* cmMakefile::AddImportedTarget(std::string const& name,
3989
                                        cm::TargetType type,
3990
                                        cm::ImportedTargetScope scope)
3991
0
{
3992
  // Create the target.
3993
0
  auto target =
3994
0
    cm::make_unique<cmTarget>(name, type, cmTarget::ImportedVisibility(scope),
3995
0
                              this, cmTarget::PerConfig::Yes);
3996
3997
  // Add to the set of available imported targets.
3998
0
  this->ImportedTargets[name] = target.get();
3999
0
  this->GetGlobalGenerator()->IndexTarget(target.get());
4000
0
  this->GetStateSnapshot().GetDirectory().AddImportedTargetName(name);
4001
4002
  // Transfer ownership to this cmMakefile object.
4003
0
  this->ImportedTargetsOwned.push_back(std::move(target));
4004
0
  return this->ImportedTargetsOwned.back().get();
4005
0
}
4006
4007
cmTarget* cmMakefile::AddForeignTarget(std::string const& origin,
4008
                                       std::string const& name)
4009
0
{
4010
0
  auto foreign_name = cmStrCat("@foreign_", origin, "::", name);
4011
0
  auto target = cm::make_unique<cmTarget>(
4012
0
    foreign_name, cm::TargetType::INTERFACE_LIBRARY,
4013
0
    cmTarget::Visibility::Foreign, this, cmTarget::PerConfig::Yes);
4014
4015
0
  this->ImportedTargets[foreign_name] = target.get();
4016
0
  this->GetGlobalGenerator()->IndexTarget(target.get());
4017
0
  this->GetStateSnapshot().GetDirectory().AddImportedTargetName(foreign_name);
4018
4019
0
  this->ImportedTargetsOwned.push_back(std::move(target));
4020
0
  return this->ImportedTargetsOwned.back().get();
4021
0
}
4022
4023
cmTarget* cmMakefile::FindTargetToUse(std::string const& name,
4024
                                      cm::TargetDomainSet domains) const
4025
0
{
4026
  // Look for an imported target.  These take priority because they
4027
  // are more local in scope and do not have to be globally unique.
4028
0
  auto targetName = name;
4029
0
  if (domains.contains(cm::TargetDomain::ALIAS)) {
4030
    // Look for local alias targets.
4031
0
    auto alias = this->AliasTargets.find(name);
4032
0
    if (alias != this->AliasTargets.end()) {
4033
0
      targetName = alias->second;
4034
0
    }
4035
0
  }
4036
0
  auto const imported = this->ImportedTargets.find(targetName);
4037
4038
0
  bool const useForeign = domains.contains(cm::TargetDomain::FOREIGN);
4039
0
  bool const useNative = domains.contains(cm::TargetDomain::NATIVE);
4040
4041
0
  if (imported != this->ImportedTargets.end()) {
4042
0
    if (imported->second->IsForeign() ? useForeign : useNative) {
4043
0
      return imported->second;
4044
0
    }
4045
0
  }
4046
4047
  // Look for a target built in this directory.
4048
0
  if (cmTarget* t = this->FindLocalNonAliasTarget(name)) {
4049
0
    if (t->IsForeign() ? useForeign : useNative) {
4050
0
      return t;
4051
0
    }
4052
0
  }
4053
4054
  // Look for a target built in this project.
4055
0
  return this->GetGlobalGenerator()->FindTarget(name, domains);
4056
0
}
4057
4058
bool cmMakefile::IsAlias(std::string const& name) const
4059
0
{
4060
0
  if (cm::contains(this->AliasTargets, name)) {
4061
0
    return true;
4062
0
  }
4063
0
  return this->GetGlobalGenerator()->IsAlias(name);
4064
0
}
4065
4066
bool cmMakefile::EnforceUniqueName(std::string const& name, std::string& msg,
4067
                                   bool isCustom) const
4068
0
{
4069
0
  if (this->IsAlias(name)) {
4070
0
    msg = cmStrCat("cannot create target \"", name,
4071
0
                   "\" because an alias with the same name already exists.");
4072
0
    return false;
4073
0
  }
4074
0
  if (cmTarget* existing = this->FindTargetToUse(name)) {
4075
    // The name given conflicts with an existing target.  Produce an
4076
    // error in a compatible way.
4077
0
    if (existing->IsImported()) {
4078
      // Imported targets were not supported in previous versions.
4079
      // This is new code, so we can make it an error.
4080
0
      msg = cmStrCat(
4081
0
        "cannot create target \"", name,
4082
0
        "\" because an imported target with the same name already exists.");
4083
0
      return false;
4084
0
    }
4085
4086
    // The conflict is with a non-imported target.
4087
    // Allow this if the user has requested support.
4088
0
    cmake* cm = this->GetCMakeInstance();
4089
0
    if (isCustom && existing->GetType() == cm::TargetType::UTILITY &&
4090
0
        this != existing->GetMakefile() &&
4091
0
        cm->GetState()->GetGlobalPropertyAsBool(
4092
0
          "ALLOW_DUPLICATE_CUSTOM_TARGETS")) {
4093
0
      return true;
4094
0
    }
4095
4096
    // Produce an error that tells the user how to work around the
4097
    // problem.
4098
0
    std::ostringstream e;
4099
0
    e << "cannot create target \"" << name
4100
0
      << "\" because another target with the same name already exists.  "
4101
0
         "The existing target is ";
4102
0
    switch (existing->GetType()) {
4103
0
      case cm::TargetType::EXECUTABLE:
4104
0
        e << "an executable ";
4105
0
        break;
4106
0
      case cm::TargetType::STATIC_LIBRARY:
4107
0
        e << "a static library ";
4108
0
        break;
4109
0
      case cm::TargetType::SHARED_LIBRARY:
4110
0
        e << "a shared library ";
4111
0
        break;
4112
0
      case cm::TargetType::MODULE_LIBRARY:
4113
0
        e << "a module library ";
4114
0
        break;
4115
0
      case cm::TargetType::UTILITY:
4116
0
        e << "a custom target ";
4117
0
        break;
4118
0
      case cm::TargetType::INTERFACE_LIBRARY:
4119
0
        e << "an interface library ";
4120
0
        break;
4121
0
      default:
4122
0
        break;
4123
0
    }
4124
0
    e << "created in source directory \""
4125
0
      << existing->GetMakefile()->GetCurrentSourceDirectory()
4126
0
      << "\".  "
4127
0
         "See documentation for policy CMP0002 for more details.";
4128
0
    msg = e.str();
4129
0
    return false;
4130
0
  }
4131
0
  return true;
4132
0
}
4133
4134
bool cmMakefile::EnforceUniqueDir(std::string const& srcPath,
4135
                                  std::string const& binPath) const
4136
0
{
4137
  // Make sure the binary directory is unique.
4138
0
  cmGlobalGenerator* gg = this->GetGlobalGenerator();
4139
0
  if (gg->BinaryDirectoryIsNew(binPath)) {
4140
0
    return true;
4141
0
  }
4142
0
  this->IssueMessage(MessageType::FATAL_ERROR,
4143
0
                     cmStrCat("The binary directory\n"
4144
0
                              "  ",
4145
0
                              binPath,
4146
0
                              "\n"
4147
0
                              "is already used to build a source directory.  "
4148
0
                              "It cannot be used to build source directory\n"
4149
0
                              "  ",
4150
0
                              srcPath,
4151
0
                              "\n"
4152
0
                              "Specify a unique binary directory name."));
4153
4154
0
  return false;
4155
0
}
4156
4157
static std::string const matchVariables[] = {
4158
  "CMAKE_MATCH_0", "CMAKE_MATCH_1", "CMAKE_MATCH_2", "CMAKE_MATCH_3",
4159
  "CMAKE_MATCH_4", "CMAKE_MATCH_5", "CMAKE_MATCH_6", "CMAKE_MATCH_7",
4160
  "CMAKE_MATCH_8", "CMAKE_MATCH_9"
4161
};
4162
4163
static std::string const nMatchesVariable = "CMAKE_MATCH_COUNT";
4164
4165
void cmMakefile::ClearMatches()
4166
0
{
4167
0
  cmValue nMatchesStr = this->GetDefinition(nMatchesVariable);
4168
0
  if (!nMatchesStr) {
4169
0
    return;
4170
0
  }
4171
0
  int nMatches = atoi(nMatchesStr->c_str());
4172
0
  for (int i = 0; i <= nMatches; i++) {
4173
0
    std::string const& var = matchVariables[i];
4174
0
    std::string const& s = this->GetSafeDefinition(var);
4175
0
    if (!s.empty()) {
4176
0
      this->AddDefinition(var, "");
4177
0
      this->MarkVariableAsUsed(var);
4178
0
    }
4179
0
  }
4180
0
  this->AddDefinition(nMatchesVariable, "0");
4181
0
  this->MarkVariableAsUsed(nMatchesVariable);
4182
0
}
4183
4184
void cmMakefile::StoreMatches(cmsys::RegularExpression& re)
4185
0
{
4186
0
  char highest = 0;
4187
0
  for (int i = 0; i < 10; i++) {
4188
0
    std::string const& m = re.match(i);
4189
0
    if (!m.empty()) {
4190
0
      std::string const& var = matchVariables[i];
4191
0
      this->AddDefinition(var, m);
4192
0
      this->MarkVariableAsUsed(var);
4193
0
      highest = static_cast<char>('0' + i);
4194
0
    }
4195
0
  }
4196
0
  char nMatches[] = { highest, '\0' };
4197
0
  this->AddDefinition(nMatchesVariable, nMatches);
4198
0
  this->MarkVariableAsUsed(nMatchesVariable);
4199
0
}
4200
4201
cmStateSnapshot cmMakefile::GetStateSnapshot() const
4202
0
{
4203
0
  return this->StateSnapshot;
4204
0
}
4205
4206
cmPolicies::PolicyStatus cmMakefile::GetPolicyStatus(cmPolicies::PolicyID id,
4207
                                                     bool parent_scope) const
4208
0
{
4209
0
  return this->StateSnapshot.GetPolicy(id, parent_scope);
4210
0
}
4211
4212
bool cmMakefile::PolicyOptionalWarningEnabled(std::string const& var) const
4213
0
{
4214
  // Check for an explicit CMAKE_POLICY_WARNING_CMP<NNNN> setting.
4215
0
  if (cmValue val = this->GetDefinition(var)) {
4216
0
    return val.IsOn();
4217
0
  }
4218
  // Enable optional policy warnings with --debug-output, --trace,
4219
  // or --trace-expand.
4220
0
  cmake* cm = this->GetCMakeInstance();
4221
0
  return cm->GetDebugOutput() || cm->GetTrace();
4222
0
}
4223
4224
bool cmMakefile::SetPolicy(char const* id, cmPolicies::PolicyStatus status)
4225
0
{
4226
0
  cmPolicies::PolicyID pid;
4227
0
  if (!cmPolicies::GetPolicyID(id, /* out */ pid)) {
4228
0
    this->IssueMessage(
4229
0
      MessageType::FATAL_ERROR,
4230
0
      cmStrCat("Policy \"", id, "\" is not known to this version of CMake."));
4231
0
    return false;
4232
0
  }
4233
0
  return this->SetPolicy(pid, status);
4234
0
}
4235
4236
bool cmMakefile::SetPolicy(cmPolicies::PolicyID id,
4237
                           cmPolicies::PolicyStatus status)
4238
0
{
4239
  // A removed policy may be set only to NEW.
4240
0
  if (cmPolicies::IsRemoved(id) && status != cmPolicies::NEW) {
4241
0
    std::string msg = cmPolicies::GetRemovedPolicyError(id);
4242
0
    this->IssueMessage(MessageType::FATAL_ERROR, msg);
4243
0
    return false;
4244
0
  }
4245
4246
  // Deprecate old policies.
4247
0
  if (status == cmPolicies::OLD && id <= cmPolicies::CMP0161 &&
4248
0
      !(this->GetCMakeInstance()->GetIsInTryCompile() &&
4249
0
        (
4250
          // Policies set by cmCoreTryCompile::TryCompileCode.
4251
0
          id == cmPolicies::CMP0083 || id == cmPolicies::CMP0091 ||
4252
0
          id == cmPolicies::CMP0104 || id == cmPolicies::CMP0123 ||
4253
0
          id == cmPolicies::CMP0126 || id == cmPolicies::CMP0128 ||
4254
0
          id == cmPolicies::CMP0136 || id == cmPolicies::CMP0141 ||
4255
0
          id == cmPolicies::CMP0155 || id == cmPolicies::CMP0157))) {
4256
0
    std::unique_ptr<PolicyPushPop> ps;
4257
0
    std::unique_ptr<DiagnosticPushPop> ds;
4258
4259
0
    cmPolicies::PolicyStatus const cmp0218 =
4260
0
      this->GetPolicyStatus(cmPolicies::CMP0218);
4261
0
    if (cmp0218 != cmPolicies::NEW) {
4262
0
      if (cmp0218 != cmPolicies::OLD) {
4263
        // Suppress warnings about using old variables.
4264
0
        ps = cm::make_unique<PolicyPushPop>(this);
4265
0
        this->SetPolicy(cmPolicies::CMP0218, cmPolicies::OLD);
4266
0
      }
4267
4268
0
      ds = cm::make_unique<DiagnosticPushPop>(this);
4269
4270
      // Use old variables to determine diagnostic action.
4271
0
      cmValue const warn = this->GetDefinition("CMAKE_WARN_DEPRECATED");
4272
0
      if (warn.IsSet() && !warn.IsOn()) {
4273
0
        this->SetDiagnostic(cmDiagnostics::CMD_DEPRECATED,
4274
0
                            cmDiagnostics::Ignore);
4275
0
      } else if (this->IsOn("CMAKE_ERROR_DEPRECATED")) {
4276
0
        this->SetDiagnostic(cmDiagnostics::CMD_DEPRECATED,
4277
0
                            cmDiagnostics::SendError);
4278
0
      } else {
4279
0
        this->SetDiagnostic(cmDiagnostics::CMD_DEPRECATED,
4280
0
                            cmDiagnostics::Warn);
4281
0
      }
4282
0
    }
4283
4284
0
    this->IssueDiagnostic(cmDiagnostics::CMD_DEPRECATED,
4285
0
                          cmPolicies::GetPolicyDeprecatedWarning(id));
4286
0
  }
4287
4288
0
  this->StateSnapshot.SetPolicy(id, status);
4289
4290
  // Handle CMAKE_PARENT_LIST_FILE for CMP0198 policy changes
4291
0
  if (id == cmPolicies::CMP0198 &&
4292
0
      this->GetCMakeInstance()->GetState()->GetRole() ==
4293
0
        cmState::Role::Project) {
4294
0
    this->UpdateParentListFileVariable();
4295
0
  }
4296
4297
0
  return true;
4298
0
}
4299
4300
cmMakefile::PolicyPushPop::PolicyPushPop(cmMakefile* m)
4301
0
  : Makefile(m)
4302
0
{
4303
0
  this->Makefile->PushPolicy();
4304
0
}
4305
4306
cmMakefile::PolicyPushPop::~PolicyPushPop()
4307
0
{
4308
0
  this->Makefile->PopPolicy();
4309
0
}
4310
4311
void cmMakefile::PushPolicy(bool weak, cmPolicies::PolicyMap const& pm)
4312
1
{
4313
1
  this->StateSnapshot.PushPolicy(pm, weak);
4314
1
}
4315
4316
void cmMakefile::PopPolicy()
4317
0
{
4318
0
  if (!this->StateSnapshot.PopPolicy()) {
4319
0
    this->IssueMessage(MessageType::FATAL_ERROR,
4320
0
                       "cmake_policy POP without matching PUSH");
4321
0
  }
4322
0
}
4323
4324
cmDiagnosticAction cmMakefile::GetDiagnosticAction(
4325
  cmDiagnosticCategory category) const
4326
0
{
4327
0
  return this->StateSnapshot.GetDiagnostic(category);
4328
0
}
4329
4330
bool cmMakefile::SetDiagnostic(cmDiagnosticCategory category,
4331
                               cmDiagnosticAction action, bool recursive)
4332
0
{
4333
0
  this->StateSnapshot.SetDiagnostic(category, action, recursive);
4334
0
  return true;
4335
0
}
4336
4337
bool cmMakefile::PromoteDiagnostic(cmDiagnosticCategory category,
4338
                                   cmDiagnosticAction action, bool recursive)
4339
0
{
4340
0
  this->StateSnapshot.PromoteDiagnostic(category, action, recursive);
4341
0
  return true;
4342
0
}
4343
4344
bool cmMakefile::DemoteDiagnostic(cmDiagnosticCategory category,
4345
                                  cmDiagnosticAction action, bool recursive)
4346
0
{
4347
0
  this->StateSnapshot.DemoteDiagnostic(category, action, recursive);
4348
0
  return true;
4349
0
}
4350
4351
cmMakefile::DiagnosticPushPop::DiagnosticPushPop(cmMakefile* m)
4352
0
  : Makefile(m)
4353
0
{
4354
0
  this->Makefile->PushDiagnostic();
4355
0
}
4356
4357
cmMakefile::DiagnosticPushPop::~DiagnosticPushPop()
4358
0
{
4359
0
  this->Makefile->PopDiagnostic();
4360
0
}
4361
4362
void cmMakefile::PushDiagnostic(bool weak, cmDiagnostics::DiagnosticMap dm)
4363
1
{
4364
1
  this->StateSnapshot.PushDiagnostic(dm, weak);
4365
1
}
4366
4367
void cmMakefile::PopDiagnostic()
4368
0
{
4369
0
  if (!this->StateSnapshot.PopDiagnostic()) {
4370
0
    this->IssueMessage(MessageType::FATAL_ERROR,
4371
0
                       "cmake_diagnostic POP without matching PUSH");
4372
0
  }
4373
0
}
4374
4375
void cmMakefile::PopSnapshot(bool reportError)
4376
1
{
4377
  // cmStateSnapshot manages nested policy/diagnostic scopes within it.
4378
  // Since the scope corresponding to the snapshot is closing,
4379
  // reject any still-open nested policy/diagnostic scopes with an error.
4380
1
  for (;;) {
4381
1
    if (this->StateSnapshot.CanPopPolicyScope()) {
4382
0
      if (reportError) {
4383
0
        this->IssueMessage(MessageType::FATAL_ERROR,
4384
0
                           "cmake_policy PUSH without matching POP");
4385
0
        reportError = false;
4386
0
      }
4387
0
      this->PopPolicy();
4388
1
    } else if (this->StateSnapshot.CanPopDiagnosticScope()) {
4389
0
      if (reportError) {
4390
0
        this->IssueMessage(MessageType::FATAL_ERROR,
4391
0
                           "cmake_diagnostic PUSH without matching POP");
4392
0
        reportError = false;
4393
0
      }
4394
0
      this->PopDiagnostic();
4395
1
    } else {
4396
1
      break;
4397
1
    }
4398
1
  }
4399
4400
1
  this->StateSnapshot = this->GetState()->Pop(this->StateSnapshot);
4401
1
  assert(this->StateSnapshot.IsValid());
4402
1
}
4403
4404
bool cmMakefile::SetPolicyVersion(std::string const& version_min,
4405
                                  std::string const& version_max)
4406
0
{
4407
0
  return cmPolicies::ApplyPolicyVersion(this, version_min, version_max,
4408
0
                                        cmPolicies::WarnCompat::On);
4409
0
}
4410
4411
void cmMakefile::UpdateParentListFileVariable()
4412
0
{
4413
  // CMP0198 determines CMAKE_PARENT_LIST_FILE behavior in CMakeLists.txt
4414
0
  if (this->GetPolicyStatus(cmPolicies::CMP0198) == cmPolicies::NEW) {
4415
0
    this->RemoveDefinition(kCMAKE_PARENT_LIST_FILE);
4416
0
  } else {
4417
0
    std::string currentSourceDir =
4418
0
      this->StateSnapshot.GetDirectory().GetCurrentSource();
4419
0
    std::string currentStart =
4420
0
      this->GetCMakeInstance()->GetCMakeListFile(currentSourceDir);
4421
4422
0
    this->AddDefinition(kCMAKE_PARENT_LIST_FILE, currentStart);
4423
0
  }
4424
0
}
4425
4426
cmMakefile::VariablePushPop::VariablePushPop(cmMakefile* m)
4427
0
  : Makefile(m)
4428
0
{
4429
0
  this->Makefile->StateSnapshot =
4430
0
    this->Makefile->GetState()->CreateVariableScopeSnapshot(
4431
0
      this->Makefile->StateSnapshot);
4432
0
}
4433
4434
cmMakefile::VariablePushPop::~VariablePushPop()
4435
0
{
4436
0
  this->Makefile->PopSnapshot();
4437
0
}
4438
4439
void cmMakefile::RecordPolicies(cmPolicies::PolicyMap& pm) const
4440
0
{
4441
  /* Record the setting of every policy.  */
4442
0
  using PolicyID = cmPolicies::PolicyID;
4443
0
  for (PolicyID pid = cmPolicies::CMP0000; pid != cmPolicies::CMPCOUNT;
4444
0
       pid = static_cast<PolicyID>(pid + 1)) {
4445
0
    pm.Set(pid, this->GetPolicyStatus(pid));
4446
0
  }
4447
0
}
4448
4449
void cmMakefile::RecordDiagnostics(cmDiagnostics::DiagnosticMap& dm) const
4450
0
{
4451
  /* Record the setting of every diagnostic category.  */
4452
0
  for (unsigned n = 0; n < cmDiagnostics::CategoryCount; ++n) {
4453
0
    cmDiagnosticCategory const dc = static_cast<cmDiagnosticCategory>(n);
4454
0
    dm[dc] = this->GetDiagnosticAction(dc);
4455
0
  }
4456
0
}
4457
4458
cmMakefile::FunctionPushPop::FunctionPushPop(cmMakefile* mf,
4459
                                             std::string const& fileName,
4460
                                             cmPolicies::PolicyMap const& pm,
4461
                                             cmDiagnostics::DiagnosticMap dm)
4462
0
  : Makefile(mf)
4463
0
{
4464
0
  this->Makefile->PushFunctionScope(fileName, pm, dm);
4465
0
}
4466
4467
cmMakefile::FunctionPushPop::~FunctionPushPop()
4468
0
{
4469
0
  this->Makefile->PopFunctionScope(this->ReportError);
4470
0
}
4471
4472
cmMakefile::MacroPushPop::MacroPushPop(cmMakefile* mf,
4473
                                       std::string const& fileName,
4474
                                       cmPolicies::PolicyMap const& pm,
4475
                                       cmDiagnostics::DiagnosticMap dm)
4476
0
  : Makefile(mf)
4477
0
{
4478
0
  this->Makefile->PushMacroScope(fileName, pm, dm);
4479
0
}
4480
4481
cmMakefile::MacroPushPop::~MacroPushPop()
4482
0
{
4483
0
  this->Makefile->PopMacroScope(this->ReportError);
4484
0
}
4485
4486
cmMakefile::FindPackageStackRAII::FindPackageStackRAII(
4487
  cmMakefile* mf, std::string const& name,
4488
  std::shared_ptr<cmPackageInformation const> pkgInfo)
4489
0
  : Makefile(mf)
4490
0
{
4491
0
  this->Makefile->FindPackageStack =
4492
0
    this->Makefile->FindPackageStack.Push(cmFindPackageCall{
4493
0
      name,
4494
0
      std::move(pkgInfo),
4495
0
      this->Makefile->FindPackageStackNextIndex,
4496
0
    });
4497
0
  this->Makefile->FindPackageStackNextIndex++;
4498
0
}
4499
4500
cmMakefile::FindPackageStackRAII::~FindPackageStackRAII()
4501
0
{
4502
0
  this->Makefile->FindPackageStackNextIndex =
4503
0
    this->Makefile->FindPackageStack.Top().Index + 1;
4504
0
  this->Makefile->FindPackageStack = this->Makefile->FindPackageStack.Pop();
4505
4506
0
  if (!this->Makefile->FindPackageStack.Empty()) {
4507
    // We have just finished an inner package found as a dependency of an
4508
    // outer package.  Targets created in the outer package after this
4509
    // point may depend on the inner package, so if they are exported,
4510
    // their find_dependency call for the outer package should be
4511
    // ordered after the find_dependency call for the inner package.
4512
    //
4513
    // Any targets created by the outer package before the inner package
4514
    // was loaded will have already saved a copy of the outer package
4515
    // stack with its original index.  Replace the top entry with a new
4516
    // one representing the same outer package with a new index.
4517
0
    cmFindPackageCall outer = this->Makefile->FindPackageStack.Top();
4518
0
    this->Makefile->FindPackageStack = this->Makefile->FindPackageStack.Pop();
4519
4520
0
    outer.Index = this->Makefile->FindPackageStackNextIndex;
4521
0
    this->Makefile->FindPackageStackNextIndex++;
4522
4523
0
    this->Makefile->FindPackageStack =
4524
0
      this->Makefile->FindPackageStack.Push(outer);
4525
0
  }
4526
0
}
4527
4528
cmMakefile::DebugFindPkgRAII::DebugFindPkgRAII(cmMakefile* mf,
4529
                                               std::string const& pkg)
4530
0
  : Makefile(mf)
4531
0
  , OldValue(this->Makefile->DebugFindPkg)
4532
0
{
4533
0
  this->Makefile->DebugFindPkg =
4534
0
    this->Makefile->GetCMakeInstance()->GetDebugFindPkgOutput(pkg);
4535
0
}
4536
4537
cmMakefile::DebugFindPkgRAII::~DebugFindPkgRAII()
4538
0
{
4539
0
  this->Makefile->DebugFindPkg = this->OldValue;
4540
0
}
4541
4542
bool cmMakefile::GetDebugFindPkgMode() const
4543
0
{
4544
0
  return this->DebugFindPkg;
4545
0
}