cmExecuteProcessCommand.cxx 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349
  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 "cm_static_string_view.hxx"
  5. #include "cmsys/Process.h"
  6. #include <algorithm>
  7. #include <ctype.h> /* isspace */
  8. #include <stdio.h>
  9. #include "cmAlgorithms.h"
  10. #include "cmArgumentParser.h"
  11. #include "cmMakefile.h"
  12. #include "cmProcessOutput.h"
  13. #include "cmSystemTools.h"
  14. class cmExecutionStatus;
  15. static bool cmExecuteProcessCommandIsWhitespace(char c)
  16. {
  17. return (isspace(static_cast<int>(c)) || c == '\n' || c == '\r');
  18. }
  19. void cmExecuteProcessCommandFixText(std::vector<char>& output,
  20. bool strip_trailing_whitespace);
  21. void cmExecuteProcessCommandAppend(std::vector<char>& output, const char* data,
  22. int length);
  23. // cmExecuteProcessCommand
  24. bool cmExecuteProcessCommand::InitialPass(std::vector<std::string> const& args,
  25. cmExecutionStatus&)
  26. {
  27. if (args.empty()) {
  28. this->SetError("called with incorrect number of arguments");
  29. return false;
  30. }
  31. struct Arguments
  32. {
  33. std::vector<std::vector<std::string>> Commands;
  34. std::string OutputVariable;
  35. std::string ErrorVariable;
  36. std::string ResultVariable;
  37. std::string ResultsVariable;
  38. std::string WorkingDirectory;
  39. std::string InputFile;
  40. std::string OutputFile;
  41. std::string ErrorFile;
  42. std::string Timeout;
  43. bool OutputQuiet = false;
  44. bool ErrorQuiet = false;
  45. bool OutputStripTrailingWhitespace = false;
  46. bool ErrorStripTrailingWhitespace = false;
  47. std::string Encoding;
  48. };
  49. static auto const parser =
  50. cmArgumentParser<Arguments>{}
  51. .Bind("COMMAND"_s, &Arguments::Commands)
  52. .Bind("OUTPUT_VARIABLE"_s, &Arguments::OutputVariable)
  53. .Bind("ERROR_VARIABLE"_s, &Arguments::ErrorVariable)
  54. .Bind("RESULT_VARIABLE"_s, &Arguments::ResultVariable)
  55. .Bind("RESULTS_VARIABLE"_s, &Arguments::ResultsVariable)
  56. .Bind("WORKING_DIRECTORY"_s, &Arguments::WorkingDirectory)
  57. .Bind("INPUT_FILE"_s, &Arguments::InputFile)
  58. .Bind("OUTPUT_FILE"_s, &Arguments::OutputFile)
  59. .Bind("ERROR_FILE"_s, &Arguments::ErrorFile)
  60. .Bind("TIMEOUT"_s, &Arguments::Timeout)
  61. .Bind("OUTPUT_QUIET"_s, &Arguments::OutputQuiet)
  62. .Bind("ERROR_QUIET"_s, &Arguments::ErrorQuiet)
  63. .Bind("OUTPUT_STRIP_TRAILING_WHITESPACE"_s,
  64. &Arguments::OutputStripTrailingWhitespace)
  65. .Bind("ERROR_STRIP_TRAILING_WHITESPACE"_s,
  66. &Arguments::ErrorStripTrailingWhitespace)
  67. .Bind("ENCODING"_s, &Arguments::Encoding);
  68. std::vector<std::string> unparsedArguments;
  69. std::vector<std::string> keywordsMissingValue;
  70. Arguments const arguments =
  71. parser.Parse(args, &unparsedArguments, &keywordsMissingValue);
  72. if (!keywordsMissingValue.empty()) {
  73. this->SetError(" called with no value for " +
  74. keywordsMissingValue.front() + ".");
  75. return false;
  76. }
  77. if (!unparsedArguments.empty()) {
  78. this->SetError(" given unknown argument \"" + unparsedArguments.front() +
  79. "\".");
  80. return false;
  81. }
  82. if (!this->Makefile->CanIWriteThisFile(arguments.OutputFile)) {
  83. this->SetError("attempted to output into a file: " + arguments.OutputFile +
  84. " into a source directory.");
  85. cmSystemTools::SetFatalErrorOccured();
  86. return false;
  87. }
  88. // Check for commands given.
  89. if (arguments.Commands.empty()) {
  90. this->SetError(" called with no COMMAND argument.");
  91. return false;
  92. }
  93. for (std::vector<std::string> const& cmd : arguments.Commands) {
  94. if (cmd.empty()) {
  95. this->SetError(" given COMMAND argument with no value.");
  96. return false;
  97. }
  98. }
  99. // Parse the timeout string.
  100. double timeout = -1;
  101. if (!arguments.Timeout.empty()) {
  102. if (sscanf(arguments.Timeout.c_str(), "%lg", &timeout) != 1) {
  103. this->SetError(" called with TIMEOUT value that could not be parsed.");
  104. return false;
  105. }
  106. }
  107. // Create a process instance.
  108. std::unique_ptr<cmsysProcess, void (*)(cmsysProcess*)> cp_ptr(
  109. cmsysProcess_New(), cmsysProcess_Delete);
  110. cmsysProcess* cp = cp_ptr.get();
  111. // Set the command sequence.
  112. for (std::vector<std::string> const& cmd : arguments.Commands) {
  113. std::vector<const char*> argv(cmd.size() + 1);
  114. std::transform(cmd.begin(), cmd.end(), argv.begin(),
  115. [](std::string const& s) { return s.c_str(); });
  116. argv.back() = nullptr;
  117. cmsysProcess_AddCommand(cp, argv.data());
  118. }
  119. // Set the process working directory.
  120. if (!arguments.WorkingDirectory.empty()) {
  121. cmsysProcess_SetWorkingDirectory(cp, arguments.WorkingDirectory.c_str());
  122. }
  123. // Always hide the process window.
  124. cmsysProcess_SetOption(cp, cmsysProcess_Option_HideWindow, 1);
  125. // Check the output variables.
  126. bool merge_output = false;
  127. if (!arguments.InputFile.empty()) {
  128. cmsysProcess_SetPipeFile(cp, cmsysProcess_Pipe_STDIN,
  129. arguments.InputFile.c_str());
  130. }
  131. if (!arguments.OutputFile.empty()) {
  132. cmsysProcess_SetPipeFile(cp, cmsysProcess_Pipe_STDOUT,
  133. arguments.OutputFile.c_str());
  134. }
  135. if (!arguments.ErrorFile.empty()) {
  136. if (arguments.ErrorFile == arguments.OutputFile) {
  137. merge_output = true;
  138. } else {
  139. cmsysProcess_SetPipeFile(cp, cmsysProcess_Pipe_STDERR,
  140. arguments.ErrorFile.c_str());
  141. }
  142. }
  143. if (!arguments.OutputVariable.empty() &&
  144. arguments.OutputVariable == arguments.ErrorVariable) {
  145. merge_output = true;
  146. }
  147. if (merge_output) {
  148. cmsysProcess_SetOption(cp, cmsysProcess_Option_MergeOutput, 1);
  149. }
  150. // Set the timeout if any.
  151. if (timeout >= 0) {
  152. cmsysProcess_SetTimeout(cp, timeout);
  153. }
  154. // Start the process.
  155. cmsysProcess_Execute(cp);
  156. // Read the process output.
  157. std::vector<char> tempOutput;
  158. std::vector<char> tempError;
  159. int length;
  160. char* data;
  161. int p;
  162. cmProcessOutput processOutput(
  163. cmProcessOutput::FindEncoding(arguments.Encoding));
  164. std::string strdata;
  165. while ((p = cmsysProcess_WaitForData(cp, &data, &length, nullptr))) {
  166. // Put the output in the right place.
  167. if (p == cmsysProcess_Pipe_STDOUT && !arguments.OutputQuiet) {
  168. if (arguments.OutputVariable.empty()) {
  169. processOutput.DecodeText(data, length, strdata, 1);
  170. cmSystemTools::Stdout(strdata);
  171. } else {
  172. cmExecuteProcessCommandAppend(tempOutput, data, length);
  173. }
  174. } else if (p == cmsysProcess_Pipe_STDERR && !arguments.ErrorQuiet) {
  175. if (arguments.ErrorVariable.empty()) {
  176. processOutput.DecodeText(data, length, strdata, 2);
  177. cmSystemTools::Stderr(strdata);
  178. } else {
  179. cmExecuteProcessCommandAppend(tempError, data, length);
  180. }
  181. }
  182. }
  183. if (!arguments.OutputQuiet && arguments.OutputVariable.empty()) {
  184. processOutput.DecodeText(std::string(), strdata, 1);
  185. if (!strdata.empty()) {
  186. cmSystemTools::Stdout(strdata);
  187. }
  188. }
  189. if (!arguments.ErrorQuiet && arguments.ErrorVariable.empty()) {
  190. processOutput.DecodeText(std::string(), strdata, 2);
  191. if (!strdata.empty()) {
  192. cmSystemTools::Stderr(strdata);
  193. }
  194. }
  195. // All output has been read. Wait for the process to exit.
  196. cmsysProcess_WaitForExit(cp, nullptr);
  197. processOutput.DecodeText(tempOutput, tempOutput);
  198. processOutput.DecodeText(tempError, tempError);
  199. // Fix the text in the output strings.
  200. cmExecuteProcessCommandFixText(tempOutput,
  201. arguments.OutputStripTrailingWhitespace);
  202. cmExecuteProcessCommandFixText(tempError,
  203. arguments.ErrorStripTrailingWhitespace);
  204. // Store the output obtained.
  205. if (!arguments.OutputVariable.empty() && !tempOutput.empty()) {
  206. this->Makefile->AddDefinition(arguments.OutputVariable, tempOutput.data());
  207. }
  208. if (!merge_output && !arguments.ErrorVariable.empty() &&
  209. !tempError.empty()) {
  210. this->Makefile->AddDefinition(arguments.ErrorVariable, tempError.data());
  211. }
  212. // Store the result of running the process.
  213. if (!arguments.ResultVariable.empty()) {
  214. switch (cmsysProcess_GetState(cp)) {
  215. case cmsysProcess_State_Exited: {
  216. int v = cmsysProcess_GetExitValue(cp);
  217. char buf[16];
  218. sprintf(buf, "%d", v);
  219. this->Makefile->AddDefinition(arguments.ResultVariable, buf);
  220. } break;
  221. case cmsysProcess_State_Exception:
  222. this->Makefile->AddDefinition(arguments.ResultVariable,
  223. cmsysProcess_GetExceptionString(cp));
  224. break;
  225. case cmsysProcess_State_Error:
  226. this->Makefile->AddDefinition(arguments.ResultVariable,
  227. cmsysProcess_GetErrorString(cp));
  228. break;
  229. case cmsysProcess_State_Expired:
  230. this->Makefile->AddDefinition(arguments.ResultVariable,
  231. "Process terminated due to timeout");
  232. break;
  233. }
  234. }
  235. // Store the result of running the processes.
  236. if (!arguments.ResultsVariable.empty()) {
  237. switch (cmsysProcess_GetState(cp)) {
  238. case cmsysProcess_State_Exited: {
  239. std::vector<std::string> res;
  240. for (size_t i = 0; i < arguments.Commands.size(); ++i) {
  241. switch (cmsysProcess_GetStateByIndex(cp, static_cast<int>(i))) {
  242. case kwsysProcess_StateByIndex_Exited: {
  243. int exitCode =
  244. cmsysProcess_GetExitValueByIndex(cp, static_cast<int>(i));
  245. char buf[16];
  246. sprintf(buf, "%d", exitCode);
  247. res.emplace_back(buf);
  248. } break;
  249. case kwsysProcess_StateByIndex_Exception:
  250. res.emplace_back(cmsysProcess_GetExceptionStringByIndex(
  251. cp, static_cast<int>(i)));
  252. break;
  253. case kwsysProcess_StateByIndex_Error:
  254. default:
  255. res.emplace_back("Error getting the child return code");
  256. break;
  257. }
  258. }
  259. this->Makefile->AddDefinition(arguments.ResultsVariable,
  260. cmJoin(res, ";").c_str());
  261. } break;
  262. case cmsysProcess_State_Exception:
  263. this->Makefile->AddDefinition(arguments.ResultsVariable,
  264. cmsysProcess_GetExceptionString(cp));
  265. break;
  266. case cmsysProcess_State_Error:
  267. this->Makefile->AddDefinition(arguments.ResultsVariable,
  268. cmsysProcess_GetErrorString(cp));
  269. break;
  270. case cmsysProcess_State_Expired:
  271. this->Makefile->AddDefinition(arguments.ResultsVariable,
  272. "Process terminated due to timeout");
  273. break;
  274. }
  275. }
  276. return true;
  277. }
  278. void cmExecuteProcessCommandFixText(std::vector<char>& output,
  279. bool strip_trailing_whitespace)
  280. {
  281. // Remove \0 characters and the \r part of \r\n pairs.
  282. unsigned int in_index = 0;
  283. unsigned int out_index = 0;
  284. while (in_index < output.size()) {
  285. char c = output[in_index++];
  286. if ((c != '\r' ||
  287. !(in_index < output.size() && output[in_index] == '\n')) &&
  288. c != '\0') {
  289. output[out_index++] = c;
  290. }
  291. }
  292. // Remove trailing whitespace if requested.
  293. if (strip_trailing_whitespace) {
  294. while (out_index > 0 &&
  295. cmExecuteProcessCommandIsWhitespace(output[out_index - 1])) {
  296. --out_index;
  297. }
  298. }
  299. // Shrink the vector to the size needed.
  300. output.resize(out_index);
  301. // Put a terminator on the text string.
  302. output.push_back('\0');
  303. }
  304. void cmExecuteProcessCommandAppend(std::vector<char>& output, const char* data,
  305. int length)
  306. {
  307. #if defined(__APPLE__)
  308. // HACK on Apple to work around bug with inserting at the
  309. // end of an empty vector. This resulted in random failures
  310. // that were hard to reproduce.
  311. if (output.empty() && length > 0) {
  312. output.push_back(data[0]);
  313. ++data;
  314. --length;
  315. }
  316. #endif
  317. output.insert(output.end(), data, data + length);
  318. }