cmExecuteProcessCommand.cxx 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408
  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 "cmExecuteProcessCommand.h"
  4. #include <algorithm>
  5. #include <cctype> /* isspace */
  6. #include <cstdio>
  7. #include <iostream>
  8. #include <memory>
  9. #include <vector>
  10. #include <cmext/algorithm>
  11. #include "cmsys/Process.h"
  12. #include "cm_static_string_view.hxx"
  13. #include "cmArgumentParser.h"
  14. #include "cmExecutionStatus.h"
  15. #include "cmMakefile.h"
  16. #include "cmMessageType.h"
  17. #include "cmProcessOutput.h"
  18. #include "cmStringAlgorithms.h"
  19. #include "cmSystemTools.h"
  20. namespace {
  21. bool cmExecuteProcessCommandIsWhitespace(char c)
  22. {
  23. return (isspace(static_cast<int>(c)) || c == '\n' || c == '\r');
  24. }
  25. void cmExecuteProcessCommandFixText(std::vector<char>& output,
  26. bool strip_trailing_whitespace);
  27. void cmExecuteProcessCommandAppend(std::vector<char>& output, const char* data,
  28. int length);
  29. }
  30. // cmExecuteProcessCommand
  31. bool cmExecuteProcessCommand(std::vector<std::string> const& args,
  32. cmExecutionStatus& status)
  33. {
  34. if (args.empty()) {
  35. status.SetError("called with incorrect number of arguments");
  36. return false;
  37. }
  38. struct Arguments
  39. {
  40. std::vector<std::vector<std::string>> Commands;
  41. std::string OutputVariable;
  42. std::string ErrorVariable;
  43. std::string ResultVariable;
  44. std::string ResultsVariable;
  45. std::string WorkingDirectory;
  46. std::string InputFile;
  47. std::string OutputFile;
  48. std::string ErrorFile;
  49. std::string Timeout;
  50. std::string CommandEcho;
  51. bool OutputQuiet = false;
  52. bool ErrorQuiet = false;
  53. bool OutputStripTrailingWhitespace = false;
  54. bool ErrorStripTrailingWhitespace = false;
  55. std::string Encoding;
  56. };
  57. static auto const parser =
  58. cmArgumentParser<Arguments>{}
  59. .Bind("COMMAND"_s, &Arguments::Commands)
  60. .Bind("COMMAND_ECHO"_s, &Arguments::CommandEcho)
  61. .Bind("OUTPUT_VARIABLE"_s, &Arguments::OutputVariable)
  62. .Bind("ERROR_VARIABLE"_s, &Arguments::ErrorVariable)
  63. .Bind("RESULT_VARIABLE"_s, &Arguments::ResultVariable)
  64. .Bind("RESULTS_VARIABLE"_s, &Arguments::ResultsVariable)
  65. .Bind("WORKING_DIRECTORY"_s, &Arguments::WorkingDirectory)
  66. .Bind("INPUT_FILE"_s, &Arguments::InputFile)
  67. .Bind("OUTPUT_FILE"_s, &Arguments::OutputFile)
  68. .Bind("ERROR_FILE"_s, &Arguments::ErrorFile)
  69. .Bind("TIMEOUT"_s, &Arguments::Timeout)
  70. .Bind("OUTPUT_QUIET"_s, &Arguments::OutputQuiet)
  71. .Bind("ERROR_QUIET"_s, &Arguments::ErrorQuiet)
  72. .Bind("OUTPUT_STRIP_TRAILING_WHITESPACE"_s,
  73. &Arguments::OutputStripTrailingWhitespace)
  74. .Bind("ERROR_STRIP_TRAILING_WHITESPACE"_s,
  75. &Arguments::ErrorStripTrailingWhitespace)
  76. .Bind("ENCODING"_s, &Arguments::Encoding);
  77. std::vector<std::string> unparsedArguments;
  78. std::vector<std::string> keywordsMissingValue;
  79. Arguments const arguments =
  80. parser.Parse(args, &unparsedArguments, &keywordsMissingValue);
  81. if (!keywordsMissingValue.empty()) {
  82. status.SetError(" called with no value for " +
  83. keywordsMissingValue.front() + ".");
  84. return false;
  85. }
  86. if (!unparsedArguments.empty()) {
  87. status.SetError(" given unknown argument \"" + unparsedArguments.front() +
  88. "\".");
  89. return false;
  90. }
  91. if (!status.GetMakefile().CanIWriteThisFile(arguments.OutputFile)) {
  92. status.SetError("attempted to output into a file: " +
  93. arguments.OutputFile + " into a source directory.");
  94. cmSystemTools::SetFatalErrorOccured();
  95. return false;
  96. }
  97. // Check for commands given.
  98. if (arguments.Commands.empty()) {
  99. status.SetError(" called with no COMMAND argument.");
  100. return false;
  101. }
  102. for (std::vector<std::string> const& cmd : arguments.Commands) {
  103. if (cmd.empty()) {
  104. status.SetError(" given COMMAND argument with no value.");
  105. return false;
  106. }
  107. }
  108. // Parse the timeout string.
  109. double timeout = -1;
  110. if (!arguments.Timeout.empty()) {
  111. if (sscanf(arguments.Timeout.c_str(), "%lg", &timeout) != 1) {
  112. status.SetError(" called with TIMEOUT value that could not be parsed.");
  113. return false;
  114. }
  115. }
  116. // Create a process instance.
  117. std::unique_ptr<cmsysProcess, void (*)(cmsysProcess*)> cp_ptr(
  118. cmsysProcess_New(), cmsysProcess_Delete);
  119. cmsysProcess* cp = cp_ptr.get();
  120. // Set the command sequence.
  121. for (std::vector<std::string> const& cmd : arguments.Commands) {
  122. std::vector<const char*> argv(cmd.size() + 1);
  123. std::transform(cmd.begin(), cmd.end(), argv.begin(),
  124. [](std::string const& s) { return s.c_str(); });
  125. argv.back() = nullptr;
  126. cmsysProcess_AddCommand(cp, argv.data());
  127. }
  128. // Set the process working directory.
  129. if (!arguments.WorkingDirectory.empty()) {
  130. cmsysProcess_SetWorkingDirectory(cp, arguments.WorkingDirectory.c_str());
  131. }
  132. // Always hide the process window.
  133. cmsysProcess_SetOption(cp, cmsysProcess_Option_HideWindow, 1);
  134. // Check the output variables.
  135. bool merge_output = false;
  136. if (!arguments.InputFile.empty()) {
  137. cmsysProcess_SetPipeFile(cp, cmsysProcess_Pipe_STDIN,
  138. arguments.InputFile.c_str());
  139. }
  140. if (!arguments.OutputFile.empty()) {
  141. cmsysProcess_SetPipeFile(cp, cmsysProcess_Pipe_STDOUT,
  142. arguments.OutputFile.c_str());
  143. }
  144. if (!arguments.ErrorFile.empty()) {
  145. if (arguments.ErrorFile == arguments.OutputFile) {
  146. merge_output = true;
  147. } else {
  148. cmsysProcess_SetPipeFile(cp, cmsysProcess_Pipe_STDERR,
  149. arguments.ErrorFile.c_str());
  150. }
  151. }
  152. if (!arguments.OutputVariable.empty() &&
  153. arguments.OutputVariable == arguments.ErrorVariable) {
  154. merge_output = true;
  155. }
  156. if (merge_output) {
  157. cmsysProcess_SetOption(cp, cmsysProcess_Option_MergeOutput, 1);
  158. }
  159. // Set the timeout if any.
  160. if (timeout >= 0) {
  161. cmsysProcess_SetTimeout(cp, timeout);
  162. }
  163. bool echo_stdout = false;
  164. bool echo_stderr = false;
  165. bool echo_output_from_variable = true;
  166. std::string echo_output = status.GetMakefile().GetSafeDefinition(
  167. "CMAKE_EXECUTE_PROCESS_COMMAND_ECHO");
  168. if (!arguments.CommandEcho.empty()) {
  169. echo_output_from_variable = false;
  170. echo_output = arguments.CommandEcho;
  171. }
  172. if (!echo_output.empty()) {
  173. if (echo_output == "STDERR") {
  174. echo_stderr = true;
  175. } else if (echo_output == "STDOUT") {
  176. echo_stdout = true;
  177. } else if (echo_output != "NONE") {
  178. std::string error;
  179. if (echo_output_from_variable) {
  180. error = "CMAKE_EXECUTE_PROCESS_COMMAND_ECHO set to '";
  181. } else {
  182. error = " called with '";
  183. }
  184. error += echo_output;
  185. error += "' expected STDERR|STDOUT|NONE";
  186. if (!echo_output_from_variable) {
  187. error += " for COMMAND_ECHO.";
  188. }
  189. status.GetMakefile().IssueMessage(MessageType::FATAL_ERROR, error);
  190. return true;
  191. }
  192. }
  193. if (echo_stdout || echo_stderr) {
  194. std::string command;
  195. for (auto& cmd : arguments.Commands) {
  196. command += "'";
  197. command += cmJoin(cmd, "' '");
  198. command += "'";
  199. command += "\n";
  200. }
  201. if (echo_stdout) {
  202. std::cout << command;
  203. } else if (echo_stderr) {
  204. std::cerr << command;
  205. }
  206. }
  207. // Start the process.
  208. cmsysProcess_Execute(cp);
  209. // Read the process output.
  210. std::vector<char> tempOutput;
  211. std::vector<char> tempError;
  212. int length;
  213. char* data;
  214. int p;
  215. cmProcessOutput processOutput(
  216. cmProcessOutput::FindEncoding(arguments.Encoding));
  217. std::string strdata;
  218. while ((p = cmsysProcess_WaitForData(cp, &data, &length, nullptr))) {
  219. // Put the output in the right place.
  220. if (p == cmsysProcess_Pipe_STDOUT && !arguments.OutputQuiet) {
  221. if (arguments.OutputVariable.empty()) {
  222. processOutput.DecodeText(data, length, strdata, 1);
  223. cmSystemTools::Stdout(strdata);
  224. } else {
  225. cmExecuteProcessCommandAppend(tempOutput, data, length);
  226. }
  227. } else if (p == cmsysProcess_Pipe_STDERR && !arguments.ErrorQuiet) {
  228. if (arguments.ErrorVariable.empty()) {
  229. processOutput.DecodeText(data, length, strdata, 2);
  230. cmSystemTools::Stderr(strdata);
  231. } else {
  232. cmExecuteProcessCommandAppend(tempError, data, length);
  233. }
  234. }
  235. }
  236. if (!arguments.OutputQuiet && arguments.OutputVariable.empty()) {
  237. processOutput.DecodeText(std::string(), strdata, 1);
  238. if (!strdata.empty()) {
  239. cmSystemTools::Stdout(strdata);
  240. }
  241. }
  242. if (!arguments.ErrorQuiet && arguments.ErrorVariable.empty()) {
  243. processOutput.DecodeText(std::string(), strdata, 2);
  244. if (!strdata.empty()) {
  245. cmSystemTools::Stderr(strdata);
  246. }
  247. }
  248. // All output has been read. Wait for the process to exit.
  249. cmsysProcess_WaitForExit(cp, nullptr);
  250. processOutput.DecodeText(tempOutput, tempOutput);
  251. processOutput.DecodeText(tempError, tempError);
  252. // Fix the text in the output strings.
  253. cmExecuteProcessCommandFixText(tempOutput,
  254. arguments.OutputStripTrailingWhitespace);
  255. cmExecuteProcessCommandFixText(tempError,
  256. arguments.ErrorStripTrailingWhitespace);
  257. // Store the output obtained.
  258. if (!arguments.OutputVariable.empty() && !tempOutput.empty()) {
  259. status.GetMakefile().AddDefinition(arguments.OutputVariable,
  260. tempOutput.data());
  261. }
  262. if (!merge_output && !arguments.ErrorVariable.empty() &&
  263. !tempError.empty()) {
  264. status.GetMakefile().AddDefinition(arguments.ErrorVariable,
  265. tempError.data());
  266. }
  267. // Store the result of running the process.
  268. if (!arguments.ResultVariable.empty()) {
  269. switch (cmsysProcess_GetState(cp)) {
  270. case cmsysProcess_State_Exited: {
  271. int v = cmsysProcess_GetExitValue(cp);
  272. char buf[16];
  273. sprintf(buf, "%d", v);
  274. status.GetMakefile().AddDefinition(arguments.ResultVariable, buf);
  275. } break;
  276. case cmsysProcess_State_Exception:
  277. status.GetMakefile().AddDefinition(
  278. arguments.ResultVariable, cmsysProcess_GetExceptionString(cp));
  279. break;
  280. case cmsysProcess_State_Error:
  281. status.GetMakefile().AddDefinition(arguments.ResultVariable,
  282. cmsysProcess_GetErrorString(cp));
  283. break;
  284. case cmsysProcess_State_Expired:
  285. status.GetMakefile().AddDefinition(
  286. arguments.ResultVariable, "Process terminated due to timeout");
  287. break;
  288. }
  289. }
  290. // Store the result of running the processes.
  291. if (!arguments.ResultsVariable.empty()) {
  292. switch (cmsysProcess_GetState(cp)) {
  293. case cmsysProcess_State_Exited: {
  294. std::vector<std::string> res;
  295. for (size_t i = 0; i < arguments.Commands.size(); ++i) {
  296. switch (cmsysProcess_GetStateByIndex(cp, static_cast<int>(i))) {
  297. case kwsysProcess_StateByIndex_Exited: {
  298. int exitCode =
  299. cmsysProcess_GetExitValueByIndex(cp, static_cast<int>(i));
  300. char buf[16];
  301. sprintf(buf, "%d", exitCode);
  302. res.emplace_back(buf);
  303. } break;
  304. case kwsysProcess_StateByIndex_Exception:
  305. res.emplace_back(cmsysProcess_GetExceptionStringByIndex(
  306. cp, static_cast<int>(i)));
  307. break;
  308. case kwsysProcess_StateByIndex_Error:
  309. default:
  310. res.emplace_back("Error getting the child return code");
  311. break;
  312. }
  313. }
  314. status.GetMakefile().AddDefinition(arguments.ResultsVariable,
  315. cmJoin(res, ";"));
  316. } break;
  317. case cmsysProcess_State_Exception:
  318. status.GetMakefile().AddDefinition(
  319. arguments.ResultsVariable, cmsysProcess_GetExceptionString(cp));
  320. break;
  321. case cmsysProcess_State_Error:
  322. status.GetMakefile().AddDefinition(arguments.ResultsVariable,
  323. cmsysProcess_GetErrorString(cp));
  324. break;
  325. case cmsysProcess_State_Expired:
  326. status.GetMakefile().AddDefinition(
  327. arguments.ResultsVariable, "Process terminated due to timeout");
  328. break;
  329. }
  330. }
  331. return true;
  332. }
  333. namespace {
  334. void cmExecuteProcessCommandFixText(std::vector<char>& output,
  335. bool strip_trailing_whitespace)
  336. {
  337. // Remove \0 characters and the \r part of \r\n pairs.
  338. unsigned int in_index = 0;
  339. unsigned int out_index = 0;
  340. while (in_index < output.size()) {
  341. char c = output[in_index++];
  342. if ((c != '\r' ||
  343. !(in_index < output.size() && output[in_index] == '\n')) &&
  344. c != '\0') {
  345. output[out_index++] = c;
  346. }
  347. }
  348. // Remove trailing whitespace if requested.
  349. if (strip_trailing_whitespace) {
  350. while (out_index > 0 &&
  351. cmExecuteProcessCommandIsWhitespace(output[out_index - 1])) {
  352. --out_index;
  353. }
  354. }
  355. // Shrink the vector to the size needed.
  356. output.resize(out_index);
  357. // Put a terminator on the text string.
  358. output.push_back('\0');
  359. }
  360. void cmExecuteProcessCommandAppend(std::vector<char>& output, const char* data,
  361. int length)
  362. {
  363. #if defined(__APPLE__)
  364. // HACK on Apple to work around bug with inserting at the
  365. // end of an empty vector. This resulted in random failures
  366. // that were hard to reproduce.
  367. if (output.empty() && length > 0) {
  368. output.push_back(data[0]);
  369. ++data;
  370. --length;
  371. }
  372. #endif
  373. cm::append(output, data, data + length);
  374. }
  375. }