cmTryRunCommand.cxx 21 KB

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