cmCTestLaunch.cxx 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626
  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 "cmState.h"
  17. #include "cmStateSnapshot.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.push_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 = this->LogDir;
  165. this->LogOut += "launch-";
  166. this->LogOut += this->LogHash;
  167. this->LogOut += "-out.txt";
  168. this->LogErr = this->LogDir;
  169. this->LogErr += "launch-";
  170. this->LogErr += this->LogHash;
  171. this->LogErr += "-err.txt";
  172. }
  173. void cmCTestLaunch::RunChild()
  174. {
  175. // Ignore noopt make rules
  176. if (this->RealArgs.empty() || this->RealArgs[0] == ":") {
  177. this->ExitCode = 0;
  178. return;
  179. }
  180. // Prepare to run the real command.
  181. cmsysProcess* cp = this->Process;
  182. cmsysProcess_SetCommand(cp, this->RealArgV);
  183. cmsys::ofstream fout;
  184. cmsys::ofstream ferr;
  185. if (this->Passthru) {
  186. // In passthru mode we just share the output pipes.
  187. cmsysProcess_SetPipeShared(cp, cmsysProcess_Pipe_STDOUT, 1);
  188. cmsysProcess_SetPipeShared(cp, cmsysProcess_Pipe_STDERR, 1);
  189. } else {
  190. // In full mode we record the child output pipes to log files.
  191. fout.open(this->LogOut.c_str(), std::ios::out | std::ios::binary);
  192. ferr.open(this->LogErr.c_str(), std::ios::out | std::ios::binary);
  193. }
  194. #ifdef _WIN32
  195. // Do this so that newline transformation is not done when writing to cout
  196. // and cerr below.
  197. _setmode(fileno(stdout), _O_BINARY);
  198. _setmode(fileno(stderr), _O_BINARY);
  199. #endif
  200. // Run the real command.
  201. cmsysProcess_Execute(cp);
  202. // Record child stdout and stderr if necessary.
  203. if (!this->Passthru) {
  204. char* data = nullptr;
  205. int length = 0;
  206. cmProcessOutput processOutput;
  207. std::string strdata;
  208. while (int p = cmsysProcess_WaitForData(cp, &data, &length, nullptr)) {
  209. if (p == cmsysProcess_Pipe_STDOUT) {
  210. processOutput.DecodeText(data, length, strdata, 1);
  211. fout.write(strdata.c_str(), strdata.size());
  212. std::cout.write(strdata.c_str(), strdata.size());
  213. this->HaveOut = true;
  214. } else if (p == cmsysProcess_Pipe_STDERR) {
  215. processOutput.DecodeText(data, length, strdata, 2);
  216. ferr.write(strdata.c_str(), strdata.size());
  217. std::cerr.write(strdata.c_str(), strdata.size());
  218. this->HaveErr = true;
  219. }
  220. }
  221. processOutput.DecodeText(std::string(), strdata, 1);
  222. if (!strdata.empty()) {
  223. fout.write(strdata.c_str(), strdata.size());
  224. std::cout.write(strdata.c_str(), strdata.size());
  225. }
  226. processOutput.DecodeText(std::string(), strdata, 2);
  227. if (!strdata.empty()) {
  228. ferr.write(strdata.c_str(), strdata.size());
  229. std::cerr.write(strdata.c_str(), strdata.size());
  230. }
  231. }
  232. // Wait for the real command to finish.
  233. cmsysProcess_WaitForExit(cp, nullptr);
  234. this->ExitCode = cmsysProcess_GetExitValue(cp);
  235. }
  236. int cmCTestLaunch::Run()
  237. {
  238. if (!this->Process) {
  239. std::cerr << "Could not allocate cmsysProcess instance!\n";
  240. return -1;
  241. }
  242. this->RunChild();
  243. if (this->CheckResults()) {
  244. return this->ExitCode;
  245. }
  246. this->LoadConfig();
  247. this->WriteXML();
  248. return this->ExitCode;
  249. }
  250. void cmCTestLaunch::LoadLabels()
  251. {
  252. if (this->OptionBuildDir.empty() || this->OptionTargetName.empty()) {
  253. return;
  254. }
  255. // Labels are listed in per-target files.
  256. std::string fname = this->OptionBuildDir;
  257. fname += cmake::GetCMakeFilesDirectory();
  258. fname += "/";
  259. fname += this->OptionTargetName;
  260. fname += ".dir/Labels.txt";
  261. // We are interested in per-target labels for this source file.
  262. std::string source = this->OptionSource;
  263. cmSystemTools::ConvertToUnixSlashes(source);
  264. // Load the labels file.
  265. cmsys::ifstream fin(fname.c_str(), std::ios::in | std::ios::binary);
  266. if (!fin) {
  267. return;
  268. }
  269. bool inTarget = true;
  270. bool inSource = false;
  271. std::string line;
  272. while (cmSystemTools::GetLineFromStream(fin, line)) {
  273. if (line.empty() || line[0] == '#') {
  274. // Ignore blank and comment lines.
  275. continue;
  276. }
  277. if (line[0] == ' ') {
  278. // Label lines appear indented by one space.
  279. if (inTarget || inSource) {
  280. this->Labels.insert(line.c_str() + 1);
  281. }
  282. } else if (!this->OptionSource.empty() && !inSource) {
  283. // Non-indented lines specify a source file name. The first one
  284. // is the end of the target-wide labels. Use labels following a
  285. // matching source.
  286. inTarget = false;
  287. inSource = this->SourceMatches(line, source);
  288. } else {
  289. return;
  290. }
  291. }
  292. }
  293. bool cmCTestLaunch::SourceMatches(std::string const& lhs,
  294. std::string const& rhs)
  295. {
  296. // TODO: Case sensitivity, UseRelativePaths, etc. Note that both
  297. // paths in the comparison get generated by CMake. This is done for
  298. // every source in the target, so it should be efficient (cannot use
  299. // cmSystemTools::IsSameFile).
  300. return lhs == rhs;
  301. }
  302. bool cmCTestLaunch::IsError() const
  303. {
  304. return this->ExitCode != 0;
  305. }
  306. void cmCTestLaunch::WriteXML()
  307. {
  308. // Name the xml file.
  309. std::string logXML = this->LogDir;
  310. logXML += this->IsError() ? "error-" : "warning-";
  311. logXML += this->LogHash;
  312. logXML += ".xml";
  313. // Use cmGeneratedFileStream to atomically create the report file.
  314. cmGeneratedFileStream fxml(logXML);
  315. cmXMLWriter xml(fxml, 2);
  316. cmXMLElement e2(xml, "Failure");
  317. e2.Attribute("type", this->IsError() ? "Error" : "Warning");
  318. this->WriteXMLAction(e2);
  319. this->WriteXMLCommand(e2);
  320. this->WriteXMLResult(e2);
  321. this->WriteXMLLabels(e2);
  322. }
  323. void cmCTestLaunch::WriteXMLAction(cmXMLElement& e2)
  324. {
  325. e2.Comment("Meta-information about the build action");
  326. cmXMLElement e3(e2, "Action");
  327. // TargetName
  328. if (!this->OptionTargetName.empty()) {
  329. e3.Element("TargetName", this->OptionTargetName);
  330. }
  331. // Language
  332. if (!this->OptionLanguage.empty()) {
  333. e3.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. e3.Element("SourceFile", source);
  346. }
  347. // OutputFile
  348. if (!this->OptionOutput.empty()) {
  349. e3.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. e3.Element("OutputType", outputType);
  368. }
  369. }
  370. void cmCTestLaunch::WriteXMLCommand(cmXMLElement& e2)
  371. {
  372. e2.Comment("Details of command");
  373. cmXMLElement e3(e2, "Command");
  374. if (!this->CWD.empty()) {
  375. e3.Element("WorkingDirectory", this->CWD);
  376. }
  377. for (std::string const& realArg : this->RealArgs) {
  378. e3.Element("Argument", realArg);
  379. }
  380. }
  381. void cmCTestLaunch::WriteXMLResult(cmXMLElement& e2)
  382. {
  383. e2.Comment("Result of command");
  384. cmXMLElement e3(e2, "Result");
  385. // StdOut
  386. this->DumpFileToXML(e3, "StdOut", this->LogOut);
  387. // StdErr
  388. this->DumpFileToXML(e3, "StdErr", this->LogErr);
  389. // ExitCondition
  390. cmXMLElement e4(e3, "ExitCondition");
  391. cmsysProcess* cp = this->Process;
  392. switch (cmsysProcess_GetState(cp)) {
  393. case cmsysProcess_State_Starting:
  394. e4.Content("No process has been executed");
  395. break;
  396. case cmsysProcess_State_Executing:
  397. e4.Content("The process is still executing");
  398. break;
  399. case cmsysProcess_State_Disowned:
  400. e4.Content("Disowned");
  401. break;
  402. case cmsysProcess_State_Killed:
  403. e4.Content("Killed by parent");
  404. break;
  405. case cmsysProcess_State_Expired:
  406. e4.Content("Killed when timeout expired");
  407. break;
  408. case cmsysProcess_State_Exited:
  409. e4.Content(this->ExitCode);
  410. break;
  411. case cmsysProcess_State_Exception:
  412. e4.Content("Terminated abnormally: ");
  413. e4.Content(cmsysProcess_GetExceptionString(cp));
  414. break;
  415. case cmsysProcess_State_Error:
  416. e4.Content("Error administrating child process: ");
  417. e4.Content(cmsysProcess_GetErrorString(cp));
  418. break;
  419. }
  420. }
  421. void cmCTestLaunch::WriteXMLLabels(cmXMLElement& e2)
  422. {
  423. this->LoadLabels();
  424. if (!this->Labels.empty()) {
  425. e2.Comment("Interested parties");
  426. cmXMLElement e3(e2, "Labels");
  427. for (std::string const& label : this->Labels) {
  428. e3.Element("Label", label);
  429. }
  430. }
  431. }
  432. void cmCTestLaunch::DumpFileToXML(cmXMLElement& e3, const char* tag,
  433. std::string const& fname)
  434. {
  435. cmsys::ifstream fin(fname.c_str(), std::ios::in | std::ios::binary);
  436. std::string line;
  437. const char* sep = "";
  438. cmXMLElement e4(e3, tag);
  439. while (cmSystemTools::GetLineFromStream(fin, line)) {
  440. if (MatchesFilterPrefix(line)) {
  441. continue;
  442. }
  443. if (this->Match(line, this->RegexWarningSuppress)) {
  444. line = "[CTest: warning suppressed] " + line;
  445. } else if (this->Match(line, this->RegexWarning)) {
  446. line = "[CTest: warning matched] " + line;
  447. }
  448. e4.Content(sep);
  449. e4.Content(line);
  450. sep = "\n";
  451. }
  452. }
  453. bool cmCTestLaunch::CheckResults()
  454. {
  455. // Skip XML in passthru mode.
  456. if (this->Passthru) {
  457. return true;
  458. }
  459. // We always report failure for error conditions.
  460. if (this->IsError()) {
  461. return false;
  462. }
  463. // Scrape the output logs to look for warnings.
  464. if ((this->HaveErr && this->ScrapeLog(this->LogErr)) ||
  465. (this->HaveOut && this->ScrapeLog(this->LogOut))) {
  466. return false;
  467. }
  468. return true;
  469. }
  470. void cmCTestLaunch::LoadScrapeRules()
  471. {
  472. if (this->ScrapeRulesLoaded) {
  473. return;
  474. }
  475. this->ScrapeRulesLoaded = true;
  476. // Common compiler warning formats. These are much simpler than the
  477. // full log-scraping expressions because we do not need to extract
  478. // file and line information.
  479. this->RegexWarning.push_back("(^|[ :])[Ww][Aa][Rr][Nn][Ii][Nn][Gg]");
  480. this->RegexWarning.push_back("(^|[ :])[Rr][Ee][Mm][Aa][Rr][Kk]");
  481. this->RegexWarning.push_back("(^|[ :])[Nn][Oo][Tt][Ee]");
  482. // Load custom match rules given to us by CTest.
  483. this->LoadScrapeRules("Warning", this->RegexWarning);
  484. this->LoadScrapeRules("WarningSuppress", this->RegexWarningSuppress);
  485. }
  486. void cmCTestLaunch::LoadScrapeRules(
  487. const char* purpose, std::vector<cmsys::RegularExpression>& regexps)
  488. {
  489. std::string fname = this->LogDir;
  490. fname += "Custom";
  491. fname += purpose;
  492. fname += ".txt";
  493. cmsys::ifstream fin(fname.c_str(), std::ios::in | std::ios::binary);
  494. std::string line;
  495. cmsys::RegularExpression rex;
  496. while (cmSystemTools::GetLineFromStream(fin, line)) {
  497. if (rex.compile(line)) {
  498. regexps.push_back(rex);
  499. }
  500. }
  501. }
  502. bool cmCTestLaunch::ScrapeLog(std::string const& fname)
  503. {
  504. this->LoadScrapeRules();
  505. // Look for log file lines matching warning expressions but not
  506. // suppression expressions.
  507. cmsys::ifstream fin(fname.c_str(), std::ios::in | std::ios::binary);
  508. std::string line;
  509. while (cmSystemTools::GetLineFromStream(fin, line)) {
  510. if (MatchesFilterPrefix(line)) {
  511. continue;
  512. }
  513. if (this->Match(line, this->RegexWarning) &&
  514. !this->Match(line, this->RegexWarningSuppress)) {
  515. return true;
  516. }
  517. }
  518. return false;
  519. }
  520. bool cmCTestLaunch::Match(std::string const& line,
  521. std::vector<cmsys::RegularExpression>& regexps)
  522. {
  523. for (cmsys::RegularExpression& r : regexps) {
  524. if (r.find(line)) {
  525. return true;
  526. }
  527. }
  528. return false;
  529. }
  530. bool cmCTestLaunch::MatchesFilterPrefix(std::string const& line) const
  531. {
  532. return !this->OptionFilterPrefix.empty() &&
  533. cmSystemTools::StringStartsWith(line, this->OptionFilterPrefix.c_str());
  534. }
  535. int cmCTestLaunch::Main(int argc, const char* const argv[])
  536. {
  537. if (argc == 2) {
  538. std::cerr << "ctest --launch: this mode is for internal CTest use only"
  539. << std::endl;
  540. return 1;
  541. }
  542. cmCTestLaunch self(argc, argv);
  543. return self.Run();
  544. }
  545. void cmCTestLaunch::LoadConfig()
  546. {
  547. cmake cm(cmake::RoleScript, cmState::CTest);
  548. cm.SetHomeDirectory("");
  549. cm.SetHomeOutputDirectory("");
  550. cm.GetCurrentSnapshot().SetDefaultDefinitions();
  551. cmGlobalGenerator gg(&cm);
  552. cmMakefile mf(&gg, cm.GetCurrentSnapshot());
  553. std::string fname = this->LogDir;
  554. fname += "CTestLaunchConfig.cmake";
  555. if (cmSystemTools::FileExists(fname) && mf.ReadListFile(fname)) {
  556. this->SourceDir = mf.GetSafeDefinition("CTEST_SOURCE_DIRECTORY");
  557. cmSystemTools::ConvertToUnixSlashes(this->SourceDir);
  558. }
  559. }