cmExecuteProcessCommand.cxx 13 KB

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