cmExecuteProcessCommand.cxx 17 KB

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