cmCTestLaunch.cxx 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421
  1. /* Distributed under the OSI-approved BSD 3-Clause License. See accompanying
  2. file LICENSE.rst or https://cmake.org/licensing for details. */
  3. #include "cmCTestLaunch.h"
  4. #include <cstdio>
  5. #include <cstring>
  6. #include <functional>
  7. #include <iostream>
  8. #include <map>
  9. #include <memory>
  10. #include <utility>
  11. #include <cm/optional>
  12. #include <cm3p/uv.h>
  13. #include "cmsys/FStream.hxx"
  14. #include "cmsys/RegularExpression.hxx"
  15. #include "cmCMakePath.h"
  16. #include "cmCTestLaunchReporter.h"
  17. #include "cmGlobalGenerator.h"
  18. #include "cmInstrumentation.h"
  19. #include "cmMakefile.h"
  20. #include "cmProcessOutput.h"
  21. #include "cmState.h"
  22. #include "cmStateSnapshot.h"
  23. #include "cmStringAlgorithms.h"
  24. #include "cmSystemTools.h"
  25. #include "cmUVHandlePtr.h"
  26. #include "cmUVProcessChain.h"
  27. #include "cmUVStream.h"
  28. #include "cmake.h"
  29. #ifdef _WIN32
  30. # include <cstdio> // for std{out,err} and fileno
  31. # include <fcntl.h> // for _O_BINARY
  32. # include <io.h> // for _setmode
  33. #endif
  34. cmCTestLaunch::cmCTestLaunch(int argc, char const* const* argv, Op operation)
  35. {
  36. if (!this->ParseArguments(argc, argv)) {
  37. return;
  38. }
  39. this->Reporter.RealArgs = this->RealArgs;
  40. this->Reporter.ComputeFileNames();
  41. this->ScrapeRulesLoaded = false;
  42. this->HaveOut = false;
  43. this->HaveErr = false;
  44. this->Operation = operation;
  45. }
  46. cmCTestLaunch::~cmCTestLaunch() = default;
  47. bool cmCTestLaunch::ParseArguments(int argc, char const* const* argv)
  48. {
  49. // Launcher options occur first and are separated from the real
  50. // command line by a '--' option.
  51. enum Doing
  52. {
  53. DoingNone,
  54. DoingOutput,
  55. DoingSource,
  56. DoingLanguage,
  57. DoingTargetLabels,
  58. DoingTargetName,
  59. DoingTargetType,
  60. DoingCommandType,
  61. DoingRole,
  62. DoingBuildDir,
  63. DoingCurrentBuildDir,
  64. DoingCount,
  65. DoingFilterPrefix,
  66. DoingConfig,
  67. DoingObjectDir
  68. };
  69. Doing doing = DoingNone;
  70. int arg0 = 0;
  71. for (int i = 1; !arg0 && i < argc; ++i) {
  72. char const* arg = argv[i];
  73. if (strcmp(arg, "--") == 0) {
  74. arg0 = i + 1;
  75. } else if (strcmp(arg, "--command-type") == 0) {
  76. doing = DoingCommandType;
  77. } else if (strcmp(arg, "--output") == 0) {
  78. doing = DoingOutput;
  79. } else if (strcmp(arg, "--source") == 0) {
  80. doing = DoingSource;
  81. } else if (strcmp(arg, "--language") == 0) {
  82. doing = DoingLanguage;
  83. } else if (strcmp(arg, "--target-labels") == 0) {
  84. doing = DoingTargetLabels;
  85. } else if (strcmp(arg, "--target-name") == 0) {
  86. doing = DoingTargetName;
  87. } else if (strcmp(arg, "--target-type") == 0) {
  88. doing = DoingTargetType;
  89. } else if (strcmp(arg, "--role") == 0) {
  90. doing = DoingRole;
  91. } else if (strcmp(arg, "--build-dir") == 0) {
  92. doing = DoingBuildDir;
  93. } else if (strcmp(arg, "--current-build-dir") == 0) {
  94. doing = DoingCurrentBuildDir;
  95. } else if (strcmp(arg, "--filter-prefix") == 0) {
  96. doing = DoingFilterPrefix;
  97. } else if (strcmp(arg, "--config") == 0) {
  98. doing = DoingConfig;
  99. } else if (strcmp(arg, "--object-dir") == 0) {
  100. doing = DoingObjectDir;
  101. } else if (doing == DoingOutput) {
  102. this->Reporter.OptionOutput = arg;
  103. doing = DoingNone;
  104. } else if (doing == DoingSource) {
  105. this->Reporter.OptionSource = arg;
  106. doing = DoingNone;
  107. } else if (doing == DoingLanguage) {
  108. this->Reporter.OptionLanguage = arg;
  109. if (this->Reporter.OptionLanguage == "CXX") {
  110. this->Reporter.OptionLanguage = "C++";
  111. }
  112. doing = DoingNone;
  113. } else if (doing == DoingTargetLabels) {
  114. this->Reporter.OptionTargetLabels = arg;
  115. doing = DoingNone;
  116. } else if (doing == DoingTargetName) {
  117. this->Reporter.OptionTargetName = arg;
  118. doing = DoingNone;
  119. } else if (doing == DoingTargetType) {
  120. this->Reporter.OptionTargetType = arg;
  121. doing = DoingNone;
  122. } else if (doing == DoingBuildDir) {
  123. this->Reporter.OptionBuildDir = arg;
  124. doing = DoingNone;
  125. } else if (doing == DoingCurrentBuildDir) {
  126. this->Reporter.OptionCurrentBuildDir = arg;
  127. doing = DoingNone;
  128. } else if (doing == DoingFilterPrefix) {
  129. this->Reporter.OptionFilterPrefix = arg;
  130. doing = DoingNone;
  131. } else if (doing == DoingCommandType) {
  132. this->Reporter.OptionCommandType = arg;
  133. doing = DoingNone;
  134. } else if (doing == DoingRole) {
  135. this->Reporter.OptionRole = arg;
  136. doing = DoingNone;
  137. } else if (doing == DoingConfig) {
  138. this->Reporter.OptionConfig = arg;
  139. doing = DoingNone;
  140. } else if (doing == DoingObjectDir) {
  141. this->Reporter.OptionObjectDir = arg;
  142. doing = DoingNone;
  143. }
  144. }
  145. // Older builds do not pass `--object-dir`, so construct a default if the
  146. // components are available.
  147. if (this->Reporter.OptionObjectDir.empty() &&
  148. !this->Reporter.OptionCurrentBuildDir.empty() &&
  149. !this->Reporter.OptionTargetName.empty()) {
  150. this->Reporter.OptionObjectDir =
  151. cmStrCat(this->Reporter.OptionCurrentBuildDir, "/CMakeFiles/",
  152. this->Reporter.OptionTargetName, ".dir");
  153. }
  154. if (!this->Reporter.OptionObjectDir.empty() &&
  155. !cmCMakePath(this->Reporter.OptionObjectDir).IsAbsolute() &&
  156. !this->Reporter.OptionBuildDir.empty()) {
  157. this->Reporter.OptionObjectDir = cmStrCat(
  158. this->Reporter.OptionBuildDir, '/', this->Reporter.OptionObjectDir);
  159. }
  160. // Extract the real command line.
  161. if (arg0) {
  162. for (int i = 0; i < argc - arg0; ++i) {
  163. this->RealArgV.emplace_back((argv + arg0)[i]);
  164. this->HandleRealArg((argv + arg0)[i]);
  165. }
  166. return true;
  167. }
  168. std::cerr << "No launch/command separator ('--') found!\n";
  169. return false;
  170. }
  171. void cmCTestLaunch::HandleRealArg(char const* arg)
  172. {
  173. #ifdef _WIN32
  174. // Expand response file arguments.
  175. if (arg[0] == '@' && cmSystemTools::FileExists(arg + 1)) {
  176. cmsys::ifstream fin(arg + 1);
  177. std::string line;
  178. while (cmSystemTools::GetLineFromStream(fin, line)) {
  179. cmSystemTools::ParseWindowsCommandLine(line.c_str(), this->RealArgs);
  180. }
  181. return;
  182. }
  183. #endif
  184. this->RealArgs.emplace_back(arg);
  185. }
  186. void cmCTestLaunch::RunChild()
  187. {
  188. // Ignore noopt make rules
  189. if (this->RealArgs.empty() || this->RealArgs[0] == ":") {
  190. this->Reporter.ExitCode = 0;
  191. return;
  192. }
  193. // Prepare to run the real command.
  194. cmUVProcessChainBuilder builder;
  195. builder.AddCommand(this->RealArgV);
  196. cmsys::ofstream fout;
  197. cmsys::ofstream ferr;
  198. if (this->Reporter.Passthru) {
  199. // In passthru mode we just share the output pipes.
  200. builder.SetExternalStream(cmUVProcessChainBuilder::Stream_OUTPUT, stdout)
  201. .SetExternalStream(cmUVProcessChainBuilder::Stream_ERROR, stderr);
  202. } else {
  203. // In full mode we record the child output pipes to log files.
  204. builder.SetBuiltinStream(cmUVProcessChainBuilder::Stream_OUTPUT)
  205. .SetBuiltinStream(cmUVProcessChainBuilder::Stream_ERROR);
  206. fout.open(this->Reporter.LogOut.c_str(), std::ios::out | std::ios::binary);
  207. ferr.open(this->Reporter.LogErr.c_str(), std::ios::out | std::ios::binary);
  208. }
  209. #ifdef _WIN32
  210. // Do this so that newline transformation is not done when writing to cout
  211. // and cerr below.
  212. _setmode(fileno(stdout), _O_BINARY);
  213. _setmode(fileno(stderr), _O_BINARY);
  214. #endif
  215. // Run the real command.
  216. auto chain = builder.Start();
  217. // Record child stdout and stderr if necessary.
  218. cm::uv_pipe_ptr outPipe;
  219. cm::uv_pipe_ptr errPipe;
  220. bool outFinished = true;
  221. bool errFinished = true;
  222. cmProcessOutput processOutput;
  223. std::unique_ptr<cmUVStreamReadHandle> outputHandle;
  224. std::unique_ptr<cmUVStreamReadHandle> errorHandle;
  225. if (!this->Reporter.Passthru) {
  226. auto beginRead = [&chain, &processOutput](
  227. cm::uv_pipe_ptr& pipe, int stream, std::ostream& out,
  228. cmsys::ofstream& file, bool& haveData, bool& finished,
  229. int id) -> std::unique_ptr<cmUVStreamReadHandle> {
  230. pipe.init(chain.GetLoop(), 0);
  231. uv_pipe_open(pipe, stream);
  232. finished = false;
  233. return cmUVStreamRead(
  234. pipe,
  235. [&processOutput, &out, &file, id, &haveData](std::vector<char> data) {
  236. std::string strdata;
  237. processOutput.DecodeText(data.data(), data.size(), strdata, id);
  238. file.write(strdata.c_str(), strdata.size());
  239. out.write(strdata.c_str(), strdata.size());
  240. haveData = true;
  241. },
  242. [&processOutput, &out, &file, &finished, id]() {
  243. std::string strdata;
  244. processOutput.DecodeText(std::string(), strdata, id);
  245. if (!strdata.empty()) {
  246. file.write(strdata.c_str(), strdata.size());
  247. out.write(strdata.c_str(), strdata.size());
  248. }
  249. finished = true;
  250. });
  251. };
  252. outputHandle = beginRead(outPipe, chain.OutputStream(), std::cout, fout,
  253. this->HaveOut, outFinished, 1);
  254. errorHandle = beginRead(errPipe, chain.ErrorStream(), std::cerr, ferr,
  255. this->HaveErr, errFinished, 2);
  256. }
  257. // Wait for the real command to finish.
  258. while (!(chain.Finished() && outFinished && errFinished)) {
  259. uv_run(&chain.GetLoop(), UV_RUN_ONCE);
  260. }
  261. this->Reporter.Status = chain.GetStatus(0);
  262. if (this->Reporter.Status.GetException().first ==
  263. cmUVProcessChain::ExceptionCode::Spawn) {
  264. this->Reporter.ExitCode = 1;
  265. } else {
  266. this->Reporter.ExitCode =
  267. static_cast<int>(this->Reporter.Status.ExitStatus);
  268. }
  269. }
  270. int cmCTestLaunch::Run()
  271. {
  272. auto instrumentation = cmInstrumentation(this->Reporter.OptionBuildDir);
  273. std::map<std::string, std::string> options;
  274. if (this->Reporter.OptionTargetName != "TARGET_NAME") {
  275. options["target"] = this->Reporter.OptionTargetName;
  276. }
  277. options["source"] = this->Reporter.OptionSource;
  278. options["language"] = this->Reporter.OptionLanguage;
  279. options["targetType"] = this->Reporter.OptionTargetType;
  280. options["role"] = this->Reporter.OptionRole;
  281. options["config"] = this->Reporter.OptionConfig;
  282. std::map<std::string, std::string> arrayOptions;
  283. arrayOptions["outputs"] = this->Reporter.OptionOutput;
  284. arrayOptions["targetLabels"] = this->Reporter.OptionTargetLabels;
  285. instrumentation.InstrumentCommand(
  286. this->Reporter.OptionCommandType, this->RealArgV,
  287. [this]() -> int {
  288. this->RunChild();
  289. return this->Reporter.ExitCode;
  290. },
  291. options, arrayOptions);
  292. if (this->Operation == Op::Normal) {
  293. if (this->CheckResults()) {
  294. return this->Reporter.ExitCode;
  295. }
  296. this->LoadConfig();
  297. this->Reporter.WriteXML();
  298. }
  299. return this->Reporter.ExitCode;
  300. }
  301. bool cmCTestLaunch::CheckResults()
  302. {
  303. // Skip XML in passthru mode.
  304. if (this->Reporter.Passthru) {
  305. return true;
  306. }
  307. // We always report failure for error conditions.
  308. if (this->Reporter.IsError()) {
  309. return false;
  310. }
  311. // Scrape the output logs to look for warnings.
  312. if ((this->HaveErr && this->ScrapeLog(this->Reporter.LogErr)) ||
  313. (this->HaveOut && this->ScrapeLog(this->Reporter.LogOut))) {
  314. return false;
  315. }
  316. return true;
  317. }
  318. void cmCTestLaunch::LoadScrapeRules()
  319. {
  320. if (this->ScrapeRulesLoaded) {
  321. return;
  322. }
  323. this->ScrapeRulesLoaded = true;
  324. // Load custom match rules given to us by CTest.
  325. this->LoadScrapeRules("Warning", this->Reporter.RegexWarning);
  326. this->LoadScrapeRules("WarningSuppress",
  327. this->Reporter.RegexWarningSuppress);
  328. }
  329. void cmCTestLaunch::LoadScrapeRules(
  330. char const* purpose, std::vector<cmsys::RegularExpression>& regexps) const
  331. {
  332. std::string fname =
  333. cmStrCat(this->Reporter.LogDir, "Custom", purpose, ".txt");
  334. cmsys::ifstream fin(fname.c_str(), std::ios::in | std::ios::binary);
  335. std::string line;
  336. cmsys::RegularExpression rex;
  337. while (cmSystemTools::GetLineFromStream(fin, line)) {
  338. if (rex.compile(line)) {
  339. regexps.push_back(rex);
  340. }
  341. }
  342. }
  343. bool cmCTestLaunch::ScrapeLog(std::string const& fname)
  344. {
  345. this->LoadScrapeRules();
  346. // Look for log file lines matching warning expressions but not
  347. // suppression expressions.
  348. cmsys::ifstream fin(fname.c_str(), std::ios::in | std::ios::binary);
  349. std::string line;
  350. while (cmSystemTools::GetLineFromStream(fin, line)) {
  351. if (this->Reporter.MatchesFilterPrefix(line)) {
  352. continue;
  353. }
  354. if (this->Reporter.Match(line, this->Reporter.RegexWarning) &&
  355. !this->Reporter.Match(line, this->Reporter.RegexWarningSuppress)) {
  356. return true;
  357. }
  358. }
  359. return false;
  360. }
  361. int cmCTestLaunch::Main(int argc, char const* const argv[], Op operation)
  362. {
  363. if (argc == 2) {
  364. std::cerr << "ctest --launch: this mode is for internal CTest use only"
  365. << std::endl;
  366. return 1;
  367. }
  368. cmCTestLaunch self(argc, argv, operation);
  369. return self.Run();
  370. }
  371. void cmCTestLaunch::LoadConfig()
  372. {
  373. cmake cm(cmState::Role::CTest);
  374. cm.GetCurrentSnapshot().SetDefaultDefinitions();
  375. cmGlobalGenerator gg(&cm);
  376. cmMakefile mf(&gg, cm.GetCurrentSnapshot());
  377. std::string fname =
  378. cmStrCat(this->Reporter.LogDir, "CTestLaunchConfig.cmake");
  379. if (cmSystemTools::FileExists(fname) && mf.ReadListFile(fname)) {
  380. this->Reporter.SourceDir = mf.GetSafeDefinition("CTEST_SOURCE_DIRECTORY");
  381. cmSystemTools::ConvertToUnixSlashes(this->Reporter.SourceDir);
  382. }
  383. }