cmTryRunCommand.cxx 13 KB

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