cmTryRunCommand.cxx 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359
  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 "cmsys/FStream.hxx"
  6. #include "cmDuration.h"
  7. #include "cmMakefile.h"
  8. #include "cmMessageType.h"
  9. #include "cmProperty.h"
  10. #include "cmRange.h"
  11. #include "cmState.h"
  12. #include "cmStateTypes.h"
  13. #include "cmStringAlgorithms.h"
  14. #include "cmSystemTools.h"
  15. #include "cmake.h"
  16. class cmExecutionStatus;
  17. // cmTryRunCommand
  18. bool cmTryRunCommand::InitialPass(std::vector<std::string> const& argv,
  19. cmExecutionStatus&)
  20. {
  21. if (argv.size() < 4) {
  22. return false;
  23. }
  24. if (this->Makefile->GetCMakeInstance()->GetWorkingMode() ==
  25. cmake::FIND_PACKAGE_MODE) {
  26. this->Makefile->IssueMessage(
  27. MessageType::FATAL_ERROR,
  28. "The TRY_RUN() command is not supported in --find-package mode.");
  29. return false;
  30. }
  31. // build an arg list for TryCompile and extract the runArgs,
  32. std::vector<std::string> tryCompile;
  33. this->CompileResultVariable.clear();
  34. this->RunResultVariable.clear();
  35. this->OutputVariable.clear();
  36. this->RunOutputVariable.clear();
  37. this->CompileOutputVariable.clear();
  38. std::string runArgs;
  39. unsigned int i;
  40. for (i = 1; i < argv.size(); ++i) {
  41. if (argv[i] == "ARGS") {
  42. ++i;
  43. while (i < argv.size() && argv[i] != "COMPILE_DEFINITIONS" &&
  44. argv[i] != "CMAKE_FLAGS" && argv[i] != "LINK_OPTIONS" &&
  45. argv[i] != "LINK_LIBRARIES") {
  46. runArgs += " ";
  47. runArgs += argv[i];
  48. ++i;
  49. }
  50. if (i < argv.size()) {
  51. tryCompile.push_back(argv[i]);
  52. }
  53. } else {
  54. if (argv[i] == "OUTPUT_VARIABLE") {
  55. if (argv.size() <= (i + 1)) {
  56. cmSystemTools::Error(
  57. "OUTPUT_VARIABLE specified but there is no variable");
  58. return false;
  59. }
  60. i++;
  61. this->OutputVariable = argv[i];
  62. } else if (argv[i] == "RUN_OUTPUT_VARIABLE") {
  63. if (argv.size() <= (i + 1)) {
  64. cmSystemTools::Error(
  65. "RUN_OUTPUT_VARIABLE specified but there is no variable");
  66. return false;
  67. }
  68. i++;
  69. this->RunOutputVariable = argv[i];
  70. } else if (argv[i] == "COMPILE_OUTPUT_VARIABLE") {
  71. if (argv.size() <= (i + 1)) {
  72. cmSystemTools::Error(
  73. "COMPILE_OUTPUT_VARIABLE specified but there is no variable");
  74. return false;
  75. }
  76. i++;
  77. this->CompileOutputVariable = argv[i];
  78. } else {
  79. tryCompile.push_back(argv[i]);
  80. }
  81. }
  82. }
  83. // although they could be used together, don't allow it, because
  84. // using OUTPUT_VARIABLE makes crosscompiling harder
  85. if (!this->OutputVariable.empty() &&
  86. (!this->RunOutputVariable.empty() ||
  87. !this->CompileOutputVariable.empty())) {
  88. cmSystemTools::Error(
  89. "You cannot use OUTPUT_VARIABLE together with COMPILE_OUTPUT_VARIABLE "
  90. "or RUN_OUTPUT_VARIABLE. Please use only COMPILE_OUTPUT_VARIABLE and/or "
  91. "RUN_OUTPUT_VARIABLE.");
  92. return false;
  93. }
  94. bool captureRunOutput = false;
  95. if (!this->OutputVariable.empty()) {
  96. captureRunOutput = true;
  97. tryCompile.emplace_back("OUTPUT_VARIABLE");
  98. tryCompile.push_back(this->OutputVariable);
  99. }
  100. if (!this->CompileOutputVariable.empty()) {
  101. tryCompile.emplace_back("OUTPUT_VARIABLE");
  102. tryCompile.push_back(this->CompileOutputVariable);
  103. }
  104. if (!this->RunOutputVariable.empty()) {
  105. captureRunOutput = true;
  106. }
  107. this->RunResultVariable = argv[0];
  108. this->CompileResultVariable = argv[1];
  109. // do the try compile
  110. int res = this->TryCompileCode(tryCompile, true);
  111. // now try running the command if it compiled
  112. if (!res) {
  113. if (this->OutputFile.empty()) {
  114. cmSystemTools::Error(this->FindErrorMessage);
  115. } else {
  116. // "run" it and capture the output
  117. std::string runOutputContents;
  118. if (this->Makefile->IsOn("CMAKE_CROSSCOMPILING") &&
  119. !this->Makefile->IsDefinitionSet("CMAKE_CROSSCOMPILING_EMULATOR")) {
  120. this->DoNotRunExecutable(
  121. runArgs, argv[3], captureRunOutput ? &runOutputContents : nullptr);
  122. } else {
  123. this->RunExecutable(runArgs, &runOutputContents);
  124. }
  125. // now put the output into the variables
  126. if (!this->RunOutputVariable.empty()) {
  127. this->Makefile->AddDefinition(this->RunOutputVariable,
  128. runOutputContents);
  129. }
  130. if (!this->OutputVariable.empty()) {
  131. // if the TryCompileCore saved output in this outputVariable then
  132. // prepend that output to this output
  133. cmProp compileOutput =
  134. this->Makefile->GetDefinition(this->OutputVariable);
  135. if (compileOutput) {
  136. runOutputContents = *compileOutput + runOutputContents;
  137. }
  138. this->Makefile->AddDefinition(this->OutputVariable, runOutputContents);
  139. }
  140. }
  141. }
  142. // if we created a directory etc, then cleanup after ourselves
  143. if (!this->Makefile->GetCMakeInstance()->GetDebugTryCompile()) {
  144. this->CleanupFiles(this->BinaryDirectory);
  145. }
  146. return true;
  147. }
  148. void cmTryRunCommand::RunExecutable(const std::string& runArgs,
  149. std::string* out)
  150. {
  151. int retVal = -1;
  152. std::string finalCommand;
  153. const std::string& emulator =
  154. this->Makefile->GetSafeDefinition("CMAKE_CROSSCOMPILING_EMULATOR");
  155. if (!emulator.empty()) {
  156. std::vector<std::string> emulatorWithArgs = cmExpandedList(emulator);
  157. finalCommand +=
  158. cmSystemTools::ConvertToRunCommandPath(emulatorWithArgs[0]);
  159. finalCommand += " ";
  160. for (std::string const& arg : cmMakeRange(emulatorWithArgs).advance(1)) {
  161. finalCommand += "\"";
  162. finalCommand += arg;
  163. finalCommand += "\"";
  164. finalCommand += " ";
  165. }
  166. }
  167. finalCommand += cmSystemTools::ConvertToRunCommandPath(this->OutputFile);
  168. if (!runArgs.empty()) {
  169. finalCommand += runArgs;
  170. }
  171. bool worked = cmSystemTools::RunSingleCommand(
  172. finalCommand, out, out, &retVal, nullptr, cmSystemTools::OUTPUT_NONE,
  173. cmDuration::zero());
  174. // set the run var
  175. char retChar[16];
  176. const char* retStr;
  177. if (worked) {
  178. sprintf(retChar, "%i", retVal);
  179. retStr = retChar;
  180. } else {
  181. retStr = "FAILED_TO_RUN";
  182. }
  183. this->Makefile->AddCacheDefinition(this->RunResultVariable, retStr,
  184. "Result of TRY_RUN",
  185. cmStateEnums::INTERNAL);
  186. }
  187. /* This is only used when cross compiling. Instead of running the
  188. executable, two cache variables are created which will hold the results
  189. the executable would have produced.
  190. */
  191. void cmTryRunCommand::DoNotRunExecutable(const std::string& runArgs,
  192. const std::string& srcFile,
  193. std::string* out)
  194. {
  195. // copy the executable out of the CMakeFiles/ directory, so it is not
  196. // removed at the end of TRY_RUN and the user can run it manually
  197. // on the target platform.
  198. std::string copyDest =
  199. cmStrCat(this->Makefile->GetHomeOutputDirectory(), "/CMakeFiles/",
  200. cmSystemTools::GetFilenameWithoutExtension(this->OutputFile), '-',
  201. this->RunResultVariable,
  202. cmSystemTools::GetFilenameExtension(this->OutputFile));
  203. cmSystemTools::CopyFileAlways(this->OutputFile, copyDest);
  204. std::string resultFileName =
  205. cmStrCat(this->Makefile->GetHomeOutputDirectory(), "/TryRunResults.cmake");
  206. std::string detailsString = cmStrCat("For details see ", resultFileName);
  207. std::string internalRunOutputName =
  208. this->RunResultVariable + "__TRYRUN_OUTPUT";
  209. bool error = false;
  210. if (!this->Makefile->GetDefinition(this->RunResultVariable)) {
  211. // if the variables doesn't exist, create it with a helpful error text
  212. // and mark it as advanced
  213. std::string comment =
  214. cmStrCat("Run result of TRY_RUN(), indicates whether the executable "
  215. "would have been able to run on its target platform.\n",
  216. detailsString);
  217. this->Makefile->AddCacheDefinition(this->RunResultVariable,
  218. "PLEASE_FILL_OUT-FAILED_TO_RUN",
  219. comment.c_str(), cmStateEnums::STRING);
  220. cmState* state = this->Makefile->GetState();
  221. cmProp existingValue = state->GetCacheEntryValue(this->RunResultVariable);
  222. if (existingValue) {
  223. state->SetCacheEntryProperty(this->RunResultVariable, "ADVANCED", "1");
  224. }
  225. error = true;
  226. }
  227. // is the output from the executable used ?
  228. if (out) {
  229. if (!this->Makefile->GetDefinition(internalRunOutputName)) {
  230. // if the variables doesn't exist, create it with a helpful error text
  231. // and mark it as advanced
  232. std::string comment = cmStrCat(
  233. "Output of TRY_RUN(), contains the text, which the executable "
  234. "would have printed on stdout and stderr on its target platform.\n",
  235. detailsString);
  236. this->Makefile->AddCacheDefinition(
  237. internalRunOutputName, "PLEASE_FILL_OUT-NOTFOUND", comment.c_str(),
  238. cmStateEnums::STRING);
  239. cmState* state = this->Makefile->GetState();
  240. cmProp existing = state->GetCacheEntryValue(internalRunOutputName);
  241. if (existing) {
  242. state->SetCacheEntryProperty(internalRunOutputName, "ADVANCED", "1");
  243. }
  244. error = true;
  245. }
  246. }
  247. if (error) {
  248. static bool firstTryRun = true;
  249. cmsys::ofstream file(resultFileName.c_str(),
  250. firstTryRun ? std::ios::out : std::ios::app);
  251. if (file) {
  252. if (firstTryRun) {
  253. /* clang-format off */
  254. file << "# This file was generated by CMake because it detected "
  255. "TRY_RUN() commands\n"
  256. "# in crosscompiling mode. It will be overwritten by the next "
  257. "CMake run.\n"
  258. "# Copy it to a safe location, set the variables to "
  259. "appropriate values\n"
  260. "# and use it then to preset the CMake cache (using -C).\n\n";
  261. /* clang-format on */
  262. }
  263. std::string comment =
  264. cmStrCat('\n', this->RunResultVariable,
  265. "\n indicates whether the executable would have been able "
  266. "to run on its\n"
  267. " target platform. If so, set ",
  268. this->RunResultVariable,
  269. " to\n"
  270. " the exit code (in many cases 0 for success), otherwise "
  271. "enter \"FAILED_TO_RUN\".\n");
  272. if (out) {
  273. comment += internalRunOutputName;
  274. comment +=
  275. "\n contains the text the executable "
  276. "would have printed on stdout and stderr.\n"
  277. " If the executable would not have been able to run, set ";
  278. comment += internalRunOutputName;
  279. comment += " empty.\n"
  280. " Otherwise check if the output is evaluated by the "
  281. "calling CMake code. If so,\n"
  282. " check what the source file would have printed when "
  283. "called with the given arguments.\n";
  284. }
  285. comment += "The ";
  286. comment += this->CompileResultVariable;
  287. comment += " variable holds the build result for this TRY_RUN().\n\n"
  288. "Source file : ";
  289. comment += srcFile + "\n";
  290. comment += "Executable : ";
  291. comment += copyDest + "\n";
  292. comment += "Run arguments : ";
  293. comment += runArgs;
  294. comment += "\n";
  295. comment += " Called from: " + this->Makefile->FormatListFileStack();
  296. cmsys::SystemTools::ReplaceString(comment, "\n", "\n# ");
  297. file << comment << "\n\n";
  298. file << "set( " << this->RunResultVariable << " \n \""
  299. << this->Makefile->GetSafeDefinition(this->RunResultVariable)
  300. << "\"\n CACHE STRING \"Result from TRY_RUN\" FORCE)\n\n";
  301. if (out) {
  302. file << "set( " << internalRunOutputName << " \n \""
  303. << this->Makefile->GetSafeDefinition(internalRunOutputName)
  304. << "\"\n CACHE STRING \"Output from TRY_RUN\" FORCE)\n\n";
  305. }
  306. file.close();
  307. }
  308. firstTryRun = false;
  309. std::string errorMessage =
  310. cmStrCat("TRY_RUN() invoked in cross-compiling mode, "
  311. "please set the following cache variables "
  312. "appropriately:\n ",
  313. this->RunResultVariable, " (advanced)\n");
  314. if (out) {
  315. errorMessage += " " + internalRunOutputName + " (advanced)\n";
  316. }
  317. errorMessage += detailsString;
  318. cmSystemTools::Error(errorMessage);
  319. return;
  320. }
  321. if (out) {
  322. (*out) = *this->Makefile->GetDefinition(internalRunOutputName);
  323. }
  324. }