Coverage Report

Created: 2026-07-30 06:52

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