cmExecuteProcessCommand.cxx 18 KB

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