cmExecuteProcessCommand.cxx 18 KB

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