cmExecuteProcessCommand.cxx 18 KB

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