cmExecuteProcessCommand.cxx 19 KB

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