cmTryRunCommand.cxx 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561
  1. /* Distributed under the OSI-approved BSD 3-Clause License. See accompanying
  2. file Copyright.txt or https://cmake.org/licensing for details. */
  3. #include "cmTryRunCommand.h"
  4. #include <cstdio>
  5. #include <stdexcept>
  6. #include <cm/optional>
  7. #include <cmext/string_view>
  8. #include "cmsys/FStream.hxx"
  9. #include "cmArgumentParserTypes.h"
  10. #include "cmConfigureLog.h"
  11. #include "cmCoreTryCompile.h"
  12. #include "cmDuration.h"
  13. #include "cmExecutionStatus.h"
  14. #include "cmMakefile.h"
  15. #include "cmMessageType.h"
  16. #include "cmRange.h"
  17. #include "cmState.h"
  18. #include "cmStateTypes.h"
  19. #include "cmStringAlgorithms.h"
  20. #include "cmSystemTools.h"
  21. #include "cmValue.h"
  22. #include "cmake.h"
  23. namespace {
  24. struct cmTryRunResult
  25. {
  26. bool VariableCached = true;
  27. std::string Variable;
  28. cm::optional<std::string> Stdout;
  29. cm::optional<std::string> Stderr;
  30. cm::optional<std::string> ExitCode;
  31. };
  32. #ifndef CMAKE_BOOTSTRAP
  33. void WriteTryRunEvent(cmConfigureLog& log, cmMakefile const& mf,
  34. cmTryCompileResult const& compileResult,
  35. cmTryRunResult const& runResult)
  36. {
  37. log.BeginEvent("try_run");
  38. log.WriteBacktrace(mf);
  39. cmCoreTryCompile::WriteTryCompileEventFields(log, compileResult);
  40. log.BeginObject("runResult"_s);
  41. log.WriteValue("variable"_s, runResult.Variable);
  42. log.WriteValue("cached"_s, runResult.VariableCached);
  43. if (runResult.Stdout) {
  44. log.WriteLiteralTextBlock("stdout"_s, *runResult.Stdout);
  45. }
  46. if (runResult.Stderr) {
  47. log.WriteLiteralTextBlock("stderr"_s, *runResult.Stderr);
  48. }
  49. if (runResult.ExitCode) {
  50. try {
  51. log.WriteValue("exitCode"_s, std::stoi(*runResult.ExitCode));
  52. } catch (std::invalid_argument const&) {
  53. log.WriteValue("exitCode"_s, *runResult.ExitCode);
  54. }
  55. }
  56. log.EndObject();
  57. log.EndEvent();
  58. }
  59. #endif
  60. class TryRunCommandImpl : public cmCoreTryCompile
  61. {
  62. public:
  63. TryRunCommandImpl(cmMakefile* mf)
  64. : cmCoreTryCompile(mf)
  65. {
  66. }
  67. bool TryRunCode(std::vector<std::string> const& args);
  68. void RunExecutable(const std::string& runArgs,
  69. cm::optional<std::string> const& workDir,
  70. std::string* runOutputContents,
  71. std::string* runOutputStdOutContents,
  72. std::string* runOutputStdErrContents);
  73. void DoNotRunExecutable(const std::string& runArgs,
  74. const std::string& srcFile,
  75. std::string const& compileResultVariable,
  76. std::string* runOutputContents,
  77. std::string* runOutputStdOutContents,
  78. std::string* runOutputStdErrContents);
  79. bool NoCache;
  80. std::string RunResultVariable;
  81. };
  82. bool TryRunCommandImpl::TryRunCode(std::vector<std::string> const& argv)
  83. {
  84. this->RunResultVariable = argv[0];
  85. cmCoreTryCompile::Arguments arguments =
  86. this->ParseArgs(cmMakeRange(argv).advance(1), true);
  87. if (!arguments) {
  88. return true;
  89. }
  90. this->NoCache = arguments.NoCache;
  91. // although they could be used together, don't allow it, because
  92. // using OUTPUT_VARIABLE makes crosscompiling harder
  93. if (arguments.OutputVariable &&
  94. (arguments.CompileOutputVariable || arguments.RunOutputVariable ||
  95. arguments.RunOutputStdOutVariable ||
  96. arguments.RunOutputStdErrVariable)) {
  97. cmSystemTools::Error(
  98. "You cannot use OUTPUT_VARIABLE together with COMPILE_OUTPUT_VARIABLE "
  99. ", RUN_OUTPUT_VARIABLE, RUN_OUTPUT_STDOUT_VARIABLE or "
  100. "RUN_OUTPUT_STDERR_VARIABLE. "
  101. "Please use only COMPILE_OUTPUT_VARIABLE, RUN_OUTPUT_VARIABLE, "
  102. "RUN_OUTPUT_STDOUT_VARIABLE "
  103. "and/or RUN_OUTPUT_STDERR_VARIABLE.");
  104. return false;
  105. }
  106. if ((arguments.RunOutputStdOutVariable ||
  107. arguments.RunOutputStdErrVariable) &&
  108. arguments.RunOutputVariable) {
  109. cmSystemTools::Error(
  110. "You cannot use RUN_OUTPUT_STDOUT_VARIABLE or "
  111. "RUN_OUTPUT_STDERR_VARIABLE together "
  112. "with RUN_OUTPUT_VARIABLE. Please use only COMPILE_OUTPUT_VARIABLE or "
  113. "RUN_OUTPUT_STDOUT_VARIABLE and/or RUN_OUTPUT_STDERR_VARIABLE.");
  114. return false;
  115. }
  116. if (arguments.RunWorkingDirectory) {
  117. if (!cmSystemTools::MakeDirectory(*arguments.RunWorkingDirectory)) {
  118. cmSystemTools::Error(cmStrCat("Error creating working directory \"",
  119. *arguments.RunWorkingDirectory, "\"."));
  120. return false;
  121. }
  122. }
  123. bool captureRunOutput = false;
  124. if (arguments.OutputVariable) {
  125. captureRunOutput = true;
  126. } else if (arguments.CompileOutputVariable) {
  127. arguments.OutputVariable = arguments.CompileOutputVariable;
  128. }
  129. // Capture the split output for the configure log unless the caller
  130. // requests combined output to be captured by a variable.
  131. bool captureRunOutputStdOutErr = true;
  132. if (!arguments.RunOutputStdOutVariable &&
  133. !arguments.RunOutputStdErrVariable) {
  134. if (arguments.RunOutputVariable) {
  135. captureRunOutput = true;
  136. captureRunOutputStdOutErr = false;
  137. } else if (arguments.OutputVariable) {
  138. captureRunOutputStdOutErr = false;
  139. }
  140. }
  141. // do the try compile
  142. cm::optional<cmTryCompileResult> compileResult =
  143. this->TryCompileCode(arguments, cmStateEnums::EXECUTABLE);
  144. cmTryRunResult runResult;
  145. runResult.Variable = this->RunResultVariable;
  146. runResult.VariableCached = !arguments.NoCache;
  147. // now try running the command if it compiled
  148. if (compileResult && compileResult->ExitCode == 0) {
  149. if (this->OutputFile.empty()) {
  150. cmSystemTools::Error(this->FindErrorMessage);
  151. } else {
  152. std::string runArgs;
  153. if (arguments.RunArgs) {
  154. runArgs = cmStrCat(" ", cmJoin(*arguments.RunArgs, " "));
  155. }
  156. // "run" it and capture the output
  157. std::string runOutputContents;
  158. std::string runOutputStdOutContents;
  159. std::string runOutputStdErrContents;
  160. if (this->Makefile->IsOn("CMAKE_CROSSCOMPILING") &&
  161. !this->Makefile->IsDefinitionSet("CMAKE_CROSSCOMPILING_EMULATOR")) {
  162. this->DoNotRunExecutable(
  163. runArgs, *arguments.SourceDirectoryOrFile,
  164. *arguments.CompileResultVariable,
  165. captureRunOutput ? &runOutputContents : nullptr,
  166. captureRunOutputStdOutErr ? &runOutputStdOutContents : nullptr,
  167. captureRunOutputStdOutErr ? &runOutputStdErrContents : nullptr);
  168. } else {
  169. this->RunExecutable(
  170. runArgs, arguments.RunWorkingDirectory,
  171. captureRunOutput ? &runOutputContents : nullptr,
  172. captureRunOutputStdOutErr ? &runOutputStdOutContents : nullptr,
  173. captureRunOutputStdOutErr ? &runOutputStdErrContents : nullptr);
  174. }
  175. if (captureRunOutputStdOutErr) {
  176. runResult.Stdout = runOutputStdOutContents;
  177. runResult.Stderr = runOutputStdErrContents;
  178. } else {
  179. runResult.Stdout = runOutputContents;
  180. }
  181. if (cmValue ec =
  182. this->Makefile->GetDefinition(this->RunResultVariable)) {
  183. runResult.ExitCode = *ec;
  184. }
  185. // now put the output into the variables
  186. if (arguments.RunOutputVariable) {
  187. this->Makefile->AddDefinition(*arguments.RunOutputVariable,
  188. runOutputContents);
  189. }
  190. if (arguments.RunOutputStdOutVariable) {
  191. this->Makefile->AddDefinition(*arguments.RunOutputStdOutVariable,
  192. runOutputStdOutContents);
  193. }
  194. if (arguments.RunOutputStdErrVariable) {
  195. this->Makefile->AddDefinition(*arguments.RunOutputStdErrVariable,
  196. runOutputStdErrContents);
  197. }
  198. if (arguments.OutputVariable && !arguments.CompileOutputVariable) {
  199. // if the TryCompileCore saved output in this outputVariable then
  200. // prepend that output to this output
  201. cmValue compileOutput =
  202. this->Makefile->GetDefinition(*arguments.OutputVariable);
  203. if (compileOutput) {
  204. runOutputContents = *compileOutput + runOutputContents;
  205. }
  206. this->Makefile->AddDefinition(*arguments.OutputVariable,
  207. runOutputContents);
  208. }
  209. }
  210. }
  211. #ifndef CMAKE_BOOTSTRAP
  212. if (compileResult) {
  213. cmMakefile const& mf = *(this->Makefile);
  214. if (cmConfigureLog* log = mf.GetCMakeInstance()->GetConfigureLog()) {
  215. WriteTryRunEvent(*log, mf, *compileResult, runResult);
  216. }
  217. }
  218. #endif
  219. // if we created a directory etc, then cleanup after ourselves
  220. if (!this->Makefile->GetCMakeInstance()->GetDebugTryCompile()) {
  221. this->CleanupFiles(this->BinaryDirectory);
  222. }
  223. return true;
  224. }
  225. void TryRunCommandImpl::RunExecutable(const std::string& runArgs,
  226. cm::optional<std::string> const& workDir,
  227. std::string* out, std::string* stdOut,
  228. std::string* stdErr)
  229. {
  230. int retVal = -1;
  231. std::string finalCommand;
  232. const std::string& emulator =
  233. this->Makefile->GetSafeDefinition("CMAKE_CROSSCOMPILING_EMULATOR");
  234. if (!emulator.empty()) {
  235. std::vector<std::string> emulatorWithArgs = cmExpandedList(emulator);
  236. finalCommand +=
  237. cmSystemTools::ConvertToRunCommandPath(emulatorWithArgs[0]);
  238. finalCommand += " ";
  239. for (std::string const& arg : cmMakeRange(emulatorWithArgs).advance(1)) {
  240. finalCommand += "\"";
  241. finalCommand += arg;
  242. finalCommand += "\"";
  243. finalCommand += " ";
  244. }
  245. }
  246. finalCommand += cmSystemTools::ConvertToRunCommandPath(this->OutputFile);
  247. if (!runArgs.empty()) {
  248. finalCommand += runArgs;
  249. }
  250. bool worked = cmSystemTools::RunSingleCommand(
  251. finalCommand, stdOut || stdErr ? stdOut : out,
  252. stdOut || stdErr ? stdErr : out, &retVal,
  253. workDir ? workDir->c_str() : nullptr, cmSystemTools::OUTPUT_NONE,
  254. cmDuration::zero());
  255. // set the run var
  256. char retChar[16];
  257. const char* retStr;
  258. if (worked) {
  259. snprintf(retChar, sizeof(retChar), "%i", retVal);
  260. retStr = retChar;
  261. } else {
  262. retStr = "FAILED_TO_RUN";
  263. }
  264. if (this->NoCache) {
  265. this->Makefile->AddDefinition(this->RunResultVariable, retStr);
  266. } else {
  267. this->Makefile->AddCacheDefinition(this->RunResultVariable, retStr,
  268. "Result of try_run()",
  269. cmStateEnums::INTERNAL);
  270. }
  271. }
  272. /* This is only used when cross compiling. Instead of running the
  273. executable, two cache variables are created which will hold the results
  274. the executable would have produced.
  275. */
  276. void TryRunCommandImpl::DoNotRunExecutable(
  277. const std::string& runArgs, const std::string& srcFile,
  278. std::string const& compileResultVariable, std::string* out,
  279. std::string* stdOut, std::string* stdErr)
  280. {
  281. // copy the executable out of the CMakeFiles/ directory, so it is not
  282. // removed at the end of try_run() and the user can run it manually
  283. // on the target platform.
  284. std::string copyDest =
  285. cmStrCat(this->Makefile->GetHomeOutputDirectory(), "/CMakeFiles/",
  286. cmSystemTools::GetFilenameWithoutExtension(this->OutputFile), '-',
  287. this->RunResultVariable,
  288. cmSystemTools::GetFilenameExtension(this->OutputFile));
  289. cmSystemTools::CopyFileAlways(this->OutputFile, copyDest);
  290. std::string resultFileName =
  291. cmStrCat(this->Makefile->GetHomeOutputDirectory(), "/TryRunResults.cmake");
  292. std::string detailsString = cmStrCat("For details see ", resultFileName);
  293. std::string internalRunOutputName =
  294. this->RunResultVariable + "__TRYRUN_OUTPUT";
  295. std::string internalRunOutputStdOutName =
  296. this->RunResultVariable + "__TRYRUN_OUTPUT_STDOUT";
  297. std::string internalRunOutputStdErrName =
  298. this->RunResultVariable + "__TRYRUN_OUTPUT_STDERR";
  299. bool error = false;
  300. if (!this->Makefile->GetDefinition(this->RunResultVariable)) {
  301. // if the variables doesn't exist, create it with a helpful error text
  302. // and mark it as advanced
  303. std::string comment =
  304. cmStrCat("Run result of try_run(), indicates whether the executable "
  305. "would have been able to run on its target platform.\n",
  306. detailsString);
  307. this->Makefile->AddCacheDefinition(this->RunResultVariable,
  308. "PLEASE_FILL_OUT-FAILED_TO_RUN",
  309. comment.c_str(), cmStateEnums::STRING);
  310. cmState* state = this->Makefile->GetState();
  311. cmValue existingValue = state->GetCacheEntryValue(this->RunResultVariable);
  312. if (existingValue) {
  313. state->SetCacheEntryProperty(this->RunResultVariable, "ADVANCED", "1");
  314. }
  315. error = true;
  316. }
  317. // is the output from the executable used ?
  318. if (stdOut || stdErr) {
  319. if (!this->Makefile->GetDefinition(internalRunOutputStdOutName)) {
  320. // if the variables doesn't exist, create it with a helpful error text
  321. // and mark it as advanced
  322. std::string comment = cmStrCat(
  323. "Output of try_run(), contains the text, which the executable "
  324. "would have printed on stdout on its target platform.\n",
  325. detailsString);
  326. this->Makefile->AddCacheDefinition(
  327. internalRunOutputStdOutName, "PLEASE_FILL_OUT-NOTFOUND",
  328. comment.c_str(), cmStateEnums::STRING);
  329. cmState* state = this->Makefile->GetState();
  330. cmValue existing =
  331. state->GetCacheEntryValue(internalRunOutputStdOutName);
  332. if (existing) {
  333. state->SetCacheEntryProperty(internalRunOutputStdOutName, "ADVANCED",
  334. "1");
  335. }
  336. error = true;
  337. }
  338. if (!this->Makefile->GetDefinition(internalRunOutputStdErrName)) {
  339. // if the variables doesn't exist, create it with a helpful error text
  340. // and mark it as advanced
  341. std::string comment = cmStrCat(
  342. "Output of try_run(), contains the text, which the executable "
  343. "would have printed on stderr on its target platform.\n",
  344. detailsString);
  345. this->Makefile->AddCacheDefinition(
  346. internalRunOutputStdErrName, "PLEASE_FILL_OUT-NOTFOUND",
  347. comment.c_str(), cmStateEnums::STRING);
  348. cmState* state = this->Makefile->GetState();
  349. cmValue existing =
  350. state->GetCacheEntryValue(internalRunOutputStdErrName);
  351. if (existing) {
  352. state->SetCacheEntryProperty(internalRunOutputStdErrName, "ADVANCED",
  353. "1");
  354. }
  355. error = true;
  356. }
  357. } else if (out) {
  358. if (!this->Makefile->GetDefinition(internalRunOutputName)) {
  359. // if the variables doesn't exist, create it with a helpful error text
  360. // and mark it as advanced
  361. std::string comment = cmStrCat(
  362. "Output of try_run(), contains the text, which the executable "
  363. "would have printed on stdout and stderr on its target platform.\n",
  364. detailsString);
  365. this->Makefile->AddCacheDefinition(
  366. internalRunOutputName, "PLEASE_FILL_OUT-NOTFOUND", comment.c_str(),
  367. cmStateEnums::STRING);
  368. cmState* state = this->Makefile->GetState();
  369. cmValue existing = state->GetCacheEntryValue(internalRunOutputName);
  370. if (existing) {
  371. state->SetCacheEntryProperty(internalRunOutputName, "ADVANCED", "1");
  372. }
  373. error = true;
  374. }
  375. }
  376. if (error) {
  377. static bool firstTryRun = true;
  378. cmsys::ofstream file(resultFileName.c_str(),
  379. firstTryRun ? std::ios::out : std::ios::app);
  380. if (file) {
  381. if (firstTryRun) {
  382. /* clang-format off */
  383. file << "# This file was generated by CMake because it detected "
  384. "try_run() commands\n"
  385. "# in crosscompiling mode. It will be overwritten by the next "
  386. "CMake run.\n"
  387. "# Copy it to a safe location, set the variables to "
  388. "appropriate values\n"
  389. "# and use it then to preset the CMake cache (using -C).\n\n";
  390. /* clang-format on */
  391. }
  392. std::string comment =
  393. cmStrCat('\n', this->RunResultVariable,
  394. "\n indicates whether the executable would have been able "
  395. "to run on its\n"
  396. " target platform. If so, set ",
  397. this->RunResultVariable,
  398. " to\n"
  399. " the exit code (in many cases 0 for success), otherwise "
  400. "enter \"FAILED_TO_RUN\".\n");
  401. if (stdOut || stdErr) {
  402. if (stdOut) {
  403. comment += internalRunOutputStdOutName;
  404. comment +=
  405. "\n contains the text the executable "
  406. "would have printed on stdout.\n"
  407. " If the executable would not have been able to run, set ";
  408. comment += internalRunOutputStdOutName;
  409. comment += " empty.\n"
  410. " Otherwise check if the output is evaluated by the "
  411. "calling CMake code. If so,\n"
  412. " check what the source file would have printed when "
  413. "called with the given arguments.\n";
  414. }
  415. if (stdErr) {
  416. comment += internalRunOutputStdErrName;
  417. comment +=
  418. "\n contains the text the executable "
  419. "would have printed on stderr.\n"
  420. " If the executable would not have been able to run, set ";
  421. comment += internalRunOutputStdErrName;
  422. comment += " empty.\n"
  423. " Otherwise check if the output is evaluated by the "
  424. "calling CMake code. If so,\n"
  425. " check what the source file would have printed when "
  426. "called with the given arguments.\n";
  427. }
  428. } else if (out) {
  429. comment += internalRunOutputName;
  430. comment +=
  431. "\n contains the text the executable "
  432. "would have printed on stdout and stderr.\n"
  433. " If the executable would not have been able to run, set ";
  434. comment += internalRunOutputName;
  435. comment += " empty.\n"
  436. " Otherwise check if the output is evaluated by the "
  437. "calling CMake code. If so,\n"
  438. " check what the source file would have printed when "
  439. "called with the given arguments.\n";
  440. }
  441. comment += "The ";
  442. comment += compileResultVariable;
  443. comment += " variable holds the build result for this try_run().\n\n"
  444. "Source file : ";
  445. comment += srcFile + "\n";
  446. comment += "Executable : ";
  447. comment += copyDest + "\n";
  448. comment += "Run arguments : ";
  449. comment += runArgs;
  450. comment += "\n";
  451. comment += " Called from: " + this->Makefile->FormatListFileStack();
  452. cmsys::SystemTools::ReplaceString(comment, "\n", "\n# ");
  453. file << comment << "\n\n";
  454. file << "set( " << this->RunResultVariable << " \n \""
  455. << this->Makefile->GetSafeDefinition(this->RunResultVariable)
  456. << "\"\n CACHE STRING \"Result from try_run\" FORCE)\n\n";
  457. if (out) {
  458. file << "set( " << internalRunOutputName << " \n \""
  459. << this->Makefile->GetSafeDefinition(internalRunOutputName)
  460. << "\"\n CACHE STRING \"Output from try_run\" FORCE)\n\n";
  461. }
  462. file.close();
  463. }
  464. firstTryRun = false;
  465. std::string errorMessage =
  466. cmStrCat("try_run() invoked in cross-compiling mode, "
  467. "please set the following cache variables "
  468. "appropriately:\n ",
  469. this->RunResultVariable, " (advanced)\n");
  470. if (out) {
  471. errorMessage += " " + internalRunOutputName + " (advanced)\n";
  472. }
  473. errorMessage += detailsString;
  474. cmSystemTools::Error(errorMessage);
  475. return;
  476. }
  477. if (stdOut || stdErr) {
  478. if (stdOut) {
  479. (*stdOut) = *this->Makefile->GetDefinition(internalRunOutputStdOutName);
  480. }
  481. if (stdErr) {
  482. (*stdErr) = *this->Makefile->GetDefinition(internalRunOutputStdErrName);
  483. }
  484. } else if (out) {
  485. (*out) = *this->Makefile->GetDefinition(internalRunOutputName);
  486. }
  487. }
  488. }
  489. bool cmTryRunCommand(std::vector<std::string> const& args,
  490. cmExecutionStatus& status)
  491. {
  492. cmMakefile& mf = status.GetMakefile();
  493. if (args.size() < 4) {
  494. mf.IssueMessage(MessageType::FATAL_ERROR,
  495. "The try_run() command requires at least 4 arguments.");
  496. return false;
  497. }
  498. if (mf.GetCMakeInstance()->GetWorkingMode() == cmake::FIND_PACKAGE_MODE) {
  499. mf.IssueMessage(
  500. MessageType::FATAL_ERROR,
  501. "The try_run() command is not supported in --find-package mode.");
  502. return false;
  503. }
  504. TryRunCommandImpl tr(&mf);
  505. return tr.TryRunCode(args);
  506. }