cmExecuteProcessCommand.cxx 17 KB

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