cmTryRunCommand.cxx 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566
  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. // 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");
  41. log.WriteBacktrace(mf);
  42. cmCoreTryCompile::WriteTryCompileEventFields(log, compileResult);
  43. log.BeginObject("runResult"_s);
  44. log.WriteValue("variable"_s, runResult.Variable);
  45. log.WriteValue("cached"_s, runResult.VariableCached);
  46. if (runResult.Stdout) {
  47. log.WriteLiteralTextBlock("stdout"_s, *runResult.Stdout);
  48. }
  49. if (runResult.Stderr) {
  50. log.WriteLiteralTextBlock("stderr"_s, *runResult.Stderr);
  51. }
  52. if (runResult.ExitCode) {
  53. try {
  54. log.WriteValue("exitCode"_s, std::stoi(*runResult.ExitCode));
  55. } catch (std::invalid_argument const&) {
  56. log.WriteValue("exitCode"_s, *runResult.ExitCode);
  57. }
  58. }
  59. log.EndObject();
  60. log.EndEvent();
  61. }
  62. }
  63. #endif
  64. class TryRunCommandImpl : public cmCoreTryCompile
  65. {
  66. public:
  67. TryRunCommandImpl(cmMakefile* mf)
  68. : cmCoreTryCompile(mf)
  69. {
  70. }
  71. bool TryRunCode(std::vector<std::string> const& args);
  72. void RunExecutable(const std::string& runArgs,
  73. cm::optional<std::string> const& workDir,
  74. std::string* runOutputContents,
  75. std::string* runOutputStdOutContents,
  76. std::string* runOutputStdErrContents);
  77. void DoNotRunExecutable(const std::string& runArgs,
  78. const std::string& srcFile,
  79. std::string const& compileResultVariable,
  80. std::string* runOutputContents,
  81. std::string* runOutputStdOutContents,
  82. std::string* runOutputStdErrContents);
  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. this->DoNotRunExecutable(
  167. runArgs, *arguments.SourceDirectoryOrFile,
  168. *arguments.CompileResultVariable,
  169. captureRunOutput ? &runOutputContents : nullptr,
  170. captureRunOutputStdOutErr ? &runOutputStdOutContents : nullptr,
  171. captureRunOutputStdOutErr ? &runOutputStdErrContents : nullptr);
  172. } else {
  173. this->RunExecutable(
  174. runArgs, arguments.RunWorkingDirectory,
  175. captureRunOutput ? &runOutputContents : nullptr,
  176. captureRunOutputStdOutErr ? &runOutputStdOutContents : nullptr,
  177. captureRunOutputStdOutErr ? &runOutputStdErrContents : nullptr);
  178. }
  179. if (captureRunOutputStdOutErr) {
  180. runResult.Stdout = runOutputStdOutContents;
  181. runResult.Stderr = runOutputStdErrContents;
  182. } else {
  183. runResult.Stdout = runOutputContents;
  184. }
  185. if (cmValue ec =
  186. this->Makefile->GetDefinition(this->RunResultVariable)) {
  187. runResult.ExitCode = *ec;
  188. }
  189. // now put the output into the variables
  190. if (arguments.RunOutputVariable) {
  191. this->Makefile->AddDefinition(*arguments.RunOutputVariable,
  192. runOutputContents);
  193. }
  194. if (arguments.RunOutputStdOutVariable) {
  195. this->Makefile->AddDefinition(*arguments.RunOutputStdOutVariable,
  196. runOutputStdOutContents);
  197. }
  198. if (arguments.RunOutputStdErrVariable) {
  199. this->Makefile->AddDefinition(*arguments.RunOutputStdErrVariable,
  200. runOutputStdErrContents);
  201. }
  202. if (arguments.OutputVariable && !arguments.CompileOutputVariable) {
  203. // if the TryCompileCore saved output in this outputVariable then
  204. // prepend that output to this output
  205. cmValue compileOutput =
  206. this->Makefile->GetDefinition(*arguments.OutputVariable);
  207. if (compileOutput) {
  208. runOutputContents = *compileOutput + runOutputContents;
  209. }
  210. this->Makefile->AddDefinition(*arguments.OutputVariable,
  211. runOutputContents);
  212. }
  213. }
  214. }
  215. #ifndef CMAKE_BOOTSTRAP
  216. if (compileResult) {
  217. cmMakefile const& mf = *(this->Makefile);
  218. if (cmConfigureLog* log = mf.GetCMakeInstance()->GetConfigureLog()) {
  219. WriteTryRunEvent(*log, mf, *compileResult, runResult);
  220. }
  221. }
  222. #endif
  223. // if we created a directory etc, then cleanup after ourselves
  224. if (!this->Makefile->GetCMakeInstance()->GetDebugTryCompile()) {
  225. this->CleanupFiles(this->BinaryDirectory);
  226. }
  227. return true;
  228. }
  229. void TryRunCommandImpl::RunExecutable(const std::string& runArgs,
  230. cm::optional<std::string> const& workDir,
  231. std::string* out, std::string* stdOut,
  232. std::string* stdErr)
  233. {
  234. int retVal = -1;
  235. std::string finalCommand;
  236. const std::string& emulator =
  237. this->Makefile->GetSafeDefinition("CMAKE_CROSSCOMPILING_EMULATOR");
  238. if (!emulator.empty()) {
  239. std::vector<std::string> emulatorWithArgs = cmExpandedList(emulator);
  240. finalCommand +=
  241. cmSystemTools::ConvertToRunCommandPath(emulatorWithArgs[0]);
  242. finalCommand += " ";
  243. for (std::string const& arg : cmMakeRange(emulatorWithArgs).advance(1)) {
  244. finalCommand += "\"";
  245. finalCommand += arg;
  246. finalCommand += "\"";
  247. finalCommand += " ";
  248. }
  249. }
  250. finalCommand += cmSystemTools::ConvertToRunCommandPath(this->OutputFile);
  251. if (!runArgs.empty()) {
  252. finalCommand += runArgs;
  253. }
  254. bool worked = cmSystemTools::RunSingleCommand(
  255. finalCommand, stdOut || stdErr ? stdOut : out,
  256. stdOut || stdErr ? stdErr : out, &retVal,
  257. workDir ? workDir->c_str() : nullptr, cmSystemTools::OUTPUT_NONE,
  258. cmDuration::zero());
  259. // set the run var
  260. char retChar[16];
  261. const char* retStr;
  262. if (worked) {
  263. snprintf(retChar, sizeof(retChar), "%i", retVal);
  264. retStr = retChar;
  265. } else {
  266. retStr = "FAILED_TO_RUN";
  267. }
  268. if (this->NoCache) {
  269. this->Makefile->AddDefinition(this->RunResultVariable, retStr);
  270. } else {
  271. this->Makefile->AddCacheDefinition(this->RunResultVariable, retStr,
  272. "Result of try_run()",
  273. cmStateEnums::INTERNAL);
  274. }
  275. }
  276. /* This is only used when cross compiling. Instead of running the
  277. executable, two cache variables are created which will hold the results
  278. the executable would have produced.
  279. */
  280. void TryRunCommandImpl::DoNotRunExecutable(
  281. const std::string& runArgs, const std::string& srcFile,
  282. std::string const& compileResultVariable, std::string* out,
  283. std::string* stdOut, std::string* stdErr)
  284. {
  285. // copy the executable out of the CMakeFiles/ directory, so it is not
  286. // removed at the end of try_run() and the user can run it manually
  287. // on the target platform.
  288. std::string copyDest =
  289. cmStrCat(this->Makefile->GetHomeOutputDirectory(), "/CMakeFiles/",
  290. cmSystemTools::GetFilenameWithoutExtension(this->OutputFile), '-',
  291. this->RunResultVariable,
  292. cmSystemTools::GetFilenameExtension(this->OutputFile));
  293. cmSystemTools::CopyFileAlways(this->OutputFile, copyDest);
  294. std::string resultFileName =
  295. cmStrCat(this->Makefile->GetHomeOutputDirectory(), "/TryRunResults.cmake");
  296. std::string detailsString = cmStrCat("For details see ", resultFileName);
  297. std::string internalRunOutputName =
  298. this->RunResultVariable + "__TRYRUN_OUTPUT";
  299. std::string internalRunOutputStdOutName =
  300. this->RunResultVariable + "__TRYRUN_OUTPUT_STDOUT";
  301. std::string internalRunOutputStdErrName =
  302. this->RunResultVariable + "__TRYRUN_OUTPUT_STDERR";
  303. bool error = false;
  304. if (!this->Makefile->GetDefinition(this->RunResultVariable)) {
  305. // if the variables doesn't exist, create it with a helpful error text
  306. // and mark it as advanced
  307. std::string comment =
  308. cmStrCat("Run result of try_run(), indicates whether the executable "
  309. "would have been able to run on its target platform.\n",
  310. detailsString);
  311. this->Makefile->AddCacheDefinition(this->RunResultVariable,
  312. "PLEASE_FILL_OUT-FAILED_TO_RUN",
  313. comment.c_str(), cmStateEnums::STRING);
  314. cmState* state = this->Makefile->GetState();
  315. cmValue existingValue = state->GetCacheEntryValue(this->RunResultVariable);
  316. if (existingValue) {
  317. state->SetCacheEntryProperty(this->RunResultVariable, "ADVANCED", "1");
  318. }
  319. error = true;
  320. }
  321. // is the output from the executable used ?
  322. if (stdOut || stdErr) {
  323. if (!this->Makefile->GetDefinition(internalRunOutputStdOutName)) {
  324. // if the variables doesn't exist, create it with a helpful error text
  325. // and mark it as advanced
  326. std::string comment = cmStrCat(
  327. "Output of try_run(), contains the text, which the executable "
  328. "would have printed on stdout on its target platform.\n",
  329. detailsString);
  330. this->Makefile->AddCacheDefinition(
  331. internalRunOutputStdOutName, "PLEASE_FILL_OUT-NOTFOUND",
  332. comment.c_str(), cmStateEnums::STRING);
  333. cmState* state = this->Makefile->GetState();
  334. cmValue existing =
  335. state->GetCacheEntryValue(internalRunOutputStdOutName);
  336. if (existing) {
  337. state->SetCacheEntryProperty(internalRunOutputStdOutName, "ADVANCED",
  338. "1");
  339. }
  340. error = true;
  341. }
  342. if (!this->Makefile->GetDefinition(internalRunOutputStdErrName)) {
  343. // if the variables doesn't exist, create it with a helpful error text
  344. // and mark it as advanced
  345. std::string comment = cmStrCat(
  346. "Output of try_run(), contains the text, which the executable "
  347. "would have printed on stderr on its target platform.\n",
  348. detailsString);
  349. this->Makefile->AddCacheDefinition(
  350. internalRunOutputStdErrName, "PLEASE_FILL_OUT-NOTFOUND",
  351. comment.c_str(), cmStateEnums::STRING);
  352. cmState* state = this->Makefile->GetState();
  353. cmValue existing =
  354. state->GetCacheEntryValue(internalRunOutputStdErrName);
  355. if (existing) {
  356. state->SetCacheEntryProperty(internalRunOutputStdErrName, "ADVANCED",
  357. "1");
  358. }
  359. error = true;
  360. }
  361. } else if (out) {
  362. if (!this->Makefile->GetDefinition(internalRunOutputName)) {
  363. // if the variables doesn't exist, create it with a helpful error text
  364. // and mark it as advanced
  365. std::string comment = cmStrCat(
  366. "Output of try_run(), contains the text, which the executable "
  367. "would have printed on stdout and stderr on its target platform.\n",
  368. detailsString);
  369. this->Makefile->AddCacheDefinition(
  370. internalRunOutputName, "PLEASE_FILL_OUT-NOTFOUND", comment.c_str(),
  371. cmStateEnums::STRING);
  372. cmState* state = this->Makefile->GetState();
  373. cmValue existing = state->GetCacheEntryValue(internalRunOutputName);
  374. if (existing) {
  375. state->SetCacheEntryProperty(internalRunOutputName, "ADVANCED", "1");
  376. }
  377. error = true;
  378. }
  379. }
  380. if (error) {
  381. static bool firstTryRun = true;
  382. cmsys::ofstream file(resultFileName.c_str(),
  383. firstTryRun ? std::ios::out : std::ios::app);
  384. if (file) {
  385. if (firstTryRun) {
  386. /* clang-format off */
  387. file << "# This file was generated by CMake because it detected "
  388. "try_run() commands\n"
  389. "# in crosscompiling mode. It will be overwritten by the next "
  390. "CMake run.\n"
  391. "# Copy it to a safe location, set the variables to "
  392. "appropriate values\n"
  393. "# and use it then to preset the CMake cache (using -C).\n\n";
  394. /* clang-format on */
  395. }
  396. std::string comment =
  397. cmStrCat('\n', this->RunResultVariable,
  398. "\n indicates whether the executable would have been able "
  399. "to run on its\n"
  400. " target platform. If so, set ",
  401. this->RunResultVariable,
  402. " to\n"
  403. " the exit code (in many cases 0 for success), otherwise "
  404. "enter \"FAILED_TO_RUN\".\n");
  405. if (stdOut || stdErr) {
  406. if (stdOut) {
  407. comment += internalRunOutputStdOutName;
  408. comment +=
  409. "\n contains the text the executable "
  410. "would have printed on stdout.\n"
  411. " If the executable would not have been able to run, set ";
  412. comment += internalRunOutputStdOutName;
  413. comment += " empty.\n"
  414. " Otherwise check if the output is evaluated by the "
  415. "calling CMake code. If so,\n"
  416. " check what the source file would have printed when "
  417. "called with the given arguments.\n";
  418. }
  419. if (stdErr) {
  420. comment += internalRunOutputStdErrName;
  421. comment +=
  422. "\n contains the text the executable "
  423. "would have printed on stderr.\n"
  424. " If the executable would not have been able to run, set ";
  425. comment += internalRunOutputStdErrName;
  426. comment += " empty.\n"
  427. " Otherwise check if the output is evaluated by the "
  428. "calling CMake code. If so,\n"
  429. " check what the source file would have printed when "
  430. "called with the given arguments.\n";
  431. }
  432. } else if (out) {
  433. comment += internalRunOutputName;
  434. comment +=
  435. "\n contains the text the executable "
  436. "would have printed on stdout and stderr.\n"
  437. " If the executable would not have been able to run, set ";
  438. comment += internalRunOutputName;
  439. comment += " empty.\n"
  440. " Otherwise check if the output is evaluated by the "
  441. "calling CMake code. If so,\n"
  442. " check what the source file would have printed when "
  443. "called with the given arguments.\n";
  444. }
  445. comment += "The ";
  446. comment += compileResultVariable;
  447. comment += " variable holds the build result for this try_run().\n\n"
  448. "Source file : ";
  449. comment += srcFile + "\n";
  450. comment += "Executable : ";
  451. comment += copyDest + "\n";
  452. comment += "Run arguments : ";
  453. comment += runArgs;
  454. comment += "\n";
  455. comment += " Called from: " + this->Makefile->FormatListFileStack();
  456. cmsys::SystemTools::ReplaceString(comment, "\n", "\n# ");
  457. file << comment << "\n\n";
  458. file << "set( " << this->RunResultVariable << " \n \""
  459. << this->Makefile->GetSafeDefinition(this->RunResultVariable)
  460. << "\"\n CACHE STRING \"Result from try_run\" FORCE)\n\n";
  461. if (out) {
  462. file << "set( " << internalRunOutputName << " \n \""
  463. << this->Makefile->GetSafeDefinition(internalRunOutputName)
  464. << "\"\n CACHE STRING \"Output from try_run\" FORCE)\n\n";
  465. }
  466. file.close();
  467. }
  468. firstTryRun = false;
  469. std::string errorMessage =
  470. cmStrCat("try_run() invoked in cross-compiling mode, "
  471. "please set the following cache variables "
  472. "appropriately:\n ",
  473. this->RunResultVariable, " (advanced)\n");
  474. if (out) {
  475. errorMessage += " " + internalRunOutputName + " (advanced)\n";
  476. }
  477. errorMessage += detailsString;
  478. cmSystemTools::Error(errorMessage);
  479. return;
  480. }
  481. if (stdOut || stdErr) {
  482. if (stdOut) {
  483. (*stdOut) = *this->Makefile->GetDefinition(internalRunOutputStdOutName);
  484. }
  485. if (stdErr) {
  486. (*stdErr) = *this->Makefile->GetDefinition(internalRunOutputStdErrName);
  487. }
  488. } else if (out) {
  489. (*out) = *this->Makefile->GetDefinition(internalRunOutputName);
  490. }
  491. }
  492. }
  493. bool cmTryRunCommand(std::vector<std::string> const& args,
  494. cmExecutionStatus& status)
  495. {
  496. cmMakefile& mf = status.GetMakefile();
  497. if (args.size() < 4) {
  498. mf.IssueMessage(MessageType::FATAL_ERROR,
  499. "The try_run() command requires at least 4 arguments.");
  500. return false;
  501. }
  502. if (mf.GetCMakeInstance()->GetWorkingMode() == cmake::FIND_PACKAGE_MODE) {
  503. mf.IssueMessage(
  504. MessageType::FATAL_ERROR,
  505. "The try_run() command is not supported in --find-package mode.");
  506. return false;
  507. }
  508. TryRunCommandImpl tr(&mf);
  509. return tr.TryRunCode(args);
  510. }