cmExecuteProcessCommand.cxx 18 KB

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