cmExecuteProcessCommand.cxx 18 KB

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