cmExecuteProcessCommand.cxx 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551
  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 "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 (isspace(static_cast<int>(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. inputFile.get());
  167. }
  168. } else {
  169. builder.SetExternalStream(cmUVProcessChainBuilder::Stream_INPUT, stdin);
  170. }
  171. std::unique_ptr<FILE, int (*)(FILE*)> outputFile(nullptr, fclose);
  172. if (!outputFilename.empty()) {
  173. outputFile.reset(cmsys::SystemTools::Fopen(outputFilename, "wb"));
  174. if (outputFile) {
  175. builder.SetExternalStream(cmUVProcessChainBuilder::Stream_OUTPUT,
  176. outputFile.get());
  177. }
  178. } else {
  179. if (arguments.OutputVariable == arguments.ErrorVariable &&
  180. !arguments.ErrorVariable.empty()) {
  181. builder.SetMergedBuiltinStreams();
  182. } else {
  183. builder.SetBuiltinStream(cmUVProcessChainBuilder::Stream_OUTPUT);
  184. }
  185. }
  186. std::unique_ptr<FILE, int (*)(FILE*)> errorFile(nullptr, fclose);
  187. if (!errorFilename.empty()) {
  188. if (errorFilename == outputFilename) {
  189. if (outputFile) {
  190. builder.SetExternalStream(cmUVProcessChainBuilder::Stream_ERROR,
  191. outputFile.get());
  192. }
  193. } else {
  194. errorFile.reset(cmsys::SystemTools::Fopen(errorFilename, "wb"));
  195. if (errorFile) {
  196. builder.SetExternalStream(cmUVProcessChainBuilder::Stream_ERROR,
  197. errorFile.get());
  198. }
  199. }
  200. } else if (arguments.ErrorVariable.empty() ||
  201. (!arguments.ErrorVariable.empty() &&
  202. arguments.OutputVariable != arguments.ErrorVariable)) {
  203. builder.SetBuiltinStream(cmUVProcessChainBuilder::Stream_ERROR);
  204. }
  205. // Set the timeout if any.
  206. int64_t timeoutMillis = static_cast<int64_t>(timeout * 1000.0);
  207. bool echo_stdout = false;
  208. bool echo_stderr = false;
  209. bool echo_output_from_variable = true;
  210. std::string echo_output = status.GetMakefile().GetSafeDefinition(
  211. "CMAKE_EXECUTE_PROCESS_COMMAND_ECHO");
  212. if (!arguments.CommandEcho.empty()) {
  213. echo_output_from_variable = false;
  214. echo_output = arguments.CommandEcho;
  215. }
  216. if (!echo_output.empty()) {
  217. if (echo_output == "STDERR") {
  218. echo_stderr = true;
  219. } else if (echo_output == "STDOUT") {
  220. echo_stdout = true;
  221. } else if (echo_output != "NONE") {
  222. std::string error;
  223. if (echo_output_from_variable) {
  224. error = "CMAKE_EXECUTE_PROCESS_COMMAND_ECHO set to '";
  225. } else {
  226. error = " called with '";
  227. }
  228. error += echo_output;
  229. error += "' expected STDERR|STDOUT|NONE";
  230. if (!echo_output_from_variable) {
  231. error += " for COMMAND_ECHO.";
  232. }
  233. status.GetMakefile().IssueMessage(MessageType::FATAL_ERROR, error);
  234. return true;
  235. }
  236. }
  237. if (echo_stdout || echo_stderr) {
  238. std::string command;
  239. for (const auto& cmd : arguments.Commands) {
  240. command += "'";
  241. command += cmJoin(cmd, "' '");
  242. command += "'";
  243. command += "\n";
  244. }
  245. if (echo_stdout) {
  246. std::cout << command;
  247. } else if (echo_stderr) {
  248. std::cerr << command;
  249. }
  250. }
  251. // Start the process.
  252. auto chain = builder.Start();
  253. bool timedOut = false;
  254. cm::uv_timer_ptr timer;
  255. if (timeoutMillis >= 0) {
  256. timer.init(chain.GetLoop(), &timedOut);
  257. timer.start(
  258. [](uv_timer_t* handle) {
  259. auto* timeoutPtr = static_cast<bool*>(handle->data);
  260. *timeoutPtr = true;
  261. },
  262. timeoutMillis, 0);
  263. }
  264. // Read the process output.
  265. struct ReadData
  266. {
  267. bool Finished = false;
  268. std::vector<char> Output;
  269. cm::uv_pipe_ptr Stream;
  270. };
  271. ReadData outputData;
  272. ReadData errorData;
  273. cmProcessOutput processOutput(
  274. cmProcessOutput::FindEncoding(arguments.Encoding));
  275. std::string strdata;
  276. std::unique_ptr<cmUVStreamReadHandle> outputHandle;
  277. if (chain.OutputStream() >= 0) {
  278. outputData.Stream.init(chain.GetLoop(), 0);
  279. uv_pipe_open(outputData.Stream, chain.OutputStream());
  280. outputHandle = cmUVStreamRead(
  281. outputData.Stream,
  282. [&arguments, &processOutput, &outputData,
  283. &strdata](std::vector<char> data) {
  284. if (!arguments.OutputQuiet) {
  285. if (arguments.OutputVariable.empty() ||
  286. arguments.EchoOutputVariable) {
  287. processOutput.DecodeText(data.data(), data.size(), strdata, 1);
  288. cmSystemTools::Stdout(strdata);
  289. }
  290. if (!arguments.OutputVariable.empty()) {
  291. cmExecuteProcessCommandAppend(outputData.Output, data.data(),
  292. data.size());
  293. }
  294. }
  295. },
  296. [&outputData]() { outputData.Finished = true; });
  297. } else {
  298. outputData.Finished = true;
  299. }
  300. std::unique_ptr<cmUVStreamReadHandle> errorHandle;
  301. if (chain.ErrorStream() >= 0 &&
  302. chain.ErrorStream() != chain.OutputStream()) {
  303. errorData.Stream.init(chain.GetLoop(), 0);
  304. uv_pipe_open(errorData.Stream, chain.ErrorStream());
  305. errorHandle = cmUVStreamRead(
  306. errorData.Stream,
  307. [&arguments, &processOutput, &errorData,
  308. &strdata](std::vector<char> data) {
  309. if (!arguments.ErrorQuiet) {
  310. if (arguments.ErrorVariable.empty() || arguments.EchoErrorVariable) {
  311. processOutput.DecodeText(data.data(), data.size(), strdata, 2);
  312. cmSystemTools::Stderr(strdata);
  313. }
  314. if (!arguments.ErrorVariable.empty()) {
  315. cmExecuteProcessCommandAppend(errorData.Output, data.data(),
  316. data.size());
  317. }
  318. }
  319. },
  320. [&errorData]() { errorData.Finished = true; });
  321. } else {
  322. errorData.Finished = true;
  323. }
  324. while (chain.Valid() && !timedOut &&
  325. !(chain.Finished() && outputData.Finished && errorData.Finished)) {
  326. uv_run(&chain.GetLoop(), UV_RUN_ONCE);
  327. }
  328. if (!arguments.OutputQuiet &&
  329. (arguments.OutputVariable.empty() || arguments.EchoOutputVariable)) {
  330. processOutput.DecodeText(std::string(), strdata, 1);
  331. if (!strdata.empty()) {
  332. cmSystemTools::Stdout(strdata);
  333. }
  334. }
  335. if (!arguments.ErrorQuiet &&
  336. (arguments.ErrorVariable.empty() || arguments.EchoErrorVariable)) {
  337. processOutput.DecodeText(std::string(), strdata, 2);
  338. if (!strdata.empty()) {
  339. cmSystemTools::Stderr(strdata);
  340. }
  341. }
  342. // All output has been read.
  343. processOutput.DecodeText(outputData.Output, outputData.Output);
  344. processOutput.DecodeText(errorData.Output, errorData.Output);
  345. // Fix the text in the output strings.
  346. cmExecuteProcessCommandFixText(outputData.Output,
  347. arguments.OutputStripTrailingWhitespace);
  348. cmExecuteProcessCommandFixText(errorData.Output,
  349. arguments.ErrorStripTrailingWhitespace);
  350. // Store the output obtained.
  351. if (!arguments.OutputVariable.empty() && !outputData.Output.empty()) {
  352. status.GetMakefile().AddDefinition(arguments.OutputVariable,
  353. outputData.Output.data());
  354. }
  355. if (arguments.ErrorVariable != arguments.OutputVariable &&
  356. !arguments.ErrorVariable.empty() && !errorData.Output.empty()) {
  357. status.GetMakefile().AddDefinition(arguments.ErrorVariable,
  358. errorData.Output.data());
  359. }
  360. // Store the result of running the process.
  361. if (!arguments.ResultVariable.empty()) {
  362. if (timedOut) {
  363. status.GetMakefile().AddDefinition(arguments.ResultVariable,
  364. "Process terminated due to timeout");
  365. } else {
  366. auto const* lastStatus = chain.GetStatus().back();
  367. auto exception = lastStatus->GetException();
  368. if (exception.first == cmUVProcessChain::ExceptionCode::None) {
  369. status.GetMakefile().AddDefinition(
  370. arguments.ResultVariable,
  371. std::to_string(static_cast<int>(lastStatus->ExitStatus)));
  372. } else {
  373. status.GetMakefile().AddDefinition(arguments.ResultVariable,
  374. exception.second);
  375. }
  376. }
  377. }
  378. // Store the result of running the processes.
  379. if (!arguments.ResultsVariable.empty()) {
  380. if (timedOut) {
  381. status.GetMakefile().AddDefinition(arguments.ResultsVariable,
  382. "Process terminated due to timeout");
  383. } else {
  384. std::vector<std::string> res;
  385. for (auto const* processStatus : chain.GetStatus()) {
  386. auto exception = processStatus->GetException();
  387. if (exception.first == cmUVProcessChain::ExceptionCode::None) {
  388. res.emplace_back(
  389. std::to_string(static_cast<int>(processStatus->ExitStatus)));
  390. } else {
  391. res.emplace_back(exception.second);
  392. }
  393. }
  394. status.GetMakefile().AddDefinition(arguments.ResultsVariable,
  395. cmList::to_string(res));
  396. }
  397. }
  398. auto queryProcessStatusByIndex = [&chain](std::size_t index) -> std::string {
  399. auto const& processStatus = chain.GetStatus(index);
  400. auto exception = processStatus.GetException();
  401. if (exception.first == cmUVProcessChain::ExceptionCode::None) {
  402. if (processStatus.ExitStatus) {
  403. return cmStrCat("Child return code: ", processStatus.ExitStatus);
  404. }
  405. return "";
  406. }
  407. return cmStrCat("Abnormal exit with child return code: ",
  408. exception.second);
  409. };
  410. if (arguments.CommandErrorIsFatal == "ANY"_s) {
  411. bool ret = true;
  412. if (timedOut) {
  413. status.SetError("Process terminated due to timeout");
  414. ret = false;
  415. } else {
  416. std::map<std::size_t, std::string> failureIndices;
  417. auto statuses = chain.GetStatus();
  418. for (std::size_t i = 0; i < statuses.size(); ++i) {
  419. std::string processStatus = queryProcessStatusByIndex(i);
  420. if (!processStatus.empty()) {
  421. failureIndices[i] = processStatus;
  422. }
  423. }
  424. if (!failureIndices.empty()) {
  425. std::ostringstream oss;
  426. oss << "failed command indexes:\n";
  427. for (auto const& e : failureIndices) {
  428. oss << " " << e.first + 1 << ": \"" << e.second << "\"\n";
  429. }
  430. status.SetError(oss.str());
  431. ret = false;
  432. }
  433. }
  434. if (!ret) {
  435. cmSystemTools::SetFatalErrorOccurred();
  436. return false;
  437. }
  438. }
  439. if (arguments.CommandErrorIsFatal == "LAST"_s) {
  440. bool ret = true;
  441. if (timedOut) {
  442. status.SetError("Process terminated due to timeout");
  443. ret = false;
  444. } else {
  445. auto const& lastStatus = chain.GetStatus(arguments.Commands.size() - 1);
  446. auto exception = lastStatus.GetException();
  447. if (exception.first != cmUVProcessChain::ExceptionCode::None) {
  448. status.SetError(cmStrCat("Abnormal exit: ", exception.second));
  449. ret = false;
  450. } else {
  451. int lastIndex = static_cast<int>(arguments.Commands.size() - 1);
  452. const std::string processStatus = queryProcessStatusByIndex(lastIndex);
  453. if (!processStatus.empty()) {
  454. status.SetError("last command failed");
  455. ret = false;
  456. }
  457. }
  458. }
  459. if (!ret) {
  460. cmSystemTools::SetFatalErrorOccurred();
  461. return false;
  462. }
  463. }
  464. return true;
  465. }
  466. namespace {
  467. void cmExecuteProcessCommandFixText(std::vector<char>& output,
  468. bool strip_trailing_whitespace)
  469. {
  470. // Remove \0 characters and the \r part of \r\n pairs.
  471. unsigned int in_index = 0;
  472. unsigned int out_index = 0;
  473. while (in_index < output.size()) {
  474. char c = output[in_index++];
  475. if ((c != '\r' ||
  476. !(in_index < output.size() && output[in_index] == '\n')) &&
  477. c != '\0') {
  478. output[out_index++] = c;
  479. }
  480. }
  481. // Remove trailing whitespace if requested.
  482. if (strip_trailing_whitespace) {
  483. while (out_index > 0 &&
  484. cmExecuteProcessCommandIsWhitespace(output[out_index - 1])) {
  485. --out_index;
  486. }
  487. }
  488. // Shrink the vector to the size needed.
  489. output.resize(out_index);
  490. // Put a terminator on the text string.
  491. output.push_back('\0');
  492. }
  493. void cmExecuteProcessCommandAppend(std::vector<char>& output, const char* data,
  494. std::size_t length)
  495. {
  496. #if defined(__APPLE__)
  497. // HACK on Apple to work around bug with inserting at the
  498. // end of an empty vector. This resulted in random failures
  499. // that were hard to reproduce.
  500. if (output.empty() && length > 0) {
  501. output.push_back(data[0]);
  502. ++data;
  503. --length;
  504. }
  505. #endif
  506. cm::append(output, data, data + length);
  507. }
  508. }