cmExecuteProcessCommand.cxx 16 KB

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