cmTryRunCommand.cxx 13 KB

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