cmCTestLaunch.cxx 17 KB

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