cmCTestLaunch.cxx 17 KB

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