cmCTestLaunch.cxx 17 KB

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