cmTryRunCommand.cxx 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560
  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 std::vector<unsigned long> const 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(std::string const& runArgs,
  72. cm::optional<std::string> const& workDir,
  73. std::string* runOutputContents,
  74. std::string* runOutputStdOutContents,
  75. std::string* runOutputStdErrContents);
  76. void DoNotRunExecutable(std::string const& 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(std::string const& 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. std::string const& emulator =
  242. this->Makefile->GetSafeDefinition("CMAKE_CROSSCOMPILING_EMULATOR");
  243. if (!emulator.empty()) {
  244. cmList emulatorWithArgs{ emulator };
  245. finalCommand += cmStrCat(
  246. cmSystemTools::ConvertToRunCommandPath(emulatorWithArgs[0]), ' ',
  247. cmWrap("\"", cmMakeRange(emulatorWithArgs).advance(1), "\"", " "), ' ');
  248. }
  249. finalCommand += cmSystemTools::ConvertToRunCommandPath(this->OutputFile);
  250. if (!runArgs.empty()) {
  251. finalCommand += runArgs;
  252. }
  253. bool worked = cmSystemTools::RunSingleCommand(
  254. finalCommand, stdOut || stdErr ? stdOut : out,
  255. stdOut || stdErr ? stdErr : out, &retVal,
  256. workDir ? workDir->c_str() : nullptr, cmSystemTools::OUTPUT_NONE,
  257. cmDuration::zero());
  258. // set the run var
  259. std::string retStr = worked ? std::to_string(retVal) : "FAILED_TO_RUN";
  260. if (this->NoCache) {
  261. this->Makefile->AddDefinition(this->RunResultVariable, retStr);
  262. } else {
  263. this->Makefile->AddCacheDefinition(this->RunResultVariable, retStr,
  264. "Result of try_run()",
  265. cmStateEnums::INTERNAL);
  266. }
  267. }
  268. /* This is only used when cross compiling. Instead of running the
  269. executable, two cache variables are created which will hold the results
  270. the executable would have produced.
  271. */
  272. void TryRunCommandImpl::DoNotRunExecutable(
  273. std::string const& runArgs, cm::optional<std::string> const& srcFile,
  274. std::string const& compileResultVariable, std::string* out,
  275. std::string* stdOut, std::string* stdErr, bool stdOutErrRequired)
  276. {
  277. // copy the executable out of the CMakeFiles/ directory, so it is not
  278. // removed at the end of try_run() and the user can run it manually
  279. // on the target platform.
  280. std::string copyDest =
  281. cmStrCat(this->Makefile->GetHomeOutputDirectory(), "/CMakeFiles/",
  282. cmSystemTools::GetFilenameWithoutExtension(this->OutputFile), '-',
  283. this->RunResultVariable,
  284. cmSystemTools::GetFilenameExtension(this->OutputFile));
  285. cmSystemTools::CopyFileAlways(this->OutputFile, copyDest);
  286. std::string resultFileName =
  287. cmStrCat(this->Makefile->GetHomeOutputDirectory(), "/TryRunResults.cmake");
  288. std::string detailsString = cmStrCat("For details see ", resultFileName);
  289. std::string internalRunOutputName =
  290. this->RunResultVariable + "__TRYRUN_OUTPUT";
  291. std::string internalRunOutputStdOutName =
  292. this->RunResultVariable + "__TRYRUN_OUTPUT_STDOUT";
  293. std::string internalRunOutputStdErrName =
  294. this->RunResultVariable + "__TRYRUN_OUTPUT_STDERR";
  295. bool error = false;
  296. if (!this->Makefile->GetDefinition(this->RunResultVariable)) {
  297. // if the variables doesn't exist, create it with a helpful error text
  298. // and mark it as advanced
  299. std::string comment =
  300. cmStrCat("Run result of try_run(), indicates whether the executable "
  301. "would have been able to run on its target platform.\n",
  302. detailsString);
  303. this->Makefile->AddCacheDefinition(this->RunResultVariable,
  304. "PLEASE_FILL_OUT-FAILED_TO_RUN",
  305. comment, cmStateEnums::STRING);
  306. cmState* state = this->Makefile->GetState();
  307. cmValue existingValue = state->GetCacheEntryValue(this->RunResultVariable);
  308. if (existingValue) {
  309. state->SetCacheEntryProperty(this->RunResultVariable, "ADVANCED", "1");
  310. }
  311. error = true;
  312. }
  313. // is the output from the executable used ?
  314. if (stdOutErrRequired) {
  315. if (!this->Makefile->GetDefinition(internalRunOutputStdOutName)) {
  316. // if the variables doesn't exist, create it with a helpful error text
  317. // and mark it as advanced
  318. std::string comment = cmStrCat(
  319. "Output of try_run(), contains the text, which the executable "
  320. "would have printed on stdout on its target platform.\n",
  321. detailsString);
  322. this->Makefile->AddCacheDefinition(internalRunOutputStdOutName,
  323. "PLEASE_FILL_OUT-NOTFOUND", comment,
  324. cmStateEnums::STRING);
  325. cmState* state = this->Makefile->GetState();
  326. cmValue existing =
  327. state->GetCacheEntryValue(internalRunOutputStdOutName);
  328. if (existing) {
  329. state->SetCacheEntryProperty(internalRunOutputStdOutName, "ADVANCED",
  330. "1");
  331. }
  332. error = true;
  333. }
  334. if (!this->Makefile->GetDefinition(internalRunOutputStdErrName)) {
  335. // if the variables doesn't exist, create it with a helpful error text
  336. // and mark it as advanced
  337. std::string comment = cmStrCat(
  338. "Output of try_run(), contains the text, which the executable "
  339. "would have printed on stderr on its target platform.\n",
  340. detailsString);
  341. this->Makefile->AddCacheDefinition(internalRunOutputStdErrName,
  342. "PLEASE_FILL_OUT-NOTFOUND", comment,
  343. cmStateEnums::STRING);
  344. cmState* state = this->Makefile->GetState();
  345. cmValue existing =
  346. state->GetCacheEntryValue(internalRunOutputStdErrName);
  347. if (existing) {
  348. state->SetCacheEntryProperty(internalRunOutputStdErrName, "ADVANCED",
  349. "1");
  350. }
  351. error = true;
  352. }
  353. } else if (out) {
  354. if (!this->Makefile->GetDefinition(internalRunOutputName)) {
  355. // if the variables doesn't exist, create it with a helpful error text
  356. // and mark it as advanced
  357. std::string comment = cmStrCat(
  358. "Output of try_run(), contains the text, which the executable "
  359. "would have printed on stdout and stderr on its target platform.\n",
  360. detailsString);
  361. this->Makefile->AddCacheDefinition(internalRunOutputName,
  362. "PLEASE_FILL_OUT-NOTFOUND", comment,
  363. cmStateEnums::STRING);
  364. cmState* state = this->Makefile->GetState();
  365. cmValue existing = state->GetCacheEntryValue(internalRunOutputName);
  366. if (existing) {
  367. state->SetCacheEntryProperty(internalRunOutputName, "ADVANCED", "1");
  368. }
  369. error = true;
  370. }
  371. }
  372. if (error) {
  373. static bool firstTryRun = true;
  374. cmsys::ofstream file(resultFileName.c_str(),
  375. firstTryRun ? std::ios::out : std::ios::app);
  376. if (file) {
  377. if (firstTryRun) {
  378. /* clang-format off */
  379. file << "# This file was generated by CMake because it detected "
  380. "try_run() commands\n"
  381. "# in crosscompiling mode. It will be overwritten by the next "
  382. "CMake run.\n"
  383. "# Copy it to a safe location, set the variables to "
  384. "appropriate values\n"
  385. "# and use it then to preset the CMake cache (using -C).\n\n";
  386. /* clang-format on */
  387. }
  388. std::string comment =
  389. cmStrCat('\n', this->RunResultVariable,
  390. "\n indicates whether the executable would have been able "
  391. "to run on its\n"
  392. " target platform. If so, set ",
  393. this->RunResultVariable,
  394. " to\n"
  395. " the exit code (in many cases 0 for success), otherwise "
  396. "enter \"FAILED_TO_RUN\".\n");
  397. if (stdOut || stdErr) {
  398. if (stdOut) {
  399. comment += cmStrCat(
  400. internalRunOutputStdOutName,
  401. "\n contains the text the executable would have printed on "
  402. "stdout.\n"
  403. " If the executable would not have been able to run, set ",
  404. internalRunOutputStdOutName,
  405. " empty.\n"
  406. " Otherwise check if the output is evaluated by the "
  407. "calling CMake code. If so,\n"
  408. " check what the source file would have printed when "
  409. "called with the given arguments.\n");
  410. }
  411. if (stdErr) {
  412. comment += cmStrCat(
  413. internalRunOutputStdErrName,
  414. "\n contains the text the executable would have printed on "
  415. "stderr.\n"
  416. " If the executable would not have been able to run, set ",
  417. internalRunOutputStdErrName,
  418. " empty.\n"
  419. " Otherwise check if the output is evaluated by the "
  420. "calling CMake code. If so,\n"
  421. " check what the source file would have printed when "
  422. "called with the given arguments.\n");
  423. }
  424. } else if (out) {
  425. comment += cmStrCat(
  426. internalRunOutputName,
  427. "\n contains the text the executable would have printed on stdout "
  428. "and stderr.\n"
  429. " If the executable would not have been able to run, set ",
  430. internalRunOutputName,
  431. " empty.\n"
  432. " Otherwise check if the output is evaluated by the "
  433. "calling CMake code. If so,\n"
  434. " check what the source file would have printed when "
  435. "called with the given arguments.\n");
  436. }
  437. comment +=
  438. cmStrCat("The ", compileResultVariable,
  439. " variable holds the build result for this try_run().\n\n");
  440. if (srcFile) {
  441. comment += cmStrCat("Source file : ", *srcFile, '\n');
  442. }
  443. comment += cmStrCat("Executable : ", copyDest,
  444. "\n"
  445. "Run arguments : ",
  446. runArgs,
  447. "\n"
  448. " Called from: ",
  449. this->Makefile->FormatListFileStack());
  450. cmsys::SystemTools::ReplaceString(comment, "\n", "\n# ");
  451. file << comment << "\n\n";
  452. file << "set( " << this->RunResultVariable << " \n \""
  453. << this->Makefile->GetSafeDefinition(this->RunResultVariable)
  454. << "\"\n CACHE STRING \"Result from try_run\" FORCE)\n\n";
  455. if (out) {
  456. file << "set( " << internalRunOutputName << " \n \""
  457. << this->Makefile->GetSafeDefinition(internalRunOutputName)
  458. << "\"\n CACHE STRING \"Output from try_run\" FORCE)\n\n";
  459. }
  460. file.close();
  461. }
  462. firstTryRun = false;
  463. std::string errorMessage =
  464. cmStrCat("try_run() invoked in cross-compiling mode, "
  465. "please set the following cache variables "
  466. "appropriately:\n ",
  467. this->RunResultVariable, " (advanced)\n");
  468. if (out) {
  469. errorMessage += " " + internalRunOutputName + " (advanced)\n";
  470. }
  471. errorMessage += detailsString;
  472. cmSystemTools::Error(errorMessage);
  473. return;
  474. }
  475. if (stdOut || stdErr) {
  476. if (stdOut) {
  477. (*stdOut) = *this->Makefile->GetDefinition(internalRunOutputStdOutName);
  478. }
  479. if (stdErr) {
  480. (*stdErr) = *this->Makefile->GetDefinition(internalRunOutputStdErrName);
  481. }
  482. } else if (out) {
  483. (*out) = *this->Makefile->GetDefinition(internalRunOutputName);
  484. }
  485. }
  486. }
  487. bool cmTryRunCommand(std::vector<std::string> const& args,
  488. cmExecutionStatus& status)
  489. {
  490. cmMakefile& mf = status.GetMakefile();
  491. if (args.size() < 4) {
  492. mf.IssueMessage(MessageType::FATAL_ERROR,
  493. "The try_run() command requires at least 4 arguments.");
  494. return false;
  495. }
  496. if (mf.GetCMakeInstance()->GetWorkingMode() == cmake::FIND_PACKAGE_MODE) {
  497. mf.IssueMessage(
  498. MessageType::FATAL_ERROR,
  499. "The try_run() command is not supported in --find-package mode.");
  500. return false;
  501. }
  502. TryRunCommandImpl tr(&mf);
  503. return tr.TryRunCode(args);
  504. }