cmCTestLaunch.cxx 17 KB

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