cmCTestLaunch.cxx 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612
  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 "cmCTestLaunch.h"
  4. #include "cmsys/FStream.hxx"
  5. #include "cmsys/Process.h"
  6. #include "cmsys/RegularExpression.hxx"
  7. #include <iostream>
  8. #include <stdlib.h>
  9. #include <string.h>
  10. #include "cmCryptoHash.h"
  11. #include "cmGeneratedFileStream.h"
  12. #include "cmGlobalGenerator.h"
  13. #include "cmMakefile.h"
  14. #include "cmProcessOutput.h"
  15. #include "cmState.h"
  16. #include "cmStateSnapshot.h"
  17. #include "cmStringAlgorithms.h"
  18. #include "cmSystemTools.h"
  19. #include "cmXMLWriter.h"
  20. #include "cmake.h"
  21. #ifdef _WIN32
  22. # include <fcntl.h> // for _O_BINARY
  23. # include <io.h> // for _setmode
  24. # include <stdio.h> // for std{out,err} and fileno
  25. #endif
  26. cmCTestLaunch::cmCTestLaunch(int argc, const char* const* argv)
  27. {
  28. this->Passthru = true;
  29. this->Process = nullptr;
  30. this->ExitCode = 1;
  31. this->CWD = cmSystemTools::GetCurrentWorkingDirectory();
  32. if (!this->ParseArguments(argc, argv)) {
  33. return;
  34. }
  35. this->ComputeFileNames();
  36. this->ScrapeRulesLoaded = false;
  37. this->HaveOut = false;
  38. this->HaveErr = false;
  39. this->Process = cmsysProcess_New();
  40. }
  41. cmCTestLaunch::~cmCTestLaunch()
  42. {
  43. cmsysProcess_Delete(this->Process);
  44. if (!this->Passthru) {
  45. cmSystemTools::RemoveFile(this->LogOut);
  46. cmSystemTools::RemoveFile(this->LogErr);
  47. }
  48. }
  49. bool cmCTestLaunch::ParseArguments(int argc, const char* const* argv)
  50. {
  51. // Launcher options occur first and are separated from the real
  52. // command line by a '--' option.
  53. enum Doing
  54. {
  55. DoingNone,
  56. DoingOutput,
  57. DoingSource,
  58. DoingLanguage,
  59. DoingTargetName,
  60. DoingTargetType,
  61. DoingBuildDir,
  62. DoingCount,
  63. DoingFilterPrefix
  64. };
  65. Doing doing = DoingNone;
  66. int arg0 = 0;
  67. for (int i = 1; !arg0 && i < argc; ++i) {
  68. const char* arg = argv[i];
  69. if (strcmp(arg, "--") == 0) {
  70. arg0 = i + 1;
  71. } else if (strcmp(arg, "--output") == 0) {
  72. doing = DoingOutput;
  73. } else if (strcmp(arg, "--source") == 0) {
  74. doing = DoingSource;
  75. } else if (strcmp(arg, "--language") == 0) {
  76. doing = DoingLanguage;
  77. } else if (strcmp(arg, "--target-name") == 0) {
  78. doing = DoingTargetName;
  79. } else if (strcmp(arg, "--target-type") == 0) {
  80. doing = DoingTargetType;
  81. } else if (strcmp(arg, "--build-dir") == 0) {
  82. doing = DoingBuildDir;
  83. } else if (strcmp(arg, "--filter-prefix") == 0) {
  84. doing = DoingFilterPrefix;
  85. } else if (doing == DoingOutput) {
  86. this->OptionOutput = arg;
  87. doing = DoingNone;
  88. } else if (doing == DoingSource) {
  89. this->OptionSource = arg;
  90. doing = DoingNone;
  91. } else if (doing == DoingLanguage) {
  92. this->OptionLanguage = arg;
  93. if (this->OptionLanguage == "CXX") {
  94. this->OptionLanguage = "C++";
  95. }
  96. doing = DoingNone;
  97. } else if (doing == DoingTargetName) {
  98. this->OptionTargetName = arg;
  99. doing = DoingNone;
  100. } else if (doing == DoingTargetType) {
  101. this->OptionTargetType = arg;
  102. doing = DoingNone;
  103. } else if (doing == DoingBuildDir) {
  104. this->OptionBuildDir = arg;
  105. doing = DoingNone;
  106. } else if (doing == DoingFilterPrefix) {
  107. this->OptionFilterPrefix = arg;
  108. doing = DoingNone;
  109. }
  110. }
  111. // Extract the real command line.
  112. if (arg0) {
  113. this->RealArgC = argc - arg0;
  114. this->RealArgV = argv + arg0;
  115. for (int i = 0; i < this->RealArgC; ++i) {
  116. this->HandleRealArg(this->RealArgV[i]);
  117. }
  118. return true;
  119. }
  120. this->RealArgC = 0;
  121. this->RealArgV = nullptr;
  122. std::cerr << "No launch/command separator ('--') found!\n";
  123. return false;
  124. }
  125. void cmCTestLaunch::HandleRealArg(const char* arg)
  126. {
  127. #ifdef _WIN32
  128. // Expand response file arguments.
  129. if (arg[0] == '@' && cmSystemTools::FileExists(arg + 1)) {
  130. cmsys::ifstream fin(arg + 1);
  131. std::string line;
  132. while (cmSystemTools::GetLineFromStream(fin, line)) {
  133. cmSystemTools::ParseWindowsCommandLine(line.c_str(), this->RealArgs);
  134. }
  135. return;
  136. }
  137. #endif
  138. this->RealArgs.emplace_back(arg);
  139. }
  140. void cmCTestLaunch::ComputeFileNames()
  141. {
  142. // We just passthru the behavior of the real command unless the
  143. // CTEST_LAUNCH_LOGS environment variable is set.
  144. const char* d = getenv("CTEST_LAUNCH_LOGS");
  145. if (!(d && *d)) {
  146. return;
  147. }
  148. this->Passthru = false;
  149. // The environment variable specifies the directory into which we
  150. // generate build logs.
  151. this->LogDir = d;
  152. cmSystemTools::ConvertToUnixSlashes(this->LogDir);
  153. this->LogDir += "/";
  154. // We hash the input command working dir and command line to obtain
  155. // a repeatable and (probably) unique name for log files.
  156. cmCryptoHash md5(cmCryptoHash::AlgoMD5);
  157. md5.Initialize();
  158. md5.Append(this->CWD);
  159. for (std::string const& realArg : this->RealArgs) {
  160. md5.Append(realArg);
  161. }
  162. this->LogHash = md5.FinalizeHex();
  163. // We store stdout and stderr in temporary log files.
  164. this->LogOut = cmStrCat(this->LogDir, "launch-", this->LogHash, "-out.txt");
  165. this->LogErr = cmStrCat(this->LogDir, "launch-", this->LogHash, "-err.txt");
  166. }
  167. void cmCTestLaunch::RunChild()
  168. {
  169. // Ignore noopt make rules
  170. if (this->RealArgs.empty() || this->RealArgs[0] == ":") {
  171. this->ExitCode = 0;
  172. return;
  173. }
  174. // Prepare to run the real command.
  175. cmsysProcess* cp = this->Process;
  176. cmsysProcess_SetCommand(cp, this->RealArgV);
  177. cmsys::ofstream fout;
  178. cmsys::ofstream ferr;
  179. if (this->Passthru) {
  180. // In passthru mode we just share the output pipes.
  181. cmsysProcess_SetPipeShared(cp, cmsysProcess_Pipe_STDOUT, 1);
  182. cmsysProcess_SetPipeShared(cp, cmsysProcess_Pipe_STDERR, 1);
  183. } else {
  184. // In full mode we record the child output pipes to log files.
  185. fout.open(this->LogOut.c_str(), std::ios::out | std::ios::binary);
  186. ferr.open(this->LogErr.c_str(), std::ios::out | std::ios::binary);
  187. }
  188. #ifdef _WIN32
  189. // Do this so that newline transformation is not done when writing to cout
  190. // and cerr below.
  191. _setmode(fileno(stdout), _O_BINARY);
  192. _setmode(fileno(stderr), _O_BINARY);
  193. #endif
  194. // Run the real command.
  195. cmsysProcess_Execute(cp);
  196. // Record child stdout and stderr if necessary.
  197. if (!this->Passthru) {
  198. char* data = nullptr;
  199. int length = 0;
  200. cmProcessOutput processOutput;
  201. std::string strdata;
  202. while (int p = cmsysProcess_WaitForData(cp, &data, &length, nullptr)) {
  203. if (p == cmsysProcess_Pipe_STDOUT) {
  204. processOutput.DecodeText(data, length, strdata, 1);
  205. fout.write(strdata.c_str(), strdata.size());
  206. std::cout.write(strdata.c_str(), strdata.size());
  207. this->HaveOut = true;
  208. } else if (p == cmsysProcess_Pipe_STDERR) {
  209. processOutput.DecodeText(data, length, strdata, 2);
  210. ferr.write(strdata.c_str(), strdata.size());
  211. std::cerr.write(strdata.c_str(), strdata.size());
  212. this->HaveErr = true;
  213. }
  214. }
  215. processOutput.DecodeText(std::string(), strdata, 1);
  216. if (!strdata.empty()) {
  217. fout.write(strdata.c_str(), strdata.size());
  218. std::cout.write(strdata.c_str(), strdata.size());
  219. }
  220. processOutput.DecodeText(std::string(), strdata, 2);
  221. if (!strdata.empty()) {
  222. ferr.write(strdata.c_str(), strdata.size());
  223. std::cerr.write(strdata.c_str(), strdata.size());
  224. }
  225. }
  226. // Wait for the real command to finish.
  227. cmsysProcess_WaitForExit(cp, nullptr);
  228. this->ExitCode = cmsysProcess_GetExitValue(cp);
  229. }
  230. int cmCTestLaunch::Run()
  231. {
  232. if (!this->Process) {
  233. std::cerr << "Could not allocate cmsysProcess instance!\n";
  234. return -1;
  235. }
  236. this->RunChild();
  237. if (this->CheckResults()) {
  238. return this->ExitCode;
  239. }
  240. this->LoadConfig();
  241. this->WriteXML();
  242. return this->ExitCode;
  243. }
  244. void cmCTestLaunch::LoadLabels()
  245. {
  246. if (this->OptionBuildDir.empty() || this->OptionTargetName.empty()) {
  247. return;
  248. }
  249. // Labels are listed in per-target files.
  250. std::string fname = cmStrCat(this->OptionBuildDir, "/CMakeFiles/",
  251. this->OptionTargetName, ".dir/Labels.txt");
  252. // We are interested in per-target labels for this source file.
  253. std::string source = this->OptionSource;
  254. cmSystemTools::ConvertToUnixSlashes(source);
  255. // Load the labels file.
  256. cmsys::ifstream fin(fname.c_str(), std::ios::in | std::ios::binary);
  257. if (!fin) {
  258. return;
  259. }
  260. bool inTarget = true;
  261. bool inSource = false;
  262. std::string line;
  263. while (cmSystemTools::GetLineFromStream(fin, line)) {
  264. if (line.empty() || line[0] == '#') {
  265. // Ignore blank and comment lines.
  266. continue;
  267. }
  268. if (line[0] == ' ') {
  269. // Label lines appear indented by one space.
  270. if (inTarget || inSource) {
  271. this->Labels.insert(line.substr(1));
  272. }
  273. } else if (!this->OptionSource.empty() && !inSource) {
  274. // Non-indented lines specify a source file name. The first one
  275. // is the end of the target-wide labels. Use labels following a
  276. // matching source.
  277. inTarget = false;
  278. inSource = this->SourceMatches(line, source);
  279. } else {
  280. return;
  281. }
  282. }
  283. }
  284. bool cmCTestLaunch::SourceMatches(std::string const& lhs,
  285. std::string const& rhs)
  286. {
  287. // TODO: Case sensitivity, UseRelativePaths, etc. Note that both
  288. // paths in the comparison get generated by CMake. This is done for
  289. // every source in the target, so it should be efficient (cannot use
  290. // cmSystemTools::IsSameFile).
  291. return lhs == rhs;
  292. }
  293. bool cmCTestLaunch::IsError() const
  294. {
  295. return this->ExitCode != 0;
  296. }
  297. void cmCTestLaunch::WriteXML()
  298. {
  299. // Name the xml file.
  300. std::string logXML =
  301. cmStrCat(this->LogDir, this->IsError() ? "error-" : "warning-",
  302. this->LogHash, ".xml");
  303. // Use cmGeneratedFileStream to atomically create the report file.
  304. cmGeneratedFileStream fxml(logXML);
  305. cmXMLWriter xml(fxml, 2);
  306. cmXMLElement e2(xml, "Failure");
  307. e2.Attribute("type", this->IsError() ? "Error" : "Warning");
  308. this->WriteXMLAction(e2);
  309. this->WriteXMLCommand(e2);
  310. this->WriteXMLResult(e2);
  311. this->WriteXMLLabels(e2);
  312. }
  313. void cmCTestLaunch::WriteXMLAction(cmXMLElement& e2)
  314. {
  315. e2.Comment("Meta-information about the build action");
  316. cmXMLElement e3(e2, "Action");
  317. // TargetName
  318. if (!this->OptionTargetName.empty()) {
  319. e3.Element("TargetName", this->OptionTargetName);
  320. }
  321. // Language
  322. if (!this->OptionLanguage.empty()) {
  323. e3.Element("Language", this->OptionLanguage);
  324. }
  325. // SourceFile
  326. if (!this->OptionSource.empty()) {
  327. std::string source = this->OptionSource;
  328. cmSystemTools::ConvertToUnixSlashes(source);
  329. // If file is in source tree use its relative location.
  330. if (cmSystemTools::FileIsFullPath(this->SourceDir) &&
  331. cmSystemTools::FileIsFullPath(source) &&
  332. cmSystemTools::IsSubDirectory(source, this->SourceDir)) {
  333. source = cmSystemTools::RelativePath(this->SourceDir, source);
  334. }
  335. e3.Element("SourceFile", source);
  336. }
  337. // OutputFile
  338. if (!this->OptionOutput.empty()) {
  339. e3.Element("OutputFile", this->OptionOutput);
  340. }
  341. // OutputType
  342. const char* outputType = nullptr;
  343. if (!this->OptionTargetType.empty()) {
  344. if (this->OptionTargetType == "EXECUTABLE") {
  345. outputType = "executable";
  346. } else if (this->OptionTargetType == "SHARED_LIBRARY") {
  347. outputType = "shared library";
  348. } else if (this->OptionTargetType == "MODULE_LIBRARY") {
  349. outputType = "module library";
  350. } else if (this->OptionTargetType == "STATIC_LIBRARY") {
  351. outputType = "static library";
  352. }
  353. } else if (!this->OptionSource.empty()) {
  354. outputType = "object file";
  355. }
  356. if (outputType) {
  357. e3.Element("OutputType", outputType);
  358. }
  359. }
  360. void cmCTestLaunch::WriteXMLCommand(cmXMLElement& e2)
  361. {
  362. e2.Comment("Details of command");
  363. cmXMLElement e3(e2, "Command");
  364. if (!this->CWD.empty()) {
  365. e3.Element("WorkingDirectory", this->CWD);
  366. }
  367. for (std::string const& realArg : this->RealArgs) {
  368. e3.Element("Argument", realArg);
  369. }
  370. }
  371. void cmCTestLaunch::WriteXMLResult(cmXMLElement& e2)
  372. {
  373. e2.Comment("Result of command");
  374. cmXMLElement e3(e2, "Result");
  375. // StdOut
  376. this->DumpFileToXML(e3, "StdOut", this->LogOut);
  377. // StdErr
  378. this->DumpFileToXML(e3, "StdErr", this->LogErr);
  379. // ExitCondition
  380. cmXMLElement e4(e3, "ExitCondition");
  381. cmsysProcess* cp = this->Process;
  382. switch (cmsysProcess_GetState(cp)) {
  383. case cmsysProcess_State_Starting:
  384. e4.Content("No process has been executed");
  385. break;
  386. case cmsysProcess_State_Executing:
  387. e4.Content("The process is still executing");
  388. break;
  389. case cmsysProcess_State_Disowned:
  390. e4.Content("Disowned");
  391. break;
  392. case cmsysProcess_State_Killed:
  393. e4.Content("Killed by parent");
  394. break;
  395. case cmsysProcess_State_Expired:
  396. e4.Content("Killed when timeout expired");
  397. break;
  398. case cmsysProcess_State_Exited:
  399. e4.Content(this->ExitCode);
  400. break;
  401. case cmsysProcess_State_Exception:
  402. e4.Content("Terminated abnormally: ");
  403. e4.Content(cmsysProcess_GetExceptionString(cp));
  404. break;
  405. case cmsysProcess_State_Error:
  406. e4.Content("Error administrating child process: ");
  407. e4.Content(cmsysProcess_GetErrorString(cp));
  408. break;
  409. }
  410. }
  411. void cmCTestLaunch::WriteXMLLabels(cmXMLElement& e2)
  412. {
  413. this->LoadLabels();
  414. if (!this->Labels.empty()) {
  415. e2.Comment("Interested parties");
  416. cmXMLElement e3(e2, "Labels");
  417. for (std::string const& label : this->Labels) {
  418. e3.Element("Label", label);
  419. }
  420. }
  421. }
  422. void cmCTestLaunch::DumpFileToXML(cmXMLElement& e3, const char* tag,
  423. std::string const& fname)
  424. {
  425. cmsys::ifstream fin(fname.c_str(), std::ios::in | std::ios::binary);
  426. std::string line;
  427. const char* sep = "";
  428. cmXMLElement e4(e3, tag);
  429. while (cmSystemTools::GetLineFromStream(fin, line)) {
  430. if (MatchesFilterPrefix(line)) {
  431. continue;
  432. }
  433. if (this->Match(line, this->RegexWarningSuppress)) {
  434. line = cmStrCat("[CTest: warning suppressed] ", line);
  435. } else if (this->Match(line, this->RegexWarning)) {
  436. line = cmStrCat("[CTest: warning matched] ", line);
  437. }
  438. e4.Content(sep);
  439. e4.Content(line);
  440. sep = "\n";
  441. }
  442. }
  443. bool cmCTestLaunch::CheckResults()
  444. {
  445. // Skip XML in passthru mode.
  446. if (this->Passthru) {
  447. return true;
  448. }
  449. // We always report failure for error conditions.
  450. if (this->IsError()) {
  451. return false;
  452. }
  453. // Scrape the output logs to look for warnings.
  454. if ((this->HaveErr && this->ScrapeLog(this->LogErr)) ||
  455. (this->HaveOut && this->ScrapeLog(this->LogOut))) {
  456. return false;
  457. }
  458. return true;
  459. }
  460. void cmCTestLaunch::LoadScrapeRules()
  461. {
  462. if (this->ScrapeRulesLoaded) {
  463. return;
  464. }
  465. this->ScrapeRulesLoaded = true;
  466. // Common compiler warning formats. These are much simpler than the
  467. // full log-scraping expressions because we do not need to extract
  468. // file and line information.
  469. this->RegexWarning.emplace_back("(^|[ :])[Ww][Aa][Rr][Nn][Ii][Nn][Gg]");
  470. this->RegexWarning.emplace_back("(^|[ :])[Rr][Ee][Mm][Aa][Rr][Kk]");
  471. this->RegexWarning.emplace_back("(^|[ :])[Nn][Oo][Tt][Ee]");
  472. // Load custom match rules given to us by CTest.
  473. this->LoadScrapeRules("Warning", this->RegexWarning);
  474. this->LoadScrapeRules("WarningSuppress", this->RegexWarningSuppress);
  475. }
  476. void cmCTestLaunch::LoadScrapeRules(
  477. const char* purpose, std::vector<cmsys::RegularExpression>& regexps)
  478. {
  479. std::string fname = cmStrCat(this->LogDir, "Custom", purpose, ".txt");
  480. cmsys::ifstream fin(fname.c_str(), std::ios::in | std::ios::binary);
  481. std::string line;
  482. cmsys::RegularExpression rex;
  483. while (cmSystemTools::GetLineFromStream(fin, line)) {
  484. if (rex.compile(line)) {
  485. regexps.push_back(rex);
  486. }
  487. }
  488. }
  489. bool cmCTestLaunch::ScrapeLog(std::string const& fname)
  490. {
  491. this->LoadScrapeRules();
  492. // Look for log file lines matching warning expressions but not
  493. // suppression expressions.
  494. cmsys::ifstream fin(fname.c_str(), std::ios::in | std::ios::binary);
  495. std::string line;
  496. while (cmSystemTools::GetLineFromStream(fin, line)) {
  497. if (MatchesFilterPrefix(line)) {
  498. continue;
  499. }
  500. if (this->Match(line, this->RegexWarning) &&
  501. !this->Match(line, this->RegexWarningSuppress)) {
  502. return true;
  503. }
  504. }
  505. return false;
  506. }
  507. bool cmCTestLaunch::Match(std::string const& line,
  508. std::vector<cmsys::RegularExpression>& regexps)
  509. {
  510. for (cmsys::RegularExpression& r : regexps) {
  511. if (r.find(line)) {
  512. return true;
  513. }
  514. }
  515. return false;
  516. }
  517. bool cmCTestLaunch::MatchesFilterPrefix(std::string const& line) const
  518. {
  519. return !this->OptionFilterPrefix.empty() &&
  520. cmHasPrefix(line, this->OptionFilterPrefix);
  521. }
  522. int cmCTestLaunch::Main(int argc, const char* const argv[])
  523. {
  524. if (argc == 2) {
  525. std::cerr << "ctest --launch: this mode is for internal CTest use only"
  526. << std::endl;
  527. return 1;
  528. }
  529. cmCTestLaunch self(argc, argv);
  530. return self.Run();
  531. }
  532. void cmCTestLaunch::LoadConfig()
  533. {
  534. cmake cm(cmake::RoleScript, cmState::CTest);
  535. cm.SetHomeDirectory("");
  536. cm.SetHomeOutputDirectory("");
  537. cm.GetCurrentSnapshot().SetDefaultDefinitions();
  538. cmGlobalGenerator gg(&cm);
  539. cmMakefile mf(&gg, cm.GetCurrentSnapshot());
  540. std::string fname = cmStrCat(this->LogDir, "CTestLaunchConfig.cmake");
  541. if (cmSystemTools::FileExists(fname) && mf.ReadListFile(fname)) {
  542. this->SourceDir = mf.GetSafeDefinition("CTEST_SOURCE_DIRECTORY");
  543. cmSystemTools::ConvertToUnixSlashes(this->SourceDir);
  544. }
  545. }