cmExecuteProcessCommand.cxx 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350
  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. cmsysProcess* cp = cmsysProcess_New();
  109. // Set the command sequence.
  110. for (std::vector<std::string> const& cmd : arguments.Commands) {
  111. std::vector<const char*> argv(cmd.size() + 1);
  112. std::transform(cmd.begin(), cmd.end(), argv.begin(),
  113. [](std::string const& s) { return s.c_str(); });
  114. argv.back() = nullptr;
  115. cmsysProcess_AddCommand(cp, argv.data());
  116. }
  117. // Set the process working directory.
  118. if (!arguments.WorkingDirectory.empty()) {
  119. cmsysProcess_SetWorkingDirectory(cp, arguments.WorkingDirectory.c_str());
  120. }
  121. // Always hide the process window.
  122. cmsysProcess_SetOption(cp, cmsysProcess_Option_HideWindow, 1);
  123. // Check the output variables.
  124. bool merge_output = false;
  125. if (!arguments.InputFile.empty()) {
  126. cmsysProcess_SetPipeFile(cp, cmsysProcess_Pipe_STDIN,
  127. arguments.InputFile.c_str());
  128. }
  129. if (!arguments.OutputFile.empty()) {
  130. cmsysProcess_SetPipeFile(cp, cmsysProcess_Pipe_STDOUT,
  131. arguments.OutputFile.c_str());
  132. }
  133. if (!arguments.ErrorFile.empty()) {
  134. if (arguments.ErrorFile == arguments.OutputFile) {
  135. merge_output = true;
  136. } else {
  137. cmsysProcess_SetPipeFile(cp, cmsysProcess_Pipe_STDERR,
  138. arguments.ErrorFile.c_str());
  139. }
  140. }
  141. if (!arguments.OutputVariable.empty() &&
  142. arguments.OutputVariable == arguments.ErrorVariable) {
  143. merge_output = true;
  144. }
  145. if (merge_output) {
  146. cmsysProcess_SetOption(cp, cmsysProcess_Option_MergeOutput, 1);
  147. }
  148. // Set the timeout if any.
  149. if (timeout >= 0) {
  150. cmsysProcess_SetTimeout(cp, timeout);
  151. }
  152. // Start the process.
  153. cmsysProcess_Execute(cp);
  154. // Read the process output.
  155. std::vector<char> tempOutput;
  156. std::vector<char> tempError;
  157. int length;
  158. char* data;
  159. int p;
  160. cmProcessOutput processOutput(
  161. cmProcessOutput::FindEncoding(arguments.Encoding));
  162. std::string strdata;
  163. while ((p = cmsysProcess_WaitForData(cp, &data, &length, nullptr))) {
  164. // Put the output in the right place.
  165. if (p == cmsysProcess_Pipe_STDOUT && !arguments.OutputQuiet) {
  166. if (arguments.OutputVariable.empty()) {
  167. processOutput.DecodeText(data, length, strdata, 1);
  168. cmSystemTools::Stdout(strdata);
  169. } else {
  170. cmExecuteProcessCommandAppend(tempOutput, data, length);
  171. }
  172. } else if (p == cmsysProcess_Pipe_STDERR && !arguments.ErrorQuiet) {
  173. if (arguments.ErrorVariable.empty()) {
  174. processOutput.DecodeText(data, length, strdata, 2);
  175. cmSystemTools::Stderr(strdata);
  176. } else {
  177. cmExecuteProcessCommandAppend(tempError, data, length);
  178. }
  179. }
  180. }
  181. if (!arguments.OutputQuiet && arguments.OutputVariable.empty()) {
  182. processOutput.DecodeText(std::string(), strdata, 1);
  183. if (!strdata.empty()) {
  184. cmSystemTools::Stdout(strdata);
  185. }
  186. }
  187. if (!arguments.ErrorQuiet && arguments.ErrorVariable.empty()) {
  188. processOutput.DecodeText(std::string(), strdata, 2);
  189. if (!strdata.empty()) {
  190. cmSystemTools::Stderr(strdata);
  191. }
  192. }
  193. // All output has been read. Wait for the process to exit.
  194. cmsysProcess_WaitForExit(cp, nullptr);
  195. processOutput.DecodeText(tempOutput, tempOutput);
  196. processOutput.DecodeText(tempError, tempError);
  197. // Fix the text in the output strings.
  198. cmExecuteProcessCommandFixText(tempOutput,
  199. arguments.OutputStripTrailingWhitespace);
  200. cmExecuteProcessCommandFixText(tempError,
  201. arguments.ErrorStripTrailingWhitespace);
  202. // Store the output obtained.
  203. if (!arguments.OutputVariable.empty() && !tempOutput.empty()) {
  204. this->Makefile->AddDefinition(arguments.OutputVariable, tempOutput.data());
  205. }
  206. if (!merge_output && !arguments.ErrorVariable.empty() &&
  207. !tempError.empty()) {
  208. this->Makefile->AddDefinition(arguments.ErrorVariable, tempError.data());
  209. }
  210. // Store the result of running the process.
  211. if (!arguments.ResultVariable.empty()) {
  212. switch (cmsysProcess_GetState(cp)) {
  213. case cmsysProcess_State_Exited: {
  214. int v = cmsysProcess_GetExitValue(cp);
  215. char buf[16];
  216. sprintf(buf, "%d", v);
  217. this->Makefile->AddDefinition(arguments.ResultVariable, buf);
  218. } break;
  219. case cmsysProcess_State_Exception:
  220. this->Makefile->AddDefinition(arguments.ResultVariable,
  221. cmsysProcess_GetExceptionString(cp));
  222. break;
  223. case cmsysProcess_State_Error:
  224. this->Makefile->AddDefinition(arguments.ResultVariable,
  225. cmsysProcess_GetErrorString(cp));
  226. break;
  227. case cmsysProcess_State_Expired:
  228. this->Makefile->AddDefinition(arguments.ResultVariable,
  229. "Process terminated due to timeout");
  230. break;
  231. }
  232. }
  233. // Store the result of running the processes.
  234. if (!arguments.ResultsVariable.empty()) {
  235. switch (cmsysProcess_GetState(cp)) {
  236. case cmsysProcess_State_Exited: {
  237. std::vector<std::string> res;
  238. for (size_t i = 0; i < arguments.Commands.size(); ++i) {
  239. switch (cmsysProcess_GetStateByIndex(cp, static_cast<int>(i))) {
  240. case kwsysProcess_StateByIndex_Exited: {
  241. int exitCode =
  242. cmsysProcess_GetExitValueByIndex(cp, static_cast<int>(i));
  243. char buf[16];
  244. sprintf(buf, "%d", exitCode);
  245. res.emplace_back(buf);
  246. } break;
  247. case kwsysProcess_StateByIndex_Exception:
  248. res.emplace_back(cmsysProcess_GetExceptionStringByIndex(
  249. cp, static_cast<int>(i)));
  250. break;
  251. case kwsysProcess_StateByIndex_Error:
  252. default:
  253. res.emplace_back("Error getting the child return code");
  254. break;
  255. }
  256. }
  257. this->Makefile->AddDefinition(arguments.ResultsVariable,
  258. cmJoin(res, ";").c_str());
  259. } break;
  260. case cmsysProcess_State_Exception:
  261. this->Makefile->AddDefinition(arguments.ResultsVariable,
  262. cmsysProcess_GetExceptionString(cp));
  263. break;
  264. case cmsysProcess_State_Error:
  265. this->Makefile->AddDefinition(arguments.ResultsVariable,
  266. cmsysProcess_GetErrorString(cp));
  267. break;
  268. case cmsysProcess_State_Expired:
  269. this->Makefile->AddDefinition(arguments.ResultsVariable,
  270. "Process terminated due to timeout");
  271. break;
  272. }
  273. }
  274. // Delete the process instance.
  275. cmsysProcess_Delete(cp);
  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. }