cmExecuteProcessCommand.cxx 18 KB

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