cmExecuteProcessCommand.cxx 13 KB

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