cmExecuteProcessCommand.cxx 17 KB

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