cmTryRunCommand.cxx 13 KB

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