Coverage Report

Created: 2026-10-28 06:38

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/CMake/Source/cmake.h
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
#pragma once
4
5
#include "cmConfigure.h" // IWYU pragma: keep
6
7
#include <cstddef>
8
#include <functional>
9
#include <map>
10
#include <memory>
11
#include <set>
12
#include <stack>
13
#include <string>
14
#include <unordered_map>
15
#include <unordered_set>
16
#include <utility>
17
#include <vector>
18
19
#include <cm/string_view>
20
#include <cmext/string_view>
21
22
#include "cmBuildArgs.h"
23
#include "cmDiagnosticContext.h"
24
#include "cmDiagnostics.h"
25
#include "cmDocumentationEntry.h" // IWYU pragma: keep
26
#include "cmGeneratedFileStream.h"
27
#include "cmInstalledFile.h"
28
#include "cmListFileCache.h"
29
#include "cmMessageType.h"
30
#include "cmState.h"
31
#include "cmStateSnapshot.h"
32
#include "cmStateTypes.h"
33
#include "cmStringAlgorithms.h"
34
#include "cmValue.h"
35
36
#if !defined(CMAKE_BOOTSTRAP)
37
#  include <cm/optional>
38
39
#  include <cm3p/json/value.h>
40
41
#  include "cmCMakePresetsGraph.h"
42
#  include "cmMakefileProfilingData.h"
43
#endif
44
45
class cmConfigureLog;
46
47
#ifdef CMake_ENABLE_DEBUGGER
48
namespace cmDebugger {
49
class cmDebuggerAdapter;
50
}
51
#endif
52
53
class cmExternalMakefileProjectGeneratorFactory;
54
class cmCMakePresetsArgs;
55
class cmCMakePresetsConfigureArgs;
56
class cmCMakePresetsWorkflowArgs;
57
class cmFileAPI;
58
class cmInstrumentation;
59
class cmFileTimeCache;
60
class cmGeneratorExpressionParseCache;
61
class cmGlobalGenerator;
62
class cmMakefile;
63
class cmMessenger;
64
class cmVariableWatch;
65
class cmGlobalGeneratorFactory;
66
struct cmBuildOptions;
67
struct cmGlobCacheEntry;
68
69
/** \brief Represents a cmake invocation.
70
 *
71
 * This class represents a cmake invocation. It is the top level class when
72
 * running cmake. Most cmake based GUIs should primarily create an instance
73
 * of this class and communicate with it.
74
 *
75
 * The basic process for a GUI is as follows:
76
 *
77
 * -# Create a cmake instance
78
 * -# Set the Home directories, generator, and cmake command. this
79
 *    can be done using the Set methods or by using SetArgs and passing in
80
 *    command line arguments.
81
 * -# Load the cache by calling LoadCache (duh)
82
 * -# if you are using command line arguments with -D or -C flags then
83
 *    call SetCacheArgs (or if for some other reason you want to modify the
84
 *    cache), do it now.
85
 * -# Finally call Configure
86
 * -# Let the user change values and go back to step 5
87
 * -# call Generate
88
89
 * If your GUI allows the user to change the home directories then
90
 * you must at a minimum redo steps 2 through 7.
91
 */
92
93
class cmake
94
{
95
public:
96
  /** \brief Describes the working modes of cmake */
97
  enum WorkingMode
98
  {
99
    NORMAL_MODE, ///< Cmake runs to create project files
100
101
    /** \brief Script mode (started by using -P).
102
     *
103
     * In script mode there is no generator and no cache. Also,
104
     * languages are not enabled, so add_executable and things do
105
     * nothing.
106
     */
107
    SCRIPT_MODE,
108
109
    /** \brief Help mode
110
     *
111
     * Used to print help for things that can only be determined after finding
112
     * the source directory, for example, the list of presets.
113
     */
114
    HELP_MODE,
115
116
    /** \brief A pkg-config like mode
117
     *
118
     * In this mode cmake just searches for a package and prints the results to
119
     * stdout. This is similar to SCRIPT_MODE, but commands like add_library()
120
     * work too, since they may be used e.g. in exported target files. Started
121
     * via --find-package.
122
     */
123
    FIND_PACKAGE_MODE
124
  };
125
126
  enum class CommandFailureAction
127
  {
128
    // When a command fails to execute, treat it as a fatal error.
129
    FATAL_ERROR,
130
131
    // When a command fails to execute, continue execution, but set the exit
132
    // code accordingly.
133
    EXIT_CODE,
134
  };
135
136
  using TraceFormat = cmTraceEnums::TraceOutputFormat;
137
138
  struct GeneratorInfo
139
  {
140
    std::string name;
141
    std::string baseName;
142
    std::string extraName;
143
    bool supportsToolset;
144
    bool supportsPlatform;
145
    std::vector<std::string> supportedPlatforms;
146
    std::string defaultPlatform;
147
    bool isAlias;
148
  };
149
150
  struct FileExtensions
151
  {
152
    bool Test(cm::string_view ext) const
153
140k
    {
154
140k
      return (this->unordered.find(ext) != this->unordered.end());
155
140k
    }
156
157
    std::vector<std::string> ordered;
158
    std::unordered_set<cm::string_view> unordered;
159
  };
160
161
  using InstalledFilesMap = std::map<std::string, cmInstalledFile>;
162
163
  static int const NO_BUILD_PARALLEL_LEVEL =
164
    cmBuildArgs::NO_BUILD_PARALLEL_LEVEL;
165
  static int const DEFAULT_BUILD_PARALLEL_LEVEL =
166
    cmBuildArgs::DEFAULT_BUILD_PARALLEL_LEVEL;
167
168
  /// Default constructor
169
  cmake(cmState::Role role,
170
        cmState::TryCompile isTryCompile = cmState::TryCompile::No);
171
  /// Destructor
172
  ~cmake();
173
174
  cmake(cmake const&) = delete;
175
  cmake& operator=(cmake const&) = delete;
176
177
#if !defined(CMAKE_BOOTSTRAP)
178
  Json::Value ReportVersionJson() const;
179
  Json::Value ReportCapabilitiesJson() const;
180
#endif
181
  std::string ReportCapabilities() const;
182
183
  /**
184
   * Set the home directory from `-S` or from a known location
185
   * that contains a CMakeLists.txt. Will generate warnings
186
   * when overriding an existing source directory.
187
   *
188
   *  |    args           | src dir| warning        |
189
   *  | ----------------- | ------ | -------------- |
190
   *  | `dirA dirA`       | dirA   | N/A            |
191
   *  | `-S dirA -S dirA` | dirA   | N/A            |
192
   *  | `-S dirA -S dirB` | dirB   | Ignoring dirA  |
193
   *  | `-S dirA dirB`    | dirB   | Ignoring dirA  |
194
   *  | `dirA -S dirB`    | dirB   | Ignoring dirA  |
195
   *  | `dirA dirB`       | dirB   | Ignoring dirA  |
196
   */
197
  void SetHomeDirectoryViaCommandLine(std::string const& path);
198
199
  //@{
200
  /**
201
   * Set/Get the home directory (or output directory) in the project. The
202
   * home directory is the top directory of the project. It is the
203
   * path-to-source cmake was run with.
204
   */
205
  void SetHomeDirectory(std::string const& dir);
206
  std::string const& GetHomeDirectory() const;
207
  void SetHomeOutputDirectory(std::string const& dir);
208
  std::string const& GetHomeOutputDirectory() const;
209
  //@}
210
211
  /**
212
   * Working directory at CMake launch
213
   */
214
  std::string const& GetCMakeWorkingDirectory() const
215
0
  {
216
0
    return this->CMakeWorkingDirectory;
217
0
  }
218
219
  /**
220
   * Handle a command line invocation of cmake.
221
   */
222
  int Run(std::vector<std::string> const& args)
223
0
  {
224
0
    return this->Run(args, false);
225
0
  }
226
  int Run(std::vector<std::string> const& args, bool noconfigure);
227
228
  /**
229
   * Run the global generator Generate step.
230
   */
231
  int Generate();
232
233
  /**
234
   * Configure the cmMakefiles. This routine will create a GlobalGenerator if
235
   * one has not already been set. It will then Call Configure on the
236
   * GlobalGenerator. This in turn will read in an process all the CMakeList
237
   * files for the tree. It will not produce any actual Makefiles, or
238
   * workspaces. Generate does that.  */
239
  int Configure();
240
  int ActualConfigure();
241
242
  //! Break up a line like VAR:type="value" into var, type and value
243
  static bool ParseCacheEntry(std::string const& entry, std::string& var,
244
                              std::string& value,
245
                              cmStateEnums::CacheEntryType& type);
246
247
  int LoadCache();
248
  bool LoadCache(std::string const& path);
249
  bool LoadCache(std::string const& path, bool internal,
250
                 std::set<std::string>& excludes,
251
                 std::set<std::string>& includes);
252
  bool SaveCache(std::string const& path);
253
  bool DeleteCache(std::string const& path);
254
  void PreLoadCMakeFiles();
255
256
  //! Create a GlobalGenerator
257
  std::unique_ptr<cmGlobalGenerator> CreateGlobalGenerator(
258
    std::string const& name);
259
260
  //! Create a GlobalGenerator and set it as our own
261
  bool CreateAndSetGlobalGenerator(std::string const& name);
262
263
#ifndef CMAKE_BOOTSTRAP
264
  bool SetArgsFromPreset(cmCMakePresetsConfigureArgs const& args,
265
                         bool haveBinaryDirArg);
266
267
  cmCMakePresetsGraph::ConfigurePresetUsabilityCheck
268
  CreateConfigurePresetUsabilityCheck() const;
269
270
  void PrintPresetList(cmCMakePresetsGraph const& graph,
271
                       cmCMakePresetsGraph::PresetListMode mode =
272
                         cmCMakePresetsGraph::PresetListMode::Available) const;
273
#endif
274
275
  //! Return the global generator assigned to this instance of cmake
276
  cmGlobalGenerator* GetGlobalGenerator()
277
5.92k
  {
278
5.92k
    return this->GlobalGenerator.get();
279
5.92k
  }
280
  //! Return the global generator assigned to this instance of cmake, const
281
  cmGlobalGenerator const* GetGlobalGenerator() const
282
0
  {
283
0
    return this->GlobalGenerator.get();
284
0
  }
285
286
  //! Return the full path to where the CMakeCache.txt file should be.
287
  static std::string FindCacheFile(std::string const& binaryDir);
288
289
  //! Return the global generator assigned to this instance of cmake
290
  void SetGlobalGenerator(std::unique_ptr<cmGlobalGenerator>);
291
292
  //! Get the names of the current registered generators
293
  void GetRegisteredGenerators(std::vector<GeneratorInfo>& generators) const;
294
295
  //! Set the name of the selected generator-specific instance.
296
  void SetGeneratorInstance(std::string const& instance)
297
0
  {
298
0
    this->GeneratorInstance = instance;
299
0
    this->GeneratorInstanceSet = true;
300
0
  }
301
302
  //! Set the name of the selected generator-specific platform.
303
  void SetGeneratorPlatform(std::string const& ts)
304
0
  {
305
0
    this->GeneratorPlatform = ts;
306
0
    this->GeneratorPlatformSet = true;
307
0
  }
308
309
  //! Set the name of the selected generator-specific toolset.
310
  void SetGeneratorToolset(std::string const& ts)
311
0
  {
312
0
    this->GeneratorToolset = ts;
313
0
    this->GeneratorToolsetSet = true;
314
0
  }
315
316
  //! Set the name of the graphviz file.
317
0
  void SetGraphVizFile(std::string const& ts) { this->GraphVizFile = ts; }
318
319
  bool IsAKnownSourceExtension(cm::string_view ext) const
320
60.4k
  {
321
60.4k
    return this->CLikeSourceFileExtensions.Test(ext) ||
322
16.0k
      this->CudaFileExtensions.Test(ext) ||
323
16.0k
      this->FortranFileExtensions.Test(ext) ||
324
16.0k
      this->HipFileExtensions.Test(ext) || this->ISPCFileExtensions.Test(ext);
325
60.4k
  }
326
327
  bool IsACLikeSourceExtension(cm::string_view ext) const
328
0
  {
329
0
    return this->CLikeSourceFileExtensions.Test(ext);
330
0
  }
331
332
  bool IsAKnownExtension(cm::string_view ext) const
333
60.4k
  {
334
60.4k
    return this->IsAKnownSourceExtension(ext) || this->IsAHeaderExtension(ext);
335
60.4k
  }
336
337
  std::vector<std::string> GetAllExtensions() const;
338
339
  std::vector<std::string> const& GetHeaderExtensions() const
340
0
  {
341
0
    return this->HeaderFileExtensions.ordered;
342
0
  }
343
344
  bool IsAHeaderExtension(cm::string_view ext) const
345
16.0k
  {
346
16.0k
    return this->HeaderFileExtensions.Test(ext);
347
16.0k
  }
348
349
  // Strips the extension (if present and known) from a filename
350
  std::string StripExtension(std::string const& file) const;
351
352
  /**
353
   * Given a variable name, return its value (as a string).
354
   */
355
  cmValue GetCacheDefinition(std::string const&) const;
356
  //! Add an entry into the cache
357
  void AddCacheEntry(std::string const& key, std::string const& value,
358
                     std::string const& helpString, int type)
359
3
  {
360
3
    this->AddCacheEntry(key, cmValue{ value }, cmValue{ helpString }, type);
361
3
  }
362
  void AddCacheEntry(std::string const& key, cmValue value,
363
                     std::string const& helpString, int type)
364
0
  {
365
0
    this->AddCacheEntry(key, value, cmValue{ helpString }, type);
366
0
  }
367
  void AddCacheEntry(std::string const& key, cmValue value, cmValue helpString,
368
                     int type);
369
370
  bool DoWriteGlobVerifyTarget() const;
371
  std::string const& GetGlobVerifyScript() const;
372
  std::string const& GetGlobVerifyStamp() const;
373
  void AddGlobCacheEntry(cmGlobCacheEntry const& entry,
374
                         std::string const& variable,
375
                         cmListFileBacktrace const& bt);
376
  std::vector<cmGlobCacheEntry> GetGlobCacheEntries() const;
377
378
  /**
379
   * Get the system information and write it to the file specified
380
   */
381
  int GetSystemInformation(std::vector<std::string>&);
382
383
  //! Parse environment variables
384
  void LoadEnvironmentPresets();
385
386
  //! Parse command line arguments
387
  void SetArgs(std::vector<std::string> const& args);
388
389
  //! Is this cmake running as a result of a TRY_COMPILE command
390
  bool GetIsInTryCompile() const;
391
392
#ifndef CMAKE_BOOTSTRAP
393
  void SetDiagnosticsFromPreset(
394
    std::map<cmDiagnosticCategory, bool> const& warnings,
395
    std::map<cmDiagnosticCategory, bool> const& errors);
396
  void ProcessPresetVariables();
397
  void PrintPresetVariables();
398
  void ProcessPresetEnvironment();
399
  void PrintPresetEnvironment();
400
#endif
401
402
  //! Parse command line arguments that might set cache values
403
  bool SetCacheArgs(std::vector<std::string> const&);
404
405
  void ProcessCacheArg(std::string const& var, std::string const& value,
406
                       cmStateEnums::CacheEntryType type);
407
408
  using ProgressCallbackType = std::function<void(std::string const&, float)>;
409
  /**
410
   *  Set the function used by GUIs to receive progress updates
411
   *  Function gets passed: message as a const char*, a progress
412
   *  amount ranging from 0 to 1.0 and client data. The progress
413
   *  number provided may be negative in cases where a message is
414
   *  to be displayed without any progress percentage.
415
   */
416
  void SetProgressCallback(ProgressCallbackType f);
417
418
  //! this is called by generators to update the progress
419
  void UpdateProgress(std::string const& msg, float prog);
420
421
#if !defined(CMAKE_BOOTSTRAP)
422
  //! Get the variable watch object
423
6.72M
  cmVariableWatch* GetVariableWatch() { return this->VariableWatch.get(); }
424
#endif
425
426
  std::vector<cmDocumentationEntry> GetGeneratorsDocumentation();
427
428
  //! Set/Get a property of this target file
429
  void SetProperty(std::string const& prop, cmValue value);
430
  void SetProperty(std::string const& prop, std::nullptr_t)
431
0
  {
432
0
    this->SetProperty(prop, cmValue{ nullptr });
433
0
  }
434
  void SetProperty(std::string const& prop, std::string const& value)
435
11.8k
  {
436
11.8k
    this->SetProperty(prop, cmValue(value));
437
11.8k
  }
438
  void AppendProperty(std::string const& prop, std::string const& value,
439
                      bool asString = false);
440
  cmValue GetProperty(std::string const& prop);
441
  bool GetPropertyAsBool(std::string const& prop);
442
443
  //! Get or create an cmInstalledFile instance and return a pointer to it
444
  cmInstalledFile* GetOrCreateInstalledFile(cmMakefile* mf,
445
                                            std::string const& name);
446
447
  cmInstalledFile const* GetInstalledFile(std::string const& name) const;
448
449
  InstalledFilesMap const& GetInstalledFiles() const
450
0
  {
451
0
    return this->InstalledFiles;
452
0
  }
453
454
  //! Do all the checks before running configure
455
  int DoPreConfigureChecks();
456
457
  bool RoleSupportsExitCode() const;
458
459
  CommandFailureAction GetCommandFailureAction() const;
460
461
  //! Debug the try compile stuff by not deleting the files
462
0
  bool GetDebugTryCompile() const { return this->DebugTryCompile; }
463
0
  void DebugTryCompileOn() { this->DebugTryCompile = true; }
464
465
  /**
466
   * Generate CMAKE_ROOT and CMAKE_COMMAND cache entries
467
   */
468
  int AddCMakePaths();
469
470
  /**
471
   * Get the file comparison class
472
   */
473
0
  cmFileTimeCache* GetFileTimeCache() { return this->FileTimeCache.get(); }
474
475
  cmGeneratorExpressionParseCache& GetGeneratorExpressionParseCache()
476
56.2k
  {
477
56.2k
    return *this->GeneratorExpressionParseCache;
478
56.2k
  }
479
480
  //! Cache for cmSystemTools::GetActualCaseForPath.
481
  std::unordered_map<std::string, std::string>* GetActualCaseCache()
482
0
  {
483
0
    return &this->ActualCaseCache;
484
0
  }
485
486
  //! Forget what is known about the file system, e.g. after files may
487
  //! have been removed or renamed.
488
  void InvalidateFileSystemCaches();
489
490
0
  bool WasLogLevelSetViaCLI() const { return this->LogLevelWasSetViaCLI; }
491
492
  //! Get the selected log level for `message()` commands during the cmake run.
493
3
  Message::LogLevel GetLogLevel() const { return this->MessageLogLevel; }
494
0
  void SetLogLevel(Message::LogLevel level) { this->MessageLogLevel = level; }
495
  static Message::LogLevel StringToLogLevel(cm::string_view levelStr);
496
  static std::string LogLevelToString(Message::LogLevel level);
497
  static TraceFormat StringToTraceFormat(std::string const& levelStr);
498
499
  bool HasCheckInProgress() const
500
0
  {
501
0
    return !this->CheckInProgressMessages.empty();
502
0
  }
503
  std::size_t GetCheckInProgressSize() const
504
0
  {
505
0
    return this->CheckInProgressMessages.size();
506
0
  }
507
  std::string GetTopCheckInProgressMessage()
508
0
  {
509
0
    auto message = this->CheckInProgressMessages.back();
510
0
    this->CheckInProgressMessages.pop_back();
511
0
    return message;
512
0
  }
513
  void PushCheckInProgressMessage(std::string message)
514
0
  {
515
0
    this->CheckInProgressMessages.emplace_back(std::move(message));
516
0
  }
517
  std::vector<std::string> const& GetCheckInProgressMessages() const
518
0
  {
519
0
    return this->CheckInProgressMessages;
520
0
  }
521
522
  //! Should `message` command display context.
523
0
  bool GetShowLogContext() const { return this->LogContext; }
524
0
  void SetShowLogContext(bool b) { this->LogContext = b; }
525
526
  //! Do we want debug output during the cmake run.
527
3.55k
  bool GetDebugOutput() const { return this->DebugOutput; }
528
0
  void SetDebugOutputOn(bool b) { this->DebugOutput = b; }
529
530
  //! Do we want debug output from the find commands during the cmake run.
531
0
  bool GetDebugFindOutput() const { return this->DebugFindOutput; }
532
  bool GetDebugFindOutput(std::string const& var) const;
533
  bool GetDebugFindPkgOutput(std::string const& pkg) const;
534
0
  void SetDebugFindOutput(bool b) { this->DebugFindOutput = b; }
535
  void SetDebugFindOutputPkgs(std::string const& args);
536
  void SetDebugFindOutputVars(std::string const& args);
537
538
  //! Do we want trace output during the cmake run.
539
  bool GetTrace() const
540
412k
  {
541
412k
    return this->Trace || !this->cmakeLangTraceCmdStack.empty();
542
412k
  }
543
0
  void SetTrace(bool b) { this->Trace = b; }
544
  void PushTraceCmd(bool expandFlag)
545
0
  {
546
0
    this->cmakeLangTraceCmdStack.emplace(expandFlag);
547
0
  }
548
  bool PopTraceCmd();
549
  bool GetTraceExpand() const
550
0
  {
551
0
    return this->TraceExpand ||
552
0
      (!this->cmakeLangTraceCmdStack.empty() &&
553
0
       this->cmakeLangTraceCmdStack.top());
554
0
  }
555
0
  void SetTraceExpand(bool b) { this->TraceExpand = b; }
556
0
  TraceFormat GetTraceFormat() const { return this->TraceFormatVar; }
557
0
  void SetTraceFormat(TraceFormat f) { this->TraceFormatVar = f; }
558
  void AddTraceSource(std::string const& file)
559
0
  {
560
0
    this->TraceOnlyThisSources.push_back(file);
561
0
  }
562
  std::vector<std::string> const& GetTraceSources() const
563
0
  {
564
0
    return this->TraceOnlyThisSources;
565
0
  }
566
  cmGeneratedFileStream& GetTraceFile()
567
0
  {
568
0
    if (this->TraceRedirect) {
569
0
      return this->TraceRedirect->GetTraceFile();
570
0
    }
571
0
    return this->TraceFile;
572
0
  }
573
  void SetTraceFile(std::string const& file);
574
  void PrintTraceFormatVersion();
575
576
#ifndef CMAKE_BOOTSTRAP
577
0
  cmConfigureLog* GetConfigureLog() const { return this->ConfigureLog.get(); }
578
#endif
579
580
  //! Use trace from another ::cmake instance.
581
  void SetTraceRedirect(cmake* other);
582
583
19.8k
  bool GetCheckSystemVars() const { return this->CheckSystemVars; }
584
0
  void SetCheckSystemVars(bool b) { this->CheckSystemVars = b; }
585
  bool GetIgnoreCompileWarningAsError() const
586
0
  {
587
0
    return this->IgnoreCompileWarningAsError;
588
0
  }
589
  void SetIgnoreCompileWarningAsError(bool b)
590
0
  {
591
0
    this->IgnoreCompileWarningAsError = b;
592
0
  }
593
  bool GetIgnoreLinkWarningAsError() const
594
0
  {
595
0
    return this->IgnoreLinkWarningAsError;
596
0
  }
597
  void SetIgnoreLinkWarningAsError(bool b)
598
0
  {
599
0
    this->IgnoreLinkWarningAsError = b;
600
0
  }
601
602
  void MarkCliAsUsed(std::string const& variable);
603
604
  /** Get the list of configurations (in upper case) considered to be
605
      debugging configurations.*/
606
  std::vector<std::string> GetDebugConfigs();
607
608
  void SetCMakeEditCommand(std::string const& s)
609
0
  {
610
0
    this->CMakeEditCommand = s;
611
0
  }
612
  std::string const& GetCMakeEditCommand() const
613
0
  {
614
0
    return this->CMakeEditCommand;
615
0
  }
616
617
0
  cmMessenger* GetMessenger() const { return this->Messenger.get(); }
618
619
#ifndef CMAKE_BOOTSTRAP
620
  /// Get the file path for SARIF logging if enabled by cache variable.
621
  cm::optional<std::string> GetProjectSarifFile() const
622
0
  {
623
0
    if (this->State->GetRole() == cmState::Role::Project) {
624
0
      if (this->GetCacheDefinition("CMAKE_EXPORT_SARIF").IsOn()) {
625
0
        return cmStrCat(this->GetHomeOutputDirectory(),
626
0
                        "/.cmake/sarif/cmake.sarif"_s);
627
0
      }
628
0
    }
629
0
    return cm::nullopt;
630
0
  }
631
#endif
632
633
  /** Display a message to the user.  */
634
  void IssueMessage(
635
    MessageType t, std::string const& text,
636
    cmListFileBacktrace const& backtrace = cmListFileBacktrace()) const;
637
  void IssueDiagnostic(cmDiagnosticCategory category, std::string const& text,
638
                       cmStateSnapshot const& state,
639
                       cmDiagnosticContext const& context = {}) const;
640
  void IssueDiagnostic(cmDiagnosticCategory category, std::string const& text,
641
                       cmDiagnosticContext const& context = {}) const
642
0
  {
643
0
    this->IssueDiagnostic(category, text, this->CurrentSnapshot, context);
644
0
  }
645
  void IssueDiagnostic(cmDiagnosticCategory category, std::string const& text,
646
                       cmListFileBacktrace backtrace) const
647
0
  {
648
0
    this->IssueDiagnostic(category, text, this->CurrentSnapshot,
649
0
                          cmDiagnosticContext{ std::move(backtrace) });
650
0
  }
651
652
  //! run the --build option
653
  int Build(cmBuildArgs buildArgs, std::vector<std::string> targets,
654
            std::vector<std::string> nativeOptions,
655
            cmBuildOptions& buildOptions,
656
            cmCMakePresetsArgs const& presetsArgs,
657
            std::vector<std::string> const& args);
658
659
  enum class DryRun
660
  {
661
    No,
662
    Yes,
663
  };
664
665
  //! run the --open option
666
  bool Open(std::string const& dir, DryRun dryRun);
667
668
  //! run the --workflow option
669
  int Workflow(cmCMakePresetsWorkflowArgs const& args);
670
671
  void UnwatchUnusedCli(std::string const& var);
672
  void WatchUnusedCli(std::string const& var);
673
674
#if !defined(CMAKE_BOOTSTRAP)
675
0
  cmFileAPI* GetFileAPI() const { return this->FileAPI.get(); }
676
  cmInstrumentation* GetInstrumentation() const
677
0
  {
678
0
    return this->Instrumentation.get();
679
0
  }
680
#endif
681
  void InitializeFileAPI();
682
  void InitializeInstrumentation();
683
684
0
  bool GetInInitialCache() const { return this->InInitialCache; }
685
0
  void SetInInitialCache(bool v) { this->InInitialCache = v; }
686
687
8.91M
  cmState* GetState() const { return this->State.get(); }
688
  void SetCurrentSnapshot(cmStateSnapshot const& snapshot)
689
0
  {
690
0
    this->CurrentSnapshot = snapshot;
691
0
  }
692
19.8k
  cmStateSnapshot GetCurrentSnapshot() const { return this->CurrentSnapshot; }
693
694
0
  bool GetRegenerateDuringBuild() const { return this->RegenerateDuringBuild; }
695
696
  void SetCMakeListName(std::string const& name);
697
  std::string GetCMakeListFile(std::string const& dir) const;
698
699
#if !defined(CMAKE_BOOTSTRAP)
700
  cmMakefileProfilingData& GetProfilingOutput();
701
  bool IsProfilingEnabled() const;
702
703
  cm::optional<cmMakefileProfilingData::RAII> CreateProfilingEntry(
704
    std::string const& category, std::string const& name)
705
122k
  {
706
122k
    return this->CreateProfilingEntry(
707
122k
      category, name, []() -> cm::nullopt_t { return cm::nullopt; });
708
122k
  }
709
710
  template <typename ArgsFunc>
711
  cm::optional<cmMakefileProfilingData::RAII> CreateProfilingEntry(
712
    std::string const& category, std::string const& name, ArgsFunc&& argsFunc)
713
576k
  {
714
576k
    if (this->IsProfilingEnabled()) {
715
0
      return cm::make_optional<cmMakefileProfilingData::RAII>(
716
0
        this->GetProfilingOutput(), category, name, argsFunc());
717
0
    }
718
576k
    return cm::nullopt;
719
576k
  }
std::__1::optional<cmMakefileProfilingData::RAII> cmake::CreateProfilingEntry<cmake::CreateProfilingEntry(std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > const&, std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > const&)::{lambda()#1}>(std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > const&, std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > const&, cmake::CreateProfilingEntry(std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > const&, std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > const&)::{lambda()#1}&&)
Line
Count
Source
713
122k
  {
714
122k
    if (this->IsProfilingEnabled()) {
715
0
      return cm::make_optional<cmMakefileProfilingData::RAII>(
716
0
        this->GetProfilingOutput(), category, name, argsFunc());
717
0
    }
718
122k
    return cm::nullopt;
719
122k
  }
cmGeneratorExpressionEvaluator.cxx:std::__1::optional<cmMakefileProfilingData::RAII> cmake::CreateProfilingEntry<GeneratorExpressionContent::Evaluate(cm::GenEx::Evaluation*, cmGeneratorExpressionDAGChecker*) const::$_0>(std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > const&, std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > const&, GeneratorExpressionContent::Evaluate(cm::GenEx::Evaluation*, cmGeneratorExpressionDAGChecker*) const::$_0&&)
Line
Count
Source
713
50.3k
  {
714
50.3k
    if (this->IsProfilingEnabled()) {
715
0
      return cm::make_optional<cmMakefileProfilingData::RAII>(
716
0
        this->GetProfilingOutput(), category, name, argsFunc());
717
0
    }
718
50.3k
    return cm::nullopt;
719
50.3k
  }
std::__1::optional<cmMakefileProfilingData::RAII> cmake::CreateProfilingEntry<cmMakefile::CallScope::CallScope(cmMakefile*, cmListFileFunction const&, cmListFileContext const&, cmExecutionStatus&)::{lambda()#1}>(cmMakefile::CallScope::CallScope(cmMakefile*, cmListFileFunction const&, cmListFileContext const&, cmExecutionStatus&)::{lambda()#1}::basic_string<char, cmMakefile::CallScope::CallScope(cmMakefile*, cmListFileFunction const&, cmListFileContext const&, cmExecutionStatus&)::{lambda()#1}::char_traits<char>, cmMakefile::CallScope::CallScope(cmMakefile*, cmListFileFunction const&, cmListFileContext const&, cmExecutionStatus&)::{lambda()#1}::allocator<char> > const&, cmMakefile::CallScope::CallScope(cmMakefile*, cmListFileFunction const&, cmListFileContext const&, cmExecutionStatus&)::{lambda()#1}::basic_string<char, cmMakefile::CallScope::CallScope(cmMakefile*, cmListFileFunction const&, cmListFileContext const&, cmExecutionStatus&)::{lambda()#1}::char_traits<char>, cmMakefile::CallScope::CallScope(cmMakefile*, cmListFileFunction const&, cmListFileContext const&, cmExecutionStatus&)::{lambda()#1}::allocator<char> > const, cmMakefile::CallScope::CallScope(cmMakefile*, cmListFileFunction const&, cmListFileContext const&, cmExecutionStatus&)::{lambda()#1}&&)
Line
Count
Source
713
403k
  {
714
403k
    if (this->IsProfilingEnabled()) {
715
0
      return cm::make_optional<cmMakefileProfilingData::RAII>(
716
0
        this->GetProfilingOutput(), category, name, argsFunc());
717
0
    }
718
403k
    return cm::nullopt;
719
403k
  }
720
#endif
721
722
#ifdef CMake_ENABLE_DEBUGGER
723
1
  bool GetDebuggerOn() const { return this->DebuggerOn; }
724
0
  std::string GetDebuggerPipe() const { return this->DebuggerPipe; }
725
  std::string GetDebuggerDapLogFile() const
726
0
  {
727
0
    return this->DebuggerDapLogFile;
728
0
  }
729
0
  void SetDebuggerOn(bool b) { this->DebuggerOn = b; }
730
  bool StartDebuggerIfEnabled();
731
  void StopDebuggerIfNeeded(int exitCode);
732
  std::shared_ptr<cmDebugger::cmDebuggerAdapter> GetDebugAdapter()
733
    const noexcept
734
817k
  {
735
817k
    return this->DebugAdapter;
736
817k
  }
737
#endif
738
739
protected:
740
  void RunCheckForUnusedVariables();
741
  int HandleDeleteCacheVariables(
742
    std::map<std::string, std::string> const& var);
743
  /**
744
   * Warn about different CMAKE_SYSTEM_ENVIRONMENT_ID, ignore, or refresh the
745
   * cache depending on CMAKE_SYSTEM_ENVIRONMENT_ACTION.
746
   *
747
   * @return 0 on success or -1 if LoadCache fails.
748
   */
749
  int HandleDifferentSystemEnvironmentId(std::string envId,
750
                                         std::string cachedId);
751
752
  using RegisteredGeneratorsVector =
753
    std::vector<std::unique_ptr<cmGlobalGeneratorFactory>>;
754
  RegisteredGeneratorsVector Generators;
755
  using RegisteredExtraGeneratorsVector =
756
    std::vector<cmExternalMakefileProjectGeneratorFactory*>;
757
  RegisteredExtraGeneratorsVector ExtraGenerators;
758
  void AddScriptingCommands() const;
759
  void AddProjectCommands() const;
760
  void AddDefaultGenerators();
761
  void AddDefaultExtraGenerators();
762
763
  std::string GeneratorInstance;
764
  std::string GeneratorPlatform;
765
  std::string GeneratorToolset;
766
  cm::optional<std::string> IntermediateDirStrategy;
767
  cm::optional<std::string> AutogenIntermediateDirStrategy;
768
  bool GeneratorInstanceSet = false;
769
  bool GeneratorPlatformSet = false;
770
  bool GeneratorToolsetSet = false;
771
772
  //! read in a cmake list file to initialize the cache
773
  void ReadListFile(std::vector<std::string> const& args,
774
                    std::string const& path);
775
  bool FindPackage(std::vector<std::string> const& args);
776
777
  //! Check if CMAKE_CACHEFILE_DIR is set. If it is not, delete the log file.
778
  ///  If it is set, truncate it to 50kb
779
  void TruncateOutputLog(char const* fname);
780
781
  /**
782
   * Method called to check build system integrity at build time.
783
   * Returns 1 if CMake should rerun and 0 otherwise.
784
   */
785
  int CheckBuildSystem();
786
787
  bool SetDirectoriesFromFile(std::string const& arg);
788
789
  //! Make sure all commands are what they say they are and there is no
790
  /// macros.
791
  void CleanupCommandsAndMacros();
792
793
  void GenerateGraphViz(std::string const& fileName) const;
794
795
private:
796
  std::vector<std::string> cmdArgs;
797
  std::string CMakeWorkingDirectory;
798
  ProgressCallbackType ProgressCallback;
799
  bool DebugOutput = false;
800
  bool DebugFindOutput = false;
801
  // Elements of `cmakeLangTraceCmdStack` are "trace requests" pushed
802
  // by `cmake_language(TRACE ON [EXPAND])` and a boolean value is
803
  // a state of a given `EXPAND` option.
804
  std::stack<bool> cmakeLangTraceCmdStack;
805
  bool Trace = false;
806
  bool TraceExpand = false;
807
  TraceFormat TraceFormatVar = TraceFormat::Human;
808
  cmGeneratedFileStream TraceFile;
809
  cmake* TraceRedirect = nullptr;
810
#ifndef CMAKE_BOOTSTRAP
811
  std::unique_ptr<cmConfigureLog> ConfigureLog;
812
#endif
813
  bool CheckSystemVars = false;
814
  bool IgnoreCompileWarningAsError = false;
815
  bool IgnoreLinkWarningAsError = false;
816
  std::map<std::string, bool> UsedCliVariables;
817
  std::string CMakeEditCommand;
818
  std::string CXXEnvironment;
819
  std::string CCEnvironment;
820
  std::string CheckBuildSystemArgument;
821
  std::string CheckStampFile;
822
  std::string CheckStampList;
823
  std::string VSSolutionFile;
824
  std::string EnvironmentGenerator;
825
  FileExtensions CLikeSourceFileExtensions;
826
  FileExtensions HeaderFileExtensions;
827
  FileExtensions CudaFileExtensions;
828
  FileExtensions ISPCFileExtensions;
829
  FileExtensions FortranFileExtensions;
830
  FileExtensions HipFileExtensions;
831
  bool ClearBuildSystem = false;
832
  bool DebugTryCompile = false;
833
  bool FreshCache = false;
834
  bool RegenerateDuringBuild = false;
835
  bool InInitialCache = false;
836
  std::string CMakeListName;
837
  std::unique_ptr<cmFileTimeCache> FileTimeCache;
838
  std::unique_ptr<cmGeneratorExpressionParseCache>
839
    GeneratorExpressionParseCache;
840
  std::unordered_map<std::string, std::string> ActualCaseCache;
841
  std::string GraphVizFile;
842
  InstalledFilesMap InstalledFiles;
843
#ifndef CMAKE_BOOTSTRAP
844
  std::map<std::string, cm::optional<cmCMakePresetsGraph::CacheVariable>>
845
    UnprocessedPresetVariables;
846
  std::map<std::string, cm::optional<std::string>>
847
    UnprocessedPresetEnvironment;
848
  std::map<std::string, cm::optional<cmCMakePresetsGraph::CacheVariable>>
849
    InitialPresetVariables;
850
#endif
851
852
#if !defined(CMAKE_BOOTSTRAP)
853
  std::unique_ptr<cmVariableWatch> VariableWatch;
854
  std::unique_ptr<cmFileAPI> FileAPI;
855
  std::unique_ptr<cmInstrumentation> Instrumentation;
856
#endif
857
858
  std::unique_ptr<cmState> State;
859
  cmStateSnapshot CurrentSnapshot;
860
  std::unique_ptr<cmMessenger> Messenger;
861
862
  using DiagnosticAlterationMethod =
863
    void (cmStateSnapshot::*)(cmDiagnosticCategory, cmDiagnosticAction, bool);
864
865
  struct DiagnosticAlteration
866
  {
867
    DiagnosticAlterationMethod const Alteration;
868
    cmDiagnosticCategory const Category;
869
    cmDiagnosticAction const DesiredAction;
870
    bool const Recurse;
871
  };
872
873
  std::vector<DiagnosticAlteration> DiagnosticAlterations;
874
875
  void AlterDiagnostic(DiagnosticAlterationMethod alteration,
876
                       cmDiagnosticCategory category,
877
                       cmDiagnosticAction desiredAction, bool recurse);
878
879
  std::vector<std::string> TraceOnlyThisSources;
880
881
  std::set<std::string> DebugFindPkgs;
882
  std::set<std::string> DebugFindVars;
883
884
  Message::LogLevel MessageLogLevel = Message::LogLevel::LOG_STATUS;
885
  bool LogLevelWasSetViaCLI = false;
886
  bool LogContext = false;
887
888
  std::vector<std::string> CheckInProgressMessages;
889
890
  std::unique_ptr<cmGlobalGenerator> GlobalGenerator;
891
892
  //! Print a list of valid generators to stderr.
893
  void PrintGeneratorList();
894
895
  std::unique_ptr<cmGlobalGenerator> EvaluateDefaultGlobalGenerator();
896
  void CreateDefaultGlobalGenerator();
897
898
  void AppendGlobalGeneratorsDocumentation(std::vector<cmDocumentationEntry>&);
899
  void AppendExtraGeneratorsDocumentation(std::vector<cmDocumentationEntry>&);
900
901
#if !defined(CMAKE_BOOTSTRAP)
902
  template <typename T>
903
  T const* FindPresetForWorkflow(
904
    cm::static_string_view type,
905
    std::map<std::string, cmCMakePresetsGraph::PresetPair<T>> const& presets,
906
    cmCMakePresetsGraph::WorkflowPreset::WorkflowStep const& step);
907
#endif
908
909
#if !defined(CMAKE_BOOTSTRAP)
910
  std::unique_ptr<cmMakefileProfilingData> ProfilingOutput;
911
#endif
912
913
#ifdef CMake_ENABLE_DEBUGGER
914
  std::shared_ptr<cmDebugger::cmDebuggerAdapter> DebugAdapter;
915
  bool DebuggerOn = false;
916
  std::string DebuggerPipe;
917
  std::string DebuggerDapLogFile;
918
#endif
919
920
  cm::optional<int> ScriptModeExitCode;
921
922
public:
923
403k
  bool HasScriptModeExitCode() const { return ScriptModeExitCode.has_value(); }
924
0
  void SetScriptModeExitCode(int code) { ScriptModeExitCode = code; }
925
0
  int GetScriptModeExitCode() const { return ScriptModeExitCode.value_or(-1); }
926
927
  static cmDocumentationEntry CMAKE_STANDARD_OPTIONS_TABLE[15];
928
};
929
930
0
#define FOR_EACH_C90_FEATURE(F) F(c_function_prototypes)
931
932
#define FOR_EACH_C99_FEATURE(F)                                               \
933
0
  F(c_restrict)                                                               \
934
0
  F(c_variadic_macros)
935
936
0
#define FOR_EACH_C11_FEATURE(F) F(c_static_assert)
937
938
#define FOR_EACH_C_FEATURE(F)                                                 \
939
0
  F(c_std_90)                                                                 \
940
0
  F(c_std_99)                                                                 \
941
0
  F(c_std_11)                                                                 \
942
0
  F(c_std_17)                                                                 \
943
0
  F(c_std_23)                                                                 \
944
0
  FOR_EACH_C90_FEATURE(F)                                                     \
945
0
  FOR_EACH_C99_FEATURE(F)                                                     \
946
0
  FOR_EACH_C11_FEATURE(F)
947
948
0
#define FOR_EACH_CXX98_FEATURE(F) F(cxx_template_template_parameters)
949
950
#define FOR_EACH_CXX11_FEATURE(F)                                             \
951
0
  F(cxx_alias_templates)                                                      \
952
0
  F(cxx_alignas)                                                              \
953
0
  F(cxx_alignof)                                                              \
954
0
  F(cxx_attributes)                                                           \
955
0
  F(cxx_auto_type)                                                            \
956
0
  F(cxx_constexpr)                                                            \
957
0
  F(cxx_decltype)                                                             \
958
0
  F(cxx_decltype_incomplete_return_types)                                     \
959
0
  F(cxx_default_function_template_args)                                       \
960
0
  F(cxx_defaulted_functions)                                                  \
961
0
  F(cxx_defaulted_move_initializers)                                          \
962
0
  F(cxx_delegating_constructors)                                              \
963
0
  F(cxx_deleted_functions)                                                    \
964
0
  F(cxx_enum_forward_declarations)                                            \
965
0
  F(cxx_explicit_conversions)                                                 \
966
0
  F(cxx_extended_friend_declarations)                                         \
967
0
  F(cxx_extern_templates)                                                     \
968
0
  F(cxx_final)                                                                \
969
0
  F(cxx_func_identifier)                                                      \
970
0
  F(cxx_generalized_initializers)                                             \
971
0
  F(cxx_inheriting_constructors)                                              \
972
0
  F(cxx_inline_namespaces)                                                    \
973
0
  F(cxx_lambdas)                                                              \
974
0
  F(cxx_local_type_template_args)                                             \
975
0
  F(cxx_long_long_type)                                                       \
976
0
  F(cxx_noexcept)                                                             \
977
0
  F(cxx_nonstatic_member_init)                                                \
978
0
  F(cxx_nullptr)                                                              \
979
0
  F(cxx_override)                                                             \
980
0
  F(cxx_range_for)                                                            \
981
0
  F(cxx_raw_string_literals)                                                  \
982
0
  F(cxx_reference_qualified_functions)                                        \
983
0
  F(cxx_right_angle_brackets)                                                 \
984
0
  F(cxx_rvalue_references)                                                    \
985
0
  F(cxx_sizeof_member)                                                        \
986
0
  F(cxx_static_assert)                                                        \
987
0
  F(cxx_strong_enums)                                                         \
988
0
  F(cxx_thread_local)                                                         \
989
0
  F(cxx_trailing_return_types)                                                \
990
0
  F(cxx_unicode_literals)                                                     \
991
0
  F(cxx_uniform_initialization)                                               \
992
0
  F(cxx_unrestricted_unions)                                                  \
993
0
  F(cxx_user_literals)                                                        \
994
0
  F(cxx_variadic_macros)                                                      \
995
0
  F(cxx_variadic_templates)
996
997
#define FOR_EACH_CXX14_FEATURE(F)                                             \
998
0
  F(cxx_aggregate_default_initializers)                                       \
999
0
  F(cxx_attribute_deprecated)                                                 \
1000
0
  F(cxx_binary_literals)                                                      \
1001
0
  F(cxx_contextual_conversions)                                               \
1002
0
  F(cxx_decltype_auto)                                                        \
1003
0
  F(cxx_digit_separators)                                                     \
1004
0
  F(cxx_generic_lambdas)                                                      \
1005
0
  F(cxx_lambda_init_captures)                                                 \
1006
0
  F(cxx_relaxed_constexpr)                                                    \
1007
0
  F(cxx_return_type_deduction)                                                \
1008
0
  F(cxx_variable_templates)
1009
1010
#define FOR_EACH_CXX_FEATURE(F)                                               \
1011
0
  F(cxx_std_98)                                                               \
1012
0
  F(cxx_std_11)                                                               \
1013
0
  F(cxx_std_14)                                                               \
1014
0
  F(cxx_std_17)                                                               \
1015
0
  F(cxx_std_20)                                                               \
1016
0
  F(cxx_std_23)                                                               \
1017
0
  F(cxx_std_26)                                                               \
1018
0
  FOR_EACH_CXX98_FEATURE(F)                                                   \
1019
0
  FOR_EACH_CXX11_FEATURE(F)                                                   \
1020
0
  FOR_EACH_CXX14_FEATURE(F)
1021
1022
#define FOR_EACH_CUDA_FEATURE(F)                                              \
1023
0
  F(cuda_std_03)                                                              \
1024
0
  F(cuda_std_11)                                                              \
1025
0
  F(cuda_std_14)                                                              \
1026
0
  F(cuda_std_17)                                                              \
1027
0
  F(cuda_std_20)                                                              \
1028
0
  F(cuda_std_23)                                                              \
1029
0
  F(cuda_std_26)
1030
1031
#define FOR_EACH_HIP_FEATURE(F)                                               \
1032
2
  F(hip_std_98)                                                               \
1033
2
  F(hip_std_11)                                                               \
1034
2
  F(hip_std_14)                                                               \
1035
2
  F(hip_std_17)                                                               \
1036
2
  F(hip_std_20)                                                               \
1037
2
  F(hip_std_23)                                                               \
1038
2
  F(hip_std_26)
1039
1040
#define FOR_EACH_SYCL_FEATURE(F)                                              \
1041
0
  F(sycl_cxx_std_98)                                                          \
1042
0
  F(sycl_cxx_std_11)                                                          \
1043
0
  F(sycl_cxx_std_14)                                                          \
1044
0
  F(sycl_cxx_std_17)                                                          \
1045
0
  F(sycl_cxx_std_20)                                                          \
1046
0
  F(sycl_cxx_std_23)                                                          \
1047
0
  F(sycl_cxx_std_26)                                                          \
1048
0
  FOR_EACH_CXX98_FEATURE(F)                                                   \
1049
0
  FOR_EACH_CXX11_FEATURE(F)                                                   \
1050
0
  FOR_EACH_CXX14_FEATURE(F)