Coverage Report

Created: 2026-06-15 07:03

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/CMake/Source/cmMacroCommand.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 "cmMacroCommand.h"
4
5
#include <functional>
6
#include <utility>
7
8
#include <cm/memory>
9
#include <cm/string_view>
10
#include <cmext/algorithm>
11
#include <cmext/string_view>
12
13
#include "cmDiagnostics.h"
14
#include "cmExecutionStatus.h"
15
#include "cmFunctionBlocker.h"
16
#include "cmList.h"
17
#include "cmListFileCache.h"
18
#include "cmMakefile.h"
19
#include "cmPolicies.h"
20
#include "cmRange.h"
21
#include "cmState.h"
22
#include "cmStateTypes.h"
23
#include "cmStringAlgorithms.h"
24
#include "cmSystemTools.h"
25
26
namespace {
27
28
// define the class for macro commands
29
class cmMacroHelperCommand
30
{
31
public:
32
  /**
33
   * This is called when the command is first encountered in
34
   * the CMakeLists.txt file.
35
   */
36
  bool operator()(std::vector<cmListFileArgument> const& args,
37
                  cmExecutionStatus& inStatus) const;
38
39
  std::vector<std::string> Args;
40
  std::vector<cmListFileFunction> Functions;
41
  cmPolicies::PolicyMap Policies;
42
  cmDiagnostics::DiagnosticMap Diagnostics;
43
  std::string FilePath;
44
};
45
46
bool cmMacroHelperCommand::operator()(
47
  std::vector<cmListFileArgument> const& args,
48
  cmExecutionStatus& inStatus) const
49
0
{
50
0
  cmMakefile& makefile = inStatus.GetMakefile();
51
52
  // Expand the argument list to the macro.
53
0
  std::vector<std::string> expandedArgs;
54
0
  makefile.ExpandArguments(args, expandedArgs);
55
56
  // make sure the number of arguments passed is at least the number
57
  // required by the signature
58
0
  if (expandedArgs.size() < this->Args.size() - 1) {
59
0
    std::string errorMsg =
60
0
      cmStrCat("Macro invoked with incorrect arguments for macro named: ",
61
0
               this->Args[0]);
62
0
    inStatus.SetError(errorMsg);
63
0
    return false;
64
0
  }
65
66
  // set the value of argc
67
0
  std::string argcDef = std::to_string(expandedArgs.size());
68
69
0
  auto expIt = expandedArgs.begin() + (this->Args.size() - 1);
70
0
  std::string expandedArgn =
71
0
    cmList::to_string(cmMakeRange(expIt, expandedArgs.end()));
72
0
  std::string expandedArgv = cmList::to_string(expandedArgs);
73
0
  {
74
0
    cmPolicies::PolicyStatus cmp0219 =
75
0
      makefile.CheckCMP0219(this->Args[0], expandedArgs);
76
0
    if (cmp0219 == cmPolicies::NEW) {
77
      // Escape macro argument backslashes so that callees receive the same
78
      // values the caller had.
79
0
      for (std::string& expandedArg : expandedArgs) {
80
0
        cmSystemTools::ReplaceString(expandedArg, "\\", "\\\\");
81
0
      }
82
0
      cmSystemTools::ReplaceString(expandedArgn, "\\", "\\\\");
83
0
      cmSystemTools::ReplaceString(expandedArgv, "\\", "\\\\");
84
0
    } else if (cmp0219 == cmPolicies::WARN) {
85
0
      makefile.IssueCMP0219Warning(this->Args[0], expandedArgs);
86
0
    }
87
0
  }
88
0
  std::vector<std::string> variables;
89
0
  variables.reserve(this->Args.size() - 1);
90
0
  for (unsigned int j = 1; j < this->Args.size(); ++j) {
91
0
    variables.emplace_back(cmStrCat("${", this->Args[j], '}'));
92
0
  }
93
0
  std::vector<std::string> argVs;
94
0
  argVs.reserve(expandedArgs.size());
95
0
  for (unsigned int j = 0; j < expandedArgs.size(); ++j) {
96
0
    argVs.emplace_back(cmStrCat("${ARGV", j, '}'));
97
0
  }
98
99
0
  cmMakefile::MacroPushPop macroScope(&makefile, this->FilePath,
100
0
                                      this->Policies, this->Diagnostics);
101
102
  // Invoke all the functions that were collected in the block.
103
  // for each function
104
0
  for (cmListFileFunction const& func : this->Functions) {
105
    // Replace the formal arguments and then invoke the command.
106
0
    std::vector<cmListFileArgument> newLFFArgs;
107
0
    newLFFArgs.reserve(func.Arguments().size());
108
109
    // for each argument of the current function
110
0
    for (cmListFileArgument const& k : func.Arguments()) {
111
0
      cmListFileArgument arg;
112
0
      arg.Value = k.Value;
113
0
      if (k.Delim != cmListFileArgument::Bracket) {
114
        // replace formal arguments
115
0
        for (unsigned int j = 0; j < variables.size(); ++j) {
116
0
          cmSystemTools::ReplaceString(arg.Value, variables[j],
117
0
                                       expandedArgs[j]);
118
0
        }
119
        // replace argc
120
0
        cmSystemTools::ReplaceString(arg.Value, "${ARGC}", argcDef);
121
122
0
        cmSystemTools::ReplaceString(arg.Value, "${ARGN}", expandedArgn);
123
0
        cmSystemTools::ReplaceString(arg.Value, "${ARGV}", expandedArgv);
124
125
        // if the current argument of the current function has ${ARGV in it
126
        // then try replacing ARGV values
127
0
        if (arg.Value.find("${ARGV") != std::string::npos) {
128
0
          for (unsigned int t = 0; t < expandedArgs.size(); ++t) {
129
0
            cmSystemTools::ReplaceString(arg.Value, argVs[t], expandedArgs[t]);
130
0
          }
131
0
        }
132
0
      }
133
0
      arg.Delim = k.Delim;
134
0
      arg.Line = k.Line;
135
0
      newLFFArgs.push_back(std::move(arg));
136
0
    }
137
0
    cmListFileFunction newLFF{ func.OriginalName(), func.Line(),
138
0
                               func.LineEnd(), std::move(newLFFArgs) };
139
0
    cmExecutionStatus status(makefile);
140
0
    if (!makefile.ExecuteCommand(newLFF, status) || status.GetNestedError()) {
141
      // The error message should have already included the call stack
142
      // so we do not need to report an error here.
143
0
      macroScope.Quiet();
144
0
      inStatus.SetNestedError();
145
0
      return false;
146
0
    }
147
0
    if (status.GetReturnInvoked()) {
148
0
      inStatus.SetReturnInvoked(status.GetReturnVariables());
149
0
      return true;
150
0
    }
151
0
    if (status.GetBreakInvoked()) {
152
0
      inStatus.SetBreakInvoked();
153
0
      return true;
154
0
    }
155
0
    if (status.GetContinueInvoked()) {
156
0
      inStatus.SetContinueInvoked();
157
0
      return true;
158
0
    }
159
0
    if (status.HasExitCode()) {
160
0
      inStatus.SetExitCode(status.GetExitCode());
161
0
      return true;
162
0
    }
163
0
  }
164
0
  return true;
165
0
}
166
167
class cmMacroFunctionBlocker : public cmFunctionBlocker
168
{
169
public:
170
0
  cm::string_view StartCommandName() const override { return "macro"_s; }
171
0
  cm::string_view EndCommandName() const override { return "endmacro"_s; }
172
173
  bool ArgumentsMatch(cmListFileFunction const&,
174
                      cmMakefile& mf) const override;
175
176
  bool Replay(std::vector<cmListFileFunction> functions,
177
              cmExecutionStatus& status) override;
178
179
  std::vector<std::string> Args;
180
};
181
182
bool cmMacroFunctionBlocker::ArgumentsMatch(cmListFileFunction const& lff,
183
                                            cmMakefile& mf) const
184
0
{
185
0
  std::vector<std::string> expandedArguments;
186
0
  mf.ExpandArguments(lff.Arguments(), expandedArguments);
187
0
  return expandedArguments.empty() || expandedArguments[0] == this->Args[0];
188
0
}
189
190
bool cmMacroFunctionBlocker::Replay(std::vector<cmListFileFunction> functions,
191
                                    cmExecutionStatus& status)
192
0
{
193
0
  cmMakefile& mf = status.GetMakefile();
194
0
  if (status.GetMakefile().GetPolicyStatus(cmPolicies::CMP0217) !=
195
0
      cmPolicies::NEW) {
196
197
0
    mf.AppendProperty("MACROS", this->Args[0]);
198
0
  }
199
  // create a new command and add it to cmake
200
0
  cmMacroHelperCommand f;
201
0
  f.Args = this->Args;
202
0
  f.Functions = std::move(functions);
203
0
  f.FilePath = this->GetStartingContext().FilePath;
204
0
  mf.RecordPolicies(f.Policies);
205
0
  mf.RecordDiagnostics(f.Diagnostics);
206
0
  return mf.GetState()->AddScriptedCommand(
207
0
    this->Args[0], cmStateEnums::CommandType::Macro,
208
0
    BT<cmState::Command>(std::move(f),
209
0
                         mf.GetBacktrace().Push(this->GetStartingContext())),
210
0
    mf);
211
0
}
212
}
213
214
bool cmMacroCommand(std::vector<std::string> const& args,
215
                    cmExecutionStatus& status)
216
0
{
217
0
  if (args.empty()) {
218
0
    status.SetError("called with incorrect number of arguments");
219
0
    return false;
220
0
  }
221
222
  // create a function blocker
223
0
  {
224
0
    auto fb = cm::make_unique<cmMacroFunctionBlocker>();
225
0
    cm::append(fb->Args, args);
226
0
    status.GetMakefile().AddFunctionBlocker(std::move(fb));
227
0
  }
228
0
  return true;
229
0
}