Coverage Report

Created: 2026-09-14 06:43

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/CMake/Source/cmake.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 "cmake.h"
4
5
#include <algorithm>
6
#include <array>
7
#include <cassert>
8
#include <chrono>
9
#include <climits>
10
#include <cstdio>
11
#include <cstdlib>
12
#include <initializer_list>
13
#include <iomanip>
14
#include <iostream>
15
#include <iterator>
16
#include <sstream>
17
#include <stdexcept>
18
#include <utility>
19
20
#include <cm/memory>
21
#include <cm/optional>
22
#include <cm/string_view>
23
#if defined(_WIN32) && !defined(__CYGWIN__) && !defined(CMAKE_BOOT_MINGW)
24
#  include <cm/iterator>
25
#endif
26
27
#include <cmext/algorithm>
28
#include <cmext/string_view>
29
30
#include <sys/types.h>
31
32
#include "cmsys/FStream.hxx"
33
#include "cmsys/Glob.hxx"
34
#include "cmsys/RegularExpression.hxx"
35
36
#include "cm_sys_stat.h"
37
38
#include "cmBuildOptions.h"
39
#include "cmCMakePath.h"
40
#include "cmCMakePresetsGraph.h"
41
#include "cmCacheDocumentationTable.h"
42
#include "cmCommandLineArgument.h"
43
#include "cmCommands.h"
44
#include "cmDocumentation.h"
45
#include "cmDocumentationEntry.h"
46
#include "cmDuration.h"
47
#include "cmExternalMakefileProjectGenerator.h"
48
#include "cmFileTimeCache.h"
49
#include "cmGeneratorTarget.h"
50
#include "cmGlobCacheEntry.h" // IWYU pragma: keep
51
#include "cmGlobalGenerator.h"
52
#include "cmGlobalGeneratorFactory.h"
53
#include "cmJSONState.h"
54
#include "cmLinkLineComputer.h"
55
#include "cmList.h"
56
#include "cmLocalGenerator.h"
57
#include "cmMakefile.h"
58
#include "cmMessenger.h"
59
#include "cmPolicies.h"
60
#include "cmState.h"
61
#include "cmStateDirectory.h"
62
#include "cmStringAlgorithms.h"
63
#include "cmSystemTools.h"
64
#include "cmTarget.h"
65
#include "cmTargetLinkLibraryType.h"
66
#include "cmUVProcessChain.h"
67
#include "cmUtils.hxx"
68
#include "cmVersionConfig.h"
69
#include "cmWorkingDirectory.h"
70
71
#ifdef CMake_ENABLE_DEBUGGER
72
#  include "cmDebuggerAdapter.h"
73
#  ifdef _WIN32
74
#    include "cmDebuggerWindowsPipeConnection.h"
75
#  else //!_WIN32
76
#    include "cmDebuggerPosixPipeConnection.h"
77
#  endif //_WIN32
78
#endif
79
80
#if !defined(CMAKE_BOOTSTRAP)
81
#  include <unordered_map>
82
83
#  include <cm3p/curl/curl.h>
84
#  include <cm3p/json/writer.h>
85
86
#  include "cmCMakePresetsArgs.h"
87
#  include "cmConfigureLog.h"
88
#  include "cmFileAPI.h"
89
#  include "cmGraphVizWriter.h"
90
#  include "cmInstrumentation.h"
91
#  include "cmInstrumentationInterrupt.h"
92
#  include "cmInstrumentationQuery.h"
93
#  include "cmMakefileProfilingData.h"
94
#  include "cmVariableWatch.h"
95
#endif
96
97
#if defined(__MINGW32__) && defined(CMAKE_BOOTSTRAP)
98
#  define CMAKE_BOOT_MINGW
99
#endif
100
101
// include the generator
102
#if defined(_WIN32) && !defined(__CYGWIN__)
103
#  if !defined(CMAKE_BOOT_MINGW)
104
#    include <cmext/memory>
105
106
#    include "cmGlobalBorlandMakefileGenerator.h"
107
#    include "cmGlobalFastbuildGenerator.h"
108
#    include "cmGlobalJOMMakefileGenerator.h"
109
#    include "cmGlobalNMakeMakefileGenerator.h"
110
#    include "cmGlobalVisualStudioVersionedGenerator.h"
111
#    include "cmVSSetupHelper.h"
112
113
#    define CMAKE_HAVE_VS_GENERATORS
114
#  endif
115
#  include "cmGlobalMSYSMakefileGenerator.h"
116
#  include "cmGlobalMinGWMakefileGenerator.h"
117
#else
118
#endif
119
#if defined(CMAKE_USE_WMAKE)
120
#  include "cmGlobalWatcomWMakeGenerator.h"
121
#endif
122
#if !defined(CMAKE_BOOTSTRAP)
123
#  include "cmGlobalNinjaGenerator.h"
124
#  include "cmGlobalUnixMakefileGenerator3.h"
125
#elif defined(CMAKE_BOOTSTRAP_MAKEFILES)
126
#  include "cmGlobalUnixMakefileGenerator3.h"
127
#elif defined(CMAKE_BOOTSTRAP_NINJA)
128
#  include "cmGlobalNinjaGenerator.h"
129
#endif
130
#include "cmGlobalFastbuildGenerator.h"
131
132
#if !defined(CMAKE_BOOTSTRAP)
133
#  include "cmExtraCodeBlocksGenerator.h"
134
#  include "cmExtraCodeLiteGenerator.h"
135
#  include "cmExtraEclipseCDT4Generator.h"
136
#  include "cmExtraKateGenerator.h"
137
#  include "cmExtraSublimeTextGenerator.h"
138
139
// NOTE: the __linux__ macro is predefined on Android host too, but
140
// main CMakeLists.txt filters out this generator by host name.
141
#  if (defined(__linux__) && !defined(__ANDROID__)) || defined(_WIN32)
142
#    include "cmGlobalGhsMultiGenerator.h"
143
#  endif
144
#endif
145
146
#if defined(__APPLE__)
147
#  if !defined(CMAKE_BOOTSTRAP)
148
#    include "cmGlobalXCodeGenerator.h"
149
150
#    define CMAKE_USE_XCODE 1
151
#  endif
152
#  include <sys/resource.h>
153
#  include <sys/time.h>
154
#endif
155
156
namespace {
157
158
#if !defined(CMAKE_BOOTSTRAP)
159
using JsonValueMapType = std::unordered_map<std::string, Json::Value>;
160
#endif
161
162
35
auto IgnoreAndTrueLambda = [](std::string const&, cmake*) -> bool {
163
35
  return true;
164
35
};
165
166
using CommandArgument =
167
  cmCommandLineArgument<bool(std::string const& value, cmake* state)>;
168
169
#ifndef CMAKE_BOOTSTRAP
170
void cmWarnUnusedCliWarning(std::string const& variable,
171
                            cmVariableWatch::AccessType /*unused*/, void* ctx,
172
                            char const* /*unused*/,
173
                            cmMakefile const* /*unused*/)
174
0
{
175
0
  cmake* cm = reinterpret_cast<cmake*>(ctx);
176
0
  cm->MarkCliAsUsed(variable);
177
0
}
178
179
void cmDeprecatedWatch(std::string const& /*unused*/,
180
                       cmVariableWatch::AccessType /*unused*/,
181
                       void* /*unused*/, char const* /*unused*/,
182
                       cmMakefile const* mf)
183
0
{
184
0
  if (mf->GetPolicyStatus(cmPolicies::CMP0218) == cmPolicies::WARN) {
185
0
    mf->IssuePolicyWarning(cmPolicies::CMP0218);
186
0
  }
187
0
}
188
#endif
189
190
void warnDeprecated(cm::string_view oldOption, cm::string_view newOption)
191
0
{
192
0
  std::cerr << "The "_s << oldOption << " option is deprecated.  Use "_s
193
0
            << newOption << " instead.\n"_s;
194
0
}
195
196
std::string normalizeCliWarningName(cm::string_view cliName)
197
0
{
198
0
  std::string out = cmStrCat("CMD_"_s, cmSystemTools::UpperCase(cliName));
199
0
  std::replace(out.begin(), out.end(), '-', '_');
200
0
  return out;
201
0
}
202
203
bool cmakeCheckStampFile(std::string const& stampName)
204
0
{
205
  // The stamp file does not exist.  Use the stamp dependencies to
206
  // determine whether it is really out of date.  This works in
207
  // conjunction with cmLocalVisualStudio7Generator to avoid
208
  // repeatedly re-running CMake when the user rebuilds the entire
209
  // solution.
210
0
  std::string stampDepends = cmStrCat(stampName, ".depend");
211
#if defined(_WIN32) || defined(__CYGWIN__)
212
  cmsys::ifstream fin(stampDepends.c_str(), std::ios::in | std::ios::binary);
213
#else
214
0
  cmsys::ifstream fin(stampDepends.c_str());
215
0
#endif
216
0
  if (!fin) {
217
    // The stamp dependencies file cannot be read.  Just assume the
218
    // build system is really out of date.
219
0
    std::cout << "CMake is re-running because " << stampName
220
0
              << " dependency file is missing.\n";
221
0
    return false;
222
0
  }
223
224
  // Compare the stamp dependencies against the dependency file itself.
225
0
  {
226
0
    cmFileTimeCache ftc;
227
0
    std::string dep;
228
0
    while (cmSystemTools::GetLineFromStream(fin, dep)) {
229
0
      int result;
230
0
      if (!dep.empty() && dep[0] != '#' &&
231
0
          (!ftc.Compare(stampDepends, dep, &result) || result < 0)) {
232
        // The stamp depends file is older than this dependency.  The
233
        // build system is really out of date.
234
        /* clang-format off */
235
0
        std::cout << "CMake is re-running because " << stampName
236
0
                  << " is out-of-date.\n"
237
0
                     "  the file '" << dep << "'\n"
238
0
                     "  is newer than '" << stampDepends << "'\n"
239
0
                     "  result='" << result << "'\n";
240
        /* clang-format on */
241
0
        return false;
242
0
      }
243
0
    }
244
0
  }
245
246
  // The build system is up to date.  The stamp file has been removed
247
  // by the VS IDE due to a "rebuild" request.  Restore it atomically.
248
0
  std::ostringstream stampTempStream;
249
0
  stampTempStream << stampName << ".tmp" << cmSystemTools::RandomNumber();
250
0
  std::string stampTemp = stampTempStream.str();
251
0
  {
252
    // TODO: Teach cmGeneratedFileStream to use a random temp file (with
253
    // multiple tries in unlikely case of conflict) and use that here.
254
0
    cmsys::ofstream stamp(stampTemp.c_str());
255
0
    stamp << "# CMake generation timestamp file for this directory.\n";
256
0
  }
257
0
  std::string err;
258
0
  if (cmSystemTools::RenameFile(stampTemp, stampName,
259
0
                                cmSystemTools::Replace::Yes, &err) ==
260
0
      cmSystemTools::RenameResult::Success) {
261
    // CMake does not need to re-run because the stamp file is up-to-date.
262
0
    return true;
263
0
  }
264
0
  cmSystemTools::RemoveFile(stampTemp);
265
0
  cmSystemTools::Error(
266
0
    cmStrCat("Cannot restore timestamp \"", stampName, "\": ", err));
267
0
  return false;
268
0
}
269
270
bool cmakeCheckStampList(std::string const& stampList)
271
0
{
272
  // If the stamp list does not exist CMake must rerun to generate it.
273
0
  if (!cmSystemTools::FileExists(stampList)) {
274
0
    std::cout << "CMake is re-running because generate.stamp.list "
275
0
                 "is missing.\n";
276
0
    return false;
277
0
  }
278
0
  cmsys::ifstream fin(stampList.c_str());
279
0
  if (!fin) {
280
0
    std::cout << "CMake is re-running because generate.stamp.list "
281
0
                 "could not be read.\n";
282
0
    return false;
283
0
  }
284
285
  // Check each stamp.
286
0
  std::string stampName;
287
0
  while (cmSystemTools::GetLineFromStream(fin, stampName)) {
288
0
    if (!cmakeCheckStampFile(stampName)) {
289
0
      return false;
290
0
    }
291
0
  }
292
0
  return true;
293
0
}
294
295
} // namespace
296
297
cmDocumentationEntry cmake::CMAKE_STANDARD_OPTIONS_TABLE[15] = {
298
  { "-S <path-to-source>", "Explicitly specify a source directory." },
299
  { "-B <path-to-build>", "Explicitly specify a build directory." },
300
  { "-C <initial-cache>", "Pre-load a script to populate the cache." },
301
  { "-D <var>[:<type>]=<value>", "Create or update a cmake cache entry." },
302
  { "-U <globbing_expr>", "Remove matching entries from CMake cache." },
303
  { "-G <generator-name>", "Specify a build system generator." },
304
  { "-T <toolset-name>", "Specify toolset name if supported by generator." },
305
  { "-A <platform-name>", "Specify platform name if supported by generator." },
306
  { "--toolchain <file>", "Specify toolchain file [CMAKE_TOOLCHAIN_FILE]." },
307
  { "--install-prefix <directory>",
308
    "Specify install directory [CMAKE_INSTALL_PREFIX]." },
309
  { "--project-file <project-file-name>",
310
    "Specify an alternate project file name." },
311
  { "-W<category>", "Enable the specified category of warnings." },
312
  { "-Wno-<category>", "Suppress the specified category of warnings." },
313
  { "-Werror=<category>", "Make the specified category of warnings errors." },
314
  { "-Wno-error=<category>",
315
    "Make the specified category of warnings not errors." },
316
};
317
318
cmake::cmake(cmState::Role role, cmState::TryCompile isTryCompile)
319
35
  : CMakeWorkingDirectory(cmSystemTools::GetLogicalWorkingDirectory())
320
35
  , FileTimeCache(cm::make_unique<cmFileTimeCache>())
321
#ifndef CMAKE_BOOTSTRAP
322
35
  , VariableWatch(cm::make_unique<cmVariableWatch>())
323
#endif
324
35
  , State(cm::make_unique<cmState>(role, isTryCompile))
325
35
  , Messenger(cm::make_unique<cmMessenger>())
326
35
{
327
35
  this->TraceFile.close();
328
35
  this->CurrentSnapshot = this->State->CreateBaseSnapshot();
329
330
#ifdef __APPLE__
331
  struct rlimit rlp;
332
  if (!getrlimit(RLIMIT_STACK, &rlp)) {
333
    if (rlp.rlim_cur != rlp.rlim_max) {
334
      rlp.rlim_cur = rlp.rlim_max;
335
      setrlimit(RLIMIT_STACK, &rlp);
336
    }
337
  }
338
#endif
339
340
35
  this->AddDefaultGenerators();
341
35
  this->AddDefaultExtraGenerators();
342
35
  if (role == cmState::Role::Project || role == cmState::Role::FindPackage ||
343
35
      role == cmState::Role::Script || role == cmState::Role::CTest ||
344
35
      role == cmState::Role::CPack) {
345
35
    this->AddScriptingCommands();
346
35
  }
347
35
  if (role == cmState::Role::Project || role == cmState::Role::FindPackage) {
348
0
    this->AddProjectCommands();
349
0
  }
350
351
35
  if (role == cmState::Role::Project || role == cmState::Role::Help) {
352
0
    this->LoadEnvironmentPresets();
353
0
  }
354
355
  // Make sure we can capture the build tool output.
356
35
  cmSystemTools::EnableVSConsoleOutput();
357
358
  // Set up a list of source and header extensions.
359
  // These are used to find files when the extension is not given.
360
35
  {
361
35
    auto setupExts = [](FileExtensions& exts,
362
210
                        std::initializer_list<cm::string_view> extList) {
363
      // Fill ordered vector
364
210
      exts.ordered.reserve(extList.size());
365
1.19k
      for (cm::string_view ext : extList) {
366
1.19k
        exts.ordered.emplace_back(ext);
367
1.19k
      }
368
      // Fill unordered set
369
210
      exts.unordered.insert(exts.ordered.begin(), exts.ordered.end());
370
210
    };
371
372
    // The "c" extension MUST precede the "C" extension.
373
35
    setupExts(this->CLikeSourceFileExtensions,
374
35
              { "c", "C", "c++", "cc", "cpp", "cxx", "cu", "mpp", "m", "M",
375
35
                "mm", "ixx", "cppm", "ccm", "cxxm", "c++m" });
376
35
    setupExts(this->HeaderFileExtensions,
377
35
              { "h", "hh", "h++", "hm", "hpp", "hxx", "in", "txx" });
378
35
    setupExts(this->CudaFileExtensions, { "cu" });
379
35
    setupExts(this->FortranFileExtensions,
380
35
              { "f", "F", "for", "f77", "f90", "f95", "f03" });
381
35
    setupExts(this->HipFileExtensions, { "hip" });
382
35
    setupExts(this->ISPCFileExtensions, { "ispc" });
383
35
  }
384
35
}
385
386
35
cmake::~cmake() = default;
387
388
#if !defined(CMAKE_BOOTSTRAP)
389
Json::Value cmake::ReportVersionJson() const
390
0
{
391
0
  Json::Value version = Json::objectValue;
392
0
  version["string"] = CMake_VERSION;
393
0
  version["major"] = CMake_VERSION_MAJOR;
394
0
  version["minor"] = CMake_VERSION_MINOR;
395
0
  version["suffix"] = CMake_VERSION_SUFFIX;
396
0
  version["isDirty"] = (CMake_VERSION_IS_DIRTY == 1);
397
0
  version["patch"] = CMake_VERSION_PATCH;
398
0
  return version;
399
0
}
400
401
Json::Value cmake::ReportCapabilitiesJson() const
402
0
{
403
0
  Json::Value obj = Json::objectValue;
404
405
  // Version information:
406
0
  obj["version"] = this->ReportVersionJson();
407
408
  // Generators:
409
0
  std::vector<cmake::GeneratorInfo> generatorInfoList;
410
0
  this->GetRegisteredGenerators(generatorInfoList);
411
412
0
  auto* curlVersion = curl_version_info(CURLVERSION_FIRST);
413
414
0
  JsonValueMapType generatorMap;
415
0
  for (cmake::GeneratorInfo const& gi : generatorInfoList) {
416
0
    if (gi.isAlias) { // skip aliases, they are there for compatibility reasons
417
                      // only
418
0
      continue;
419
0
    }
420
421
0
    if (gi.extraName.empty()) {
422
0
      Json::Value gen = Json::objectValue;
423
0
      gen["name"] = gi.name;
424
0
      gen["toolsetSupport"] = gi.supportsToolset;
425
0
      gen["platformSupport"] = gi.supportsPlatform;
426
0
      if (!gi.supportedPlatforms.empty()) {
427
0
        Json::Value supportedPlatforms = Json::arrayValue;
428
0
        for (std::string const& platform : gi.supportedPlatforms) {
429
0
          supportedPlatforms.append(platform);
430
0
        }
431
0
        gen["supportedPlatforms"] = std::move(supportedPlatforms);
432
0
      }
433
0
      gen["extraGenerators"] = Json::arrayValue;
434
0
      generatorMap[gi.name] = gen;
435
0
    } else {
436
0
      Json::Value& gen = generatorMap[gi.baseName];
437
0
      gen["extraGenerators"].append(gi.extraName);
438
0
    }
439
0
  }
440
441
0
  Json::Value generators = Json::arrayValue;
442
0
  for (auto const& i : generatorMap) {
443
0
    generators.append(i.second);
444
0
  }
445
0
  obj["generators"] = generators;
446
0
  obj["fileApi"] = cmFileAPI::ReportCapabilities();
447
0
  obj["serverMode"] = false;
448
0
  obj["tls"] = static_cast<bool>(curlVersion->features & CURL_VERSION_SSL);
449
0
#  ifdef CMake_ENABLE_DEBUGGER
450
0
  obj["debugger"] = true;
451
#  else
452
  obj["debugger"] = false;
453
#  endif
454
455
0
  return obj;
456
0
}
457
#endif
458
459
std::string cmake::ReportCapabilities() const
460
0
{
461
0
  std::string result;
462
0
#if !defined(CMAKE_BOOTSTRAP)
463
0
  Json::FastWriter writer;
464
0
  result = writer.write(this->ReportCapabilitiesJson());
465
#else
466
  result = "Not supported";
467
#endif
468
0
  return result;
469
0
}
470
471
bool cmake::RoleSupportsExitCode() const
472
0
{
473
0
  cmState::Role const role = this->State->GetRole();
474
0
  return role == cmState::Role::Script || role == cmState::Role::CTest;
475
0
}
476
477
cmake::CommandFailureAction cmake::GetCommandFailureAction() const
478
0
{
479
0
  switch (this->State->GetRole()) {
480
0
    case cmState::Role::Project:
481
0
    case cmState::Role::CTest:
482
0
      return CommandFailureAction::EXIT_CODE;
483
0
    default:
484
0
      return CommandFailureAction::FATAL_ERROR;
485
0
  }
486
0
}
487
488
void cmake::CleanupCommandsAndMacros()
489
0
{
490
0
  this->CurrentSnapshot = this->State->Reset(this->CurrentSnapshot);
491
0
  this->State->RemoveUserDefinedCommands();
492
0
  this->CurrentSnapshot.SetDefaultDefinitions();
493
  // FIXME: InstalledFiles probably belongs in the global generator.
494
0
  this->InstalledFiles.clear();
495
0
}
496
497
#ifndef CMAKE_BOOTSTRAP
498
void cmake::SetDiagnosticsFromPreset(
499
  std::map<cmDiagnosticCategory, bool> const& warnings,
500
  std::map<cmDiagnosticCategory, bool> const& errors)
501
0
{
502
0
  for (unsigned i = 1; i < cmDiagnostics::CategoryCount; ++i) {
503
0
    auto const category = static_cast<cmDiagnosticCategory>(i);
504
505
0
    auto const wi = warnings.find(category);
506
0
    if (wi != warnings.end()) {
507
0
      if (wi->second) {
508
0
        this->AlterDiagnostic(&cmStateSnapshot::PromoteDiagnostic, category,
509
0
                              cmDiagnostics::Warn, true);
510
0
      } else {
511
0
        this->AlterDiagnostic(&cmStateSnapshot::DemoteDiagnostic, category,
512
0
                              cmDiagnostics::Ignore, true);
513
0
      }
514
0
    }
515
516
0
    auto const ei = errors.find(category);
517
0
    if (ei != errors.end()) {
518
0
      if (ei->second) {
519
0
        this->AlterDiagnostic(&cmStateSnapshot::PromoteDiagnostic, category,
520
0
                              cmDiagnostics::SendError, true);
521
0
      } else {
522
0
        this->AlterDiagnostic(&cmStateSnapshot::DemoteDiagnostic, category,
523
0
                              cmDiagnostics::Warn, true);
524
0
      }
525
0
    }
526
0
  }
527
0
}
528
529
void cmake::ProcessPresetVariables()
530
1
{
531
1
  for (auto const& var : this->UnprocessedPresetVariables) {
532
0
    if (!var.second) {
533
0
      continue;
534
0
    }
535
0
    cmStateEnums::CacheEntryType type = cmStateEnums::UNINITIALIZED;
536
0
    if (!var.second->Type.empty()) {
537
0
      type = cmState::StringToCacheEntryType(var.second->Type);
538
0
    }
539
0
    this->ProcessCacheArg(var.first, var.second->Value, type);
540
0
  }
541
1
}
542
543
void cmake::PrintPresetVariables()
544
0
{
545
0
  bool first = true;
546
0
  for (auto const& var : this->UnprocessedPresetVariables) {
547
0
    if (!var.second) {
548
0
      continue;
549
0
    }
550
0
    cmStateEnums::CacheEntryType type = cmStateEnums::UNINITIALIZED;
551
0
    if (!var.second->Type.empty()) {
552
0
      type = cmState::StringToCacheEntryType(var.second->Type);
553
0
    }
554
0
    if (first) {
555
0
      std::cout << "Preset CMake variables:\n\n";
556
0
      first = false;
557
0
    }
558
0
    std::cout << "  " << var.first;
559
0
    if (type != cmStateEnums::UNINITIALIZED) {
560
0
      std::cout << ':' << cmState::CacheEntryTypeToString(type);
561
0
    }
562
0
    std::cout << "=\"" << var.second->Value << "\"\n";
563
0
  }
564
0
  if (!first) {
565
0
    std::cout << '\n';
566
0
  }
567
0
  this->UnprocessedPresetVariables.clear();
568
0
}
569
570
void cmake::ProcessPresetEnvironment()
571
1
{
572
1
  for (auto const& var : this->UnprocessedPresetEnvironment) {
573
0
    if (var.second) {
574
0
      cmSystemTools::PutEnv(cmStrCat(var.first, '=', *var.second));
575
0
    }
576
0
  }
577
1
}
578
579
void cmake::PrintPresetEnvironment()
580
0
{
581
0
  bool first = true;
582
0
  for (auto const& var : this->UnprocessedPresetEnvironment) {
583
0
    if (!var.second) {
584
0
      continue;
585
0
    }
586
0
    if (first) {
587
0
      std::cout << "Preset environment variables:\n\n";
588
0
      first = false;
589
0
    }
590
0
    std::cout << "  " << var.first << "=\"" << *var.second << "\"\n";
591
0
  }
592
0
  if (!first) {
593
0
    std::cout << '\n';
594
0
  }
595
0
  this->UnprocessedPresetEnvironment.clear();
596
0
}
597
#endif
598
599
// Parse the args
600
bool cmake::SetCacheArgs(std::vector<std::string> const& args)
601
1
{
602
1
  static std::string const kCMAKE_POLICY_VERSION_MINIMUM =
603
1
    "CMAKE_POLICY_VERSION_MINIMUM";
604
1
  if (!this->State->GetInitializedCacheValue(kCMAKE_POLICY_VERSION_MINIMUM)) {
605
1
    cm::optional<std::string> policyVersion =
606
1
      cmSystemTools::GetEnvVar(kCMAKE_POLICY_VERSION_MINIMUM);
607
1
    if (policyVersion && !policyVersion->empty()) {
608
0
      this->AddCacheEntry(
609
0
        kCMAKE_POLICY_VERSION_MINIMUM, *policyVersion,
610
0
        "Override policy version for cmake_minimum_required calls.",
611
0
        cmStateEnums::STRING);
612
0
      this->State->SetCacheEntryProperty(kCMAKE_POLICY_VERSION_MINIMUM,
613
0
                                         "ADVANCED", "1");
614
0
    }
615
1
  }
616
617
1
  auto DefineLambda = [](std::string const& entry, cmake* state) -> bool {
618
0
    std::string var;
619
0
    std::string value;
620
0
    cmStateEnums::CacheEntryType type = cmStateEnums::UNINITIALIZED;
621
0
    if (cmState::ParseCacheEntry(entry, var, value, type)) {
622
0
#ifndef CMAKE_BOOTSTRAP
623
0
      state->UnprocessedPresetVariables.erase(var);
624
0
#endif
625
0
      state->ProcessCacheArg(var, value, type);
626
0
    } else {
627
0
      cmSystemTools::Error(cmStrCat("Parse error in command line argument: ",
628
0
                                    entry, "\n Should be: VAR:type=value\n"));
629
0
      return false;
630
0
    }
631
0
    return true;
632
0
  };
633
634
1
  auto WarningLambda = [](cm::string_view option, cmake* state) -> bool {
635
0
    bool foundNo = false;
636
0
    bool foundError = false;
637
638
0
    cm::string_view cname = option;
639
0
    if (cmHasLiteralPrefix(cname, "no-")) {
640
0
      foundNo = true;
641
0
      cname.remove_prefix(3);
642
0
    }
643
644
0
    if (cmHasLiteralPrefix(cname, "error=")) {
645
0
      foundError = true;
646
0
      cname.remove_prefix(6);
647
0
    }
648
649
0
    if (cname.empty()) {
650
0
      cmSystemTools::Error("No warning name provided.");
651
0
      return false;
652
0
    }
653
654
0
    cm::optional<cmDiagnosticCategory> category;
655
0
    if (cname == "dev"_s) {
656
0
      warnDeprecated(
657
0
        option,
658
0
        cmStrCat("-W"_s, option.substr(0, option.size() - 3), "author"_s));
659
0
      category = cmDiagnostics::CMD_AUTHOR;
660
0
    } else {
661
0
      category =
662
0
        cmDiagnostics::GetDiagnosticCategory(normalizeCliWarningName(cname));
663
0
      if (!category) {
664
0
        cmSystemTools::Error(
665
0
          cmStrCat("The warning category \""_s, cname, "\" is not known."));
666
0
        return false;
667
0
      }
668
0
    }
669
670
0
    if (foundNo) {
671
0
      state->AlterDiagnostic(
672
0
        &cmStateSnapshot::DemoteDiagnostic, *category,
673
0
        foundError ? cmDiagnostics::Warn : cmDiagnostics::Ignore, true);
674
0
    } else {
675
0
      state->AlterDiagnostic(
676
0
        &cmStateSnapshot::PromoteDiagnostic, *category,
677
0
        foundError ? cmDiagnostics::SendError : cmDiagnostics::Warn, true);
678
0
    }
679
0
    return true;
680
0
  };
681
682
1
  auto UnSetLambda = [](std::string const& entryPattern,
683
1
                        cmake* state) -> bool {
684
0
    cmsys::RegularExpression regex(
685
0
      cmsys::Glob::PatternToRegex(entryPattern, true, true));
686
    // go through all cache entries and collect the vars which will be
687
    // removed
688
0
    std::vector<std::string> entriesToDelete;
689
0
    std::vector<std::string> cacheKeys = state->State->GetCacheEntryKeys();
690
0
    for (std::string const& ck : cacheKeys) {
691
0
      cmStateEnums::CacheEntryType t = state->State->GetCacheEntryType(ck);
692
0
      if (t != cmStateEnums::STATIC) {
693
0
        if (regex.find(ck)) {
694
0
          entriesToDelete.push_back(ck);
695
0
        }
696
0
      }
697
0
    }
698
699
    // now remove them from the cache
700
0
    for (std::string const& currentEntry : entriesToDelete) {
701
0
#ifndef CMAKE_BOOTSTRAP
702
0
      state->UnprocessedPresetVariables.erase(currentEntry);
703
0
#endif
704
0
      state->State->RemoveCacheEntry(currentEntry);
705
0
    }
706
0
    return true;
707
0
  };
708
709
1
  auto ScriptLambda = [&](std::string const& path, cmake* state) -> bool {
710
1
    assert(this->State->GetRole() == cmState::Role::Script);
711
1
#ifdef CMake_ENABLE_DEBUGGER
712
    // Script mode doesn't hit the usual code path in cmake::Run() that starts
713
    // the debugger, so start it manually here instead.
714
1
    if (!this->StartDebuggerIfEnabled()) {
715
0
      return false;
716
0
    }
717
1
#endif
718
    // Register fake project commands that hint misuse in script mode.
719
1
    GetProjectCommandsInScriptMode(state->GetState());
720
    // Documented behavior of CMAKE{,_CURRENT}_{SOURCE,BINARY}_DIR is to be
721
    // set to $PWD for -P mode.
722
1
    state->SetHomeDirectory(cmSystemTools::GetLogicalWorkingDirectory());
723
1
    state->SetHomeOutputDirectory(cmSystemTools::GetLogicalWorkingDirectory());
724
1
    state->ReadListFile(args, cmSystemTools::ToNormalizedPathOnDisk(path));
725
1
    return true;
726
1
  };
727
728
1
  auto PrefixLambda = [&](std::string const& path, cmake* state) -> bool {
729
0
    std::string const var = "CMAKE_INSTALL_PREFIX";
730
0
    cmStateEnums::CacheEntryType type = cmStateEnums::PATH;
731
0
    cmCMakePath absolutePath(path);
732
0
    if (absolutePath.IsAbsolute()) {
733
0
#ifndef CMAKE_BOOTSTRAP
734
0
      state->UnprocessedPresetVariables.erase(var);
735
0
#endif
736
0
      state->ProcessCacheArg(var, path, type);
737
0
      return true;
738
0
    }
739
0
    cmSystemTools::Error("Absolute paths are required for --install-prefix");
740
0
    return false;
741
0
  };
742
743
1
  auto ToolchainLambda = [&](std::string const& path, cmake* state) -> bool {
744
0
    std::string const var = "CMAKE_TOOLCHAIN_FILE";
745
0
    cmStateEnums::CacheEntryType type = cmStateEnums::FILEPATH;
746
0
#ifndef CMAKE_BOOTSTRAP
747
0
    state->UnprocessedPresetVariables.erase(var);
748
0
#endif
749
0
    state->ProcessCacheArg(var, path, type);
750
0
    return true;
751
0
  };
752
753
1
  std::vector<CommandArgument> arguments = {
754
1
    CommandArgument{ "-D", "-D must be followed with VAR=VALUE.",
755
1
                     CommandArgument::Values::One,
756
1
                     CommandArgument::RequiresSeparator::No, DefineLambda },
757
1
    CommandArgument{ "-W", "-W must be followed with [no-]<name>.",
758
1
                     CommandArgument::Values::One,
759
1
                     CommandArgument::RequiresSeparator::No, WarningLambda },
760
1
    CommandArgument{ "-U", "-U must be followed with VAR.",
761
1
                     CommandArgument::Values::One,
762
1
                     CommandArgument::RequiresSeparator::No, UnSetLambda },
763
1
    CommandArgument{
764
1
      "-C", "-C must be followed by a file name.",
765
1
      CommandArgument::Values::One, CommandArgument::RequiresSeparator::No,
766
1
      [&](std::string const& value, cmake* state) -> bool {
767
0
        if (value.empty()) {
768
0
          cmSystemTools::Error("No file name specified for -C");
769
0
          return false;
770
0
        }
771
0
        state->SetInInitialCache(true);
772
0
        cmSystemTools::Stdout(
773
0
          cmStrCat("loading initial cache file ", value, '\n'));
774
        // Resolve script path specified on command line
775
        // relative to $PWD.
776
0
        auto path = cmSystemTools::ToNormalizedPathOnDisk(value);
777
0
        state->InitializeFileAPI();
778
0
        state->ReadListFile(args, path);
779
0
        state->SetInInitialCache(false);
780
0
        return true;
781
0
      } },
782
783
1
    CommandArgument{ "-P", "-P must be followed by a file name.",
784
1
                     CommandArgument::Values::One,
785
1
                     CommandArgument::RequiresSeparator::No, ScriptLambda },
786
1
    CommandArgument{ "--toolchain", "No file specified for --toolchain",
787
1
                     CommandArgument::Values::One, ToolchainLambda },
788
1
    CommandArgument{ "--install-prefix",
789
1
                     "No install directory specified for --install-prefix",
790
1
                     CommandArgument::Values::One, PrefixLambda },
791
1
    CommandArgument{ "--find-package", CommandArgument::Values::Zero,
792
1
                     IgnoreAndTrueLambda },
793
1
  };
794
2
  for (decltype(args.size()) i = 1; i < args.size(); ++i) {
795
1
    std::string const& arg = args[i];
796
797
1
    if (arg == "--" && this->State->GetRole() == cmState::Role::Script) {
798
      // Stop processing CMake args and avoid possible errors
799
      // when arbitrary args are given to CMake script.
800
0
      break;
801
0
    }
802
8
    for (auto const& m : arguments) {
803
8
      if (m.matches(arg)) {
804
1
        bool const parsedCorrectly = m.parse(arg, i, args, this);
805
1
        if (!parsedCorrectly) {
806
0
          return false;
807
0
        }
808
1
      }
809
8
    }
810
1
  }
811
812
1
  if (this->State->GetRole() == cmState::Role::FindPackage) {
813
0
    return this->FindPackage(args);
814
0
  }
815
816
1
  return true;
817
1
}
818
819
void cmake::ProcessCacheArg(std::string const& var, std::string const& value,
820
                            cmStateEnums::CacheEntryType type)
821
0
{
822
0
  cmDiagnosticAction const warnUnusedCli =
823
0
    this->CurrentSnapshot.GetDiagnostic(cmDiagnostics::CMD_UNUSED_CLI);
824
825
  // The value is transformed if it is a filepath for example, so
826
  // we can't compare whether the value is already in the cache until
827
  // after we call AddCacheEntry.
828
0
  bool haveValue = false;
829
0
  std::string cachedValue;
830
0
  if (warnUnusedCli != cmDiagnostics::Ignore) {
831
0
    if (cmValue v = this->State->GetInitializedCacheValue(var)) {
832
0
      haveValue = true;
833
0
      cachedValue = *v;
834
0
    }
835
0
  }
836
837
  // See also CMP0218.
838
0
  if (var == "CMAKE_WARN_DEPRECATED") {
839
0
    std::cerr << "The CMAKE_WARN_DEPRECATED variable is deprecated.  "
840
0
                 "Use -W[no-]deprecated instead.\n"_s;
841
0
  } else if (var == "CMAKE_ERROR_DEPRECATED") {
842
0
    std::cerr << "The CMAKE_ERROR_DEPRECATED variable is deprecated.  "
843
0
                 "Use -W[no-]error=deprecated instead.\n"_s;
844
0
  }
845
846
0
  auto const builtIn = cmCacheDocumentationTable::Get(var);
847
0
  std::string const helpString = builtIn.Summary.empty()
848
0
    ? std::string("No help, variable specified on the command line.")
849
0
    : std::string(builtIn.Summary);
850
851
0
  this->AddCacheEntry(var, value, helpString, type);
852
853
0
  if (warnUnusedCli != cmDiagnostics::Ignore) {
854
0
    if (!haveValue ||
855
0
        cachedValue != *this->State->GetInitializedCacheValue(var)) {
856
0
      this->WatchUnusedCli(var);
857
0
    }
858
0
  }
859
0
}
860
861
void cmake::ReadListFile(std::vector<std::string> const& args,
862
                         std::string const& path)
863
1
{
864
  // if a generator was not yet created, temporarily create one
865
1
  cmGlobalGenerator* gg = this->GetGlobalGenerator();
866
867
  // if a generator was not specified use a generic one
868
1
  std::unique_ptr<cmGlobalGenerator> gen;
869
1
  if (!gg) {
870
1
    gen = cm::make_unique<cmGlobalGenerator>(this);
871
1
    gg = gen.get();
872
1
  }
873
874
  // read in the list file to fill the cache
875
1
  if (!path.empty()) {
876
1
    this->CurrentSnapshot = this->State->Reset(this->CurrentSnapshot);
877
1
    cmStateSnapshot snapshot = this->GetCurrentSnapshot();
878
1
    snapshot.GetDirectory().SetCurrentBinary(this->GetHomeOutputDirectory());
879
1
    snapshot.GetDirectory().SetCurrentSource(this->GetHomeDirectory());
880
1
    snapshot.SetDefaultDefinitions();
881
1
    cmMakefile mf(gg, snapshot);
882
1
    if (this->State->GetRole() == cmState::Role::Script) {
883
1
      mf.SetScriptModeFile(path);
884
1
      mf.SetArgcArgv(args);
885
1
    }
886
1
    if (!cmSystemTools::FileExists(path, true)) {
887
0
      cmSystemTools::Error("Not a file: " + path);
888
0
    }
889
1
    if (!mf.ReadListFile(path)) {
890
1
      cmSystemTools::Error("Error processing file: " + path);
891
1
    }
892
1
  }
893
1
}
894
895
bool cmake::FindPackage(std::vector<std::string> const& args)
896
0
{
897
0
  this->SetHomeDirectory(cmSystemTools::GetLogicalWorkingDirectory());
898
0
  this->SetHomeOutputDirectory(cmSystemTools::GetLogicalWorkingDirectory());
899
900
0
  this->SetGlobalGenerator(cm::make_unique<cmGlobalGenerator>(this));
901
902
0
  cmStateSnapshot snapshot = this->GetCurrentSnapshot();
903
0
  snapshot.GetDirectory().SetCurrentBinary(
904
0
    cmSystemTools::GetLogicalWorkingDirectory());
905
0
  snapshot.GetDirectory().SetCurrentSource(
906
0
    cmSystemTools::GetLogicalWorkingDirectory());
907
  // read in the list file to fill the cache
908
0
  snapshot.SetDefaultDefinitions();
909
0
  auto mfu = cm::make_unique<cmMakefile>(this->GetGlobalGenerator(), snapshot);
910
0
  cmMakefile* mf = mfu.get();
911
0
  this->GlobalGenerator->AddMakefile(std::move(mfu));
912
913
0
  mf->SetArgcArgv(args);
914
915
0
  std::string systemFile = mf->GetModulesFile("CMakeFindPackageMode.cmake");
916
0
  mf->ReadListFile(systemFile);
917
918
0
  std::string language = mf->GetSafeDefinition("LANGUAGE");
919
0
  std::string mode = mf->GetSafeDefinition("MODE");
920
0
  std::string packageName = mf->GetSafeDefinition("NAME");
921
0
  bool packageFound = mf->IsOn("PACKAGE_FOUND");
922
0
  bool quiet = mf->IsOn("PACKAGE_QUIET");
923
924
0
  if (!packageFound) {
925
0
    if (!quiet) {
926
0
      printf("%s not found.\n", packageName.c_str());
927
0
    }
928
0
  } else if (mode == "EXIST"_s) {
929
0
    if (!quiet) {
930
0
      printf("%s found.\n", packageName.c_str());
931
0
    }
932
0
  } else if (mode == "COMPILE"_s) {
933
0
    std::string includes = mf->GetSafeDefinition("PACKAGE_INCLUDE_DIRS");
934
0
    cmList includeDirs{ includes };
935
936
0
    this->GlobalGenerator->CreateGenerationObjects();
937
0
    auto const& lg = this->GlobalGenerator->LocalGenerators[0];
938
0
    std::string includeFlags =
939
0
      lg->GetIncludeFlags(includeDirs, nullptr, language, std::string());
940
941
0
    std::string definitions = mf->GetSafeDefinition("PACKAGE_DEFINITIONS");
942
0
    printf("%s %s\n", includeFlags.c_str(), definitions.c_str());
943
0
  } else if (mode == "LINK"_s) {
944
0
    char const* targetName = "dummy";
945
0
    std::vector<std::string> srcs;
946
0
    cmTarget* tgt = mf->AddExecutable(targetName, srcs, true);
947
0
    tgt->SetProperty("LINKER_LANGUAGE", language);
948
949
0
    std::string libs = mf->GetSafeDefinition("PACKAGE_LIBRARIES");
950
0
    cmList libList{ libs };
951
0
    for (std::string const& lib : libList) {
952
0
      tgt->AddLinkLibrary(*mf, lib, GENERAL_LibraryType);
953
0
    }
954
955
0
    std::string buildType = mf->GetSafeDefinition("CMAKE_BUILD_TYPE");
956
0
    buildType = cmSystemTools::UpperCase(buildType);
957
958
0
    std::string linkLibs;
959
0
    std::string frameworkPath;
960
0
    std::string linkPath;
961
0
    std::string flags;
962
0
    std::string linkFlags;
963
0
    this->GlobalGenerator->CreateGenerationObjects();
964
0
    cmGeneratorTarget* gtgt =
965
0
      this->GlobalGenerator->FindGeneratorTarget(tgt->GetName());
966
0
    cmLocalGenerator* lg = gtgt->GetLocalGenerator();
967
0
    cmLinkLineComputer linkLineComputer(lg,
968
0
                                        lg->GetStateSnapshot().GetDirectory());
969
0
    lg->GetTargetFlags(&linkLineComputer, buildType, linkLibs, flags,
970
0
                       linkFlags, frameworkPath, linkPath, gtgt);
971
0
    linkLibs = frameworkPath + linkPath + linkLibs;
972
973
0
    printf("%s\n", linkLibs.c_str());
974
975
    /*    if ( use_win32 )
976
          {
977
          tgt->SetProperty("WIN32_EXECUTABLE", "ON");
978
          }
979
        if ( use_macbundle)
980
          {
981
          tgt->SetProperty("MACOSX_BUNDLE", "ON");
982
          }*/
983
0
  }
984
985
0
  return packageFound;
986
0
}
987
988
void cmake::LoadEnvironmentPresets()
989
0
{
990
0
  std::string envGenVar;
991
0
  bool hasEnvironmentGenerator = false;
992
0
  if (cmSystemTools::GetEnv("CMAKE_GENERATOR", envGenVar)) {
993
0
    hasEnvironmentGenerator = true;
994
0
    this->EnvironmentGenerator = envGenVar;
995
0
  }
996
997
0
  auto readGeneratorVar = [&](std::string const& name, std::string& key) {
998
0
    std::string varValue;
999
0
    if (cmSystemTools::GetEnv(name, varValue)) {
1000
0
      if (hasEnvironmentGenerator) {
1001
0
        key = varValue;
1002
0
      } else if (!this->GetIsInTryCompile()) {
1003
0
        std::string message =
1004
0
          cmStrCat("Warning: Environment variable ", name,
1005
0
                   " will be ignored, because CMAKE_GENERATOR is not set.");
1006
0
        cmSystemTools::Message(message, "Warning");
1007
0
      }
1008
0
    }
1009
0
  };
1010
1011
0
  readGeneratorVar("CMAKE_GENERATOR_INSTANCE", this->GeneratorInstance);
1012
0
  readGeneratorVar("CMAKE_GENERATOR_PLATFORM", this->GeneratorPlatform);
1013
0
  readGeneratorVar("CMAKE_GENERATOR_TOOLSET", this->GeneratorToolset);
1014
0
  this->IntermediateDirStrategy =
1015
0
    cmSystemTools::GetEnvVar("CMAKE_INTERMEDIATE_DIR_STRATEGY");
1016
0
  this->AutogenIntermediateDirStrategy =
1017
0
    cmSystemTools::GetEnvVar("CMAKE_AUTOGEN_INTERMEDIATE_DIR_STRATEGY");
1018
0
}
1019
1020
// Parse the args
1021
void cmake::SetArgs(std::vector<std::string> const& args)
1022
35
{
1023
35
  this->cmdArgs = args;
1024
35
  bool haveToolset = false;
1025
35
  bool havePlatform = false;
1026
35
  bool haveBArg = false;
1027
35
  bool haveCMLName = false;
1028
35
  std::string possibleUnknownArg;
1029
35
  std::string extraProvidedPath;
1030
35
#if !defined(CMAKE_BOOTSTRAP)
1031
35
  std::string profilingFormat;
1032
35
  std::string profilingOutput;
1033
1034
35
  cmCMakePresetsConfigureArgs presetsArgs;
1035
35
  using ListPresets = cmCMakePresetsConfigureArgs::ListPresetsOption;
1036
35
#endif
1037
1038
35
  auto EmptyStringArgLambda = [](std::string const&, cmake* state) -> bool {
1039
0
    state->IssueMessage(
1040
0
      MessageType::WARNING,
1041
0
      "Ignoring empty string (\"\") provided on the command line.");
1042
0
    return true;
1043
0
  };
1044
1045
35
  auto SourceArgLambda = [](std::string const& value, cmake* state) -> bool {
1046
0
    if (value.empty()) {
1047
0
      cmSystemTools::Error("No source directory specified for -S");
1048
0
      return false;
1049
0
    }
1050
0
    state->SetHomeDirectoryViaCommandLine(
1051
0
      cmSystemTools::ToNormalizedPathOnDisk(value));
1052
0
    return true;
1053
0
  };
1054
1055
35
  auto BuildArgLambda = [&](std::string const& value, cmake* state) -> bool {
1056
0
    if (value.empty()) {
1057
0
      cmSystemTools::Error("No build directory specified for -B");
1058
0
      return false;
1059
0
    }
1060
0
    state->SetHomeOutputDirectory(
1061
0
      cmSystemTools::ToNormalizedPathOnDisk(value));
1062
0
    haveBArg = true;
1063
0
    return true;
1064
0
  };
1065
1066
35
  auto PlatformLambda = [&](std::string const& value, cmake* state) -> bool {
1067
0
    if (havePlatform) {
1068
0
      cmSystemTools::Error("Multiple -A options not allowed");
1069
0
      return false;
1070
0
    }
1071
0
    state->SetGeneratorPlatform(value);
1072
0
    havePlatform = true;
1073
0
    return true;
1074
0
  };
1075
1076
35
  auto ToolsetLambda = [&](std::string const& value, cmake* state) -> bool {
1077
0
    if (haveToolset) {
1078
0
      cmSystemTools::Error("Multiple -T options not allowed");
1079
0
      return false;
1080
0
    }
1081
0
    state->SetGeneratorToolset(value);
1082
0
    haveToolset = true;
1083
0
    return true;
1084
0
  };
1085
1086
35
  auto CMakeListsFileLambda = [&](std::string const& value,
1087
35
                                  cmake* state) -> bool {
1088
0
    if (haveCMLName) {
1089
0
      cmSystemTools::Error("Multiple --project-file options not allowed");
1090
0
      return false;
1091
0
    }
1092
0
    state->SetCMakeListName(value);
1093
0
    haveCMLName = true;
1094
0
    return true;
1095
0
  };
1096
1097
35
  std::vector<CommandArgument> arguments = {
1098
35
    CommandArgument{ "", CommandArgument::Values::Zero, EmptyStringArgLambda },
1099
35
    CommandArgument{ "-S", "No source directory specified for -S",
1100
35
                     CommandArgument::Values::One,
1101
35
                     CommandArgument::RequiresSeparator::No, SourceArgLambda },
1102
35
    CommandArgument{ "-H", "No source directory specified for -H",
1103
35
                     CommandArgument::Values::One,
1104
35
                     CommandArgument::RequiresSeparator::No, SourceArgLambda },
1105
35
    CommandArgument{ "-O", CommandArgument::Values::Zero,
1106
35
                     IgnoreAndTrueLambda },
1107
35
    CommandArgument{ "-B", "No build directory specified for -B",
1108
35
                     CommandArgument::Values::One,
1109
35
                     CommandArgument::RequiresSeparator::No, BuildArgLambda },
1110
35
    CommandArgument{ "--fresh", CommandArgument::Values::Zero,
1111
35
                     [](std::string const&, cmake* cm) -> bool {
1112
0
                       cm->FreshCache = true;
1113
0
                       return true;
1114
0
                     } },
1115
35
    CommandArgument{ "-P", "-P must be followed by a file name.",
1116
35
                     CommandArgument::Values::One,
1117
35
                     CommandArgument::RequiresSeparator::No,
1118
35
                     IgnoreAndTrueLambda },
1119
35
    CommandArgument{ "-D", "-D must be followed with VAR=VALUE.",
1120
35
                     CommandArgument::Values::One,
1121
35
                     CommandArgument::RequiresSeparator::No,
1122
35
                     IgnoreAndTrueLambda },
1123
35
    CommandArgument{ "-C", "-C must be followed by a file name.",
1124
35
                     CommandArgument::Values::One,
1125
35
                     CommandArgument::RequiresSeparator::No,
1126
35
                     IgnoreAndTrueLambda },
1127
35
    CommandArgument{
1128
35
      "-U", "-U must be followed with VAR.", CommandArgument::Values::One,
1129
35
      CommandArgument::RequiresSeparator::No, IgnoreAndTrueLambda },
1130
35
    CommandArgument{ "-W", "-W must be followed with [no-]<name>.",
1131
35
                     CommandArgument::Values::One,
1132
35
                     CommandArgument::RequiresSeparator::No,
1133
35
                     IgnoreAndTrueLambda },
1134
35
    CommandArgument{ "-A", "No platform specified for -A",
1135
35
                     CommandArgument::Values::One,
1136
35
                     CommandArgument::RequiresSeparator::No, PlatformLambda },
1137
35
    CommandArgument{ "-T", "No toolset specified for -T",
1138
35
                     CommandArgument::Values::One,
1139
35
                     CommandArgument::RequiresSeparator::No, ToolsetLambda },
1140
35
    CommandArgument{ "--toolchain", "No file specified for --toolchain",
1141
35
                     CommandArgument::Values::One, IgnoreAndTrueLambda },
1142
35
    CommandArgument{ "--install-prefix",
1143
35
                     "No install directory specified for --install-prefix",
1144
35
                     CommandArgument::Values::One, IgnoreAndTrueLambda },
1145
1146
35
    CommandArgument{ "--check-build-system", CommandArgument::Values::Two,
1147
35
                     [](std::string const& value, cmake* state) -> bool {
1148
0
                       cmList values{ value };
1149
0
                       state->CheckBuildSystemArgument = values[0];
1150
0
                       state->ClearBuildSystem = (atoi(values[1].c_str()) > 0);
1151
0
                       return true;
1152
0
                     } },
1153
35
    CommandArgument{ "--check-stamp-file", CommandArgument::Values::One,
1154
35
                     [](std::string const& value, cmake* state) -> bool {
1155
0
                       state->CheckStampFile = value;
1156
0
                       return true;
1157
0
                     } },
1158
35
    CommandArgument{ "--check-stamp-list", CommandArgument::Values::One,
1159
35
                     [](std::string const& value, cmake* state) -> bool {
1160
0
                       state->CheckStampList = value;
1161
0
                       return true;
1162
0
                     } },
1163
35
    CommandArgument{ "--regenerate-during-build",
1164
35
                     CommandArgument::Values::Zero,
1165
35
                     [](std::string const&, cmake* state) -> bool {
1166
0
                       state->RegenerateDuringBuild = true;
1167
0
                       return true;
1168
0
                     } },
1169
1170
35
    CommandArgument{ "--find-package", CommandArgument::Values::Zero,
1171
35
                     IgnoreAndTrueLambda },
1172
1173
35
    CommandArgument{ "--graphviz", "No file specified for --graphviz",
1174
35
                     CommandArgument::Values::One,
1175
35
                     [](std::string const& value, cmake* state) -> bool {
1176
0
                       state->SetGraphVizFile(
1177
0
                         cmSystemTools::ToNormalizedPathOnDisk(value));
1178
0
                       return true;
1179
0
                     } },
1180
1181
35
    CommandArgument{ "--debug-trycompile", CommandArgument::Values::Zero,
1182
35
                     [](std::string const&, cmake* state) -> bool {
1183
0
                       std::cout << "debug trycompile on\n";
1184
0
                       state->DebugTryCompileOn();
1185
0
                       return true;
1186
0
                     } },
1187
35
    CommandArgument{ "--debug-output", CommandArgument::Values::Zero,
1188
35
                     [](std::string const&, cmake* state) -> bool {
1189
0
                       std::cout << "Running with debug output on.\n";
1190
0
                       state->SetDebugOutputOn(true);
1191
0
                       return true;
1192
0
                     } },
1193
1194
35
    CommandArgument{ "--log-level", "Invalid level specified for --log-level",
1195
35
                     CommandArgument::Values::One,
1196
35
                     [](std::string const& value, cmake* state) -> bool {
1197
0
                       auto const logLevel = StringToLogLevel(value);
1198
0
                       if (logLevel == Message::LogLevel::LOG_UNDEFINED) {
1199
0
                         cmSystemTools::Error(
1200
0
                           "Invalid level specified for --log-level");
1201
0
                         return false;
1202
0
                       }
1203
0
                       state->SetLogLevel(logLevel);
1204
0
                       state->LogLevelWasSetViaCLI = true;
1205
0
                       return true;
1206
0
                     } },
1207
    // This is supported for backward compatibility. This option only
1208
    // appeared in the 3.15.x release series and was renamed to
1209
    // --log-level in 3.16.0
1210
35
    CommandArgument{ "--loglevel", "Invalid level specified for --loglevel",
1211
35
                     CommandArgument::Values::One,
1212
35
                     [](std::string const& value, cmake* state) -> bool {
1213
0
                       auto const logLevel = StringToLogLevel(value);
1214
0
                       if (logLevel == Message::LogLevel::LOG_UNDEFINED) {
1215
0
                         cmSystemTools::Error(
1216
0
                           "Invalid level specified for --loglevel");
1217
0
                         return false;
1218
0
                       }
1219
0
                       state->SetLogLevel(logLevel);
1220
0
                       state->LogLevelWasSetViaCLI = true;
1221
0
                       return true;
1222
0
                     } },
1223
1224
35
    CommandArgument{ "--log-context", CommandArgument::Values::Zero,
1225
35
                     [](std::string const&, cmake* state) -> bool {
1226
0
                       state->SetShowLogContext(true);
1227
0
                       return true;
1228
0
                     } },
1229
35
    CommandArgument{ "--project-file",
1230
35
                     "No filename specified for --project-file",
1231
35
                     CommandArgument::Values::One, CMakeListsFileLambda },
1232
35
    CommandArgument{
1233
35
      "--debug-find", CommandArgument::Values::Zero,
1234
35
      [](std::string const&, cmake* state) -> bool {
1235
0
        std::cout << "Running with debug output on for the `find` commands.\n";
1236
0
        state->SetDebugFindOutput(true);
1237
0
        return true;
1238
0
      } },
1239
35
    CommandArgument{
1240
35
      "--debug-find-pkg", "Provide a package argument for --debug-find-pkg",
1241
35
      CommandArgument::Values::One, CommandArgument::RequiresSeparator::Yes,
1242
35
      [](std::string const& value, cmake* state) -> bool {
1243
0
        std::vector<std::string> find_pkgs(cmTokenize(value, ','));
1244
0
        std::cout << "Running with debug output on for the 'find' commands "
1245
0
                     "for package(s)";
1246
0
        for (auto const& v : find_pkgs) {
1247
0
          std::cout << ' ' << v;
1248
0
          state->SetDebugFindOutputPkgs(v);
1249
0
        }
1250
0
        std::cout << ".\n";
1251
0
        return true;
1252
0
      } },
1253
35
    CommandArgument{
1254
35
      "--debug-find-var", CommandArgument::Values::One,
1255
35
      CommandArgument::RequiresSeparator::Yes,
1256
35
      [](std::string const& value, cmake* state) -> bool {
1257
0
        std::vector<std::string> find_vars(cmTokenize(value, ','));
1258
0
        std::cout << "Running with debug output on for the variable(s)";
1259
0
        for (auto const& v : find_vars) {
1260
0
          std::cout << ' ' << v;
1261
0
          state->SetDebugFindOutputVars(v);
1262
0
        }
1263
0
        std::cout << ".\n";
1264
0
        return true;
1265
0
      } },
1266
35
    CommandArgument{ "--trace", CommandArgument::Values::Zero,
1267
35
                     [](std::string const&, cmake* state) -> bool {
1268
0
                       std::cout << "Put cmake in trace mode.\n";
1269
0
                       state->SetTrace(true);
1270
0
                       state->SetTraceExpand(false);
1271
0
                       return true;
1272
0
                     } },
1273
35
    CommandArgument{ "--trace-expand", CommandArgument::Values::Zero,
1274
35
                     [](std::string const&, cmake* state) -> bool {
1275
0
                       std::cout << "Put cmake in trace mode, but with "
1276
0
                                    "variables expanded.\n";
1277
0
                       state->SetTrace(true);
1278
0
                       state->SetTraceExpand(true);
1279
0
                       return true;
1280
0
                     } },
1281
35
    CommandArgument{
1282
35
      "--trace-format", "Invalid format specified for --trace-format",
1283
35
      CommandArgument::Values::One,
1284
35
      [](std::string const& value, cmake* state) -> bool {
1285
0
        std::cout << "Put cmake in trace mode and sets the "
1286
0
                     "trace output format.\n";
1287
0
        state->SetTrace(true);
1288
0
        auto const traceFormat = StringToTraceFormat(value);
1289
0
        if (traceFormat == TraceFormat::Undefined) {
1290
0
          cmSystemTools::Error("Invalid format specified for --trace-format. "
1291
0
                               "Valid formats are human, json-v1.");
1292
0
          return false;
1293
0
        }
1294
0
        state->SetTraceFormat(traceFormat);
1295
0
        return true;
1296
0
      } },
1297
35
    CommandArgument{ "--trace-source", "No file specified for --trace-source",
1298
35
                     CommandArgument::Values::OneOrMore,
1299
35
                     [](std::string const& values, cmake* state) -> bool {
1300
0
                       std::cout << "Put cmake in trace mode, but output only "
1301
0
                                    "lines of a specified file. Multiple "
1302
0
                                    "options are allowed.\n";
1303
0
                       for (auto file :
1304
0
                            cmSystemTools::SplitString(values, ';')) {
1305
0
                         cmSystemTools::ConvertToUnixSlashes(file);
1306
0
                         state->AddTraceSource(file);
1307
0
                       }
1308
0
                       state->SetTrace(true);
1309
0
                       return true;
1310
0
                     } },
1311
35
    CommandArgument{ "--trace-redirect",
1312
35
                     "No file specified for --trace-redirect",
1313
35
                     CommandArgument::Values::One,
1314
35
                     [](std::string const& value, cmake* state) -> bool {
1315
0
                       std::cout
1316
0
                         << "Put cmake in trace mode and redirect trace "
1317
0
                            "output to a file instead of stderr.\n";
1318
0
                       std::string file(value);
1319
0
                       cmSystemTools::ConvertToUnixSlashes(file);
1320
0
                       state->SetTraceFile(file);
1321
0
                       state->SetTrace(true);
1322
0
                       return true;
1323
0
                     } },
1324
35
    CommandArgument{
1325
35
      "--warn-uninitialized", CommandArgument::Values::Zero,
1326
35
      [](std::string const&, cmake* state) -> bool {
1327
0
        warnDeprecated("--warn-uninitialized"_s, "-Wuninitialized"_s);
1328
0
        state->AlterDiagnostic(&cmStateSnapshot::PromoteDiagnostic,
1329
0
                               cmDiagnostics::CMD_UNINITIALIZED,
1330
0
                               cmDiagnostics::Warn, true);
1331
0
        return true;
1332
0
      } },
1333
35
    CommandArgument{ "--warn-unused-vars", CommandArgument::Values::Zero,
1334
35
                     IgnoreAndTrueLambda }, // Option was removed.
1335
35
    CommandArgument{
1336
35
      "--no-warn-unused-cli", CommandArgument::Values::Zero,
1337
35
      [](std::string const&, cmake* state) -> bool {
1338
0
        warnDeprecated("--no-warn-unused-cli"_s, "-Wno-unused-cli"_s);
1339
0
        state->AlterDiagnostic(&cmStateSnapshot::DemoteDiagnostic,
1340
0
                               cmDiagnostics::CMD_UNUSED_CLI,
1341
0
                               cmDiagnostics::Ignore, true);
1342
0
        return true;
1343
0
      } },
1344
35
    CommandArgument{
1345
35
      "--check-system-vars", CommandArgument::Values::Zero,
1346
35
      [](std::string const&, cmake* state) -> bool {
1347
0
        std::cout << "Also check system files when warning about unused and "
1348
0
                     "uninitialized variables.\n";
1349
0
        state->SetCheckSystemVars(true);
1350
0
        return true;
1351
0
      } },
1352
35
    CommandArgument{
1353
35
      "--compile-no-warning-as-error", CommandArgument::Values::Zero,
1354
35
      [](std::string const&, cmake* state) -> bool {
1355
0
        std::cout << "Ignoring COMPILE_WARNING_AS_ERROR target property and "
1356
0
                     "CMAKE_COMPILE_WARNING_AS_ERROR variable.\n";
1357
0
        state->SetIgnoreCompileWarningAsError(true);
1358
0
        return true;
1359
0
      } },
1360
35
    CommandArgument{
1361
35
      "--link-no-warning-as-error", CommandArgument::Values::Zero,
1362
35
      [](std::string const&, cmake* state) -> bool {
1363
0
        std::cout << "Ignoring LINK_WARNING_AS_ERROR target property and "
1364
0
                     "CMAKE_LINK_WARNING_AS_ERROR variable.\n";
1365
0
        state->SetIgnoreLinkWarningAsError(true);
1366
0
        return true;
1367
0
      } },
1368
35
    CommandArgument{ "--debugger", CommandArgument::Values::Zero,
1369
35
                     [](std::string const&, cmake* state) -> bool {
1370
0
#ifdef CMake_ENABLE_DEBUGGER
1371
0
                       std::cout << "Running with debugger on.\n";
1372
0
                       state->SetDebuggerOn(true);
1373
0
                       return true;
1374
#else
1375
                       static_cast<void>(state);
1376
                       cmSystemTools::Error(
1377
                         "CMake was not built with support for --debugger");
1378
                       return false;
1379
#endif
1380
0
                     } },
1381
35
    CommandArgument{ "--debugger-pipe",
1382
35
                     "No path specified for --debugger-pipe",
1383
35
                     CommandArgument::Values::One,
1384
35
                     [](std::string const& value, cmake* state) -> bool {
1385
0
#ifdef CMake_ENABLE_DEBUGGER
1386
0
                       state->DebuggerPipe = value;
1387
0
                       return true;
1388
#else
1389
                       static_cast<void>(value);
1390
                       static_cast<void>(state);
1391
                       cmSystemTools::Error("CMake was not built with support "
1392
                                            "for --debugger-pipe");
1393
                       return false;
1394
#endif
1395
0
                     } },
1396
35
    CommandArgument{ "--debugger-dap-log",
1397
35
                     "No file specified for --debugger-dap-log",
1398
35
                     CommandArgument::Values::One,
1399
35
                     [](std::string const& value, cmake* state) -> bool {
1400
0
#ifdef CMake_ENABLE_DEBUGGER
1401
0
                       state->DebuggerDapLogFile =
1402
0
                         cmSystemTools::ToNormalizedPathOnDisk(value);
1403
0
                       return true;
1404
#else
1405
                       static_cast<void>(value);
1406
                       static_cast<void>(state);
1407
                       cmSystemTools::Error("CMake was not built with support "
1408
                                            "for --debugger-dap-log");
1409
                       return false;
1410
#endif
1411
0
                     } },
1412
35
  };
1413
1414
#if defined(CMAKE_HAVE_VS_GENERATORS)
1415
  arguments.emplace_back("--vs-solution-file", CommandArgument::Values::One,
1416
                         [](std::string const& value, cmake* state) -> bool {
1417
                           state->VSSolutionFile = value;
1418
                           return true;
1419
                         });
1420
#endif
1421
1422
35
#if !defined(CMAKE_BOOTSTRAP)
1423
35
  arguments.emplace_back("--profiling-format",
1424
35
                         "No format specified for --profiling-format",
1425
35
                         CommandArgument::Values::One,
1426
35
                         [&](std::string const& value, cmake*) -> bool {
1427
0
                           profilingFormat = value;
1428
0
                           return true;
1429
0
                         });
1430
35
  arguments.emplace_back(
1431
35
    "--profiling-output", "No path specified for --profiling-output",
1432
35
    CommandArgument::Values::One,
1433
35
    [&profilingOutput](std::string const& value, cmake*) -> bool {
1434
0
      profilingOutput = cmSystemTools::ToNormalizedPathOnDisk(value);
1435
0
      return true;
1436
0
    });
1437
35
  arguments.emplace_back("--preset", "No preset specified for --preset",
1438
35
                         CommandArgument::Values::One,
1439
35
                         [&](std::string const& value, cmake*) -> bool {
1440
0
                           presetsArgs.PresetName = value;
1441
0
                           return true;
1442
0
                         });
1443
35
  arguments.emplace_back(
1444
35
    "--presets-file", "No file specified for --presets-file",
1445
35
    CommandArgument::Values::One,
1446
35
    [&presetsArgs](std::string const& value, cmake*) -> bool {
1447
0
      presetsArgs.PresetsFile = cmSystemTools::ToNormalizedPathOnDisk(value);
1448
0
      return true;
1449
0
    });
1450
35
  arguments.emplace_back(
1451
35
    "--list-presets", CommandArgument::Values::ZeroOrOne,
1452
35
    [&](std::string const& value, cmake*) -> bool {
1453
0
      std::string type = value;
1454
0
      auto const mode = presetsArgs.ParseListPresetsMode(type);
1455
1456
0
      if (type.empty() || type == "configure") {
1457
0
        presetsArgs.ListPresets = ListPresets::Configure;
1458
0
      } else if (type == "build") {
1459
0
        presetsArgs.ListPresets = ListPresets::Build;
1460
0
      } else if (type == "test") {
1461
0
        presetsArgs.ListPresets = ListPresets::Test;
1462
0
      } else if (type == "package") {
1463
0
        presetsArgs.ListPresets = ListPresets::Package;
1464
0
      } else if (type == "workflow") {
1465
0
        presetsArgs.ListPresets = ListPresets::Workflow;
1466
0
      } else if (type == "all") {
1467
0
        presetsArgs.ListPresets = ListPresets::All;
1468
0
      } else {
1469
0
        cmSystemTools::Error(
1470
0
          "Invalid value specified for --list-presets.\n"
1471
0
          "Valid values are configure, build, test, package, workflow, all, "
1472
0
          "defined, or any of the type values suffixed with -defined. When "
1473
0
          "no value is passed the default is configure.");
1474
0
        return false;
1475
0
      }
1476
1477
0
      presetsArgs.ListPresetsMode = mode;
1478
0
      return true;
1479
0
    });
1480
1481
35
#endif
1482
1483
35
  bool badGeneratorName = false;
1484
35
  CommandArgument generatorCommand(
1485
35
    "-G", "No generator specified for -G", CommandArgument::Values::One,
1486
35
    CommandArgument::RequiresSeparator::No,
1487
35
    [&](std::string const& value, cmake* state) -> bool {
1488
0
      bool valid = state->CreateAndSetGlobalGenerator(value);
1489
0
      badGeneratorName = !valid;
1490
0
      return valid;
1491
0
    });
1492
1493
70
  for (decltype(args.size()) i = 1; i < args.size(); ++i) {
1494
    // iterate each argument
1495
35
    std::string const& arg = args[i];
1496
1497
35
    if (this->State->GetRole() == cmState::Role::Script && arg == "--") {
1498
      // Stop processing CMake args and avoid possible errors
1499
      // when arbitrary args are given to CMake script.
1500
0
      break;
1501
0
    }
1502
1503
    // Generator flag has special handling for when to print help
1504
    // so it becomes the exception
1505
35
    if (generatorCommand.matches(arg)) {
1506
0
      bool parsed = generatorCommand.parse(arg, i, args, this);
1507
0
      if (!parsed && !badGeneratorName) {
1508
0
        this->PrintGeneratorList();
1509
0
        return;
1510
0
      }
1511
0
      continue;
1512
0
    }
1513
1514
35
    bool matched = false;
1515
35
    bool parsedCorrectly = true; // needs to be true so we can ignore
1516
                                 // arguments so as -E
1517
245
    for (auto const& m : arguments) {
1518
245
      if (m.matches(arg)) {
1519
35
        matched = true;
1520
35
        parsedCorrectly = m.parse(arg, i, args, this);
1521
35
        break;
1522
35
      }
1523
245
    }
1524
1525
    // We have an issue where arguments to a "-P" script mode
1526
    // can be provided before the "-P" argument. This means
1527
    // that we need to lazily check this argument after checking
1528
    // all args.
1529
    // Additionally it can't be the source/binary tree location
1530
35
    if (!parsedCorrectly) {
1531
0
      cmSystemTools::Error("Run 'cmake --help' for all supported options.");
1532
0
      exit(1);
1533
35
    } else if (!matched && cmHasPrefix(arg, '-')) {
1534
0
      possibleUnknownArg = arg;
1535
35
    } else if (!matched) {
1536
0
      bool parsedDirectory = this->SetDirectoriesFromFile(arg);
1537
0
      if (!parsedDirectory) {
1538
0
        extraProvidedPath = arg;
1539
0
      }
1540
0
    }
1541
35
  }
1542
1543
35
  if (!extraProvidedPath.empty() &&
1544
0
      this->State->GetRole() == cmState::Role::Project) {
1545
0
    this->IssueMessage(MessageType::WARNING,
1546
0
                       cmStrCat("Ignoring extra path from command line:\n \"",
1547
0
                                extraProvidedPath, '"'));
1548
0
  }
1549
35
  if (!possibleUnknownArg.empty() &&
1550
0
      this->State->GetRole() != cmState::Role::Script) {
1551
0
    cmSystemTools::Error(cmStrCat("Unknown argument ", possibleUnknownArg));
1552
0
    cmSystemTools::Error("Run 'cmake --help' for all supported options.");
1553
0
    exit(1);
1554
0
  }
1555
1556
  // Empty instance, platform and toolset if only a generator is specified
1557
35
  if (this->GlobalGenerator) {
1558
0
    this->GeneratorInstance = "";
1559
0
    if (!this->GeneratorPlatformSet) {
1560
0
      this->GeneratorPlatform = "";
1561
0
    }
1562
0
    if (!this->GeneratorToolsetSet) {
1563
0
      this->GeneratorToolset = "";
1564
0
    }
1565
0
  }
1566
1567
35
#if !defined(CMAKE_BOOTSTRAP)
1568
35
  if (!profilingOutput.empty() || !profilingFormat.empty()) {
1569
0
    if (profilingOutput.empty()) {
1570
0
      cmSystemTools::Error(
1571
0
        "--profiling-format specified but no --profiling-output!");
1572
0
      return;
1573
0
    }
1574
0
    if (profilingFormat == "google-trace"_s) {
1575
0
      try {
1576
0
        this->ProfilingOutput =
1577
0
          cm::make_unique<cmMakefileProfilingData>(profilingOutput);
1578
0
      } catch (std::runtime_error& e) {
1579
0
        cmSystemTools::Error(
1580
0
          cmStrCat("Could not start profiling: ", e.what()));
1581
0
        return;
1582
0
      }
1583
0
    } else {
1584
0
      cmSystemTools::Error("Invalid format specified for --profiling-format");
1585
0
      return;
1586
0
    }
1587
0
  }
1588
35
#endif
1589
1590
35
  bool const haveSourceDir = !this->GetHomeDirectory().empty();
1591
35
  bool const haveBinaryDir = !this->GetHomeOutputDirectory().empty();
1592
35
  bool const havePreset =
1593
#ifdef CMAKE_BOOTSTRAP
1594
    false;
1595
#else
1596
35
    !presetsArgs.PresetName.empty();
1597
35
#endif
1598
1599
35
  if (this->State->GetRole() == cmState::Role::Project && !haveSourceDir &&
1600
0
      !haveBinaryDir && !havePreset) {
1601
0
    this->IssueMessage(
1602
0
      MessageType::WARNING,
1603
0
      "No source or binary directory provided. Both will be assumed to be "
1604
0
      "the same as the current working directory, but note that this "
1605
0
      "warning will become a fatal error in future CMake releases.");
1606
0
  }
1607
1608
35
  if (!haveSourceDir) {
1609
0
    this->SetHomeDirectory(cmSystemTools::GetLogicalWorkingDirectory());
1610
0
  }
1611
35
  if (!haveBinaryDir) {
1612
0
    this->SetHomeOutputDirectory(cmSystemTools::GetLogicalWorkingDirectory());
1613
0
  }
1614
1615
35
  if (this->State->GetRole() == cmState::Role::Script && havePreset) {
1616
0
    this->IssueMessage(MessageType::FATAL_ERROR,
1617
0
                       "Presets are not supported in CMake script mode.");
1618
0
  }
1619
1620
35
#if !defined(CMAKE_BOOTSTRAP)
1621
35
  if (presetsArgs.HasPresetsArg()) {
1622
0
    this->SetArgsFromPreset(presetsArgs, haveBArg);
1623
0
  }
1624
35
#endif
1625
35
}
1626
1627
namespace {
1628
using LevelsPair = std::pair<cm::string_view, Message::LogLevel>;
1629
using LevelsPairArray = std::array<LevelsPair, 7>;
1630
LevelsPairArray const& getStringToLogLevelPairs()
1631
0
{
1632
0
  static LevelsPairArray const levels = {
1633
0
    { { "error", Message::LogLevel::LOG_ERROR },
1634
0
      { "warning", Message::LogLevel::LOG_WARNING },
1635
0
      { "notice", Message::LogLevel::LOG_NOTICE },
1636
0
      { "status", Message::LogLevel::LOG_STATUS },
1637
0
      { "verbose", Message::LogLevel::LOG_VERBOSE },
1638
0
      { "debug", Message::LogLevel::LOG_DEBUG },
1639
0
      { "trace", Message::LogLevel::LOG_TRACE } }
1640
0
  };
1641
0
  return levels;
1642
0
}
1643
} // namespace
1644
1645
Message::LogLevel cmake::StringToLogLevel(cm::string_view levelStr)
1646
0
{
1647
0
  LevelsPairArray const& levels = getStringToLogLevelPairs();
1648
1649
0
  auto const levelStrLowCase =
1650
0
    cmSystemTools::LowerCase(std::string{ levelStr });
1651
1652
  // NOLINTNEXTLINE(readability-qualified-auto)
1653
0
  auto const it = std::find_if(levels.cbegin(), levels.cend(),
1654
0
                               [&levelStrLowCase](LevelsPair const& p) {
1655
0
                                 return p.first == levelStrLowCase;
1656
0
                               });
1657
0
  return (it != levels.cend()) ? it->second : Message::LogLevel::LOG_UNDEFINED;
1658
0
}
1659
1660
std::string cmake::LogLevelToString(Message::LogLevel level)
1661
0
{
1662
0
  LevelsPairArray const& levels = getStringToLogLevelPairs();
1663
1664
  // NOLINTNEXTLINE(readability-qualified-auto)
1665
0
  auto const it =
1666
0
    std::find_if(levels.cbegin(), levels.cend(),
1667
0
                 [&level](LevelsPair const& p) { return p.second == level; });
1668
0
  cm::string_view const levelStrLowerCase =
1669
0
    (it != levels.cend()) ? it->first : "undefined";
1670
0
  std::string levelStrUpperCase =
1671
0
    cmSystemTools::UpperCase(std::string{ levelStrLowerCase });
1672
0
  return levelStrUpperCase;
1673
0
}
1674
1675
cmake::TraceFormat cmake::StringToTraceFormat(std::string const& traceStr)
1676
0
{
1677
0
  using TracePair = std::pair<std::string, TraceFormat>;
1678
0
  static std::vector<TracePair> const levels = {
1679
0
    { "human", TraceFormat::Human },
1680
0
    { "json-v1", TraceFormat::JSONv1 },
1681
0
  };
1682
1683
0
  auto const traceStrLowCase = cmSystemTools::LowerCase(traceStr);
1684
1685
0
  auto const it = std::find_if(levels.cbegin(), levels.cend(),
1686
0
                               [&traceStrLowCase](TracePair const& p) {
1687
0
                                 return p.first == traceStrLowCase;
1688
0
                               });
1689
0
  return (it != levels.cend()) ? it->second : TraceFormat::Undefined;
1690
0
}
1691
1692
bool cmake::PopTraceCmd()
1693
0
{
1694
0
  if (this->cmakeLangTraceCmdStack.empty()) {
1695
    // Nothing to pop! A caller should report an error.
1696
0
    return false;
1697
0
  }
1698
0
  this->cmakeLangTraceCmdStack.pop();
1699
0
  return true;
1700
0
}
1701
1702
void cmake::SetTraceFile(std::string const& file)
1703
0
{
1704
0
  this->TraceFile.close();
1705
0
  this->TraceFile.open(file.c_str());
1706
0
  if (!this->TraceFile) {
1707
0
    cmSystemTools::Error(cmStrCat("Error opening trace file ", file, ": ",
1708
0
                                  cmSystemTools::GetLastSystemError()));
1709
0
    return;
1710
0
  }
1711
0
  std::cout << "Trace will be written to " << file << '\n';
1712
0
}
1713
1714
void cmake::PrintTraceFormatVersion()
1715
0
{
1716
0
  if (!this->GetTrace()) {
1717
0
    return;
1718
0
  }
1719
1720
0
  std::string msg;
1721
1722
0
  switch (this->GetTraceFormat()) {
1723
0
    case TraceFormat::JSONv1: {
1724
0
#ifndef CMAKE_BOOTSTRAP
1725
0
      Json::Value val;
1726
0
      Json::Value version;
1727
0
      Json::StreamWriterBuilder builder;
1728
0
      builder["indentation"] = "";
1729
0
      version["major"] = 1;
1730
0
      version["minor"] = 2;
1731
0
      val["version"] = version;
1732
0
      msg = Json::writeString(builder, val);
1733
0
#endif
1734
0
      break;
1735
0
    }
1736
0
    case TraceFormat::Human:
1737
0
      msg = "";
1738
0
      break;
1739
0
    case TraceFormat::Undefined:
1740
0
      msg = "INTERNAL ERROR: Trace format is Undefined";
1741
0
      break;
1742
0
  }
1743
1744
0
  if (msg.empty()) {
1745
0
    return;
1746
0
  }
1747
1748
0
  auto& f = this->GetTraceFile();
1749
0
  if (f) {
1750
0
    f << msg << '\n';
1751
0
  } else {
1752
0
    cmSystemTools::Message(msg);
1753
0
  }
1754
0
}
1755
1756
void cmake::SetTraceRedirect(cmake* other)
1757
0
{
1758
0
  this->Trace = other->Trace;
1759
0
  this->TraceExpand = other->TraceExpand;
1760
0
  this->TraceFormatVar = other->TraceFormatVar;
1761
0
  this->TraceOnlyThisSources = other->TraceOnlyThisSources;
1762
1763
0
  this->TraceRedirect = other;
1764
0
}
1765
1766
bool cmake::SetDirectoriesFromFile(std::string const& arg)
1767
0
{
1768
  // Check if the argument refers to a CMakeCache.txt or CMakeLists.txt file.
1769
  // Do not check for the custom project filename CMAKE_LIST_FILE_NAME, as it
1770
  // cannot be determined until after reading the CMakeCache.txt
1771
0
  std::string listPath;
1772
0
  std::string cachePath;
1773
0
  bool is_source_dir = false;
1774
0
  bool is_empty_directory = false;
1775
0
  if (cmSystemTools::FileIsDirectory(arg)) {
1776
0
    std::string path = cmSystemTools::ToNormalizedPathOnDisk(arg);
1777
0
    std::string cacheFile = cmStrCat(path, "/CMakeCache.txt");
1778
0
    std::string listFile = this->GetCMakeListFile(path);
1779
1780
0
    is_empty_directory = true;
1781
0
    if (cmSystemTools::FileExists(cacheFile)) {
1782
0
      cachePath = path;
1783
0
      is_empty_directory = false;
1784
0
    }
1785
0
    if (cmSystemTools::FileExists(listFile)) {
1786
0
      listPath = path;
1787
0
      is_empty_directory = false;
1788
0
      is_source_dir = true;
1789
0
    }
1790
0
  } else if (cmSystemTools::FileExists(arg)) {
1791
0
    std::string fullPath = cmSystemTools::ToNormalizedPathOnDisk(arg);
1792
0
    std::string name = cmSystemTools::GetFilenameName(fullPath);
1793
0
    name = cmSystemTools::LowerCase(name);
1794
0
    if (name == "cmakecache.txt"_s) {
1795
0
      cachePath = cmSystemTools::GetFilenamePath(fullPath);
1796
0
    } else if (name == "cmakelists.txt"_s) {
1797
0
      listPath = cmSystemTools::GetFilenamePath(fullPath);
1798
0
    }
1799
0
  } else {
1800
    // Specified file or directory does not exist.  Try to set things
1801
    // up to produce a meaningful error message.
1802
0
    std::string fullPath = cmSystemTools::CollapseFullPath(arg);
1803
0
    std::string name = cmSystemTools::GetFilenameName(fullPath);
1804
0
    name = cmSystemTools::LowerCase(name);
1805
0
    if (name == "cmakecache.txt"_s || name == "cmakelists.txt"_s) {
1806
0
      listPath = cmSystemTools::GetFilenamePath(fullPath);
1807
0
    } else {
1808
0
      listPath = fullPath;
1809
0
    }
1810
0
  }
1811
1812
  // If there is a CMakeCache.txt file, use its settings.
1813
0
  if (!cachePath.empty()) {
1814
0
    if (this->LoadCache(cachePath)) {
1815
0
      cmValue existingValue =
1816
0
        this->State->GetCacheEntryValue("CMAKE_HOME_DIRECTORY");
1817
0
      if (existingValue && !existingValue.IsEmpty()) {
1818
0
        this->SetHomeOutputDirectory(cachePath);
1819
0
        this->SetHomeDirectory(*existingValue);
1820
0
        return true;
1821
0
      }
1822
0
    }
1823
0
  }
1824
1825
0
  bool no_source_tree = this->GetHomeDirectory().empty();
1826
0
  bool no_build_tree = this->GetHomeOutputDirectory().empty();
1827
1828
  // When invoked with a path that points to an existing CMakeCache
1829
  // This function is called multiple times with the same path
1830
0
  bool const passed_same_path = (listPath == this->GetHomeDirectory()) ||
1831
0
    (listPath == this->GetHomeOutputDirectory());
1832
0
  bool used_provided_path =
1833
0
    (passed_same_path || is_source_dir || no_build_tree);
1834
1835
  // If there is a CMakeLists.txt file, use it as the source tree.
1836
0
  if (!listPath.empty()) {
1837
    // When invoked with a path that points to an existing CMakeCache
1838
    // This function is called multiple times with the same path
1839
0
    if (is_source_dir) {
1840
0
      this->SetHomeDirectoryViaCommandLine(listPath);
1841
0
      if (no_build_tree) {
1842
0
        this->SetHomeOutputDirectory(
1843
0
          cmSystemTools::GetLogicalWorkingDirectory());
1844
0
      }
1845
0
    } else if (no_source_tree && no_build_tree) {
1846
0
      this->SetHomeDirectory(listPath);
1847
0
      this->SetHomeOutputDirectory(
1848
0
        cmSystemTools::GetLogicalWorkingDirectory());
1849
0
    } else if (no_build_tree) {
1850
0
      this->SetHomeOutputDirectory(listPath);
1851
0
    }
1852
0
  } else {
1853
0
    if (no_source_tree) {
1854
      // We didn't find a CMakeLists.txt and it wasn't specified
1855
      // with -S. Assume it is the path to the source tree
1856
0
      this->SetHomeDirectory(cmSystemTools::ToNormalizedPathOnDisk(arg));
1857
0
    }
1858
0
    if (no_build_tree && !no_source_tree && is_empty_directory) {
1859
      // passed `-S <path> <build_dir> when build_dir is an empty directory
1860
0
      this->SetHomeOutputDirectory(cmSystemTools::ToNormalizedPathOnDisk(arg));
1861
0
    } else if (no_build_tree) {
1862
      // We didn't find a CMakeCache.txt and it wasn't specified
1863
      // with -B. Assume the current working directory as the build tree.
1864
0
      this->SetHomeOutputDirectory(
1865
0
        cmSystemTools::GetLogicalWorkingDirectory());
1866
0
      used_provided_path = false;
1867
0
    }
1868
0
  }
1869
1870
0
  return used_provided_path;
1871
0
}
1872
1873
// at the end of this CMAKE_ROOT and CMAKE_COMMAND should be added to the
1874
// cache
1875
int cmake::AddCMakePaths()
1876
1
{
1877
  // Save the value in the cache
1878
1
  this->AddCacheEntry("CMAKE_COMMAND", cmSystemTools::GetCMakeCommand(),
1879
1
                      "Path to CMake executable.", cmStateEnums::INTERNAL);
1880
1
#ifndef CMAKE_BOOTSTRAP
1881
1
  this->AddCacheEntry("CMAKE_CTEST_COMMAND", cmSystemTools::GetCTestCommand(),
1882
1
                      "Path to ctest program executable.",
1883
1
                      cmStateEnums::INTERNAL);
1884
1
  this->AddCacheEntry("CMAKE_CPACK_COMMAND", cmSystemTools::GetCPackCommand(),
1885
1
                      "Path to cpack program executable.",
1886
1
                      cmStateEnums::INTERNAL);
1887
1
#endif
1888
1
  if (!cmSystemTools::FileExists(
1889
1
        (cmSystemTools::GetCMakeRoot() + "/Modules/CMake.cmake"))) {
1890
    // couldn't find modules
1891
1
    cmSystemTools::Error(
1892
1
      cmStrCat("Could not find CMAKE_ROOT !!!\n"
1893
1
               "CMake has most likely not been installed correctly.\n"
1894
1
               "Modules directory not found in\n",
1895
1
               cmSystemTools::GetCMakeRoot()));
1896
1
    return 0;
1897
1
  }
1898
0
  this->AddCacheEntry("CMAKE_ROOT", cmSystemTools::GetCMakeRoot(),
1899
0
                      "Path to CMake installation.", cmStateEnums::INTERNAL);
1900
1901
0
  return 1;
1902
1
}
1903
1904
void cmake::AddDefaultExtraGenerators()
1905
35
{
1906
35
#if !defined(CMAKE_BOOTSTRAP)
1907
35
  this->ExtraGenerators.push_back(cmExtraCodeBlocksGenerator::GetFactory());
1908
35
  this->ExtraGenerators.push_back(cmExtraCodeLiteGenerator::GetFactory());
1909
35
  this->ExtraGenerators.push_back(cmExtraEclipseCDT4Generator::GetFactory());
1910
35
  this->ExtraGenerators.push_back(cmExtraKateGenerator::GetFactory());
1911
35
  this->ExtraGenerators.push_back(cmExtraSublimeTextGenerator::GetFactory());
1912
35
#endif
1913
35
}
1914
1915
void cmake::GetRegisteredGenerators(
1916
  std::vector<GeneratorInfo>& generators) const
1917
0
{
1918
0
  for (auto const& gen : this->Generators) {
1919
0
    std::vector<std::string> names = gen->GetGeneratorNames();
1920
1921
0
    for (std::string const& name : names) {
1922
0
      GeneratorInfo info;
1923
0
      info.supportsToolset = gen->SupportsToolset();
1924
0
      info.supportsPlatform = gen->SupportsPlatform();
1925
0
      info.supportedPlatforms = gen->GetKnownPlatforms();
1926
0
      info.defaultPlatform = gen->GetDefaultPlatformName();
1927
0
      info.name = name;
1928
0
      info.baseName = name;
1929
0
      info.isAlias = false;
1930
0
      generators.push_back(std::move(info));
1931
0
    }
1932
0
  }
1933
1934
0
  for (cmExternalMakefileProjectGeneratorFactory* eg : this->ExtraGenerators) {
1935
0
    std::vector<std::string> const genList =
1936
0
      eg->GetSupportedGlobalGenerators();
1937
0
    for (std::string const& gen : genList) {
1938
0
      GeneratorInfo info;
1939
0
      info.name = cmExternalMakefileProjectGenerator::CreateFullGeneratorName(
1940
0
        gen, eg->GetName());
1941
0
      info.baseName = gen;
1942
0
      info.extraName = eg->GetName();
1943
0
      info.supportsPlatform = false;
1944
0
      info.supportsToolset = false;
1945
0
      info.isAlias = false;
1946
0
      generators.push_back(std::move(info));
1947
0
    }
1948
0
    for (std::string const& a : eg->Aliases) {
1949
0
      GeneratorInfo info;
1950
0
      info.name = a;
1951
0
      if (!genList.empty()) {
1952
0
        info.baseName = genList.at(0);
1953
0
      }
1954
0
      info.extraName = eg->GetName();
1955
0
      info.supportsPlatform = false;
1956
0
      info.supportsToolset = false;
1957
0
      info.isAlias = true;
1958
0
      generators.push_back(std::move(info));
1959
0
    }
1960
0
  }
1961
0
}
1962
1963
static std::pair<std::unique_ptr<cmExternalMakefileProjectGenerator>,
1964
                 std::string>
1965
createExtraGenerator(
1966
  std::vector<cmExternalMakefileProjectGeneratorFactory*> const& in,
1967
  std::string const& name)
1968
0
{
1969
0
  for (cmExternalMakefileProjectGeneratorFactory* i : in) {
1970
0
    std::vector<std::string> const generators =
1971
0
      i->GetSupportedGlobalGenerators();
1972
0
    if (i->GetName() == name) { // Match aliases
1973
0
      return { i->CreateExternalMakefileProjectGenerator(), generators.at(0) };
1974
0
    }
1975
0
    for (std::string const& g : generators) {
1976
0
      std::string const fullName =
1977
0
        cmExternalMakefileProjectGenerator::CreateFullGeneratorName(
1978
0
          g, i->GetName());
1979
0
      if (fullName == name) {
1980
0
        return { i->CreateExternalMakefileProjectGenerator(), g };
1981
0
      }
1982
0
    }
1983
0
  }
1984
0
  return { nullptr, name };
1985
0
}
1986
1987
std::unique_ptr<cmGlobalGenerator> cmake::CreateGlobalGenerator(
1988
  std::string const& gname)
1989
0
{
1990
0
  std::pair<std::unique_ptr<cmExternalMakefileProjectGenerator>, std::string>
1991
0
    extra = createExtraGenerator(this->ExtraGenerators, gname);
1992
0
  std::unique_ptr<cmExternalMakefileProjectGenerator>& extraGenerator =
1993
0
    extra.first;
1994
0
  std::string const& name = extra.second;
1995
1996
0
  std::unique_ptr<cmGlobalGenerator> generator;
1997
0
  for (auto const& g : this->Generators) {
1998
0
    generator = g->CreateGlobalGenerator(name, this);
1999
0
    if (generator) {
2000
0
      break;
2001
0
    }
2002
0
  }
2003
2004
0
  if (generator) {
2005
0
    generator->SetExternalMakefileProjectGenerator(std::move(extraGenerator));
2006
0
  }
2007
2008
0
  return generator;
2009
0
}
2010
2011
bool cmake::CreateAndSetGlobalGenerator(std::string const& name)
2012
0
{
2013
0
  auto gen = this->CreateGlobalGenerator(name);
2014
0
  if (!gen) {
2015
0
    std::string kdevError;
2016
0
    std::string vsError;
2017
0
    if (name.find("KDevelop3", 0) != std::string::npos) {
2018
0
      kdevError = "\nThe KDevelop3 generator is not supported anymore.";
2019
0
    }
2020
0
    if (cmHasLiteralPrefix(name, "Visual Studio ") &&
2021
0
        name.length() >= cmStrLen("Visual Studio xx xxxx ")) {
2022
0
      vsError = "\nUsing platforms in Visual Studio generator names is not "
2023
0
                "supported in CMakePresets.json.";
2024
0
    }
2025
2026
0
    cmSystemTools::Error(
2027
0
      cmStrCat("Could not create named generator ", name, kdevError, vsError));
2028
0
    this->PrintGeneratorList();
2029
0
    return false;
2030
0
  }
2031
2032
0
  this->SetGlobalGenerator(std::move(gen));
2033
0
  return true;
2034
0
}
2035
2036
#ifndef CMAKE_BOOTSTRAP
2037
bool cmake::SetArgsFromPreset(cmCMakePresetsConfigureArgs const& args,
2038
                              bool haveBinaryDirArg)
2039
0
{
2040
0
  using ListPresets = cmCMakePresetsConfigureArgs::ListPresetsOption;
2041
2042
0
  cmCMakePresetsGraph presetsGraph;
2043
0
  auto result = presetsGraph.ReadProjectPresets(this->GetHomeDirectory(),
2044
0
                                                args.PresetsFile);
2045
0
  if (result != true) {
2046
0
    std::string errorMsg =
2047
0
      cmStrCat("Could not read presets from ", this->GetHomeDirectory(), ":\n",
2048
0
               presetsGraph.parseState.GetErrorMessage());
2049
0
    cmSystemTools::Error(errorMsg);
2050
0
    return false;
2051
0
  }
2052
2053
0
  if (args.ListPresets != ListPresets::None) {
2054
0
    auto configureUsabilityCheck = this->CreateConfigurePresetUsabilityCheck();
2055
0
    switch (args.ListPresets) {
2056
0
      case ListPresets::Configure:
2057
0
        presetsGraph.PrintConfigurePresetList(args.ListPresetsMode,
2058
0
                                              configureUsabilityCheck);
2059
0
        break;
2060
0
      case ListPresets::Build:
2061
0
        presetsGraph.PrintBuildPresetList(args.ListPresetsMode,
2062
0
                                          configureUsabilityCheck);
2063
0
        break;
2064
0
      case ListPresets::Test:
2065
0
        presetsGraph.PrintTestPresetList(args.ListPresetsMode,
2066
0
                                         configureUsabilityCheck);
2067
0
        break;
2068
0
      case ListPresets::Package:
2069
0
        presetsGraph.PrintPackagePresetList(args.ListPresetsMode,
2070
0
                                            configureUsabilityCheck);
2071
0
        break;
2072
0
      case ListPresets::Workflow:
2073
0
        presetsGraph.PrintWorkflowPresetList(args.ListPresetsMode,
2074
0
                                             configureUsabilityCheck);
2075
0
        break;
2076
0
      case ListPresets::All:
2077
0
        presetsGraph.PrintConfigurePresetList(args.ListPresetsMode,
2078
0
                                              configureUsabilityCheck);
2079
0
        presetsGraph.PrintBuildPresetList(args.ListPresetsMode,
2080
0
                                          configureUsabilityCheck);
2081
0
        presetsGraph.PrintTestPresetList(args.ListPresetsMode,
2082
0
                                         configureUsabilityCheck);
2083
0
        presetsGraph.PrintPackagePresetList(args.ListPresetsMode,
2084
0
                                            configureUsabilityCheck);
2085
0
        presetsGraph.PrintWorkflowPresetList(args.ListPresetsMode,
2086
0
                                             configureUsabilityCheck);
2087
0
        break;
2088
0
      default:
2089
0
        break;
2090
0
    }
2091
2092
0
    this->State->SetRoleToHelpForListPresets();
2093
0
    return false;
2094
0
  }
2095
2096
0
  auto resolveResult =
2097
0
    presetsGraph.ResolvePreset(args.PresetName, presetsGraph.ConfigurePresets);
2098
0
  using ConfigurePreset = cmCMakePresetsGraph::ConfigurePreset;
2099
0
  using S = cmCMakePresetsGraph::PresetResolveStatus;
2100
0
  auto resolveError = cmCMakePresetsGraph::FormatPresetError<ConfigurePreset>(
2101
0
    resolveResult.StatusCode, resolveResult.ErrorPresetName,
2102
0
    this->GetHomeDirectory());
2103
0
  if (resolveError) {
2104
0
    cmSystemTools::Error(*resolveError);
2105
0
    if (resolveResult.StatusCode == S::NotFound ||
2106
0
        resolveResult.StatusCode == S::Hidden) {
2107
0
      this->PrintPresetList(presetsGraph);
2108
0
    }
2109
0
    return false;
2110
0
  }
2111
0
  auto const* expandedPreset = resolveResult.Preset;
2112
2113
0
  if (!this->State->IsCacheLoaded() && !haveBinaryDirArg &&
2114
0
      !expandedPreset->BinaryDir.empty()) {
2115
0
    this->SetHomeOutputDirectory(expandedPreset->BinaryDir);
2116
0
  }
2117
0
  if (!this->GlobalGenerator && !expandedPreset->Generator.empty()) {
2118
0
    if (!this->CreateAndSetGlobalGenerator(expandedPreset->Generator)) {
2119
0
      return false;
2120
0
    }
2121
0
  }
2122
0
  this->UnprocessedPresetVariables = expandedPreset->CacheVariables;
2123
0
  this->UnprocessedPresetEnvironment = expandedPreset->Environment;
2124
2125
0
  if (!expandedPreset->InstallDir.empty() &&
2126
0
      !this->State->GetInitializedCacheValue("CMAKE_INSTALL_PREFIX")) {
2127
0
    this->UnprocessedPresetVariables["CMAKE_INSTALL_PREFIX"] = {
2128
0
      "PATH", expandedPreset->InstallDir
2129
0
    };
2130
0
  }
2131
0
  if (!expandedPreset->ToolchainFile.empty() &&
2132
0
      !this->State->GetInitializedCacheValue("CMAKE_TOOLCHAIN_FILE")) {
2133
0
    this->UnprocessedPresetVariables["CMAKE_TOOLCHAIN_FILE"] = {
2134
0
      "FILEPATH", expandedPreset->ToolchainFile
2135
0
    };
2136
0
  }
2137
2138
0
  if (!expandedPreset->ArchitectureStrategy ||
2139
0
      expandedPreset->ArchitectureStrategy ==
2140
0
        cmCMakePresetsGraph::ArchToolsetStrategy::Set) {
2141
0
    if (!this->GeneratorPlatformSet && !expandedPreset->Architecture.empty()) {
2142
0
      this->SetGeneratorPlatform(expandedPreset->Architecture);
2143
0
    }
2144
0
  }
2145
0
  if (!expandedPreset->ToolsetStrategy ||
2146
0
      expandedPreset->ToolsetStrategy ==
2147
0
        cmCMakePresetsGraph::ArchToolsetStrategy::Set) {
2148
0
    if (!this->GeneratorToolsetSet && !expandedPreset->Toolset.empty()) {
2149
0
      this->SetGeneratorToolset(expandedPreset->Toolset);
2150
0
    }
2151
0
  }
2152
2153
0
  if (!expandedPreset->GraphVizFile.empty()) {
2154
0
    if (this->GraphVizFile.empty()) {
2155
0
      this->SetGraphVizFile(
2156
0
        cmSystemTools::CollapseFullPath(expandedPreset->GraphVizFile));
2157
0
    }
2158
0
  }
2159
2160
0
  this->SetDiagnosticsFromPreset(expandedPreset->Warnings,
2161
0
                                 expandedPreset->Errors);
2162
0
  if (expandedPreset->WarnSystemVars == true) {
2163
0
    this->SetCheckSystemVars(true);
2164
0
  }
2165
0
  if (expandedPreset->DebugOutput == true) {
2166
0
    this->SetDebugOutputOn(true);
2167
0
  }
2168
0
  if (expandedPreset->DebugTryCompile == true) {
2169
0
    this->DebugTryCompileOn();
2170
0
  }
2171
0
  if (expandedPreset->DebugFind == true) {
2172
0
    this->SetDebugFindOutput(true);
2173
0
  }
2174
0
  if (expandedPreset->TraceMode &&
2175
0
      expandedPreset->TraceMode !=
2176
0
        cmCMakePresetsGraph::TraceEnableMode::Disable) {
2177
0
    this->SetTrace(true);
2178
0
    if (expandedPreset->TraceMode ==
2179
0
        cmCMakePresetsGraph::TraceEnableMode::Expand) {
2180
0
      this->SetTraceExpand(true);
2181
0
    }
2182
0
  }
2183
0
  if (expandedPreset->TraceFormat) {
2184
0
    this->SetTrace(true);
2185
0
    this->SetTraceFormat(*expandedPreset->TraceFormat);
2186
0
  }
2187
0
  if (!expandedPreset->TraceSource.empty()) {
2188
0
    this->SetTrace(true);
2189
0
    for (std::string const& filePaths : expandedPreset->TraceSource) {
2190
0
      this->AddTraceSource(filePaths);
2191
0
    }
2192
0
  }
2193
0
  if (!expandedPreset->TraceRedirect.empty()) {
2194
0
    this->SetTrace(true);
2195
0
    this->SetTraceFile(expandedPreset->TraceRedirect);
2196
0
  }
2197
2198
  // Store preset variables in case of cache reset.
2199
0
  this->InitialPresetVariables = this->UnprocessedPresetVariables;
2200
2201
0
  return true;
2202
0
}
2203
2204
cmCMakePresetsGraph::ConfigurePresetUsabilityCheck
2205
cmake::CreateConfigurePresetUsabilityCheck() const
2206
0
{
2207
0
  std::vector<GeneratorInfo> generators;
2208
0
  this->GetRegisteredGenerators(generators);
2209
2210
0
  std::set<std::string> generatorNames;
2211
0
  for (auto const& generator : generators) {
2212
0
    generatorNames.insert(generator.name);
2213
0
  }
2214
2215
0
  return [generatorNames](cmCMakePresetsGraph::ConfigurePreset const& preset)
2216
0
           -> cm::optional<std::string> {
2217
0
    if (preset.Generator.empty() ||
2218
0
        generatorNames.count(preset.Generator) != 0) {
2219
0
      return cm::nullopt;
2220
0
    }
2221
0
    return cmStrCat("generator \"", preset.Generator, "\" is not available");
2222
0
  };
2223
0
}
2224
2225
void cmake::PrintPresetList(cmCMakePresetsGraph const& graph,
2226
                            cmCMakePresetsGraph::PresetListMode mode) const
2227
0
{
2228
0
  graph.PrintConfigurePresetList(mode,
2229
0
                                 this->CreateConfigurePresetUsabilityCheck());
2230
0
}
2231
#endif
2232
2233
void cmake::SetHomeDirectoryViaCommandLine(std::string const& path)
2234
0
{
2235
0
  if (path.empty()) {
2236
0
    return;
2237
0
  }
2238
2239
0
  auto prev_path = this->GetHomeDirectory();
2240
0
  if (prev_path != path && !prev_path.empty() &&
2241
0
      this->State->GetRole() == cmState::Role::Project) {
2242
0
    this->IssueMessage(
2243
0
      MessageType::WARNING,
2244
0
      cmStrCat("Ignoring extra path from command line:\n \"", prev_path, '"'));
2245
0
  }
2246
0
  this->SetHomeDirectory(path);
2247
0
}
2248
2249
void cmake::SetHomeDirectory(std::string const& dir)
2250
36
{
2251
36
  assert(!dir.empty());
2252
36
  this->State->SetSourceDirectory(dir);
2253
36
  if (this->CurrentSnapshot.IsValid()) {
2254
36
    this->CurrentSnapshot.SetDefinition("CMAKE_SOURCE_DIR", dir);
2255
36
  }
2256
2257
36
  if (this->State->GetIsTryCompile() == cmState::TryCompile::No) {
2258
36
    this->Messenger->SetTopSource(this->GetHomeDirectory());
2259
36
  } else {
2260
0
    this->Messenger->SetTopSource(cm::nullopt);
2261
0
  }
2262
36
}
2263
2264
std::string const& cmake::GetHomeDirectory() const
2265
72
{
2266
72
  return this->State->GetSourceDirectory();
2267
72
}
2268
2269
void cmake::SetHomeOutputDirectory(std::string const& dir)
2270
36
{
2271
36
  assert(!dir.empty());
2272
36
  this->State->SetBinaryDirectory(dir);
2273
36
  if (this->CurrentSnapshot.IsValid()) {
2274
36
    this->CurrentSnapshot.SetDefinition("CMAKE_BINARY_DIR", dir);
2275
36
  }
2276
36
}
2277
2278
std::string const& cmake::GetHomeOutputDirectory() const
2279
36
{
2280
36
  return this->State->GetBinaryDirectory();
2281
36
}
2282
2283
std::string cmake::FindCacheFile(std::string const& binaryDir)
2284
0
{
2285
0
  std::string cachePath = binaryDir;
2286
0
  cmSystemTools::ConvertToUnixSlashes(cachePath);
2287
0
  std::string cacheFile = cmStrCat(cachePath, "/CMakeCache.txt");
2288
0
  if (!cmSystemTools::FileExists(cacheFile)) {
2289
    // search in parent directories for cache
2290
0
    std::string cmakeFiles = cmStrCat(cachePath, "/CMakeFiles");
2291
0
    if (cmSystemTools::FileExists(cmakeFiles)) {
2292
0
      std::string cachePathFound =
2293
0
        cmSystemTools::FileExistsInParentDirectories("CMakeCache.txt",
2294
0
                                                     cachePath, "/");
2295
0
      if (!cachePathFound.empty()) {
2296
0
        cachePath = cmSystemTools::GetFilenamePath(cachePathFound);
2297
0
      }
2298
0
    }
2299
0
  }
2300
0
  return cachePath;
2301
0
}
2302
2303
void cmake::SetGlobalGenerator(std::unique_ptr<cmGlobalGenerator> gg)
2304
0
{
2305
0
  if (!gg) {
2306
0
    cmSystemTools::Error("Error SetGlobalGenerator called with null");
2307
0
    return;
2308
0
  }
2309
0
  if (this->GlobalGenerator) {
2310
    // restore the original environment variables CXX and CC
2311
0
    std::string env = "CC=";
2312
0
    if (!this->CCEnvironment.empty()) {
2313
0
      env += this->CCEnvironment;
2314
0
      cmSystemTools::PutEnv(env);
2315
0
    } else {
2316
0
      cmSystemTools::UnPutEnv(env);
2317
0
    }
2318
0
    env = "CXX=";
2319
0
    if (!this->CXXEnvironment.empty()) {
2320
0
      env += this->CXXEnvironment;
2321
0
      cmSystemTools::PutEnv(env);
2322
0
    } else {
2323
0
      cmSystemTools::UnPutEnv(env);
2324
0
    }
2325
0
  }
2326
2327
  // set the new
2328
0
  this->GlobalGenerator = std::move(gg);
2329
2330
  // set the global flag for unix style paths on cmSystemTools as soon as
2331
  // the generator is set.  This allows gmake to be used on windows.
2332
0
  cmSystemTools::SetForceUnixPaths(this->GlobalGenerator->GetForceUnixPaths());
2333
2334
  // Save the environment variables CXX and CC
2335
0
  if (!cmSystemTools::GetEnv("CXX", this->CXXEnvironment)) {
2336
0
    this->CXXEnvironment.clear();
2337
0
  }
2338
0
  if (!cmSystemTools::GetEnv("CC", this->CCEnvironment)) {
2339
0
    this->CCEnvironment.clear();
2340
0
  }
2341
0
}
2342
2343
int cmake::DoPreConfigureChecks()
2344
0
{
2345
  // Make sure the Source directory contains a CMakeLists.txt file.
2346
0
  std::string srcList =
2347
0
    cmStrCat(this->GetHomeDirectory(), '/', this->CMakeListName);
2348
0
  if (!cmSystemTools::FileExists(srcList)) {
2349
0
    std::ostringstream err;
2350
0
    if (cmSystemTools::FileIsDirectory(this->GetHomeDirectory())) {
2351
0
      err << "The source directory \"" << this->GetHomeDirectory()
2352
0
          << "\" does not appear to contain " << this->CMakeListName << ".\n";
2353
0
    } else if (cmSystemTools::FileExists(this->GetHomeDirectory())) {
2354
0
      err << "The source directory \"" << this->GetHomeDirectory()
2355
0
          << "\" is a file, not a directory.\n";
2356
0
    } else {
2357
0
      err << "The source directory \"" << this->GetHomeDirectory()
2358
0
          << "\" does not exist.\n";
2359
0
    }
2360
0
    err << "Specify --help for usage, or press the help button on the CMake "
2361
0
           "GUI.";
2362
0
    cmSystemTools::Error(err.str());
2363
0
    return -2;
2364
0
  }
2365
2366
  // do a sanity check on some values
2367
0
  if (cmValue dir =
2368
0
        this->State->GetInitializedCacheValue("CMAKE_HOME_DIRECTORY")) {
2369
0
    std::string cacheStart = cmStrCat(*dir, '/', this->CMakeListName);
2370
0
    if (!cmSystemTools::SameFile(cacheStart, srcList)) {
2371
0
      std::string message =
2372
0
        cmStrCat("The source \"", srcList, "\" does not match the source \"",
2373
0
                 cacheStart,
2374
0
                 "\" used to generate cache.  Re-run cmake with a different "
2375
0
                 "source directory.");
2376
0
      cmSystemTools::Error(message);
2377
0
      return -2;
2378
0
    }
2379
0
  } else {
2380
0
    return 0;
2381
0
  }
2382
0
  return 1;
2383
0
}
2384
struct SaveCacheEntry
2385
{
2386
  std::string key;
2387
  std::string value;
2388
  std::string help;
2389
  cmStateEnums::CacheEntryType type;
2390
};
2391
2392
int cmake::HandleDeleteCacheVariables(
2393
  std::map<std::string, std::string> const& vars)
2394
0
{
2395
  // erase the set to avoid infinite recursion
2396
0
  this->State->ClearDeleteCacheChangeVars();
2397
0
  if (this->GetIsInTryCompile()) {
2398
0
    return 0;
2399
0
  }
2400
0
  std::vector<SaveCacheEntry> saved;
2401
0
  std::ostringstream warning;
2402
0
  warning
2403
0
    << "You have changed variables that require your cache to be deleted.\n"
2404
0
       "Configure will be re-run and you may have to reset some variables.\n"
2405
0
       "The following variables have changed:\n";
2406
0
  for (auto const& var : vars) {
2407
0
    SaveCacheEntry save;
2408
0
    save.key = var.first;
2409
0
    save.value = var.second;
2410
0
    warning << save.key << "= " << save.value << '\n';
2411
0
    cmValue existingValue = this->State->GetCacheEntryValue(save.key);
2412
0
    if (existingValue) {
2413
0
      save.type = this->State->GetCacheEntryType(save.key);
2414
0
      if (cmValue help =
2415
0
            this->State->GetCacheEntryProperty(save.key, "HELPSTRING")) {
2416
0
        save.help = *help;
2417
0
      }
2418
0
    } else {
2419
0
      save.type = cmStateEnums::CacheEntryType::UNINITIALIZED;
2420
0
    }
2421
0
    saved.push_back(std::move(save));
2422
0
  }
2423
2424
  // remove the cache
2425
0
  this->DeleteCache(this->GetHomeOutputDirectory());
2426
  // load the empty cache
2427
0
  this->LoadCache();
2428
0
#ifndef CMAKE_BOOTSTRAP
2429
  // Restore preset cache variables.
2430
0
  this->UnprocessedPresetVariables = this->InitialPresetVariables;
2431
0
  this->ProcessPresetVariables();
2432
0
#endif
2433
  // Restore command line cache variables (from this invocation cmake only).
2434
0
  bool resetArgsSuccess = this->SetCacheArgs(this->cmdArgs);
2435
0
  assert(resetArgsSuccess);
2436
0
  (void)resetArgsSuccess;
2437
  // restore the changed compilers
2438
0
  for (SaveCacheEntry const& i : saved) {
2439
0
    this->AddCacheEntry(i.key, i.value, i.help, i.type);
2440
0
  }
2441
0
  cmSystemTools::Message(warning.str());
2442
  // avoid reconfigure if there were errors
2443
0
  if (!cmSystemTools::GetErrorOccurredFlag()) {
2444
    // re-run configure
2445
0
    this->State->SetReconfiguring(true);
2446
0
    return this->Configure();
2447
0
  }
2448
2449
  // Toolchain changes trigger a fatal error, but reconfiguring with the new
2450
  // toolchain should fix them.
2451
0
  if (vars.count("CMAKE_TOOLCHAIN_FILE") && !this->State->IsReconfiguring()) {
2452
0
    cmSystemTools::ResetErrorOccurredFlag();
2453
0
    this->State->SetReconfiguring(true);
2454
0
    return this->Configure();
2455
0
  }
2456
0
  return 0;
2457
0
}
2458
2459
int cmake::Configure()
2460
0
{
2461
0
#if !defined(CMAKE_BOOTSTRAP)
2462
0
  auto profilingRAII = this->CreateProfilingEntry("project", "configure");
2463
0
#endif
2464
2465
  // We now need to harmonize the previous initial diagnostic state with any
2466
  // changes requested via command line options and/or presets. We do this by
2467
  // first applying the prior (cached) state, then applying all deferred
2468
  // alterations.
2469
2470
0
  if (cmValue cachedDiagnostics =
2471
0
        this->State->GetCacheEntryValue("CMAKE_DIAGNOSTIC_INIT")) {
2472
0
    for (std::string const& item : cmList{ cachedDiagnostics }) {
2473
0
      std::string::size_type n = item.find('=');
2474
0
      if (n != std::string::npos) {
2475
0
        cm::string_view v = item;
2476
0
        cm::optional<cmDiagnosticCategory> const& category =
2477
0
          cmDiagnostics::GetDiagnosticCategory(v.substr(0, n));
2478
0
        cm::optional<cmDiagnosticAction> const& action =
2479
0
          cmDiagnostics::GetDiagnosticAction(v.substr(n + 1));
2480
2481
0
        if (category && action) {
2482
0
          this->CurrentSnapshot.SetDiagnostic(*category, *action, false);
2483
0
        }
2484
0
      }
2485
0
    }
2486
0
  }
2487
2488
0
  cmValue cachedWarnDeprecated =
2489
0
    this->State->GetCacheEntryValue("CMAKE_WARN_DEPRECATED");
2490
0
  if (cachedWarnDeprecated) {
2491
0
    if (cachedWarnDeprecated.IsOn()) {
2492
0
      this->CurrentSnapshot.PromoteDiagnostic(cmDiagnostics::CMD_DEPRECATED,
2493
0
                                              cmDiagnostics::Warn, false);
2494
0
    } else {
2495
0
      this->CurrentSnapshot.DemoteDiagnostic(cmDiagnostics::CMD_DEPRECATED,
2496
0
                                             cmDiagnostics::Ignore, false);
2497
0
    }
2498
0
  }
2499
2500
0
  cmValue cachedErrorDeprecated =
2501
0
    this->State->GetCacheEntryValue("CMAKE_ERROR_DEPRECATED");
2502
0
  if (cachedErrorDeprecated) {
2503
0
    if (cachedErrorDeprecated.IsOn()) {
2504
0
      this->CurrentSnapshot.PromoteDiagnostic(cmDiagnostics::CMD_DEPRECATED,
2505
0
                                              cmDiagnostics::SendError, false);
2506
0
    } else {
2507
0
      this->CurrentSnapshot.DemoteDiagnostic(cmDiagnostics::CMD_DEPRECATED,
2508
0
                                             cmDiagnostics::Warn, false);
2509
0
    }
2510
0
  }
2511
2512
0
  for (DiagnosticAlteration const& da : this->DiagnosticAlterations) {
2513
0
    (this->CurrentSnapshot.*da.Alteration)(da.Category, da.DesiredAction,
2514
0
                                           da.Recurse);
2515
0
  }
2516
2517
  // Now write the diagnostic state back to the cache.
2518
0
  cmList diagnostics;
2519
0
  for (unsigned i = 1; i < cmDiagnostics::CategoryCount; ++i) {
2520
0
    auto const category = static_cast<cmDiagnosticCategory>(i);
2521
0
    auto const action = this->CurrentSnapshot.GetDiagnostic(category);
2522
2523
0
    diagnostics.emplace_back(
2524
0
      cmStrCat(cmDiagnostics::GetCategoryString(category), '=',
2525
0
               cmDiagnostics::GetActionString(action)));
2526
2527
0
    if (category == cmDiagnostics::CMD_DEPRECATED) {
2528
0
      std::string const warnValue =
2529
0
        (action >= cmDiagnostics::Warn ? "ON" : "OFF");
2530
0
      this->AddCacheEntry("CMAKE_WARN_DEPRECATED", warnValue,
2531
0
                          "Deprecated.  Use -W[no-]deprecated instead.",
2532
0
                          cmStateEnums::INTERNAL);
2533
0
      std::string const errorValue =
2534
0
        (action >= cmDiagnostics::SendError ? "ON" : "OFF");
2535
0
      this->AddCacheEntry("CMAKE_ERROR_DEPRECATED", errorValue,
2536
0
                          "Deprecated.  Use -W[no-]error=deprecated instead.",
2537
0
                          cmStateEnums::INTERNAL);
2538
0
    }
2539
0
  }
2540
2541
0
  this->AddCacheEntry("CMAKE_DIAGNOSTIC_INIT", cmJoin(diagnostics, ";"_s),
2542
0
                      "Set initial state for CMake diagnostics; "
2543
0
                      "used to persist state set by command-line options "
2544
0
                      "across invocations.",
2545
0
                      cmStateEnums::INTERNAL);
2546
2547
0
  int ret = this->ActualConfigure();
2548
0
  std::map<std::string, std::string> delCacheVars =
2549
0
    this->State->GetDeleteCacheChangeVars();
2550
0
  if (!delCacheVars.empty()) {
2551
0
    return this->HandleDeleteCacheVariables(delCacheVars);
2552
0
  }
2553
0
  return ret;
2554
0
}
2555
2556
int cmake::ActualConfigure()
2557
0
{
2558
  // Construct right now our path conversion table before it's too late:
2559
0
  this->CleanupCommandsAndMacros();
2560
2561
0
  cmSystemTools::RemoveADirectory(this->GetHomeOutputDirectory() +
2562
0
                                  "/CMakeFiles/CMakeScratch");
2563
2564
0
  std::string cmlNameCache =
2565
0
    this->State->GetInitializedCacheValue("CMAKE_LIST_FILE_NAME");
2566
0
  if (!cmlNameCache.empty() && !this->CMakeListName.empty() &&
2567
0
      cmlNameCache != this->CMakeListName) {
2568
0
    std::string message =
2569
0
      cmStrCat("CMakeLists filename : \"", this->CMakeListName,
2570
0
               "\"\nDoes not match the previous: \"", cmlNameCache,
2571
0
               "\"\nEither remove the CMakeCache.txt file and CMakeFiles "
2572
0
               "directory or choose a different binary directory.");
2573
0
    cmSystemTools::Error(message);
2574
0
    return -2;
2575
0
  }
2576
0
  if (this->CMakeListName.empty()) {
2577
0
    this->CMakeListName =
2578
0
      cmlNameCache.empty() ? "CMakeLists.txt" : cmlNameCache;
2579
0
  }
2580
0
  if (this->CMakeListName != "CMakeLists.txt") {
2581
0
    this->IssueMessage(
2582
0
      MessageType::WARNING,
2583
0
      "This project has been configured with a project file other than "
2584
0
      "CMakeLists.txt. This feature is intended for temporary use during "
2585
0
      "development and not for publication of a final product.");
2586
0
  }
2587
0
  this->AddCacheEntry("CMAKE_LIST_FILE_NAME", this->CMakeListName,
2588
0
                      "Name of CMakeLists files to read",
2589
0
                      cmStateEnums::INTERNAL);
2590
2591
0
  int res = this->DoPreConfigureChecks();
2592
0
  if (res < 0) {
2593
0
    return -2;
2594
0
  }
2595
0
  if (!res) {
2596
0
    this->AddCacheEntry(
2597
0
      "CMAKE_HOME_DIRECTORY", this->GetHomeDirectory(),
2598
0
      "Source directory with the top level CMakeLists.txt file for this "
2599
0
      "project",
2600
0
      cmStateEnums::INTERNAL);
2601
0
  }
2602
2603
  // We want to create the package redirects directory as early as possible,
2604
  // but not before pre-configure checks have passed. This ensures we get
2605
  // errors about inappropriate source/binary directories first.
2606
0
  auto const redirectsDir =
2607
0
    cmStrCat(this->GetHomeOutputDirectory(), "/CMakeFiles/pkgRedirects");
2608
0
  cmSystemTools::RemoveADirectory(redirectsDir);
2609
0
  if (!cmSystemTools::MakeDirectory(redirectsDir)) {
2610
0
    cmSystemTools::Error(
2611
0
      cmStrCat("Unable to (re)create the private pkgRedirects directory:\n  ",
2612
0
               redirectsDir,
2613
0
               "\n"
2614
0
               "This may be caused by not having read/write access to "
2615
0
               "the build directory.\n"
2616
0
               "Try specifying a location with read/write access like:\n"
2617
0
               "  cmake -B build\n"
2618
0
               "If using a CMake presets file, ensure that preset parameter\n"
2619
0
               "'binaryDir' expands to a writable directory.\n"));
2620
0
    return -1;
2621
0
  }
2622
0
  this->AddCacheEntry("CMAKE_FIND_PACKAGE_REDIRECTS_DIR", redirectsDir,
2623
0
                      "Value Computed by CMake.", cmStateEnums::STATIC);
2624
2625
  // no generator specified on the command line
2626
0
  if (!this->GlobalGenerator) {
2627
0
    cmValue genName = this->State->GetInitializedCacheValue("CMAKE_GENERATOR");
2628
0
    cmValue extraGenName =
2629
0
      this->State->GetInitializedCacheValue("CMAKE_EXTRA_GENERATOR");
2630
0
    if (genName) {
2631
0
      std::string fullName =
2632
0
        cmExternalMakefileProjectGenerator::CreateFullGeneratorName(
2633
0
          *genName, extraGenName ? *extraGenName : "");
2634
0
      this->GlobalGenerator = this->CreateGlobalGenerator(fullName);
2635
0
    }
2636
0
    if (this->GlobalGenerator) {
2637
      // set the global flag for unix style paths on cmSystemTools as
2638
      // soon as the generator is set.  This allows gmake to be used
2639
      // on windows.
2640
0
      cmSystemTools::SetForceUnixPaths(
2641
0
        this->GlobalGenerator->GetForceUnixPaths());
2642
0
    } else {
2643
0
      this->CreateDefaultGlobalGenerator();
2644
0
    }
2645
0
    if (!this->GlobalGenerator) {
2646
0
      cmSystemTools::Error("Could not create generator");
2647
0
      return -1;
2648
0
    }
2649
0
  }
2650
2651
0
  cmValue genName = this->State->GetInitializedCacheValue("CMAKE_GENERATOR");
2652
0
  if (genName) {
2653
0
    if (!this->GlobalGenerator->MatchesGeneratorName(*genName)) {
2654
0
      std::string message =
2655
0
        cmStrCat("Error: generator : ", this->GlobalGenerator->GetName(),
2656
0
                 "\n"
2657
0
                 "Does not match the generator used previously: ",
2658
0
                 *genName,
2659
0
                 "\n"
2660
0
                 "Either remove the CMakeCache.txt file and CMakeFiles "
2661
0
                 "directory or choose a different binary directory.");
2662
0
      cmSystemTools::Error(message);
2663
0
      return -2;
2664
0
    }
2665
0
  }
2666
0
  if (!genName) {
2667
0
    this->AddCacheEntry("CMAKE_GENERATOR", this->GlobalGenerator->GetName(),
2668
0
                        "Name of generator.", cmStateEnums::INTERNAL);
2669
0
    this->AddCacheEntry(
2670
0
      "CMAKE_EXTRA_GENERATOR", this->GlobalGenerator->GetExtraGeneratorName(),
2671
0
      "Name of external makefile project generator.", cmStateEnums::INTERNAL);
2672
2673
0
    if (!this->State->GetInitializedCacheValue("CMAKE_TOOLCHAIN_FILE")) {
2674
0
      std::string envToolchain;
2675
0
      if (cmSystemTools::GetEnv("CMAKE_TOOLCHAIN_FILE", envToolchain) &&
2676
0
          !envToolchain.empty()) {
2677
0
        this->AddCacheEntry("CMAKE_TOOLCHAIN_FILE", envToolchain,
2678
0
                            "The CMake toolchain file",
2679
0
                            cmStateEnums::FILEPATH);
2680
0
      }
2681
0
    }
2682
0
  }
2683
2684
0
  if (cmValue instance =
2685
0
        this->State->GetInitializedCacheValue("CMAKE_GENERATOR_INSTANCE")) {
2686
0
    if (this->GeneratorInstanceSet && this->GeneratorInstance != *instance) {
2687
0
      std::string message =
2688
0
        cmStrCat("Error: generator instance: ", this->GeneratorInstance,
2689
0
                 "\n"
2690
0
                 "Does not match the instance used previously: ",
2691
0
                 *instance,
2692
0
                 "\n"
2693
0
                 "Either remove the CMakeCache.txt file and CMakeFiles "
2694
0
                 "directory or choose a different binary directory.");
2695
0
      cmSystemTools::Error(message);
2696
0
      return -2;
2697
0
    }
2698
0
  } else {
2699
0
    this->AddCacheEntry("CMAKE_GENERATOR_INSTANCE", this->GeneratorInstance,
2700
0
                        "Generator instance identifier.",
2701
0
                        cmStateEnums::INTERNAL);
2702
0
  }
2703
2704
0
  if (cmValue platformName =
2705
0
        this->State->GetInitializedCacheValue("CMAKE_GENERATOR_PLATFORM")) {
2706
0
    if (this->GeneratorPlatformSet &&
2707
0
        this->GeneratorPlatform != *platformName) {
2708
0
      std::string message =
2709
0
        cmStrCat("Error: generator platform: ", this->GeneratorPlatform,
2710
0
                 "\n"
2711
0
                 "Does not match the platform used previously: ",
2712
0
                 *platformName,
2713
0
                 "\n"
2714
0
                 "Either remove the CMakeCache.txt file and CMakeFiles "
2715
0
                 "directory or choose a different binary directory.");
2716
0
      cmSystemTools::Error(message);
2717
0
      return -2;
2718
0
    }
2719
0
  } else {
2720
0
    this->AddCacheEntry("CMAKE_GENERATOR_PLATFORM", this->GeneratorPlatform,
2721
0
                        "Name of generator platform.", cmStateEnums::INTERNAL);
2722
0
  }
2723
2724
0
  if (cmValue tsName =
2725
0
        this->State->GetInitializedCacheValue("CMAKE_GENERATOR_TOOLSET")) {
2726
0
    if (this->GeneratorToolsetSet && this->GeneratorToolset != *tsName) {
2727
0
      std::string message =
2728
0
        cmStrCat("Error: generator toolset: ", this->GeneratorToolset,
2729
0
                 "\n"
2730
0
                 "Does not match the toolset used previously: ",
2731
0
                 *tsName,
2732
0
                 "\n"
2733
0
                 "Either remove the CMakeCache.txt file and CMakeFiles "
2734
0
                 "directory or choose a different binary directory.");
2735
0
      cmSystemTools::Error(message);
2736
0
      return -2;
2737
0
    }
2738
0
  } else {
2739
0
    this->AddCacheEntry("CMAKE_GENERATOR_TOOLSET", this->GeneratorToolset,
2740
0
                        "Name of generator toolset.", cmStateEnums::INTERNAL);
2741
0
  }
2742
2743
0
  if (!this->State->GetInitializedCacheValue(
2744
0
        "CMAKE_INTERMEDIATE_DIR_STRATEGY") &&
2745
0
      this->IntermediateDirStrategy) {
2746
0
    this->AddCacheEntry(
2747
0
      "CMAKE_INTERMEDIATE_DIR_STRATEGY", *this->IntermediateDirStrategy,
2748
0
      "Select the intermediate directory strategy", cmStateEnums::INTERNAL);
2749
0
  }
2750
0
  if (!this->State->GetInitializedCacheValue(
2751
0
        "CMAKE_AUTOGEN_INTERMEDIATE_DIR_STRATEGY") &&
2752
0
      this->AutogenIntermediateDirStrategy) {
2753
0
    this->AddCacheEntry(
2754
0
      "CMAKE_AUTOGEN_INTERMEDIATE_DIR_STRATEGY",
2755
0
      *this->AutogenIntermediateDirStrategy,
2756
0
      "Select the intermediate directory strategy for Autogen",
2757
0
      cmStateEnums::INTERNAL);
2758
0
  }
2759
2760
0
  if (!this->State->GetInitializedCacheValue("CMAKE_TEST_LAUNCHER")) {
2761
0
    cm::optional<std::string> testLauncher =
2762
0
      cmSystemTools::GetEnvVar("CMAKE_TEST_LAUNCHER");
2763
0
    if (testLauncher && !testLauncher->empty()) {
2764
0
      std::string message = "Test launcher to run tests executable.";
2765
0
      this->AddCacheEntry("CMAKE_TEST_LAUNCHER", *testLauncher, message,
2766
0
                          cmStateEnums::STRING);
2767
0
    }
2768
0
  }
2769
2770
0
  if (!this->State->GetInitializedCacheValue(
2771
0
        "CMAKE_CROSSCOMPILING_EMULATOR")) {
2772
0
    cm::optional<std::string> emulator =
2773
0
      cmSystemTools::GetEnvVar("CMAKE_CROSSCOMPILING_EMULATOR");
2774
0
    if (emulator && !emulator->empty()) {
2775
0
      std::string message =
2776
0
        "Emulator to run executables and tests when cross compiling.";
2777
0
      this->AddCacheEntry("CMAKE_CROSSCOMPILING_EMULATOR", *emulator, message,
2778
0
                          cmStateEnums::STRING);
2779
0
    }
2780
0
  }
2781
2782
0
  if (!this->State->GetInitializedCacheValue(
2783
0
        "CMAKE_DISABLE_PRECOMPILE_HEADERS")) {
2784
0
    cm::optional<std::string> disablePrecompileHeaders =
2785
0
      cmSystemTools::GetEnvVar("CMAKE_DISABLE_PRECOMPILE_HEADERS");
2786
0
    if (disablePrecompileHeaders && !disablePrecompileHeaders->empty()) {
2787
0
      std::string message =
2788
0
        "Default value for DISABLE_PRECOMPILE_HEADERS of targets.";
2789
0
      this->AddCacheEntry("CMAKE_DISABLE_PRECOMPILE_HEADERS",
2790
0
                          *disablePrecompileHeaders, message,
2791
0
                          cmStateEnums::BOOL);
2792
0
    }
2793
0
  }
2794
2795
  // reset any system configuration information, except for when we are
2796
  // InTryCompile. With TryCompile the system info is taken from the parent's
2797
  // info to save time
2798
0
  if (!this->GetIsInTryCompile()) {
2799
0
    this->GlobalGenerator->ClearEnabledLanguages();
2800
0
  }
2801
2802
0
#if !defined(CMAKE_BOOTSTRAP)
2803
0
  this->InitializeFileAPI();
2804
0
  this->FileAPI->ReadQueries();
2805
0
  this->InitializeInstrumentation();
2806
2807
0
  if (!this->GetIsInTryCompile()) {
2808
0
    this->TruncateOutputLog("CMakeConfigureLog.yaml");
2809
0
    this->ConfigureLog = cm::make_unique<cmConfigureLog>(
2810
0
      cmStrCat(this->GetHomeOutputDirectory(), "/CMakeFiles"_s),
2811
0
      this->FileAPI->GetConfigureLogVersions());
2812
0
    this->Instrumentation->ClearGeneratedQueries();
2813
0
    this->Instrumentation->CheckCDashVariable();
2814
0
  }
2815
0
#endif
2816
2817
  // actually do the configure
2818
0
  auto startTime = std::chrono::steady_clock::now();
2819
0
#if !defined(CMAKE_BOOTSTRAP)
2820
0
  if (this->Instrumentation->HasErrors()) {
2821
0
    return 1;
2822
0
  }
2823
0
  auto doConfigure = [this]() -> int {
2824
0
    this->GlobalGenerator->Configure();
2825
0
    return 0;
2826
0
  };
2827
0
  int ret = this->Instrumentation->InstrumentCommand(
2828
0
    "configure", this->cmdArgs,
2829
0
    [doConfigure]() -> cmInstrumentation::CommandResult {
2830
0
      return { doConfigure(), cm::nullopt, cm::nullopt, cm::nullopt };
2831
0
    },
2832
0
    cm::nullopt, cm::nullopt,
2833
0
    this->GetIsInTryCompile() ? cmInstrumentation::LoadQueriesAfter::No
2834
0
                              : cmInstrumentation::LoadQueriesAfter::Yes);
2835
0
  if (ret != 0) {
2836
0
    return ret;
2837
0
  }
2838
#else
2839
  this->GlobalGenerator->Configure();
2840
#endif
2841
0
  auto endTime = std::chrono::steady_clock::now();
2842
2843
  // configure result
2844
0
  if (this->State->GetRole() == cmState::Role::Project) {
2845
0
    std::ostringstream msg;
2846
0
    if (cmSystemTools::GetErrorOccurredFlag()) {
2847
0
      msg << "Configuring incomplete, errors occurred!";
2848
0
    } else {
2849
0
      auto ms = std::chrono::duration_cast<std::chrono::milliseconds>(
2850
0
        endTime - startTime);
2851
0
      msg << "Configuring done (" << std::fixed << std::setprecision(1)
2852
0
          << ms.count() / 1000.0L << "s)";
2853
0
    }
2854
0
    this->UpdateProgress(msg.str(), -1);
2855
0
  }
2856
2857
0
#if !defined(CMAKE_BOOTSTRAP)
2858
0
  this->ConfigureLog.reset();
2859
0
#endif
2860
2861
  // Before saving the cache
2862
  // if the project did not define one of the entries below, add them now
2863
  // so users can edit the values in the cache:
2864
2865
0
  auto const& mf = this->GlobalGenerator->GetMakefiles()[0];
2866
2867
0
  if (mf->IsOn("CTEST_USE_LAUNCHERS") &&
2868
0
      !this->State->GetGlobalProperty("RULE_LAUNCH_COMPILE")) {
2869
0
    this->IssueMessage(MessageType::FATAL_ERROR,
2870
0
                       "CTEST_USE_LAUNCHERS is enabled, but the "
2871
0
                       "RULE_LAUNCH_COMPILE global property is not defined.\n"
2872
0
                       "Did you forget to include(CTest) in the toplevel "
2873
0
                       "CMakeLists.txt ?");
2874
0
  }
2875
  // Setup launchers for instrumentation
2876
0
#if !defined(CMAKE_BOOTSTRAP)
2877
0
  if (this->Instrumentation->HasQuery()) {
2878
0
    std::string launcher;
2879
0
    if (mf->IsOn("CTEST_USE_LAUNCHERS")) {
2880
0
      launcher = cmStrCat('"', cmSystemTools::GetCTestCommand(),
2881
0
                          "\" --launch "
2882
0
                          "--current-build-dir <CMAKE_CURRENT_BINARY_DIR> "
2883
0
                          "--object-dir <TARGET_SUPPORT_DIR> ");
2884
0
    } else {
2885
0
      launcher =
2886
0
        cmStrCat('"', cmSystemTools::GetCTestCommand(), "\" --instrument ");
2887
0
    }
2888
0
    std::string common_args =
2889
0
      cmStrCat(" --target-name <TARGET_NAME> --config <CONFIG> --build-dir \"",
2890
0
               this->State->GetBinaryDirectory(), "\" ");
2891
0
    this->State->SetGlobalProperty(
2892
0
      "RULE_LAUNCH_COMPILE",
2893
0
      cmStrCat(
2894
0
        launcher, "--command-type compile", common_args,
2895
0
        "--output <OBJECT> --source <SOURCE> --language <LANGUAGE> -- "));
2896
0
    this->State->SetGlobalProperty(
2897
0
      "RULE_LAUNCH_LINK",
2898
0
      cmStrCat(
2899
0
        launcher, "--command-type link", common_args,
2900
0
        "--output <TARGET> --config <CONFIG> --language <LANGUAGE> -- "));
2901
0
    this->State->SetGlobalProperty(
2902
0
      "RULE_LAUNCH_CUSTOM",
2903
0
      cmStrCat(
2904
0
        launcher, "--command-type custom", common_args,
2905
0
        "--output-as-file-name \"<OUTPUT_STORE_TO_FILE>\" --role <ROLE> -- "));
2906
0
  }
2907
0
#endif
2908
2909
0
  this->State->SaveVerificationScript(this->GetHomeOutputDirectory(),
2910
0
                                      this->Messenger.get());
2911
0
  this->SaveCache(this->GetHomeOutputDirectory());
2912
0
  if (cmSystemTools::GetErrorOccurredFlag()) {
2913
0
#if !defined(CMAKE_BOOTSTRAP)
2914
0
    this->FileAPI->WriteReplies(cmFileAPI::IndexFor::FailedConfigure);
2915
0
#endif
2916
0
    return -1;
2917
0
  }
2918
0
  return 0;
2919
0
}
2920
2921
std::unique_ptr<cmGlobalGenerator> cmake::EvaluateDefaultGlobalGenerator()
2922
0
{
2923
0
  if (!this->EnvironmentGenerator.empty()) {
2924
0
    auto gen = this->CreateGlobalGenerator(this->EnvironmentGenerator);
2925
0
    if (!gen) {
2926
0
      cmSystemTools::Error("CMAKE_GENERATOR was set but the specified "
2927
0
                           "generator doesn't exist. Using CMake default.");
2928
0
    } else {
2929
0
      return gen;
2930
0
    }
2931
0
  }
2932
#if defined(_WIN32) && !defined(__CYGWIN__) && !defined(CMAKE_BOOT_MINGW)
2933
  std::string found;
2934
  // Try to find the newest VS installed on the computer and
2935
  // use that as a default if -G is not specified
2936
  if (cmVSSetupAPIHelper(18).IsVSInstalled()) {
2937
    found = "Visual Studio 18 2026";
2938
  } else if (cmVSSetupAPIHelper(17).IsVSInstalled()) {
2939
    found = "Visual Studio 17 2022";
2940
  } else if (cmVSSetupAPIHelper(16).IsVSInstalled()) {
2941
    found = "Visual Studio 16 2019";
2942
  } else if (cmVSSetupAPIHelper(15).IsVSInstalled()) {
2943
    found = "Visual Studio 15 2017";
2944
  }
2945
  auto gen = this->CreateGlobalGenerator(found);
2946
  if (!gen) {
2947
    gen = cm::make_unique<cmGlobalNMakeMakefileGenerator>(this);
2948
  }
2949
  return std::unique_ptr<cmGlobalGenerator>(std::move(gen));
2950
#elif defined(CMAKE_BOOTSTRAP_NINJA)
2951
  return std::unique_ptr<cmGlobalGenerator>(
2952
    cm::make_unique<cmGlobalNinjaGenerator>(this));
2953
#else
2954
0
  return std::unique_ptr<cmGlobalGenerator>(
2955
0
    cm::make_unique<cmGlobalUnixMakefileGenerator3>(this));
2956
0
#endif
2957
0
}
2958
2959
void cmake::CreateDefaultGlobalGenerator()
2960
0
{
2961
0
  auto gen = this->EvaluateDefaultGlobalGenerator();
2962
#if defined(_WIN32) && !defined(__CYGWIN__) && !defined(CMAKE_BOOT_MINGW)
2963
  // This print could be unified for all platforms
2964
  std::cout << "-- Building for: " << gen->GetName() << '\n';
2965
#endif
2966
0
  this->SetGlobalGenerator(std::move(gen));
2967
0
}
2968
2969
void cmake::PreLoadCMakeFiles()
2970
0
{
2971
0
  std::vector<std::string> args;
2972
0
  std::string pre_load = this->GetHomeDirectory();
2973
0
  if (!pre_load.empty()) {
2974
0
    pre_load += "/PreLoad.cmake";
2975
0
    if (cmSystemTools::FileExists(pre_load)) {
2976
0
      this->ReadListFile(args, pre_load);
2977
0
    }
2978
0
  }
2979
0
  pre_load = this->GetHomeOutputDirectory();
2980
0
  if (!pre_load.empty()) {
2981
0
    pre_load += "/PreLoad.cmake";
2982
0
    if (cmSystemTools::FileExists(pre_load)) {
2983
0
      this->ReadListFile(args, pre_load);
2984
0
    }
2985
0
  }
2986
0
}
2987
2988
#ifdef CMake_ENABLE_DEBUGGER
2989
2990
bool cmake::StartDebuggerIfEnabled()
2991
1
{
2992
1
  if (!this->GetDebuggerOn()) {
2993
1
    return true;
2994
1
  }
2995
2996
0
  if (!DebugAdapter) {
2997
0
    if (this->GetDebuggerPipe().empty()) {
2998
0
      std::cerr
2999
0
        << "Error: --debugger-pipe must be set when debugging is enabled.\n";
3000
0
      return false;
3001
0
    }
3002
3003
0
    try {
3004
0
      DebugAdapter = std::make_shared<cmDebugger::cmDebuggerAdapter>(
3005
0
        std::make_shared<cmDebugger::cmDebuggerPipeConnection>(
3006
0
          this->GetDebuggerPipe()),
3007
0
        this->GetDebuggerDapLogFile());
3008
0
    } catch (std::runtime_error const& error) {
3009
0
      std::cerr << "Error: Failed to create debugger adapter.\n";
3010
0
      std::cerr << error.what() << "\n";
3011
0
      return false;
3012
0
    }
3013
0
    Messenger->SetDebuggerAdapter(DebugAdapter);
3014
0
  }
3015
3016
0
  return true;
3017
0
}
3018
3019
void cmake::StopDebuggerIfNeeded(int exitCode)
3020
0
{
3021
0
  if (!this->GetDebuggerOn()) {
3022
0
    return;
3023
0
  }
3024
3025
  // The debug adapter may have failed to start (e.g. invalid pipe path).
3026
0
  if (DebugAdapter) {
3027
0
    DebugAdapter->ReportExitCode(exitCode);
3028
0
    DebugAdapter.reset();
3029
0
  }
3030
0
}
3031
3032
#endif
3033
3034
void cmake::InitializeFileAPI()
3035
0
{
3036
0
#ifndef CMAKE_BOOTSTRAP
3037
0
  if (!this->FileAPI) {
3038
0
    this->FileAPI = cm::make_unique<cmFileAPI>(this);
3039
0
  }
3040
0
#endif
3041
0
}
3042
3043
void cmake::InitializeInstrumentation()
3044
0
{
3045
0
#ifndef CMAKE_BOOTSTRAP
3046
0
  if (!this->Instrumentation) {
3047
0
    this->Instrumentation = cm::make_unique<cmInstrumentation>(
3048
0
      this->State->GetBinaryDirectory(),
3049
0
      cmInstrumentation::LoadQueriesAfter::No);
3050
0
  }
3051
0
#endif
3052
0
}
3053
3054
int cmake::HandleDifferentSystemEnvironmentId(std::string envId,
3055
                                              std::string cachedId)
3056
0
{
3057
0
  enum class Action
3058
0
  {
3059
0
    Ignore,
3060
0
    Warn,
3061
0
    Refresh,
3062
0
  } action = Action::Warn;
3063
0
  static std::string const actionEnvName = "CMAKE_SYSTEM_ENVIRONMENT_ACTION";
3064
0
  if (cmSystemTools::HasEnv(actionEnvName)) {
3065
0
    std::string actionEnv;
3066
0
    cmSystemTools::GetEnv(actionEnvName, actionEnv);
3067
0
    if (actionEnv == "IGNORE") {
3068
0
      action = Action::Ignore;
3069
0
    } else if (actionEnv == "WARN") {
3070
0
      action = Action::Warn;
3071
0
    } else if (actionEnv == "REFRESH") {
3072
0
      action = Action::Refresh;
3073
0
    } else {
3074
0
      this->IssueMessage(
3075
0
        MessageType::FATAL_ERROR,
3076
0
        cmStrCat("Unsupported ", actionEnvName, " '", actionEnv, '\''));
3077
0
      return -1;
3078
0
    }
3079
0
  }
3080
0
  switch (action) {
3081
0
    case Action::Ignore:
3082
0
      break;
3083
0
    case Action::Warn: {
3084
0
      std::string msg = cmStrCat(
3085
0
        "CMAKE_SYSTEM_ENVIRONMENT_ID: ", envId,
3086
0
        "\nDoes not match the previous value: ", cachedId,
3087
0
        "\nThe configure results are probably outdated. Consider running"
3088
0
        " cmake with --fresh, removing the CMakeCache.txt file and"
3089
0
        " CMakeFiles directory, or choosing a different binary"
3090
0
        " directory.");
3091
0
      this->IssueMessage(MessageType::WARNING, msg);
3092
0
      break;
3093
0
    }
3094
0
    case Action::Refresh: {
3095
0
      std::string msg =
3096
0
        cmStrCat("CMAKE_SYSTEM_ENVIRONMENT_ID: ", envId,
3097
0
                 "\nDoes not match the previous value: ", cachedId,
3098
0
                 "\nThe cache will be refreshed automatically.");
3099
0
      this->IssueMessage(MessageType::MESSAGE, msg);
3100
0
      this->DeleteCache(this->GetHomeOutputDirectory());
3101
0
      if (this->LoadCache() < 0) {
3102
0
        cmSystemTools::Error(
3103
0
          "Error executing cmake::LoadCache(). Aborting.\n");
3104
0
        return -1;
3105
0
      }
3106
0
      this->AddCacheEntry(
3107
0
        "CMAKE_SYSTEM_ENVIRONMENT_ID", envId,
3108
0
        "Opaque identifier for the current system environment",
3109
0
        cmStateEnums::INTERNAL);
3110
0
      break;
3111
0
    }
3112
0
  }
3113
0
  return 0;
3114
0
}
3115
3116
// handle a command line invocation
3117
int cmake::Run(std::vector<std::string> const& args, bool noconfigure)
3118
35
{
3119
  // Process the arguments
3120
35
  this->SetArgs(args);
3121
35
  if (cmSystemTools::GetErrorOccurredFlag()) {
3122
34
    return -1;
3123
34
  }
3124
1
  if (this->State->GetRole() == cmState::Role::Help) {
3125
0
    return 0;
3126
0
  }
3127
3128
1
#ifndef CMAKE_BOOTSTRAP
3129
1
  if (this->State->GetRole() == cmState::Role::Project) {
3130
0
    this->MarkCliAsUsed("CMAKE_EXPORT_SARIF");
3131
0
  }
3132
3133
1
  this->VariableWatch->AddWatch("CMAKE_WARN_DEPRECATED", cmDeprecatedWatch);
3134
1
  this->VariableWatch->AddWatch("CMAKE_ERROR_DEPRECATED", cmDeprecatedWatch);
3135
1
#endif
3136
3137
  // Log the trace format version to the desired output
3138
1
  if (this->GetTrace()) {
3139
0
    this->PrintTraceFormatVersion();
3140
0
  }
3141
3142
  // If we are given a stamp list file check if it is really out of date.
3143
1
  if (!this->CheckStampList.empty() &&
3144
0
      cmakeCheckStampList(this->CheckStampList)) {
3145
0
    return 0;
3146
0
  }
3147
3148
  // If we are given a stamp file check if it is really out of date.
3149
1
  if (!this->CheckStampFile.empty() &&
3150
0
      cmakeCheckStampFile(this->CheckStampFile)) {
3151
0
    return 0;
3152
0
  }
3153
3154
1
  if (this->State->GetRole() == cmState::Role::Project) {
3155
0
    if (this->FreshCache) {
3156
0
      this->DeleteCache(this->GetHomeOutputDirectory());
3157
0
    }
3158
    // load the cache
3159
0
    if (this->LoadCache() < 0) {
3160
0
      cmSystemTools::Error("Error executing cmake::LoadCache(). Aborting.\n");
3161
0
      return -1;
3162
0
    }
3163
0
    std::string const idKey = "CMAKE_SYSTEM_ENVIRONMENT_ID";
3164
0
    cmValue cachedEnvId = this->State->GetInitializedCacheValue(idKey);
3165
0
    std::string sysEnvId;
3166
0
    cmSystemTools::GetEnv(idKey, sysEnvId);
3167
0
    if (cachedEnvId) {
3168
0
      if (sysEnvId != *cachedEnvId) {
3169
0
        if (this->HandleDifferentSystemEnvironmentId(sysEnvId, *cachedEnvId) <
3170
0
            0) {
3171
          // Failed to LoadCache()
3172
0
          return -1;
3173
0
        }
3174
0
      }
3175
0
    } else {
3176
0
      this->AddCacheEntry(
3177
0
        idKey, sysEnvId,
3178
0
        "Opaque identifier for the current system environment",
3179
0
        cmStateEnums::INTERNAL);
3180
0
    }
3181
1
  } else {
3182
1
    if (this->FreshCache) {
3183
0
      cmSystemTools::Error("--fresh allowed only when configuring a project");
3184
0
      return -1;
3185
0
    }
3186
1
    this->AddCMakePaths();
3187
1
  }
3188
3189
1
#ifndef CMAKE_BOOTSTRAP
3190
1
  this->ProcessPresetVariables();
3191
1
  this->ProcessPresetEnvironment();
3192
1
#endif
3193
  // Add any cache args
3194
1
  if (!this->SetCacheArgs(args)) {
3195
0
    cmSystemTools::Error("Run 'cmake --help' for all supported options.");
3196
0
    return -1;
3197
0
  }
3198
1
#ifndef CMAKE_BOOTSTRAP
3199
1
  if (this->GetLogLevel() == Message::LogLevel::LOG_VERBOSE ||
3200
1
      this->GetLogLevel() == Message::LogLevel::LOG_DEBUG ||
3201
1
      this->GetLogLevel() == Message::LogLevel::LOG_TRACE) {
3202
0
    this->PrintPresetVariables();
3203
0
    this->PrintPresetEnvironment();
3204
0
  }
3205
1
#endif
3206
3207
  // In script mode we terminate after running the script.
3208
1
  if (this->State->GetRole() != cmState::Role::Project) {
3209
1
    if (cmSystemTools::GetErrorOccurredFlag()) {
3210
1
      return -1;
3211
1
    }
3212
0
    return this->HasScriptModeExitCode() ? this->GetScriptModeExitCode() : 0;
3213
1
  }
3214
3215
  // If MAKEFLAGS are given in the environment, remove the environment
3216
  // variable.  This will prevent try-compile from succeeding when it
3217
  // should fail (if "-i" is an option).  We cannot simply test
3218
  // whether "-i" is given and remove it because some make programs
3219
  // encode the MAKEFLAGS variable in a strange way.
3220
0
  if (cmSystemTools::HasEnv("MAKEFLAGS")) {
3221
0
    cmSystemTools::PutEnv("MAKEFLAGS=");
3222
0
  }
3223
3224
0
  this->PreLoadCMakeFiles();
3225
3226
0
  if (noconfigure) {
3227
0
    return 0;
3228
0
  }
3229
3230
  // now run the global generate
3231
  // Check the state of the build system to see if we need to regenerate.
3232
0
  if (!this->CheckBuildSystem()) {
3233
0
    return 0;
3234
0
  }
3235
  // After generating fbuild.bff, FastBuild sees rebuild-bff as outdated since
3236
  // it hasn’t built the target yet. To make it a no-op for future runs, we
3237
  // trigger a dummy fbuild invocation that creates this marker file and runs
3238
  // CMake, marking rebuild-bff as up-to-date.
3239
0
  std::string const FBuildRestatFile =
3240
0
    cmStrCat(this->GetHomeOutputDirectory(), '/', FASTBUILD_RESTAT_FILE);
3241
0
  if (cmSystemTools::FileExists(FBuildRestatFile)) {
3242
0
    cmsys::ifstream restat(FBuildRestatFile.c_str(),
3243
0
                           std::ios::in | std::ios::binary);
3244
0
    std::string const file((std::istreambuf_iterator<char>(restat)),
3245
0
                           std::istreambuf_iterator<char>());
3246
    // On Windows can not delete file if it's still opened.
3247
0
    restat.close();
3248
0
    cmSystemTools::Touch(file, true);
3249
0
    cmSystemTools::RemoveFile(FBuildRestatFile);
3250
0
    return 0;
3251
0
  }
3252
3253
0
#ifdef CMake_ENABLE_DEBUGGER
3254
0
  if (!this->StartDebuggerIfEnabled()) {
3255
0
    return -1;
3256
0
  }
3257
0
#endif
3258
3259
0
  int ret = this->Configure();
3260
0
  if (ret) {
3261
#if defined(CMAKE_HAVE_VS_GENERATORS)
3262
    if (!this->VSSolutionFile.empty() && this->GlobalGenerator) {
3263
      // CMake is running to regenerate a Visual Studio build tree
3264
      // during a build from the VS IDE.  The build files cannot be
3265
      // regenerated, so we should stop the build.
3266
      cmSystemTools::Message("CMake Configure step failed.  "
3267
                             "Build files cannot be regenerated correctly.  "
3268
                             "Attempting to stop IDE build.");
3269
      cmGlobalVisualStudioGenerator& gg =
3270
        cm::static_reference_cast<cmGlobalVisualStudioGenerator>(
3271
          this->GlobalGenerator);
3272
      gg.CallVisualStudioMacro(cmGlobalVisualStudioGenerator::MacroStop,
3273
                               this->VSSolutionFile);
3274
    }
3275
#endif
3276
0
    return ret;
3277
0
  }
3278
0
  ret = this->Generate();
3279
0
  if (ret) {
3280
0
    cmSystemTools::Message("CMake Generate step failed.  "
3281
0
                           "Build files cannot be regenerated correctly.");
3282
0
    return ret;
3283
0
  }
3284
0
  std::string message = cmStrCat("Build files have been written to: ",
3285
0
                                 this->GetHomeOutputDirectory());
3286
0
  this->UpdateProgress(message, -1);
3287
0
  return ret;
3288
0
}
3289
3290
int cmake::Generate()
3291
0
{
3292
0
  if (!this->GlobalGenerator) {
3293
0
    return -1;
3294
0
  }
3295
3296
0
  auto startTime = std::chrono::steady_clock::now();
3297
0
#if !defined(CMAKE_BOOTSTRAP)
3298
0
  auto profilingRAII = this->CreateProfilingEntry("project", "generate");
3299
0
  auto doGenerate = [this]() -> int {
3300
0
    if (!this->GlobalGenerator->Compute()) {
3301
0
      this->FileAPI->WriteReplies(cmFileAPI::IndexFor::FailedCompute);
3302
0
      return -1;
3303
0
    }
3304
0
    this->GlobalGenerator->Generate();
3305
0
    if (this->Instrumentation->HasQuery()) {
3306
0
      this->Instrumentation->WriteCMakeContent(this->GlobalGenerator);
3307
0
    }
3308
0
    return 0;
3309
0
  };
3310
3311
0
  int ret = this->Instrumentation->InstrumentCommand(
3312
0
    "generate", this->cmdArgs,
3313
0
    [doGenerate]() -> cmInstrumentation::CommandResult {
3314
0
      return { doGenerate(), cm::nullopt, cm::nullopt, cm::nullopt };
3315
0
    });
3316
0
  if (ret != 0) {
3317
0
    return ret;
3318
0
  }
3319
#else
3320
  if (!this->GlobalGenerator->Compute()) {
3321
    return -1;
3322
  }
3323
  this->GlobalGenerator->Generate();
3324
#endif
3325
0
  auto endTime = std::chrono::steady_clock::now();
3326
0
  {
3327
0
    auto ms = std::chrono::duration_cast<std::chrono::milliseconds>(endTime -
3328
0
                                                                    startTime);
3329
0
    std::ostringstream msg;
3330
0
    msg << "Generating done (" << std::fixed << std::setprecision(1)
3331
0
        << ms.count() / 1000.0L << "s)";
3332
0
    this->UpdateProgress(msg.str(), -1);
3333
0
  }
3334
0
  if (!this->GraphVizFile.empty()) {
3335
0
    std::cout << "Generate graphviz: " << this->GraphVizFile << '\n';
3336
0
    this->GenerateGraphViz(this->GraphVizFile);
3337
0
  }
3338
0
  this->RunCheckForUnusedVariables();
3339
0
  if (cmSystemTools::GetErrorOccurredFlag()) {
3340
0
#if !defined(CMAKE_BOOTSTRAP)
3341
0
    this->FileAPI->WriteReplies(cmFileAPI::IndexFor::FailedGenerate);
3342
0
#endif
3343
0
    return -1;
3344
0
  }
3345
  // Save the cache again after a successful Generate so that any internal
3346
  // variables created during Generate are saved. (Specifically target GUIDs
3347
  // for the Visual Studio and Xcode generators.)
3348
0
  this->SaveCache(this->GetHomeOutputDirectory());
3349
3350
0
#if !defined(CMAKE_BOOTSTRAP)
3351
0
  this->GlobalGenerator->WriteInstallJson();
3352
0
  this->FileAPI->WriteReplies(cmFileAPI::IndexFor::Success);
3353
0
  this->Instrumentation->CollectTimingData(
3354
0
    cmInstrumentationQuery::Hook::PostGenerate);
3355
0
#endif
3356
3357
0
  return 0;
3358
0
}
3359
3360
void cmake::AddCacheEntry(std::string const& key, cmValue value,
3361
                          cmValue helpString, int type)
3362
3
{
3363
3
  this->State->AddCacheEntry(key, value, helpString,
3364
3
                             static_cast<cmStateEnums::CacheEntryType>(type));
3365
3
  this->UnwatchUnusedCli(key);
3366
3
}
3367
3368
bool cmake::DoWriteGlobVerifyTarget() const
3369
0
{
3370
0
  return this->State->DoWriteGlobVerifyTarget();
3371
0
}
3372
3373
std::string const& cmake::GetGlobVerifyScript() const
3374
0
{
3375
0
  return this->State->GetGlobVerifyScript();
3376
0
}
3377
3378
std::string const& cmake::GetGlobVerifyStamp() const
3379
0
{
3380
0
  return this->State->GetGlobVerifyStamp();
3381
0
}
3382
3383
void cmake::AddGlobCacheEntry(cmGlobCacheEntry const& entry,
3384
                              std::string const& variable,
3385
                              cmListFileBacktrace const& backtrace)
3386
0
{
3387
0
  this->State->AddGlobCacheEntry(entry, variable, backtrace,
3388
0
                                 this->Messenger.get());
3389
0
}
3390
3391
std::vector<cmGlobCacheEntry> cmake::GetGlobCacheEntries() const
3392
0
{
3393
0
  return this->State->GetGlobCacheEntries();
3394
0
}
3395
3396
std::vector<std::string> cmake::GetAllExtensions() const
3397
0
{
3398
0
  std::vector<std::string> allExt = this->CLikeSourceFileExtensions.ordered;
3399
0
  allExt.insert(allExt.end(), this->HeaderFileExtensions.ordered.begin(),
3400
0
                this->HeaderFileExtensions.ordered.end());
3401
  // cuda extensions are also in SourceFileExtensions so we ignore it here
3402
0
  allExt.insert(allExt.end(), this->FortranFileExtensions.ordered.begin(),
3403
0
                this->FortranFileExtensions.ordered.end());
3404
0
  allExt.insert(allExt.end(), this->HipFileExtensions.ordered.begin(),
3405
0
                this->HipFileExtensions.ordered.end());
3406
0
  allExt.insert(allExt.end(), this->ISPCFileExtensions.ordered.begin(),
3407
0
                this->ISPCFileExtensions.ordered.end());
3408
0
  return allExt;
3409
0
}
3410
3411
std::string cmake::StripExtension(std::string const& file) const
3412
0
{
3413
0
  auto dotpos = file.rfind('.');
3414
0
  if (dotpos != std::string::npos) {
3415
#if defined(_WIN32) || defined(__APPLE__)
3416
    auto ext = cmSystemTools::LowerCase(file.substr(dotpos + 1));
3417
#else
3418
0
    auto ext = cm::string_view(file).substr(dotpos + 1);
3419
0
#endif
3420
0
    if (this->IsAKnownExtension(ext)) {
3421
0
      return file.substr(0, dotpos);
3422
0
    }
3423
0
  }
3424
0
  return file;
3425
0
}
3426
3427
cmValue cmake::GetCacheDefinition(std::string const& name) const
3428
0
{
3429
0
  return this->State->GetInitializedCacheValue(name);
3430
0
}
3431
3432
void cmake::AddScriptingCommands() const
3433
35
{
3434
35
  GetScriptingCommands(this->GetState());
3435
35
}
3436
3437
void cmake::AddProjectCommands() const
3438
0
{
3439
0
  GetProjectCommands(this->GetState());
3440
0
}
3441
3442
void cmake::AddDefaultGenerators()
3443
35
{
3444
#if defined(_WIN32) && !defined(__CYGWIN__)
3445
#  if !defined(CMAKE_BOOT_MINGW)
3446
  this->Generators.push_back(
3447
    cmGlobalVisualStudioVersionedGenerator::NewFactory18());
3448
  this->Generators.push_back(
3449
    cmGlobalVisualStudioVersionedGenerator::NewFactory17());
3450
  this->Generators.push_back(
3451
    cmGlobalVisualStudioVersionedGenerator::NewFactory16());
3452
  this->Generators.push_back(
3453
    cmGlobalVisualStudioVersionedGenerator::NewFactory15());
3454
  this->Generators.push_back(cmGlobalBorlandMakefileGenerator::NewFactory());
3455
  this->Generators.push_back(cmGlobalNMakeMakefileGenerator::NewFactory());
3456
  this->Generators.push_back(cmGlobalJOMMakefileGenerator::NewFactory());
3457
#  endif
3458
  this->Generators.push_back(cmGlobalMSYSMakefileGenerator::NewFactory());
3459
  this->Generators.push_back(cmGlobalMinGWMakefileGenerator::NewFactory());
3460
#endif
3461
35
#if !defined(CMAKE_BOOTSTRAP)
3462
35
#  if (defined(__linux__) && !defined(__ANDROID__)) || defined(_WIN32)
3463
35
  this->Generators.push_back(cmGlobalGhsMultiGenerator::NewFactory());
3464
35
#  endif
3465
35
  this->Generators.push_back(cmGlobalUnixMakefileGenerator3::NewFactory());
3466
35
  this->Generators.push_back(cmGlobalNinjaGenerator::NewFactory());
3467
35
  this->Generators.push_back(cmGlobalNinjaMultiGenerator::NewFactory());
3468
35
  this->Generators.push_back(cmGlobalFastbuildGenerator::NewFactory());
3469
#elif defined(CMAKE_BOOTSTRAP_NINJA)
3470
  this->Generators.push_back(cmGlobalNinjaGenerator::NewFactory());
3471
#elif defined(CMAKE_BOOTSTRAP_MAKEFILES)
3472
  this->Generators.push_back(cmGlobalUnixMakefileGenerator3::NewFactory());
3473
#endif
3474
35
#if defined(CMAKE_USE_WMAKE)
3475
35
  this->Generators.push_back(cmGlobalWatcomWMakeGenerator::NewFactory());
3476
35
#endif
3477
#ifdef CMAKE_USE_XCODE
3478
  this->Generators.push_back(cmGlobalXCodeGenerator::NewFactory());
3479
#endif
3480
35
}
3481
3482
bool cmake::ParseCacheEntry(std::string const& entry, std::string& var,
3483
                            std::string& value,
3484
                            cmStateEnums::CacheEntryType& type)
3485
0
{
3486
0
  return cmState::ParseCacheEntry(entry, var, value, type);
3487
0
}
3488
3489
int cmake::LoadCache()
3490
0
{
3491
  // could we not read the cache
3492
0
  if (!this->LoadCache(this->GetHomeOutputDirectory())) {
3493
    // if it does exist, but isn't readable then warn the user
3494
0
    std::string cacheFile =
3495
0
      cmStrCat(this->GetHomeOutputDirectory(), "/CMakeCache.txt");
3496
0
    if (cmSystemTools::FileExists(cacheFile)) {
3497
0
      cmSystemTools::Error(
3498
0
        "There is a CMakeCache.txt file for the current binary tree but "
3499
0
        "cmake does not have permission to read it. Please check the "
3500
0
        "permissions of the directory you are trying to run CMake on.");
3501
0
      return -1;
3502
0
    }
3503
0
  }
3504
3505
  // setup CMAKE_ROOT and CMAKE_COMMAND
3506
0
  if (!this->AddCMakePaths()) {
3507
0
    return -3;
3508
0
  }
3509
0
  return 0;
3510
0
}
3511
3512
bool cmake::LoadCache(std::string const& path)
3513
0
{
3514
0
  std::set<std::string> emptySet;
3515
0
  return this->LoadCache(path, true, emptySet, emptySet);
3516
0
}
3517
3518
bool cmake::LoadCache(std::string const& path, bool internal,
3519
                      std::set<std::string>& excludes,
3520
                      std::set<std::string>& includes)
3521
0
{
3522
0
  bool result = this->State->LoadCache(path, internal, excludes, includes);
3523
0
  static auto const entries = { "CMAKE_CACHE_MAJOR_VERSION",
3524
0
                                "CMAKE_CACHE_MINOR_VERSION" };
3525
0
  for (auto const& entry : entries) {
3526
0
    this->UnwatchUnusedCli(entry);
3527
0
  }
3528
0
  return result;
3529
0
}
3530
3531
bool cmake::SaveCache(std::string const& path)
3532
0
{
3533
0
  bool result = this->State->SaveCache(path, this->GetMessenger());
3534
0
  static auto const entries = { "CMAKE_CACHE_MAJOR_VERSION",
3535
0
                                "CMAKE_CACHE_MINOR_VERSION",
3536
0
                                "CMAKE_CACHE_PATCH_VERSION",
3537
0
                                "CMAKE_CACHEFILE_DIR" };
3538
0
  for (auto const& entry : entries) {
3539
0
    this->UnwatchUnusedCli(entry);
3540
0
  }
3541
0
  return result;
3542
0
}
3543
3544
bool cmake::DeleteCache(std::string const& path)
3545
0
{
3546
0
  return this->State->DeleteCache(path);
3547
0
}
3548
3549
void cmake::SetProgressCallback(ProgressCallbackType f)
3550
0
{
3551
0
  this->ProgressCallback = std::move(f);
3552
0
}
3553
3554
void cmake::UpdateProgress(std::string const& msg, float prog)
3555
0
{
3556
0
  if (this->ProgressCallback && !this->GetIsInTryCompile()) {
3557
0
    this->ProgressCallback(msg, prog);
3558
0
  }
3559
0
}
3560
3561
bool cmake::GetIsInTryCompile() const
3562
0
{
3563
0
  return this->State->GetIsTryCompile() == cmState::TryCompile::Yes;
3564
0
}
3565
3566
void cmake::AppendGlobalGeneratorsDocumentation(
3567
  std::vector<cmDocumentationEntry>& v)
3568
0
{
3569
0
  auto const defaultGenerator = this->EvaluateDefaultGlobalGenerator();
3570
0
  auto const defaultName = defaultGenerator->GetName();
3571
0
  auto foundDefaultOne = false;
3572
3573
0
  for (auto const& g : this->Generators) {
3574
0
    v.emplace_back(g->GetDocumentation());
3575
0
    if (!foundDefaultOne && cmHasPrefix(v.back().Name, defaultName)) {
3576
0
      v.back().CustomNamePrefix = '*';
3577
0
      foundDefaultOne = true;
3578
0
    }
3579
0
  }
3580
0
}
3581
3582
void cmake::AppendExtraGeneratorsDocumentation(
3583
  std::vector<cmDocumentationEntry>& v)
3584
0
{
3585
0
  for (cmExternalMakefileProjectGeneratorFactory* eg : this->ExtraGenerators) {
3586
0
    std::string const doc = eg->GetDocumentation();
3587
0
    std::string const name = eg->GetName();
3588
3589
    // Aliases:
3590
0
    for (std::string const& a : eg->Aliases) {
3591
0
      v.emplace_back(cmDocumentationEntry{ a, doc });
3592
0
    }
3593
3594
    // Full names:
3595
0
    for (std::string const& g : eg->GetSupportedGlobalGenerators()) {
3596
0
      v.emplace_back(cmDocumentationEntry{
3597
0
        cmExternalMakefileProjectGenerator::CreateFullGeneratorName(g, name),
3598
0
        doc });
3599
0
    }
3600
0
  }
3601
0
}
3602
3603
std::vector<cmDocumentationEntry> cmake::GetGeneratorsDocumentation()
3604
0
{
3605
0
  std::vector<cmDocumentationEntry> v;
3606
0
  this->AppendGlobalGeneratorsDocumentation(v);
3607
0
  this->AppendExtraGeneratorsDocumentation(v);
3608
0
  return v;
3609
0
}
3610
3611
void cmake::PrintGeneratorList()
3612
0
{
3613
0
#ifndef CMAKE_BOOTSTRAP
3614
0
  cmDocumentation doc;
3615
0
  auto generators = this->GetGeneratorsDocumentation();
3616
0
  doc.AppendSection("Generators", generators);
3617
0
  std::cerr << '\n';
3618
0
  doc.PrintDocumentation(cmDocumentation::ListGenerators, std::cerr);
3619
0
#endif
3620
0
}
3621
3622
int cmake::CheckBuildSystem()
3623
0
{
3624
  // We do not need to rerun CMake.  Check dependency integrity.
3625
0
  bool const verbose = isCMakeVerbose();
3626
3627
  // This method will check the integrity of the build system if the
3628
  // option was given on the command line.  It reads the given file to
3629
  // determine whether CMake should rerun.
3630
3631
  // If no file is provided for the check, we have to rerun.
3632
0
  if (this->CheckBuildSystemArgument.empty()) {
3633
0
    if (verbose) {
3634
0
      cmSystemTools::Stdout("Re-run cmake no build system arguments\n");
3635
0
    }
3636
0
    return 1;
3637
0
  }
3638
3639
  // If the file provided does not exist, we have to rerun.
3640
0
  if (!cmSystemTools::FileExists(this->CheckBuildSystemArgument)) {
3641
0
    if (verbose) {
3642
0
      std::ostringstream msg;
3643
0
      msg << "Re-run cmake missing file: " << this->CheckBuildSystemArgument
3644
0
          << '\n';
3645
0
      cmSystemTools::Stdout(msg.str());
3646
0
    }
3647
0
    return 1;
3648
0
  }
3649
3650
  // Read the rerun check file and use it to decide whether to do the
3651
  // global generate.
3652
  // Actually, all we need is the `set` command.
3653
0
  cmake cm(cmState::Role::Script);
3654
0
  cm.GetCurrentSnapshot().SetDefaultDefinitions();
3655
0
  cmGlobalGenerator gg(&cm);
3656
0
  cmMakefile mf(&gg, cm.GetCurrentSnapshot());
3657
0
  if (!mf.ReadListFile(this->CheckBuildSystemArgument) ||
3658
0
      cmSystemTools::GetErrorOccurredFlag()) {
3659
0
    if (verbose) {
3660
0
      std::ostringstream msg;
3661
0
      msg << "Re-run cmake error reading : " << this->CheckBuildSystemArgument
3662
0
          << '\n';
3663
0
      cmSystemTools::Stdout(msg.str());
3664
0
    }
3665
    // There was an error reading the file.  Just rerun.
3666
0
    return 1;
3667
0
  }
3668
3669
0
  if (this->ClearBuildSystem) {
3670
    // Get the generator used for this build system.
3671
0
    std::string genName = mf.GetSafeDefinition("CMAKE_DEPENDS_GENERATOR");
3672
0
    if (!cmNonempty(genName)) {
3673
0
      genName = "Unix Makefiles";
3674
0
    }
3675
3676
    // Create the generator and use it to clear the dependencies.
3677
0
    std::unique_ptr<cmGlobalGenerator> ggd =
3678
0
      this->CreateGlobalGenerator(genName);
3679
0
    if (ggd) {
3680
0
      cm.GetCurrentSnapshot().SetDefaultDefinitions();
3681
0
      cmMakefile mfd(ggd.get(), cm.GetCurrentSnapshot());
3682
0
      auto lgd = ggd->CreateLocalGenerator(&mfd);
3683
0
      lgd->ClearDependencies(&mfd, verbose);
3684
0
    }
3685
0
  }
3686
3687
  // If any byproduct of makefile generation is missing we must re-run.
3688
0
  cmList products{ mf.GetDefinition("CMAKE_MAKEFILE_PRODUCTS") };
3689
0
  for (auto const& p : products) {
3690
0
    if (!cmSystemTools::PathExists(p)) {
3691
0
      if (verbose) {
3692
0
        cmSystemTools::Stdout(
3693
0
          cmStrCat("Re-run cmake, missing byproduct: ", p, '\n'));
3694
0
      }
3695
0
      return 1;
3696
0
    }
3697
0
  }
3698
3699
  // Get the set of dependencies and outputs.
3700
0
  cmList depends{ mf.GetDefinition("CMAKE_MAKEFILE_DEPENDS") };
3701
0
  cmList outputs;
3702
0
  if (!depends.empty()) {
3703
0
    outputs.assign(mf.GetDefinition("CMAKE_MAKEFILE_OUTPUTS"));
3704
0
  }
3705
0
  if (depends.empty() || outputs.empty()) {
3706
    // Not enough information was provided to do the test.  Just rerun.
3707
0
    if (verbose) {
3708
0
      cmSystemTools::Stdout("Re-run cmake no CMAKE_MAKEFILE_DEPENDS "
3709
0
                            "or CMAKE_MAKEFILE_OUTPUTS :\n");
3710
0
    }
3711
0
    return 1;
3712
0
  }
3713
3714
  // Find the newest dependency.
3715
0
  auto dep = depends.begin();
3716
0
  std::string dep_newest = *dep++;
3717
0
  for (; dep != depends.end(); ++dep) {
3718
0
    int result = 0;
3719
0
    if (this->FileTimeCache->Compare(dep_newest, *dep, &result)) {
3720
0
      if (result < 0) {
3721
0
        dep_newest = *dep;
3722
0
      }
3723
0
    } else {
3724
0
      if (verbose) {
3725
0
        cmSystemTools::Stdout(
3726
0
          "Re-run cmake: build system dependency is missing\n");
3727
0
      }
3728
0
      return 1;
3729
0
    }
3730
0
  }
3731
3732
  // Find the oldest output.
3733
0
  auto out = outputs.begin();
3734
0
  std::string out_oldest = *out++;
3735
0
  for (; out != outputs.end(); ++out) {
3736
0
    int result = 0;
3737
0
    if (this->FileTimeCache->Compare(out_oldest, *out, &result)) {
3738
0
      if (result > 0) {
3739
0
        out_oldest = *out;
3740
0
      }
3741
0
    } else {
3742
0
      if (verbose) {
3743
0
        cmSystemTools::Stdout(
3744
0
          "Re-run cmake: build system output is missing\n");
3745
0
      }
3746
0
      return 1;
3747
0
    }
3748
0
  }
3749
3750
  // If any output is older than any dependency then rerun.
3751
0
  {
3752
0
    int result = 0;
3753
0
    if (!this->FileTimeCache->Compare(out_oldest, dep_newest, &result) ||
3754
0
        result < 0) {
3755
0
      if (verbose) {
3756
0
        std::ostringstream msg;
3757
0
        msg << "Re-run cmake file: " << out_oldest
3758
0
            << " older than: " << dep_newest << '\n';
3759
0
        cmSystemTools::Stdout(msg.str());
3760
0
      }
3761
0
      return 1;
3762
0
    }
3763
0
  }
3764
3765
  // No need to rerun.
3766
0
  return 0;
3767
0
}
3768
3769
void cmake::TruncateOutputLog(char const* fname)
3770
0
{
3771
0
  std::string fullPath = cmStrCat(this->GetHomeOutputDirectory(), '/', fname);
3772
0
  struct stat st;
3773
0
  if (::stat(fullPath.c_str(), &st)) {
3774
0
    return;
3775
0
  }
3776
0
  if (!this->State->GetInitializedCacheValue("CMAKE_CACHEFILE_DIR")) {
3777
0
    cmSystemTools::RemoveFile(fullPath);
3778
0
    return;
3779
0
  }
3780
0
  off_t fsize = st.st_size;
3781
0
  off_t const maxFileSize = 50 * 1024;
3782
0
  if (fsize < maxFileSize) {
3783
    // TODO: truncate file
3784
0
    return;
3785
0
  }
3786
0
}
3787
3788
void cmake::MarkCliAsUsed(std::string const& variable)
3789
0
{
3790
0
  this->UsedCliVariables[variable] = true;
3791
0
}
3792
3793
void cmake::GenerateGraphViz(std::string const& fileName) const
3794
0
{
3795
0
#ifndef CMAKE_BOOTSTRAP
3796
0
  cmGraphVizWriter gvWriter(fileName, this->GetGlobalGenerator());
3797
3798
0
  std::string settingsFile =
3799
0
    cmStrCat(this->GetHomeOutputDirectory(), "/CMakeGraphVizOptions.cmake");
3800
0
  std::string fallbackSettingsFile =
3801
0
    cmStrCat(this->GetHomeDirectory(), "/CMakeGraphVizOptions.cmake");
3802
3803
0
  gvWriter.ReadSettings(settingsFile, fallbackSettingsFile);
3804
3805
0
  gvWriter.Write();
3806
3807
0
#endif
3808
0
}
3809
3810
void cmake::SetProperty(std::string const& prop, cmValue value)
3811
0
{
3812
0
  this->State->SetGlobalProperty(prop, value);
3813
0
}
3814
3815
void cmake::AppendProperty(std::string const& prop, std::string const& value,
3816
                           bool asString)
3817
0
{
3818
0
  this->State->AppendGlobalProperty(prop, value, asString);
3819
0
}
3820
3821
cmValue cmake::GetProperty(std::string const& prop)
3822
0
{
3823
0
  return this->State->GetGlobalProperty(prop);
3824
0
}
3825
3826
bool cmake::GetPropertyAsBool(std::string const& prop)
3827
0
{
3828
0
  return this->State->GetGlobalPropertyAsBool(prop);
3829
0
}
3830
3831
cmInstalledFile* cmake::GetOrCreateInstalledFile(cmMakefile* mf,
3832
                                                 std::string const& name)
3833
0
{
3834
0
  auto i = this->InstalledFiles.find(name);
3835
3836
0
  if (i != this->InstalledFiles.end()) {
3837
0
    cmInstalledFile& file = i->second;
3838
0
    return &file;
3839
0
  }
3840
0
  cmInstalledFile& file = this->InstalledFiles[name];
3841
0
  file.SetName(mf, name);
3842
0
  return &file;
3843
0
}
3844
3845
cmInstalledFile const* cmake::GetInstalledFile(std::string const& name) const
3846
0
{
3847
0
  auto i = this->InstalledFiles.find(name);
3848
3849
0
  if (i != this->InstalledFiles.end()) {
3850
0
    cmInstalledFile const& file = i->second;
3851
0
    return &file;
3852
0
  }
3853
0
  return nullptr;
3854
0
}
3855
3856
int cmake::GetSystemInformation(std::vector<std::string>& args)
3857
0
{
3858
  // so create the directory
3859
0
  std::string resultFile;
3860
0
  std::string cwd = cmSystemTools::GetLogicalWorkingDirectory();
3861
0
  std::string destPath = cwd + "/__cmake_systeminformation";
3862
0
  cmSystemTools::RemoveADirectory(destPath);
3863
0
  if (!cmSystemTools::MakeDirectory(destPath)) {
3864
0
    std::cerr << "Error: --system-information must be run from a "
3865
0
                 "writable directory!\n";
3866
0
    return 1;
3867
0
  }
3868
3869
  // process the arguments
3870
0
  bool writeToStdout = true;
3871
0
  for (unsigned int i = 1; i < args.size(); ++i) {
3872
0
    std::string const& arg = args[i];
3873
0
    if (cmHasLiteralPrefix(arg, "-G")) {
3874
0
      std::string value = arg.substr(2);
3875
0
      if (value.empty()) {
3876
0
        ++i;
3877
0
        if (i >= args.size()) {
3878
0
          cmSystemTools::Error("No generator specified for -G");
3879
0
          this->PrintGeneratorList();
3880
0
          return -1;
3881
0
        }
3882
0
        value = args[i];
3883
0
      }
3884
0
      auto gen = this->CreateGlobalGenerator(value);
3885
0
      if (!gen) {
3886
0
        cmSystemTools::Error("Could not create named generator " + value);
3887
0
        this->PrintGeneratorList();
3888
0
      } else {
3889
0
        this->SetGlobalGenerator(std::move(gen));
3890
0
      }
3891
0
    }
3892
    // no option assume it is the output file
3893
0
    else {
3894
0
      if (!cmSystemTools::FileIsFullPath(arg)) {
3895
0
        resultFile = cmStrCat(cwd, '/');
3896
0
      }
3897
0
      resultFile += arg;
3898
0
      writeToStdout = false;
3899
0
    }
3900
0
  }
3901
3902
  // we have to find the module directory, so we can copy the files
3903
0
  this->AddCMakePaths();
3904
0
  std::string modulesPath =
3905
0
    cmStrCat(cmSystemTools::GetCMakeRoot(), "/Modules");
3906
0
  std::string inFile = cmStrCat(modulesPath, "/SystemInformation.cmake");
3907
0
  std::string outFile = cmStrCat(destPath, "/CMakeLists.txt");
3908
3909
  // Copy file
3910
0
  if (!cmsys::SystemTools::CopyFileAlways(inFile, outFile)) {
3911
0
    std::cerr << "Error copying file \"" << inFile << "\" to \"" << outFile
3912
0
              << "\".\n";
3913
0
    return 1;
3914
0
  }
3915
3916
  // do we write to a file or to stdout?
3917
0
  if (resultFile.empty()) {
3918
0
    resultFile = cmStrCat(cwd, "/__cmake_systeminformation/results.txt");
3919
0
  }
3920
3921
0
  {
3922
    // now run cmake on the CMakeLists file
3923
0
    cmWorkingDirectory workdir(destPath);
3924
0
    if (workdir.Failed()) {
3925
      // We created the directory and we were able to copy the CMakeLists.txt
3926
      // file to it, so we wouldn't expect to get here unless the default
3927
      // permissions are questionable or some other process has deleted the
3928
      // directory
3929
0
      std::cerr << workdir.GetError() << '\n';
3930
0
      return 1;
3931
0
    }
3932
0
    std::vector<std::string> args2;
3933
0
    args2.reserve(3);
3934
0
    args2.emplace_back(args[0]);
3935
0
    args2.emplace_back(destPath);
3936
0
    args2.emplace_back("-DRESULT_FILE=" + resultFile);
3937
0
    int res = this->Run(args2, false);
3938
3939
0
    if (res != 0) {
3940
0
      std::cerr << "Error: --system-information failed on internal CMake!\n";
3941
0
      return res;
3942
0
    }
3943
0
  }
3944
3945
  // echo results to stdout if needed
3946
0
  if (writeToStdout) {
3947
0
    FILE* fin = cmsys::SystemTools::Fopen(resultFile, "r");
3948
0
    if (fin) {
3949
0
      int const bufferSize = 4096;
3950
0
      char buffer[bufferSize];
3951
0
      size_t n;
3952
0
      while ((n = fread(buffer, 1, bufferSize, fin)) > 0) {
3953
0
        for (char* c = buffer; c < buffer + n; ++c) {
3954
0
          putc(*c, stdout);
3955
0
        }
3956
0
        fflush(stdout);
3957
0
      }
3958
0
      fclose(fin);
3959
0
    }
3960
0
  }
3961
3962
  // clean up the directory
3963
0
  cmSystemTools::RemoveADirectory(destPath);
3964
0
  return 0;
3965
0
}
3966
3967
void cmake::IssueMessage(MessageType t, std::string const& text,
3968
                         cmListFileBacktrace const& backtrace) const
3969
1
{
3970
1
  this->Messenger->IssueMessage(t, text, backtrace);
3971
1
}
3972
3973
void cmake::IssueDiagnostic(cmDiagnosticCategory category,
3974
                            std::string const& text,
3975
                            cmStateSnapshot const& state,
3976
                            cmDiagnosticContext const& context) const
3977
0
{
3978
0
  this->Messenger->IssueDiagnostic(category, text, state, context);
3979
0
}
3980
3981
std::vector<std::string> cmake::GetDebugConfigs()
3982
0
{
3983
0
  cmList configs;
3984
0
  if (cmValue config_list =
3985
0
        this->State->GetGlobalProperty("DEBUG_CONFIGURATIONS")) {
3986
    // Expand the specified list and convert to upper-case.
3987
0
    configs.assign(*config_list);
3988
0
    configs.transform(cmList::TransformAction::TOUPPER);
3989
0
  }
3990
  // If no configurations were specified, use a default list.
3991
0
  if (configs.empty()) {
3992
0
    configs.emplace_back("DEBUG");
3993
0
  }
3994
0
  return std::move(configs.data());
3995
0
}
3996
3997
int cmake::Build(cmBuildArgs buildArgs, std::vector<std::string> targets,
3998
                 std::vector<std::string> nativeOptions,
3999
                 cmBuildOptions& buildOptions,
4000
                 cmCMakePresetsArgs const& presetsArgs,
4001
                 std::vector<std::string> const& args)
4002
0
{
4003
0
  buildArgs.timeout = cmDuration::zero();
4004
4005
0
#if !defined(CMAKE_BOOTSTRAP)
4006
0
  if (presetsArgs.HasPresetsArg()) {
4007
    // If the binary directory was specified, use it to find
4008
    // the source directory so we can locate the presets file.
4009
0
    if (!buildArgs.binaryDir.empty() &&
4010
0
        this->SetDirectoriesFromFile(buildArgs.binaryDir)) {
4011
      // HomeDirectory is now the source directory (found in CMakeCache.txt)
4012
0
    } else {
4013
      // Otherwise we assume this command was called from the source directory.
4014
0
      this->SetHomeDirectory(cmSystemTools::GetLogicalWorkingDirectory());
4015
0
      this->SetHomeOutputDirectory(
4016
0
        cmSystemTools::GetLogicalWorkingDirectory());
4017
0
    }
4018
0
    cmCMakePresetsGraph settingsFile;
4019
0
    auto result = settingsFile.ReadProjectPresets(this->GetHomeDirectory(),
4020
0
                                                  presetsArgs.PresetsFile);
4021
0
    if (result != true) {
4022
0
      cmSystemTools::Error(
4023
0
        cmStrCat("Could not read presets from ", this->GetHomeDirectory(),
4024
0
                 ":\n", settingsFile.parseState.GetErrorMessage()));
4025
0
      return 1;
4026
0
    }
4027
4028
0
    if (presetsArgs.ListPresetsMode) {
4029
0
      auto configureUsabilityCheck =
4030
0
        this->CreateConfigurePresetUsabilityCheck();
4031
0
      settingsFile.PrintBuildPresetList(*presetsArgs.ListPresetsMode,
4032
0
                                        configureUsabilityCheck);
4033
0
      return 0;
4034
0
    }
4035
4036
0
    auto resolveResult = settingsFile.ResolvePreset(presetsArgs.PresetName,
4037
0
                                                    settingsFile.BuildPresets);
4038
0
    auto resolveError =
4039
0
      cmCMakePresetsGraph::FormatPresetError<cmCMakePresetsGraph::BuildPreset>(
4040
0
        resolveResult.StatusCode, resolveResult.ErrorPresetName,
4041
0
        this->GetHomeDirectory());
4042
0
    if (resolveError) {
4043
0
      cmSystemTools::Error(*resolveError);
4044
0
      settingsFile.PrintBuildPresetList();
4045
0
      return 1;
4046
0
    }
4047
0
    auto const* expandedPreset = resolveResult.Preset;
4048
4049
0
    auto configurePresetPair =
4050
0
      settingsFile.ConfigurePresets.find(expandedPreset->ConfigurePreset);
4051
0
    if (configurePresetPair == settingsFile.ConfigurePresets.end()) {
4052
0
      cmSystemTools::Error(cmStrCat("No such configure preset in ",
4053
0
                                    this->GetHomeDirectory(), ": \"",
4054
0
                                    expandedPreset->ConfigurePreset, '"'));
4055
0
      this->PrintPresetList(settingsFile);
4056
0
      return 1;
4057
0
    }
4058
4059
0
    if (configurePresetPair->second.Unexpanded.Hidden) {
4060
0
      cmSystemTools::Error(cmStrCat("Cannot use hidden configure preset in ",
4061
0
                                    this->GetHomeDirectory(), ": \"",
4062
0
                                    expandedPreset->ConfigurePreset, '"'));
4063
0
      this->PrintPresetList(settingsFile);
4064
0
      return 1;
4065
0
    }
4066
4067
0
    auto const& expandedConfigurePreset = configurePresetPair->second.Expanded;
4068
0
    if (!expandedConfigurePreset) {
4069
0
      cmSystemTools::Error(cmStrCat("Could not evaluate configure preset \"",
4070
0
                                    expandedPreset->ConfigurePreset,
4071
0
                                    "\": Invalid macro expansion"));
4072
0
      return 1;
4073
0
    }
4074
4075
0
    if (buildArgs.binaryDir.empty() &&
4076
0
        !expandedConfigurePreset->BinaryDir.empty()) {
4077
0
      buildArgs.binaryDir = expandedConfigurePreset->BinaryDir;
4078
0
    }
4079
4080
0
    this->UnprocessedPresetEnvironment = expandedPreset->Environment;
4081
0
    this->ProcessPresetEnvironment();
4082
4083
0
    if ((buildArgs.jobs == cmake::DEFAULT_BUILD_PARALLEL_LEVEL ||
4084
0
         buildArgs.jobs == cmake::NO_BUILD_PARALLEL_LEVEL) &&
4085
0
        expandedPreset->Jobs) {
4086
0
      if (*expandedPreset->Jobs > static_cast<unsigned int>(INT_MAX)) {
4087
0
        cmSystemTools::Error(
4088
0
          "The build preset \"jobs\" value is too large.\n");
4089
0
        return 1;
4090
0
      }
4091
0
      buildArgs.jobs = *expandedPreset->Jobs;
4092
0
    }
4093
4094
0
    if (targets.empty()) {
4095
0
      targets.insert(targets.begin(), expandedPreset->Targets.begin(),
4096
0
                     expandedPreset->Targets.end());
4097
0
    }
4098
4099
0
    if (buildArgs.config.empty()) {
4100
0
      buildArgs.config = expandedPreset->Configuration;
4101
0
    }
4102
4103
0
    if (!buildOptions.Clean && expandedPreset->CleanFirst) {
4104
0
      buildOptions.Clean = *expandedPreset->CleanFirst;
4105
0
    }
4106
4107
0
    if (buildOptions.ResolveMode == PackageResolveMode::Default &&
4108
0
        expandedPreset->ResolvePackageReferences) {
4109
0
      buildOptions.ResolveMode = *expandedPreset->ResolvePackageReferences;
4110
0
    }
4111
4112
0
    if (!buildArgs.verbose && expandedPreset->Verbose) {
4113
0
      buildArgs.verbose = *expandedPreset->Verbose;
4114
0
    }
4115
4116
0
    if (nativeOptions.empty()) {
4117
0
      nativeOptions.insert(nativeOptions.begin(),
4118
0
                           expandedPreset->NativeToolOptions.begin(),
4119
0
                           expandedPreset->NativeToolOptions.end());
4120
0
    }
4121
0
  }
4122
0
#endif
4123
4124
0
  if (!cmSystemTools::FileIsDirectory(buildArgs.binaryDir)) {
4125
0
    std::cerr << "Error: " << buildArgs.binaryDir << " is not a directory\n";
4126
0
    return 1;
4127
0
  }
4128
4129
0
  std::string cachePath = FindCacheFile(buildArgs.binaryDir);
4130
0
  if (!this->LoadCache(cachePath)) {
4131
0
    std::cerr
4132
0
      << "Error: not a CMake build directory (missing CMakeCache.txt)\n";
4133
0
    return 1;
4134
0
  }
4135
0
  cmValue cachedGenerator = this->State->GetCacheEntryValue("CMAKE_GENERATOR");
4136
0
  if (!cachedGenerator) {
4137
0
    std::cerr << "Error: could not find CMAKE_GENERATOR in Cache\n";
4138
0
    return 1;
4139
0
  }
4140
0
  auto gen = this->CreateGlobalGenerator(*cachedGenerator);
4141
0
  if (!gen) {
4142
0
    std::cerr << "Error: could not create CMAKE_GENERATOR \""
4143
0
              << *cachedGenerator << "\"\n";
4144
0
    return 1;
4145
0
  }
4146
0
  this->SetGlobalGenerator(std::move(gen));
4147
0
  cmValue cachedGeneratorInstance =
4148
0
    this->State->GetCacheEntryValue("CMAKE_GENERATOR_INSTANCE");
4149
0
  if (cachedGeneratorInstance) {
4150
0
    cmMakefile mf(this->GetGlobalGenerator(), this->GetCurrentSnapshot());
4151
0
    if (!this->GlobalGenerator->SetGeneratorInstance(*cachedGeneratorInstance,
4152
0
                                                     &mf)) {
4153
0
      return 1;
4154
0
    }
4155
0
  }
4156
0
  cmValue cachedGeneratorPlatform =
4157
0
    this->State->GetCacheEntryValue("CMAKE_GENERATOR_PLATFORM");
4158
0
  if (cachedGeneratorPlatform) {
4159
0
    cmMakefile mf(this->GetGlobalGenerator(), this->GetCurrentSnapshot());
4160
0
    if (!this->GlobalGenerator->SetGeneratorPlatform(*cachedGeneratorPlatform,
4161
0
                                                     &mf)) {
4162
0
      return 1;
4163
0
    }
4164
0
  }
4165
0
  cmValue cachedGeneratorToolset =
4166
0
    this->State->GetCacheEntryValue("CMAKE_GENERATOR_TOOLSET");
4167
0
  if (cachedGeneratorToolset) {
4168
0
    cmMakefile mf(this->GetGlobalGenerator(), this->GetCurrentSnapshot());
4169
0
    if (!this->GlobalGenerator->SetGeneratorToolset(*cachedGeneratorToolset,
4170
0
                                                    true, &mf)) {
4171
0
      return 1;
4172
0
    }
4173
0
  }
4174
0
  cmValue cachedProjectName =
4175
0
    this->State->GetCacheEntryValue("CMAKE_PROJECT_NAME");
4176
0
  if (!cachedProjectName) {
4177
0
    std::cerr << "Error: could not find CMAKE_PROJECT_NAME in Cache\n";
4178
0
    return 1;
4179
0
  }
4180
0
  buildArgs.projectName = *cachedProjectName;
4181
4182
0
  if (this->State->GetCacheEntryValue("CMAKE_VERBOSE_MAKEFILE").IsOn()) {
4183
0
    buildArgs.verbose = true;
4184
0
  }
4185
4186
#ifdef CMAKE_HAVE_VS_GENERATORS
4187
  // For VS generators, explicitly check if regeneration is necessary before
4188
  // actually starting the build. If not done separately from the build
4189
  // itself, there is the risk of building an out-of-date solution file due
4190
  // to limitations of the underlying build system.
4191
  std::string const stampList =
4192
    cmStrCat(cachePath, "/CMakeFiles/",
4193
             cmGlobalVisualStudioVersionedGenerator::GetGenerateStampList());
4194
4195
  // Note that the stampList file only exists for VS generators.
4196
  if (cmSystemTools::FileExists(stampList) &&
4197
      !cmakeCheckStampList(stampList)) {
4198
    // Upgrade cmake role from --build to reconfigure the project.
4199
    this->State->SetRoleToProjectForCMakeBuildVsReconfigure();
4200
    this->AddScriptingCommands();
4201
    this->AddProjectCommands();
4202
4203
    // Correctly initialize the home (=source) and home output (=binary)
4204
    // directories, which is required for running the generation step.
4205
    this->SetDirectoriesFromFile(cachePath);
4206
4207
    int ret = this->Configure();
4208
    if (ret) {
4209
      cmSystemTools::Message("CMake Configure step failed.  "
4210
                             "Build files cannot be regenerated correctly.");
4211
      return ret;
4212
    }
4213
    ret = this->Generate();
4214
    if (ret) {
4215
      cmSystemTools::Message("CMake Generate step failed.  "
4216
                             "Build files cannot be regenerated correctly.");
4217
      return ret;
4218
    }
4219
    std::string message = cmStrCat("Build files have been written to: ",
4220
                                   this->GetHomeOutputDirectory());
4221
    this->UpdateProgress(message, -1);
4222
  }
4223
#endif
4224
4225
0
  if (!this->GlobalGenerator->ReadCacheEntriesForBuild(*this->State)) {
4226
0
    return 1;
4227
0
  }
4228
4229
0
#if !defined(CMAKE_BOOTSTRAP)
4230
0
  cmInstrumentation instrumentation(buildArgs.binaryDir);
4231
0
  if (instrumentation.HasErrors()) {
4232
0
    return 1;
4233
0
  }
4234
0
  instrumentation.CollectTimingData(
4235
0
    cmInstrumentationQuery::Hook::PreCMakeBuild);
4236
0
#endif
4237
4238
0
  this->GlobalGenerator->PrintBuildCommandAdvice(std::cerr, buildArgs.jobs);
4239
0
  std::stringstream ostr;
4240
  // `cmGlobalGenerator::Build` logs metadata about what directory and commands
4241
  // are being executed to the `output` parameter. If CMake is verbose, print
4242
  // this out.
4243
0
  std::ostream& verbose_ostr = buildArgs.verbose ? std::cout : ostr;
4244
0
  auto doBuild = [this, targets, &verbose_ostr, buildOptions, buildArgs,
4245
0
                  nativeOptions]() -> int {
4246
0
    return this->GlobalGenerator->Build(
4247
0
      buildArgs, targets, verbose_ostr, "", buildArgs.config, buildOptions,
4248
0
      buildArgs.timeout, cmSystemTools::OUTPUT_PASSTHROUGH, nativeOptions);
4249
0
  };
4250
4251
0
#if !defined(CMAKE_BOOTSTRAP)
4252
  // Block the instrumentation build daemon from spawning during this build.
4253
  // This lock will be released when the process exits at the end of the build.
4254
0
  instrumentation.LockBuildDaemon();
4255
  // Run the build under an interrupt handler so that a user interrupt (e.g.
4256
  // Ctrl+C) still writes the overall `cmakeBuild` snippet before we exit.
4257
0
  cmInstrumentationInterrupt::InterruptOutcome buildOutcome =
4258
0
    cmInstrumentationInterrupt::HandleInterrupt(
4259
0
      instrumentation.HasQuery(),
4260
0
      [&instrumentation, &args, &doBuild]() -> int {
4261
0
        return instrumentation.InstrumentCommand(
4262
0
          "cmakeBuild", args,
4263
0
          [&doBuild]() -> cmInstrumentation::CommandResult {
4264
0
            return { doBuild(), cm::nullopt, cm::nullopt, cm::nullopt };
4265
0
          });
4266
0
      });
4267
0
  int buildresult = buildOutcome.ExitCode;
4268
0
  if (buildOutcome.Interrupted) {
4269
    // The build was interrupted and its snippet has been written.  Skip the
4270
    // post-build indexing hook (which would run callbacks and delete data).
4271
    // For a real OS interrupt, re-raise so the exit status reflects it; for a
4272
    // test-injected interrupt, exit cleanly.  The next indexing run will
4273
    // reclaim the snippet written above.
4274
0
    if (buildOutcome.ShouldRaise) {
4275
0
      cmInstrumentationInterrupt::RaiseInterrupt(buildOutcome.Signal);
4276
0
    }
4277
0
    return buildresult;
4278
0
  }
4279
0
  instrumentation.CollectTimingData(
4280
0
    cmInstrumentationQuery::Hook::PostCMakeBuild);
4281
#else
4282
  int buildresult = doBuild();
4283
#endif
4284
4285
0
  return buildresult;
4286
0
}
4287
4288
bool cmake::Open(std::string const& dir, DryRun dryRun)
4289
0
{
4290
0
  if (!cmSystemTools::FileIsDirectory(dir)) {
4291
0
    if (dryRun == DryRun::No) {
4292
0
      std::cerr << "Error: " << dir << " is not a directory\n";
4293
0
    }
4294
0
    return false;
4295
0
  }
4296
4297
0
  std::string cachePath = FindCacheFile(dir);
4298
0
  if (!this->LoadCache(cachePath)) {
4299
0
    std::cerr
4300
0
      << "Error: not a CMake build directory (missing CMakeCache.txt)\n";
4301
0
    return false;
4302
0
  }
4303
0
  cmValue genName = this->State->GetCacheEntryValue("CMAKE_GENERATOR");
4304
0
  if (!genName) {
4305
0
    std::cerr << "Error: could not find CMAKE_GENERATOR in Cache\n";
4306
0
    return false;
4307
0
  }
4308
0
  cmValue extraGenName =
4309
0
    this->State->GetInitializedCacheValue("CMAKE_EXTRA_GENERATOR");
4310
0
  std::string fullName =
4311
0
    cmExternalMakefileProjectGenerator::CreateFullGeneratorName(
4312
0
      *genName, extraGenName ? *extraGenName : "");
4313
4314
0
  std::unique_ptr<cmGlobalGenerator> gen =
4315
0
    this->CreateGlobalGenerator(fullName);
4316
0
  if (!gen) {
4317
0
    std::cerr << "Error: could not create CMAKE_GENERATOR \"" << fullName
4318
0
              << "\"\n";
4319
0
    return false;
4320
0
  }
4321
4322
0
  cmValue cachedProjectName =
4323
0
    this->State->GetCacheEntryValue("CMAKE_PROJECT_NAME");
4324
0
  if (!cachedProjectName) {
4325
0
    std::cerr << "Error: could not find CMAKE_PROJECT_NAME in Cache\n";
4326
0
    return false;
4327
0
  }
4328
4329
0
  return gen->Open(dir, *cachedProjectName, dryRun == DryRun::Yes);
4330
0
}
4331
4332
#if !defined(CMAKE_BOOTSTRAP)
4333
namespace {
4334
std::string WorkflowStepLabel(cm::static_string_view type,
4335
                              std::string const& name)
4336
0
{
4337
0
  return cmStrCat("of type \"", type, "\" named \"", name, '"');
4338
0
}
4339
}
4340
4341
template <typename T>
4342
T const* cmake::FindPresetForWorkflow(
4343
  cm::static_string_view type,
4344
  std::map<std::string, cmCMakePresetsGraph::PresetPair<T>> const& presets,
4345
  cmCMakePresetsGraph::WorkflowPreset::WorkflowStep const& step)
4346
0
{
4347
0
  std::string const stepLabel = WorkflowStepLabel(type, step.PresetName);
4348
0
  auto it = presets.find(step.PresetName);
4349
0
  if (it == presets.end()) {
4350
0
    cmSystemTools::Error(cmStrCat("No such preset for workflow step ",
4351
0
                                  stepLabel, " in ",
4352
0
                                  this->GetHomeDirectory()));
4353
0
    return nullptr;
4354
0
  }
4355
4356
0
  if (it->second.Unexpanded.Hidden) {
4357
0
    cmSystemTools::Error(
4358
0
      cmStrCat("Cannot use hidden preset for workflow step ", stepLabel,
4359
0
               " in ", this->GetHomeDirectory()));
4360
0
    return nullptr;
4361
0
  }
4362
4363
0
  if (!it->second.Expanded) {
4364
0
    cmSystemTools::Error(cmStrCat("Could not evaluate workflow step ",
4365
0
                                  stepLabel, ": Invalid macro expansion"));
4366
0
    return nullptr;
4367
0
  }
4368
4369
0
  if (!it->second.Expanded->ConditionResult) {
4370
0
    cmSystemTools::Error(
4371
0
      cmStrCat("Cannot use disabled preset for workflow step ", stepLabel,
4372
0
               " in ", this->GetHomeDirectory()));
4373
0
    return nullptr;
4374
0
  }
4375
4376
0
  return &*it->second.Expanded;
4377
0
}
Unexecuted instantiation: cmCMakePresetsGraph::ConfigurePreset const* cmake::FindPresetForWorkflow<cmCMakePresetsGraph::ConfigurePreset>(cm::static_string_view, std::__1::map<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> >, cmCMakePresetsGraph::PresetPair<cmCMakePresetsGraph::ConfigurePreset>, std::__1::less<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > >, std::__1::allocator<std::__1::pair<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > const, cmCMakePresetsGraph::PresetPair<cmCMakePresetsGraph::ConfigurePreset> > > > const&, cmCMakePresetsGraph::WorkflowPreset::WorkflowStep const&)
Unexecuted instantiation: cmCMakePresetsGraph::BuildPreset const* cmake::FindPresetForWorkflow<cmCMakePresetsGraph::BuildPreset>(cm::static_string_view, std::__1::map<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> >, cmCMakePresetsGraph::PresetPair<cmCMakePresetsGraph::BuildPreset>, std::__1::less<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > >, std::__1::allocator<std::__1::pair<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > const, cmCMakePresetsGraph::PresetPair<cmCMakePresetsGraph::BuildPreset> > > > const&, cmCMakePresetsGraph::WorkflowPreset::WorkflowStep const&)
Unexecuted instantiation: cmCMakePresetsGraph::TestPreset const* cmake::FindPresetForWorkflow<cmCMakePresetsGraph::TestPreset>(cm::static_string_view, std::__1::map<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> >, cmCMakePresetsGraph::PresetPair<cmCMakePresetsGraph::TestPreset>, std::__1::less<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > >, std::__1::allocator<std::__1::pair<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > const, cmCMakePresetsGraph::PresetPair<cmCMakePresetsGraph::TestPreset> > > > const&, cmCMakePresetsGraph::WorkflowPreset::WorkflowStep const&)
Unexecuted instantiation: cmCMakePresetsGraph::PackagePreset const* cmake::FindPresetForWorkflow<cmCMakePresetsGraph::PackagePreset>(cm::static_string_view, std::__1::map<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> >, cmCMakePresetsGraph::PresetPair<cmCMakePresetsGraph::PackagePreset>, std::__1::less<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > >, std::__1::allocator<std::__1::pair<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > const, cmCMakePresetsGraph::PresetPair<cmCMakePresetsGraph::PackagePreset> > > > const&, cmCMakePresetsGraph::WorkflowPreset::WorkflowStep const&)
4378
4379
namespace {
4380
4381
std::function<cmUVProcessChain::Status()> buildWorkflowStep(
4382
  std::vector<std::string> const& args)
4383
0
{
4384
0
  cmUVProcessChainBuilder builder;
4385
0
  builder.AddCommand(args)
4386
0
    .SetExternalStream(cmUVProcessChainBuilder::Stream_OUTPUT, stdout)
4387
0
    .SetExternalStream(cmUVProcessChainBuilder::Stream_ERROR, stderr);
4388
0
  return [builder]() -> cmUVProcessChain::Status {
4389
0
    auto chain = builder.Start();
4390
0
    chain.Wait();
4391
0
    return chain.GetStatus(0);
4392
0
  };
4393
0
}
4394
4395
}
4396
#endif
4397
4398
int cmake::Workflow(cmCMakePresetsWorkflowArgs const& args)
4399
0
{
4400
0
  int exitStatus = 0;
4401
0
#ifndef CMAKE_BOOTSTRAP
4402
0
  this->SetHomeDirectory(cmSystemTools::GetLogicalWorkingDirectory());
4403
0
  this->SetHomeOutputDirectory(cmSystemTools::GetLogicalWorkingDirectory());
4404
4405
0
  cmCMakePresetsGraph settingsFile;
4406
0
  auto result = settingsFile.ReadProjectPresets(this->GetHomeDirectory(),
4407
0
                                                args.PresetsFile);
4408
0
  if (result != true) {
4409
0
    cmSystemTools::Error(cmStrCat("Could not read presets from ",
4410
0
                                  this->GetHomeDirectory(), ":\n",
4411
0
                                  settingsFile.parseState.GetErrorMessage()));
4412
0
    return 1;
4413
0
  }
4414
4415
0
  if (args.ListPresetsMode) {
4416
0
    auto configureUsabilityCheck = this->CreateConfigurePresetUsabilityCheck();
4417
0
    settingsFile.PrintWorkflowPresetList(*args.ListPresetsMode,
4418
0
                                         configureUsabilityCheck);
4419
0
    return 0;
4420
0
  }
4421
4422
0
  auto presetPair = settingsFile.WorkflowPresets.find(args.PresetName);
4423
0
  if (presetPair == settingsFile.WorkflowPresets.end()) {
4424
0
    cmSystemTools::Error(cmStrCat("No such workflow preset in ",
4425
0
                                  this->GetHomeDirectory(), ": \"",
4426
0
                                  args.PresetName, '"'));
4427
0
    settingsFile.PrintWorkflowPresetList();
4428
0
    return 1;
4429
0
  }
4430
4431
0
  if (presetPair->second.Unexpanded.Hidden) {
4432
0
    cmSystemTools::Error(cmStrCat("Cannot use hidden workflow preset in ",
4433
0
                                  this->GetHomeDirectory(), ": \"",
4434
0
                                  args.PresetName, '"'));
4435
0
    settingsFile.PrintWorkflowPresetList();
4436
0
    return 1;
4437
0
  }
4438
4439
0
  auto const& expandedPreset = presetPair->second.Expanded;
4440
0
  if (!expandedPreset) {
4441
0
    cmSystemTools::Error(cmStrCat("Could not evaluate workflow preset \"",
4442
0
                                  args.PresetName,
4443
0
                                  "\": Invalid macro expansion"));
4444
0
    settingsFile.PrintWorkflowPresetList();
4445
0
    return 1;
4446
0
  }
4447
4448
0
  if (!expandedPreset->ConditionResult) {
4449
0
    cmSystemTools::Error(cmStrCat("Cannot use disabled workflow preset in ",
4450
0
                                  this->GetHomeDirectory(), ": \"",
4451
0
                                  args.PresetName, '"'));
4452
0
    settingsFile.PrintWorkflowPresetList();
4453
0
    return 1;
4454
0
  }
4455
4456
0
  struct CalculatedStep
4457
0
  {
4458
0
    int StepNumber;
4459
0
    cm::static_string_view Type;
4460
0
    std::string Name;
4461
0
    std::function<cmUVProcessChain::Status()> Action;
4462
4463
0
    CalculatedStep(int stepNumber, cm::static_string_view type,
4464
0
                   std::string name,
4465
0
                   std::function<cmUVProcessChain::Status()> action)
4466
0
      : StepNumber(stepNumber)
4467
0
      , Type(type)
4468
0
      , Name(std::move(name))
4469
0
      , Action(std::move(action))
4470
0
    {
4471
0
    }
4472
0
  };
4473
4474
0
  auto buildPresetCommand = [&args](std::vector<std::string> cmd,
4475
0
                                    std::string const& presetName) {
4476
0
    cmd.insert(cmd.end(), { "--preset", presetName });
4477
0
    if (!args.PresetsFile.empty()) {
4478
0
      cmd.insert(cmd.end(), { "--presets-file", args.PresetsFile });
4479
0
    }
4480
0
    return cmd;
4481
0
  };
4482
4483
0
  std::vector<CalculatedStep> steps;
4484
0
  steps.reserve(expandedPreset->Steps.size());
4485
0
  int stepNumber = 1;
4486
0
  cmCMakePresetsGraph::ConfigurePreset const* configurePreset = {};
4487
0
  for (auto const& step : expandedPreset->Steps) {
4488
0
    switch (step.PresetType) {
4489
0
      case cmCMakePresetsGraph::WorkflowPreset::WorkflowStep::Type::
4490
0
        Configure: {
4491
0
        configurePreset = this->FindPresetForWorkflow(
4492
0
          "configure"_s, settingsFile.ConfigurePresets, step);
4493
0
        if (!configurePreset) {
4494
0
          return 1;
4495
0
        }
4496
0
        std::vector<std::string> configureCmdArgs = buildPresetCommand(
4497
0
          { cmSystemTools::GetCMakeCommand() }, step.PresetName);
4498
0
        if (args.Fresh) {
4499
0
          configureCmdArgs.emplace_back("--fresh");
4500
0
        }
4501
0
        steps.emplace_back(stepNumber, "configure"_s, step.PresetName,
4502
0
                           buildWorkflowStep(configureCmdArgs));
4503
0
      } break;
4504
0
      case cmCMakePresetsGraph::WorkflowPreset::WorkflowStep::Type::Build: {
4505
0
        auto const* buildPreset = this->FindPresetForWorkflow(
4506
0
          "build"_s, settingsFile.BuildPresets, step);
4507
0
        if (!buildPreset) {
4508
0
          return 1;
4509
0
        }
4510
0
        std::vector<std::string> buildCmdArgs = buildPresetCommand(
4511
0
          { cmSystemTools::GetCMakeCommand(), "--build" }, step.PresetName);
4512
0
        steps.emplace_back(stepNumber, "build"_s, step.PresetName,
4513
0
                           buildWorkflowStep(buildCmdArgs));
4514
0
      } break;
4515
0
      case cmCMakePresetsGraph::WorkflowPreset::WorkflowStep::Type::Test: {
4516
0
        auto const* testPreset = this->FindPresetForWorkflow(
4517
0
          "test"_s, settingsFile.TestPresets, step);
4518
0
        if (!testPreset) {
4519
0
          return 1;
4520
0
        }
4521
0
        std::vector<std::string> testCmdArgs = buildPresetCommand(
4522
0
          { cmSystemTools::GetCTestCommand() }, step.PresetName);
4523
0
        steps.emplace_back(stepNumber, "test"_s, step.PresetName,
4524
0
                           buildWorkflowStep(testCmdArgs));
4525
0
      } break;
4526
0
      case cmCMakePresetsGraph::WorkflowPreset::WorkflowStep::Type::Package: {
4527
0
        auto const* packagePreset = this->FindPresetForWorkflow(
4528
0
          "package"_s, settingsFile.PackagePresets, step);
4529
0
        if (!packagePreset) {
4530
0
          return 1;
4531
0
        }
4532
0
        std::vector<std::string> packageCmdArgs = buildPresetCommand(
4533
0
          { cmSystemTools::GetCPackCommand() }, step.PresetName);
4534
0
        steps.emplace_back(stepNumber, "package"_s, step.PresetName,
4535
0
                           buildWorkflowStep(packageCmdArgs));
4536
0
      } break;
4537
0
    }
4538
0
    stepNumber++;
4539
0
  }
4540
4541
0
  bool first = true;
4542
0
  for (auto const& step : steps) {
4543
0
    if (!first) {
4544
0
      std::cout << "\n";
4545
0
    }
4546
0
    std::cout << "Executing workflow step " << step.StepNumber << " of "
4547
0
              << steps.size() << ": " << step.Type << " preset \"" << step.Name
4548
0
              << "\"\n\n"
4549
0
              << std::flush;
4550
0
    cmUVProcessChain::Status const status = step.Action();
4551
0
    if (status.ExitStatus != 0) {
4552
0
      cmSystemTools::Error(
4553
0
        cmStrCat("Workflow step ", WorkflowStepLabel(step.Type, step.Name),
4554
0
                 " failed with exit code ", status.ExitStatus));
4555
0
      exitStatus = static_cast<int>(status.ExitStatus);
4556
0
      break;
4557
0
    }
4558
0
    auto const codeReasonPair = status.GetException();
4559
0
    if (codeReasonPair.first != cmUVProcessChain::ExceptionCode::None) {
4560
0
      cmSystemTools::Error(
4561
0
        cmStrCat("Workflow step ", WorkflowStepLabel(step.Type, step.Name),
4562
0
                 " command ended abnormally: ", codeReasonPair.second));
4563
0
      exitStatus =
4564
0
        status.SpawnResult != 0 ? status.SpawnResult : status.TermSignal;
4565
0
      break;
4566
0
    }
4567
0
    first = false;
4568
0
  }
4569
0
  if (configurePreset) {
4570
0
    cmInstrumentation instrumentation(configurePreset->BinaryDir);
4571
0
    instrumentation.CollectTimingData(
4572
0
      cmInstrumentationQuery::Hook::PostCMakeWorkflow);
4573
0
  }
4574
0
#endif
4575
4576
0
  return exitStatus;
4577
0
}
4578
4579
void cmake::WatchUnusedCli(std::string const& var)
4580
0
{
4581
0
#ifndef CMAKE_BOOTSTRAP
4582
0
  this->VariableWatch->AddWatch(var, cmWarnUnusedCliWarning, this);
4583
0
  if (!cm::contains(this->UsedCliVariables, var)) {
4584
0
    this->UsedCliVariables[var] = false;
4585
0
  }
4586
0
#endif
4587
0
}
4588
4589
void cmake::UnwatchUnusedCli(std::string const& var)
4590
3
{
4591
3
#ifndef CMAKE_BOOTSTRAP
4592
3
  this->VariableWatch->RemoveWatch(var, cmWarnUnusedCliWarning);
4593
3
  this->UsedCliVariables.erase(var);
4594
3
#endif
4595
3
}
4596
4597
void cmake::RunCheckForUnusedVariables()
4598
0
{
4599
0
#ifndef CMAKE_BOOTSTRAP
4600
0
  cmDiagnosticAction const action =
4601
0
    this->CurrentSnapshot.GetDiagnostic(cmDiagnostics::CMD_UNUSED_CLI);
4602
0
  if (action != cmDiagnostics::Ignore) {
4603
0
    bool haveUnused = false;
4604
0
    std::ostringstream msg;
4605
0
    msg << "Manually-specified variables were not used by the project:";
4606
0
    for (auto const& it : this->UsedCliVariables) {
4607
0
      if (!it.second) {
4608
0
        haveUnused = true;
4609
0
        msg << "\n  " << it.first;
4610
0
      }
4611
0
    }
4612
0
    if (haveUnused) {
4613
0
      this->IssueDiagnostic(cmDiagnostics::CMD_UNUSED_CLI, msg.str());
4614
0
    }
4615
0
  }
4616
0
#endif
4617
0
}
4618
4619
void cmake::AlterDiagnostic(DiagnosticAlterationMethod alteration,
4620
                            cmDiagnosticCategory category,
4621
                            cmDiagnosticAction desiredAction, bool recurse)
4622
0
{
4623
  // In Project mode, we need to defer applying any diagnostic changes until
4624
  // after reading the prior state from the cache. In all other modes, changes
4625
  // should be applied immediately.
4626
0
  if (this->State->GetRole() == cmState::Role::Project) {
4627
0
    this->DiagnosticAlterations.emplace_back( // clang-format: break
4628
0
      DiagnosticAlteration{ alteration, category, desiredAction, recurse });
4629
0
  } else {
4630
0
    (this->CurrentSnapshot.*alteration)(category, desiredAction, recurse);
4631
0
  }
4632
0
}
4633
4634
void cmake::SetDebugFindOutputPkgs(std::string const& args)
4635
0
{
4636
0
  this->DebugFindPkgs.emplace(args);
4637
0
}
4638
4639
void cmake::SetDebugFindOutputVars(std::string const& args)
4640
0
{
4641
0
  this->DebugFindVars.emplace(args);
4642
0
}
4643
4644
bool cmake::GetDebugFindOutput(std::string const& var) const
4645
0
{
4646
0
  return this->DebugFindVars.count(var);
4647
0
}
4648
4649
bool cmake::GetDebugFindPkgOutput(std::string const& pkg) const
4650
0
{
4651
0
  return this->DebugFindPkgs.count(pkg);
4652
0
}
4653
4654
void cmake::SetCMakeListName(std::string const& name)
4655
0
{
4656
0
  this->CMakeListName = name;
4657
0
}
4658
4659
std::string cmake::GetCMakeListFile(std::string const& dir) const
4660
0
{
4661
0
  assert(!dir.empty());
4662
0
  cm::string_view const slash = dir.back() != '/' ? "/"_s : ""_s;
4663
0
  std::string listFile;
4664
0
  if (!this->CMakeListName.empty()) {
4665
0
    listFile = cmStrCat(dir, slash, this->CMakeListName);
4666
0
  }
4667
0
  if (listFile.empty() || !cmSystemTools::FileExists(listFile, true)) {
4668
0
    listFile = cmStrCat(dir, slash, "CMakeLists.txt");
4669
0
  }
4670
0
  return listFile;
4671
0
}
4672
4673
#if !defined(CMAKE_BOOTSTRAP)
4674
cmMakefileProfilingData& cmake::GetProfilingOutput()
4675
0
{
4676
0
  return *(this->ProfilingOutput);
4677
0
}
4678
4679
bool cmake::IsProfilingEnabled() const
4680
0
{
4681
0
  return static_cast<bool>(this->ProfilingOutput);
4682
0
}
4683
#endif