Coverage Report

Created: 2026-07-14 07:09

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