cmExecuteProcessCommand.cxx 13 KB

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