cmTryRunCommand.cxx 12.5 KB
Newer Older
1 2
/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
   file Copyright.txt or https://cmake.org/licensing for details.  */
Ken Martin's avatar
Ken Martin committed
3
#include "cmTryRunCommand.h"
Brad King's avatar
Brad King committed
4

5
#include "cmsys/FStream.hxx"
6 7
#include <stdio.h>

8
#include "cmDuration.h"
9
#include "cmMakefile.h"
10
#include "cmMessageType.h"
11
#include "cmRange.h"
12
#include "cmState.h"
13
#include "cmStateTypes.h"
14
#include "cmStringAlgorithms.h"
15
#include "cmSystemTools.h"
16
#include "cmake.h"
17

18
class cmExecutionStatus;
Ken Martin's avatar
Ken Martin committed
19

20
// cmTryRunCommand
21 22
bool cmTryRunCommand::InitialPass(std::vector<std::string> const& argv,
                                  cmExecutionStatus&)
Ken Martin's avatar
Ken Martin committed
23
{
24
  if (argv.size() < 4) {
Ken Martin's avatar
Ken Martin committed
25
    return false;
26
  }
Ken Martin's avatar
Ken Martin committed
27

28 29 30
  if (this->Makefile->GetCMakeInstance()->GetWorkingMode() ==
      cmake::FIND_PACKAGE_MODE) {
    this->Makefile->IssueMessage(
31
      MessageType::FATAL_ERROR,
32
      "The TRY_RUN() command is not supported in --find-package mode.");
33
    return false;
34
  }
35

36
  // build an arg list for TryCompile and extract the runArgs,
Ken Martin's avatar
Ken Martin committed
37
  std::vector<std::string> tryCompile;
38

39 40 41 42 43
  this->CompileResultVariable.clear();
  this->RunResultVariable.clear();
  this->OutputVariable.clear();
  this->RunOutputVariable.clear();
  this->CompileOutputVariable.clear();
44

Ken Martin's avatar
Ken Martin committed
45
  std::string runArgs;
Ken Martin's avatar
Ken Martin committed
46
  unsigned int i;
47 48
  for (i = 1; i < argv.size(); ++i) {
    if (argv[i] == "ARGS") {
Ken Martin's avatar
Ken Martin committed
49 50
      ++i;
      while (i < argv.size() && argv[i] != "COMPILE_DEFINITIONS" &&
51 52
             argv[i] != "CMAKE_FLAGS" && argv[i] != "LINK_OPTIONS" &&
             argv[i] != "LINK_LIBRARIES") {
Ken Martin's avatar
Ken Martin committed
53 54 55
        runArgs += " ";
        runArgs += argv[i];
        ++i;
56 57
      }
      if (i < argv.size()) {
Ken Martin's avatar
Ken Martin committed
58
        tryCompile.push_back(argv[i]);
59
      }
60 61 62
    } else {
      if (argv[i] == "OUTPUT_VARIABLE") {
        if (argv.size() <= (i + 1)) {
63
          cmSystemTools::Error(
Bill Hoffman's avatar
Bill Hoffman committed
64
            "OUTPUT_VARIABLE specified but there is no variable");
65
          return false;
66
        }
67 68
        i++;
        this->OutputVariable = argv[i];
69 70
      } else if (argv[i] == "RUN_OUTPUT_VARIABLE") {
        if (argv.size() <= (i + 1)) {
71 72 73
          cmSystemTools::Error(
            "RUN_OUTPUT_VARIABLE specified but there is no variable");
          return false;
74
        }
75 76
        i++;
        this->RunOutputVariable = argv[i];
77 78
      } else if (argv[i] == "COMPILE_OUTPUT_VARIABLE") {
        if (argv.size() <= (i + 1)) {
79 80 81
          cmSystemTools::Error(
            "COMPILE_OUTPUT_VARIABLE specified but there is no variable");
          return false;
82
        }
83 84
        i++;
        this->CompileOutputVariable = argv[i];
85
      } else {
86
        tryCompile.push_back(argv[i]);
Ken Martin's avatar
Ken Martin committed
87 88
      }
    }
89
  }
90 91 92

  // although they could be used together, don't allow it, because
  // using OUTPUT_VARIABLE makes crosscompiling harder
93 94 95
  if (!this->OutputVariable.empty() &&
      (!this->RunOutputVariable.empty() ||
       !this->CompileOutputVariable.empty())) {
96 97 98 99 100
    cmSystemTools::Error(
      "You cannot use OUTPUT_VARIABLE together with COMPILE_OUTPUT_VARIABLE "
      "or RUN_OUTPUT_VARIABLE. Please use only COMPILE_OUTPUT_VARIABLE and/or "
      "RUN_OUTPUT_VARIABLE.");
    return false;
101
  }
102 103

  bool captureRunOutput = false;
104
  if (!this->OutputVariable.empty()) {
105
    captureRunOutput = true;
wahikihiki's avatar
wahikihiki committed
106
    tryCompile.emplace_back("OUTPUT_VARIABLE");
107
    tryCompile.push_back(this->OutputVariable);
108 109
  }
  if (!this->CompileOutputVariable.empty()) {
wahikihiki's avatar
wahikihiki committed
110
    tryCompile.emplace_back("OUTPUT_VARIABLE");
111
    tryCompile.push_back(this->CompileOutputVariable);
112 113
  }
  if (!this->RunOutputVariable.empty()) {
114
    captureRunOutput = true;
115
  }
116 117 118 119

  this->RunResultVariable = argv[0];
  this->CompileResultVariable = argv[1];

Ken Martin's avatar
Ken Martin committed
120
  // do the try compile
121
  int res = this->TryCompileCode(tryCompile, true);
122

Ken Martin's avatar
Ken Martin committed
123
  // now try running the command if it compiled
124 125
  if (!res) {
    if (this->OutputFile.empty()) {
126
      cmSystemTools::Error(this->FindErrorMessage);
127
    } else {
128 129
      // "run" it and capture the output
      std::string runOutputContents;
130
      if (this->Makefile->IsOn("CMAKE_CROSSCOMPILING") &&
131
          !this->Makefile->IsDefinitionSet("CMAKE_CROSSCOMPILING_EMULATOR")) {
Daniel Pfeifer's avatar
Daniel Pfeifer committed
132 133
        this->DoNotRunExecutable(
          runArgs, argv[3], captureRunOutput ? &runOutputContents : nullptr);
134
      } else {
135
        this->RunExecutable(runArgs, &runOutputContents);
136
      }
137 138

      // now put the output into the variables
139
      if (!this->RunOutputVariable.empty()) {
Stephen Kelly's avatar
Stephen Kelly committed
140
        this->Makefile->AddDefinition(this->RunOutputVariable,
141
                                      runOutputContents);
142
      }
143

144
      if (!this->OutputVariable.empty()) {
145 146
        // if the TryCompileCore saved output in this outputVariable then
        // prepend that output to this output
147 148 149
        const char* compileOutput =
          this->Makefile->GetDefinition(this->OutputVariable);
        if (compileOutput) {
150
          runOutputContents = compileOutput + runOutputContents;
151
        }
152
        this->Makefile->AddDefinition(this->OutputVariable, runOutputContents);
Ken Martin's avatar
Ken Martin committed
153
      }
154
    }
155
  }
156

157
  // if we created a directory etc, then cleanup after ourselves
158
  if (!this->Makefile->GetCMakeInstance()->GetDebugTryCompile()) {
159
    this->CleanupFiles(this->BinaryDirectory);
160
  }
Ken Martin's avatar
Ken Martin committed
161 162
  return true;
}
163 164 165 166 167

void cmTryRunCommand::RunExecutable(const std::string& runArgs,
                                    std::string* out)
{
  int retVal = -1;
168 169

  std::string finalCommand;
170
  const std::string& emulator =
171 172
    this->Makefile->GetSafeDefinition("CMAKE_CROSSCOMPILING_EMULATOR");
  if (!emulator.empty()) {
173
    std::vector<std::string> emulatorWithArgs;
174
    cmExpandList(emulator, emulatorWithArgs);
175
    finalCommand +=
176
      cmSystemTools::ConvertToRunCommandPath(emulatorWithArgs[0]);
177
    finalCommand += " ";
178
    for (std::string const& arg : cmMakeRange(emulatorWithArgs).advance(1)) {
179
      finalCommand += "\"";
180
      finalCommand += arg;
181 182 183
      finalCommand += "\"";
      finalCommand += " ";
    }
184
  }
185
  finalCommand += cmSystemTools::ConvertToRunCommandPath(this->OutputFile);
186
  if (!runArgs.empty()) {
187
    finalCommand += runArgs;
188
  }
Daniel Pfeifer's avatar
Daniel Pfeifer committed
189
  bool worked = cmSystemTools::RunSingleCommand(
190 191
    finalCommand, out, out, &retVal, nullptr, cmSystemTools::OUTPUT_NONE,
    cmDuration::zero());
192
  // set the run var
193 194
  char retChar[16];
  const char* retStr;
195
  if (worked) {
196
    sprintf(retChar, "%i", retVal);
197
    retStr = retChar;
198
  } else {
199
    retStr = "FAILED_TO_RUN";
200
  }
201
  this->Makefile->AddCacheDefinition(this->RunResultVariable, retStr,
202 203
                                     "Result of TRY_RUN",
                                     cmStateEnums::INTERNAL);
204 205 206 207
}

/* This is only used when cross compiling. Instead of running the
 executable, two cache variables are created which will hold the results
208
 the executable would have produced.
209
*/
210
void cmTryRunCommand::DoNotRunExecutable(const std::string& runArgs,
211 212
                                         const std::string& srcFile,
                                         std::string* out)
213
{
214 215 216
  // copy the executable out of the CMakeFiles/ directory, so it is not
  // removed at the end of TRY_RUN and the user can run it manually
  // on the target platform.
217
  std::string copyDest = this->Makefile->GetHomeOutputDirectory();
218
  copyDest += "/CMakeFiles/";
219
  copyDest += cmSystemTools::GetFilenameWithoutExtension(this->OutputFile);
220 221
  copyDest += "-";
  copyDest += this->RunResultVariable;
Stephen Kelly's avatar
Stephen Kelly committed
222
  copyDest += cmSystemTools::GetFilenameExtension(this->OutputFile);
223
  cmSystemTools::CopyFileAlways(this->OutputFile, copyDest);
224

225
  std::string resultFileName = this->Makefile->GetHomeOutputDirectory();
226 227 228 229
  resultFileName += "/TryRunResults.cmake";

  std::string detailsString = "For details see ";
  detailsString += resultFileName;
230

231 232
  std::string internalRunOutputName =
    this->RunResultVariable + "__TRYRUN_OUTPUT";
233 234
  bool error = false;

235
  if (!this->Makefile->GetDefinition(this->RunResultVariable)) {
236 237 238
    // if the variables doesn't exist, create it with a helpful error text
    // and mark it as advanced
    std::string comment;
239 240 241
    comment += "Run result of TRY_RUN(), indicates whether the executable "
               "would have been able to run on its target platform.\n";
    comment += detailsString;
Stephen Kelly's avatar
Stephen Kelly committed
242
    this->Makefile->AddCacheDefinition(this->RunResultVariable,
243
                                       "PLEASE_FILL_OUT-FAILED_TO_RUN",
244
                                       comment.c_str(), cmStateEnums::STRING);
245

Stephen Kelly's avatar
Stephen Kelly committed
246
    cmState* state = this->Makefile->GetState();
247 248 249
    const char* existingValue =
      state->GetCacheEntryValue(this->RunResultVariable);
    if (existingValue) {
Stephen Kelly's avatar
Stephen Kelly committed
250
      state->SetCacheEntryProperty(this->RunResultVariable, "ADVANCED", "1");
251
    }
252 253

    error = true;
254
  }
255

256
  // is the output from the executable used ?
257 258
  if (out) {
    if (!this->Makefile->GetDefinition(internalRunOutputName)) {
259 260 261
      // if the variables doesn't exist, create it with a helpful error text
      // and mark it as advanced
      std::string comment;
262 263 264
      comment +=
        "Output of TRY_RUN(), contains the text, which the executable "
        "would have printed on stdout and stderr on its target platform.\n";
265
      comment += detailsString;
266

267 268 269
      this->Makefile->AddCacheDefinition(
        internalRunOutputName, "PLEASE_FILL_OUT-NOTFOUND", comment.c_str(),
        cmStateEnums::STRING);
Stephen Kelly's avatar
Stephen Kelly committed
270
      cmState* state = this->Makefile->GetState();
271 272 273 274
      const char* existing = state->GetCacheEntryValue(internalRunOutputName);
      if (existing) {
        state->SetCacheEntryProperty(internalRunOutputName, "ADVANCED", "1");
      }
275 276 277

      error = true;
    }
278
  }
279

280
  if (error) {
281
    static bool firstTryRun = true;
282
    cmsys::ofstream file(resultFileName.c_str(),
283 284 285
                         firstTryRun ? std::ios::out : std::ios::app);
    if (file) {
      if (firstTryRun) {
286
        /* clang-format off */
287 288 289 290 291 292 293
        file << "# This file was generated by CMake because it detected "
                "TRY_RUN() commands\n"
                "# in crosscompiling mode. It will be overwritten by the next "
                "CMake run.\n"
                "# Copy it to a safe location, set the variables to "
                "appropriate values\n"
                "# and use it then to preset the CMake cache (using -C).\n\n";
294
        /* clang-format on */
295
      }
296

297
      std::string comment = "\n";
298
      comment += this->RunResultVariable;
299
      comment += "\n   indicates whether the executable would have been able "
300 301
                 "to run on its\n"
                 "   target platform. If so, set ";
302 303
      comment += this->RunResultVariable;
      comment += " to\n"
304
                 "   the exit code (in many cases 0 for success), otherwise "
305
                 "enter \"FAILED_TO_RUN\".\n";
306
      if (out) {
307
        comment += internalRunOutputName;
308 309 310 311
        comment +=
          "\n   contains the text the executable "
          "would have printed on stdout and stderr.\n"
          "   If the executable would not have been able to run, set ";
312 313
        comment += internalRunOutputName;
        comment += " empty.\n"
314
                   "   Otherwise check if the output is evaluated by the "
315
                   "calling CMake code. If so,\n"
316 317
                   "   check what the source file would have printed when "
                   "called with the given arguments.\n";
318
      }
319 320 321 322 323 324 325 326 327 328
      comment += "The ";
      comment += this->CompileResultVariable;
      comment += " variable holds the build result for this TRY_RUN().\n\n"
                 "Source file   : ";
      comment += srcFile + "\n";
      comment += "Executable    : ";
      comment += copyDest + "\n";
      comment += "Run arguments : ";
      comment += runArgs;
      comment += "\n";
329
      comment += "   Called from: " + this->Makefile->FormatListFileStack();
330 331 332
      cmsys::SystemTools::ReplaceString(comment, "\n", "\n# ");
      file << comment << "\n\n";

333
      file << "set( " << this->RunResultVariable << " \n     \""
Stephen Kelly's avatar
Stephen Kelly committed
334
           << this->Makefile->GetDefinition(this->RunResultVariable)
335
           << "\"\n     CACHE STRING \"Result from TRY_RUN\" FORCE)\n\n";
336

337
      if (out) {
338
        file << "set( " << internalRunOutputName << " \n     \""
Stephen Kelly's avatar
Stephen Kelly committed
339
             << this->Makefile->GetDefinition(internalRunOutputName)
340
             << "\"\n     CACHE STRING \"Output from TRY_RUN\" FORCE)\n\n";
341
      }
342 343
      file.close();
    }
344
    firstTryRun = false;
345

346 347
    std::string errorMessage = "TRY_RUN() invoked in cross-compiling mode, "
                               "please set the following cache variables "
348
                               "appropriately:\n";
349
    errorMessage += "   " + this->RunResultVariable + " (advanced)\n";
350
    if (out) {
351
      errorMessage += "   " + internalRunOutputName + " (advanced)\n";
352
    }
353
    errorMessage += detailsString;
354
    cmSystemTools::Error(errorMessage);
355
    return;
356
  }
357

358
  if (out) {
Stephen Kelly's avatar
Stephen Kelly committed
359
    (*out) = this->Makefile->GetDefinition(internalRunOutputName);
360
  }
361
}