cmTryRunCommand.cxx 13 KB

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