cmCTestLaunch.cxx 13 KB

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