cmCTestLaunch.cxx 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637
  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.c_str()) &&
  341. cmSystemTools::FileIsFullPath(source.c_str()) &&
  342. cmSystemTools::IsSubDirectory(source, this->SourceDir)) {
  343. source =
  344. cmSystemTools::RelativePath(this->SourceDir.c_str(), source.c_str());
  345. }
  346. xml.Element("SourceFile", source);
  347. }
  348. // OutputFile
  349. if (!this->OptionOutput.empty()) {
  350. xml.Element("OutputFile", this->OptionOutput);
  351. }
  352. // OutputType
  353. const char* outputType = nullptr;
  354. if (!this->OptionTargetType.empty()) {
  355. if (this->OptionTargetType == "EXECUTABLE") {
  356. outputType = "executable";
  357. } else if (this->OptionTargetType == "SHARED_LIBRARY") {
  358. outputType = "shared library";
  359. } else if (this->OptionTargetType == "MODULE_LIBRARY") {
  360. outputType = "module library";
  361. } else if (this->OptionTargetType == "STATIC_LIBRARY") {
  362. outputType = "static library";
  363. }
  364. } else if (!this->OptionSource.empty()) {
  365. outputType = "object file";
  366. }
  367. if (outputType) {
  368. xml.Element("OutputType", outputType);
  369. }
  370. xml.EndElement(); // Action
  371. }
  372. void cmCTestLaunch::WriteXMLCommand(cmXMLWriter& xml)
  373. {
  374. xml.Comment("Details of command");
  375. xml.StartElement("Command");
  376. if (!this->CWD.empty()) {
  377. xml.Element("WorkingDirectory", this->CWD);
  378. }
  379. for (std::string const& realArg : this->RealArgs) {
  380. xml.Element("Argument", realArg);
  381. }
  382. xml.EndElement(); // Command
  383. }
  384. void cmCTestLaunch::WriteXMLResult(cmXMLWriter& xml)
  385. {
  386. xml.Comment("Result of command");
  387. xml.StartElement("Result");
  388. // StdOut
  389. xml.StartElement("StdOut");
  390. this->DumpFileToXML(xml, this->LogOut);
  391. xml.EndElement(); // StdOut
  392. // StdErr
  393. xml.StartElement("StdErr");
  394. this->DumpFileToXML(xml, this->LogErr);
  395. xml.EndElement(); // StdErr
  396. // ExitCondition
  397. xml.StartElement("ExitCondition");
  398. cmsysProcess* cp = this->Process;
  399. switch (cmsysProcess_GetState(cp)) {
  400. case cmsysProcess_State_Starting:
  401. xml.Content("No process has been executed");
  402. break;
  403. case cmsysProcess_State_Executing:
  404. xml.Content("The process is still executing");
  405. break;
  406. case cmsysProcess_State_Disowned:
  407. xml.Content("Disowned");
  408. break;
  409. case cmsysProcess_State_Killed:
  410. xml.Content("Killed by parent");
  411. break;
  412. case cmsysProcess_State_Expired:
  413. xml.Content("Killed when timeout expired");
  414. break;
  415. case cmsysProcess_State_Exited:
  416. xml.Content(this->ExitCode);
  417. break;
  418. case cmsysProcess_State_Exception:
  419. xml.Content("Terminated abnormally: ");
  420. xml.Content(cmsysProcess_GetExceptionString(cp));
  421. break;
  422. case cmsysProcess_State_Error:
  423. xml.Content("Error administrating child process: ");
  424. xml.Content(cmsysProcess_GetErrorString(cp));
  425. break;
  426. };
  427. xml.EndElement(); // ExitCondition
  428. xml.EndElement(); // Result
  429. }
  430. void cmCTestLaunch::WriteXMLLabels(cmXMLWriter& xml)
  431. {
  432. this->LoadLabels();
  433. if (!this->Labels.empty()) {
  434. xml.Comment("Interested parties");
  435. xml.StartElement("Labels");
  436. for (std::string const& label : this->Labels) {
  437. xml.Element("Label", label);
  438. }
  439. xml.EndElement(); // Labels
  440. }
  441. }
  442. void cmCTestLaunch::DumpFileToXML(cmXMLWriter& xml, std::string const& fname)
  443. {
  444. cmsys::ifstream fin(fname.c_str(), std::ios::in | std::ios::binary);
  445. std::string line;
  446. const char* sep = "";
  447. while (cmSystemTools::GetLineFromStream(fin, line)) {
  448. if (MatchesFilterPrefix(line)) {
  449. continue;
  450. }
  451. if (this->Match(line, this->RegexWarningSuppress)) {
  452. line = "[CTest: warning suppressed] " + line;
  453. } else if (this->Match(line, this->RegexWarning)) {
  454. line = "[CTest: warning matched] " + line;
  455. }
  456. xml.Content(sep);
  457. xml.Content(line);
  458. sep = "\n";
  459. }
  460. }
  461. bool cmCTestLaunch::CheckResults()
  462. {
  463. // Skip XML in passthru mode.
  464. if (this->Passthru) {
  465. return true;
  466. }
  467. // We always report failure for error conditions.
  468. if (this->IsError()) {
  469. return false;
  470. }
  471. // Scrape the output logs to look for warnings.
  472. if ((this->HaveErr && this->ScrapeLog(this->LogErr)) ||
  473. (this->HaveOut && this->ScrapeLog(this->LogOut))) {
  474. return false;
  475. }
  476. return true;
  477. }
  478. void cmCTestLaunch::LoadScrapeRules()
  479. {
  480. if (this->ScrapeRulesLoaded) {
  481. return;
  482. }
  483. this->ScrapeRulesLoaded = true;
  484. // Common compiler warning formats. These are much simpler than the
  485. // full log-scraping expressions because we do not need to extract
  486. // file and line information.
  487. this->RegexWarning.push_back("(^|[ :])[Ww][Aa][Rr][Nn][Ii][Nn][Gg]");
  488. this->RegexWarning.push_back("(^|[ :])[Rr][Ee][Mm][Aa][Rr][Kk]");
  489. this->RegexWarning.push_back("(^|[ :])[Nn][Oo][Tt][Ee]");
  490. // Load custom match rules given to us by CTest.
  491. this->LoadScrapeRules("Warning", this->RegexWarning);
  492. this->LoadScrapeRules("WarningSuppress", this->RegexWarningSuppress);
  493. }
  494. void cmCTestLaunch::LoadScrapeRules(
  495. const char* purpose, std::vector<cmsys::RegularExpression>& regexps)
  496. {
  497. std::string fname = this->LogDir;
  498. fname += "Custom";
  499. fname += purpose;
  500. fname += ".txt";
  501. cmsys::ifstream fin(fname.c_str(), std::ios::in | std::ios::binary);
  502. std::string line;
  503. cmsys::RegularExpression rex;
  504. while (cmSystemTools::GetLineFromStream(fin, line)) {
  505. if (rex.compile(line.c_str())) {
  506. regexps.push_back(rex);
  507. }
  508. }
  509. }
  510. bool cmCTestLaunch::ScrapeLog(std::string const& fname)
  511. {
  512. this->LoadScrapeRules();
  513. // Look for log file lines matching warning expressions but not
  514. // suppression expressions.
  515. cmsys::ifstream fin(fname.c_str(), std::ios::in | std::ios::binary);
  516. std::string line;
  517. while (cmSystemTools::GetLineFromStream(fin, line)) {
  518. if (MatchesFilterPrefix(line)) {
  519. continue;
  520. }
  521. if (this->Match(line, this->RegexWarning) &&
  522. !this->Match(line, this->RegexWarningSuppress)) {
  523. return true;
  524. }
  525. }
  526. return false;
  527. }
  528. bool cmCTestLaunch::Match(std::string const& line,
  529. std::vector<cmsys::RegularExpression>& regexps)
  530. {
  531. for (cmsys::RegularExpression& r : regexps) {
  532. if (r.find(line.c_str())) {
  533. return true;
  534. }
  535. }
  536. return false;
  537. }
  538. bool cmCTestLaunch::MatchesFilterPrefix(std::string const& line) const
  539. {
  540. return !this->OptionFilterPrefix.empty() &&
  541. cmSystemTools::StringStartsWith(line, this->OptionFilterPrefix.c_str());
  542. }
  543. int cmCTestLaunch::Main(int argc, const char* const argv[])
  544. {
  545. if (argc == 2) {
  546. std::cerr << "ctest --launch: this mode is for internal CTest use only"
  547. << std::endl;
  548. return 1;
  549. }
  550. cmCTestLaunch self(argc, argv);
  551. return self.Run();
  552. }
  553. void cmCTestLaunch::LoadConfig()
  554. {
  555. cmake cm(cmake::RoleScript);
  556. cm.SetHomeDirectory("");
  557. cm.SetHomeOutputDirectory("");
  558. cm.GetCurrentSnapshot().SetDefaultDefinitions();
  559. cmGlobalGenerator gg(&cm);
  560. cmMakefile mf(&gg, cm.GetCurrentSnapshot());
  561. std::string fname = this->LogDir;
  562. fname += "CTestLaunchConfig.cmake";
  563. if (cmSystemTools::FileExists(fname.c_str()) &&
  564. mf.ReadListFile(fname.c_str())) {
  565. this->SourceDir = mf.GetSafeDefinition("CTEST_SOURCE_DIRECTORY");
  566. cmSystemTools::ConvertToUnixSlashes(this->SourceDir);
  567. }
  568. }