cmCTestCoverageHandler.cxx 79 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284
  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 "cmCTestCoverageHandler.h"
  4. #include <algorithm>
  5. #include <chrono>
  6. #include <cstdio>
  7. #include <cstdlib>
  8. #include <cstring>
  9. #include <iomanip>
  10. #include <iterator>
  11. #include <memory>
  12. #include <ratio>
  13. #include <sstream>
  14. #include <type_traits>
  15. #include <utility>
  16. #include <cmext/algorithm>
  17. #include "cmsys/FStream.hxx"
  18. #include "cmsys/Glob.hxx"
  19. #include "cmsys/RegularExpression.hxx"
  20. #include "cmCTest.h"
  21. #include "cmDuration.h"
  22. #include "cmGeneratedFileStream.h"
  23. #include "cmParseBlanketJSCoverage.h"
  24. #include "cmParseCacheCoverage.h"
  25. #include "cmParseCoberturaCoverage.h"
  26. #include "cmParseDelphiCoverage.h"
  27. #include "cmParseGTMCoverage.h"
  28. #include "cmParseJacocoCoverage.h"
  29. #include "cmParsePHPCoverage.h"
  30. #include "cmStringAlgorithms.h"
  31. #include "cmSystemTools.h"
  32. #include "cmUVProcessChain.h"
  33. #include "cmWorkingDirectory.h"
  34. #include "cmXMLWriter.h"
  35. class cmMakefile;
  36. #define SAFEDIV(x, y) (((y) != 0) ? ((x) / (y)) : (0))
  37. cmCTestCoverageHandler::cmCTestCoverageHandler() = default;
  38. void cmCTestCoverageHandler::Initialize()
  39. {
  40. this->Superclass::Initialize();
  41. this->CustomCoverageExclude.clear();
  42. this->SourceLabels.clear();
  43. this->TargetDirs.clear();
  44. this->LabelIdMap.clear();
  45. this->Labels.clear();
  46. this->LabelFilter.clear();
  47. }
  48. void cmCTestCoverageHandler::CleanCoverageLogFiles(std::ostream& log)
  49. {
  50. std::string logGlob =
  51. cmStrCat(this->CTest->GetCTestConfiguration("BuildDirectory"), "/Testing/",
  52. this->CTest->GetCurrentTag(), "/CoverageLog*");
  53. cmsys::Glob gl;
  54. gl.FindFiles(logGlob);
  55. std::vector<std::string> const& files = gl.GetFiles();
  56. for (std::string const& f : files) {
  57. log << "Removing old coverage log: " << f << "\n";
  58. cmSystemTools::RemoveFile(f);
  59. }
  60. }
  61. bool cmCTestCoverageHandler::StartCoverageLogFile(
  62. cmGeneratedFileStream& covLogFile, int logFileCount)
  63. {
  64. char covLogFilename[1024];
  65. snprintf(covLogFilename, sizeof(covLogFilename), "CoverageLog-%d",
  66. logFileCount);
  67. cmCTestOptionalLog(this->CTest, HANDLER_VERBOSE_OUTPUT,
  68. "Open file: " << covLogFilename << std::endl,
  69. this->Quiet);
  70. if (!this->StartResultingXML(cmCTest::PartCoverage, covLogFilename,
  71. covLogFile)) {
  72. cmCTestLog(this->CTest, ERROR_MESSAGE,
  73. "Cannot open log file: " << covLogFilename << std::endl);
  74. return false;
  75. }
  76. return true;
  77. }
  78. void cmCTestCoverageHandler::EndCoverageLogFile(cmGeneratedFileStream& ostr,
  79. int logFileCount)
  80. {
  81. char covLogFilename[1024];
  82. snprintf(covLogFilename, sizeof(covLogFilename), "CoverageLog-%d.xml",
  83. logFileCount);
  84. cmCTestOptionalLog(this->CTest, HANDLER_VERBOSE_OUTPUT,
  85. "Close file: " << covLogFilename << std::endl,
  86. this->Quiet);
  87. ostr.Close();
  88. }
  89. void cmCTestCoverageHandler::StartCoverageLogXML(cmXMLWriter& xml)
  90. {
  91. this->CTest->StartXML(xml, this->AppendXML);
  92. xml.StartElement("CoverageLog");
  93. xml.Element("StartDateTime", this->CTest->CurrentTime());
  94. xml.Element("StartTime", std::chrono::system_clock::now());
  95. }
  96. void cmCTestCoverageHandler::EndCoverageLogXML(cmXMLWriter& xml)
  97. {
  98. xml.Element("EndDateTime", this->CTest->CurrentTime());
  99. xml.Element("EndTime", std::chrono::system_clock::now());
  100. xml.EndElement(); // CoverageLog
  101. this->CTest->EndXML(xml);
  102. }
  103. bool cmCTestCoverageHandler::ShouldIDoCoverage(std::string const& file,
  104. std::string const& srcDir,
  105. std::string const& binDir)
  106. {
  107. if (this->IsFilteredOut(file)) {
  108. return false;
  109. }
  110. for (cmsys::RegularExpression& rx : this->CustomCoverageExcludeRegex) {
  111. if (rx.find(file)) {
  112. cmCTestOptionalLog(
  113. this->CTest, HANDLER_VERBOSE_OUTPUT,
  114. " File " << file << " is excluded in CTestCustom.ctest" << std::endl;
  115. , this->Quiet);
  116. return false;
  117. }
  118. }
  119. std::string fSrcDir = cmSystemTools::CollapseFullPath(srcDir);
  120. std::string fBinDir = cmSystemTools::CollapseFullPath(binDir);
  121. std::string fFile = cmSystemTools::CollapseFullPath(file);
  122. bool sourceSubDir = cmSystemTools::IsSubDirectory(fFile, fSrcDir);
  123. bool buildSubDir = cmSystemTools::IsSubDirectory(fFile, fBinDir);
  124. // Always check parent directory of the file.
  125. std::string fileDir = cmSystemTools::GetFilenamePath(fFile);
  126. std::string checkDir;
  127. // We also need to check the binary/source directory pair.
  128. if (sourceSubDir && buildSubDir) {
  129. if (fSrcDir.size() > fBinDir.size()) {
  130. checkDir = fSrcDir;
  131. } else {
  132. checkDir = fBinDir;
  133. }
  134. } else if (sourceSubDir) {
  135. checkDir = fSrcDir;
  136. } else if (buildSubDir) {
  137. checkDir = fBinDir;
  138. }
  139. std::string ndc = cmSystemTools::FileExistsInParentDirectories(
  140. ".NoDartCoverage", fFile, checkDir);
  141. if (!ndc.empty()) {
  142. cmCTestOptionalLog(this->CTest, HANDLER_VERBOSE_OUTPUT,
  143. "Found: " << ndc << " so skip coverage of " << file
  144. << std::endl,
  145. this->Quiet);
  146. return false;
  147. }
  148. // By now checkDir should be set to parent directory of the file.
  149. // Get the relative path to the file an apply it to the opposite directory.
  150. // If it is the same as fileDir, then ignore, otherwise check.
  151. std::string relPath;
  152. if (!checkDir.empty()) {
  153. relPath = cmSystemTools::RelativePath(checkDir, fFile);
  154. } else {
  155. relPath = fFile;
  156. }
  157. if (checkDir == fSrcDir) {
  158. checkDir = fBinDir;
  159. } else {
  160. checkDir = fSrcDir;
  161. }
  162. fFile = checkDir + "/" + relPath;
  163. fFile = cmSystemTools::GetFilenamePath(fFile);
  164. if (fileDir == fFile) {
  165. // This is in-source build, so we trust the previous check.
  166. return true;
  167. }
  168. ndc = cmSystemTools::FileExistsInParentDirectories(".NoDartCoverage", fFile,
  169. checkDir);
  170. if (!ndc.empty()) {
  171. cmCTestOptionalLog(this->CTest, HANDLER_VERBOSE_OUTPUT,
  172. "Found: " << ndc << " so skip coverage of: " << file
  173. << std::endl,
  174. this->Quiet);
  175. return false;
  176. }
  177. // Ok, nothing in source tree, nothing in binary tree
  178. return true;
  179. }
  180. // clearly it would be nice if this were broken up into a few smaller
  181. // functions and commented...
  182. int cmCTestCoverageHandler::ProcessHandler()
  183. {
  184. this->CTest->ClearSubmitFiles(cmCTest::PartCoverage);
  185. int error = 0;
  186. // do we have time for this
  187. if (this->CTest->GetRemainingTimeAllowed() < std::chrono::minutes(2)) {
  188. return error;
  189. }
  190. std::string coverage_start_time = this->CTest->CurrentTime();
  191. auto coverage_start_time_time = std::chrono::system_clock::now();
  192. std::string sourceDir =
  193. this->CTest->GetCTestConfiguration("SourceDirectory");
  194. std::string binaryDir = this->CTest->GetCTestConfiguration("BuildDirectory");
  195. if (binaryDir.empty()) {
  196. cmCTestLog(this->CTest, ERROR_MESSAGE,
  197. "Binary directory is not set. "
  198. "No coverage checking will be performed."
  199. << std::endl);
  200. return 0;
  201. }
  202. this->LoadLabels();
  203. cmGeneratedFileStream ofs;
  204. auto elapsed_time_start = std::chrono::steady_clock::now();
  205. if (!this->StartLogFile("Coverage", ofs)) {
  206. cmCTestLog(this->CTest, ERROR_MESSAGE,
  207. "Cannot create LastCoverage.log file" << std::endl);
  208. }
  209. ofs << "Performing coverage: "
  210. << elapsed_time_start.time_since_epoch().count() << std::endl;
  211. this->CleanCoverageLogFiles(ofs);
  212. cmSystemTools::ConvertToUnixSlashes(sourceDir);
  213. cmSystemTools::ConvertToUnixSlashes(binaryDir);
  214. cmCTestOptionalLog(this->CTest, HANDLER_OUTPUT,
  215. "Performing coverage" << std::endl, this->Quiet);
  216. cmCTestCoverageHandlerContainer cont;
  217. cont.Error = error;
  218. cont.SourceDir = sourceDir;
  219. cont.BinaryDir = binaryDir;
  220. cont.OFS = &ofs;
  221. cont.Quiet = this->Quiet;
  222. // setup the regex exclude stuff
  223. this->CustomCoverageExcludeRegex.clear();
  224. for (std::string const& rex : this->CustomCoverageExclude) {
  225. this->CustomCoverageExcludeRegex.emplace_back(rex);
  226. }
  227. if (this->HandleBullseyeCoverage(&cont)) {
  228. return cont.Error;
  229. }
  230. int file_count = 0;
  231. file_count += this->HandleGCovCoverage(&cont);
  232. error = cont.Error;
  233. if (file_count < 0) {
  234. return error;
  235. }
  236. file_count += this->HandleLCovCoverage(&cont);
  237. error = cont.Error;
  238. if (file_count < 0) {
  239. return error;
  240. }
  241. file_count += this->HandleTracePyCoverage(&cont);
  242. error = cont.Error;
  243. if (file_count < 0) {
  244. return error;
  245. }
  246. file_count += this->HandlePHPCoverage(&cont);
  247. error = cont.Error;
  248. if (file_count < 0) {
  249. return error;
  250. }
  251. file_count += this->HandleCoberturaCoverage(&cont);
  252. error = cont.Error;
  253. if (file_count < 0) {
  254. return error;
  255. }
  256. file_count += this->HandleMumpsCoverage(&cont);
  257. error = cont.Error;
  258. if (file_count < 0) {
  259. return error;
  260. }
  261. file_count += this->HandleJacocoCoverage(&cont);
  262. error = cont.Error;
  263. if (file_count < 0) {
  264. return error;
  265. }
  266. file_count += this->HandleBlanketJSCoverage(&cont);
  267. error = cont.Error;
  268. if (file_count < 0) {
  269. return error;
  270. }
  271. file_count += this->HandleDelphiCoverage(&cont);
  272. error = cont.Error;
  273. if (file_count < 0) {
  274. return error;
  275. }
  276. std::set<std::string> uncovered = this->FindUncoveredFiles(&cont);
  277. if (file_count == 0 && this->ExtraCoverageGlobs.empty()) {
  278. cmCTestOptionalLog(
  279. this->CTest, WARNING,
  280. " Cannot find any coverage files. Ignoring Coverage request."
  281. << std::endl,
  282. this->Quiet);
  283. return error;
  284. }
  285. cmGeneratedFileStream covSumFile;
  286. cmGeneratedFileStream covLogFile;
  287. cmXMLWriter covSumXML(covSumFile);
  288. cmXMLWriter covLogXML(covLogFile);
  289. if (!this->StartResultingXML(cmCTest::PartCoverage, "Coverage",
  290. covSumFile)) {
  291. cmCTestLog(this->CTest, ERROR_MESSAGE,
  292. "Cannot open coverage summary file." << std::endl);
  293. return -1;
  294. }
  295. covSumFile.setf(std::ios::fixed, std::ios::floatfield);
  296. covSumFile.precision(2);
  297. this->CTest->StartXML(covSumXML, this->AppendXML);
  298. // Produce output xml files
  299. covSumXML.StartElement("Coverage");
  300. covSumXML.Element("StartDateTime", coverage_start_time);
  301. covSumXML.Element("StartTime", coverage_start_time_time);
  302. int logFileCount = 0;
  303. if (!this->StartCoverageLogFile(covLogFile, logFileCount)) {
  304. return -1;
  305. }
  306. this->StartCoverageLogXML(covLogXML);
  307. int cnt = 0;
  308. long total_tested = 0;
  309. long total_untested = 0;
  310. // std::string fullSourceDir = sourceDir + "/";
  311. // std::string fullBinaryDir = binaryDir + "/";
  312. cmCTestOptionalLog(this->CTest, HANDLER_OUTPUT, std::endl, this->Quiet);
  313. cmCTestOptionalLog(
  314. this->CTest, HANDLER_OUTPUT,
  315. " Accumulating results (each . represents one file):" << std::endl,
  316. this->Quiet);
  317. cmCTestOptionalLog(this->CTest, HANDLER_OUTPUT, " ", this->Quiet);
  318. std::vector<std::string> errorsWhileAccumulating;
  319. file_count = 0;
  320. for (auto const& file : cont.TotalCoverage) {
  321. cmCTestOptionalLog(this->CTest, HANDLER_OUTPUT, "." << std::flush,
  322. this->Quiet);
  323. file_count++;
  324. if (file_count % 50 == 0) {
  325. cmCTestOptionalLog(this->CTest, HANDLER_OUTPUT,
  326. " processed: " << file_count << " out of "
  327. << cont.TotalCoverage.size()
  328. << std::endl,
  329. this->Quiet);
  330. cmCTestOptionalLog(this->CTest, HANDLER_OUTPUT, " ", this->Quiet);
  331. }
  332. const std::string fullFileName = file.first;
  333. bool shouldIDoCoverage =
  334. this->ShouldIDoCoverage(fullFileName, sourceDir, binaryDir);
  335. if (!shouldIDoCoverage) {
  336. cmCTestOptionalLog(this->CTest, HANDLER_VERBOSE_OUTPUT,
  337. ".NoDartCoverage found, so skip coverage check for: "
  338. << fullFileName << std::endl,
  339. this->Quiet);
  340. continue;
  341. }
  342. cmCTestOptionalLog(this->CTest, HANDLER_VERBOSE_OUTPUT,
  343. "Process file: " << fullFileName << std::endl,
  344. this->Quiet);
  345. if (!cmSystemTools::FileExists(fullFileName)) {
  346. cmCTestLog(this->CTest, ERROR_MESSAGE,
  347. "Cannot find file: " << fullFileName << std::endl);
  348. continue;
  349. }
  350. if (++cnt % 100 == 0) {
  351. this->EndCoverageLogXML(covLogXML);
  352. this->EndCoverageLogFile(covLogFile, logFileCount);
  353. logFileCount++;
  354. if (!this->StartCoverageLogFile(covLogFile, logFileCount)) {
  355. return -1;
  356. }
  357. this->StartCoverageLogXML(covLogXML);
  358. }
  359. const std::string fileName = cmSystemTools::GetFilenameName(fullFileName);
  360. const std::string shortFileName =
  361. this->CTest->GetShortPathToFile(fullFileName);
  362. const cmCTestCoverageHandlerContainer::SingleFileCoverageVector& fcov =
  363. file.second;
  364. covLogXML.StartElement("File");
  365. covLogXML.Attribute("Name", fileName);
  366. covLogXML.Attribute("FullPath", shortFileName);
  367. covLogXML.StartElement("Report");
  368. cmsys::ifstream ifs(fullFileName.c_str());
  369. if (!ifs) {
  370. std::ostringstream ostr;
  371. ostr << "Cannot open source file: " << fullFileName;
  372. errorsWhileAccumulating.push_back(ostr.str());
  373. error++;
  374. continue;
  375. }
  376. int tested = 0;
  377. int untested = 0;
  378. cmCTestCoverageHandlerContainer::SingleFileCoverageVector::size_type cc;
  379. std::string line;
  380. cmCTestOptionalLog(this->CTest, HANDLER_VERBOSE_OUTPUT,
  381. "Actually performing coverage for: " << fullFileName
  382. << std::endl,
  383. this->Quiet);
  384. for (cc = 0; cc < fcov.size(); cc++) {
  385. if (!cmSystemTools::GetLineFromStream(ifs, line) &&
  386. cc != fcov.size() - 1) {
  387. std::ostringstream ostr;
  388. ostr << "Problem reading source file: " << fullFileName
  389. << " line:" << cc << " out total: " << fcov.size() - 1;
  390. errorsWhileAccumulating.push_back(ostr.str());
  391. error++;
  392. break;
  393. }
  394. covLogXML.StartElement("Line");
  395. covLogXML.Attribute("Number", cc);
  396. covLogXML.Attribute("Count", fcov[cc]);
  397. covLogXML.Content(line);
  398. covLogXML.EndElement(); // Line
  399. if (fcov[cc] == 0) {
  400. untested++;
  401. } else if (fcov[cc] > 0) {
  402. tested++;
  403. }
  404. }
  405. if (cmSystemTools::GetLineFromStream(ifs, line)) {
  406. std::ostringstream ostr;
  407. ostr << "Looks like there are more lines in the file: " << fullFileName;
  408. errorsWhileAccumulating.push_back(ostr.str());
  409. }
  410. float cper = 0;
  411. float cmet = 0;
  412. if (tested + untested > 0) {
  413. cper = (100 *
  414. SAFEDIV(static_cast<float>(tested),
  415. static_cast<float>(tested + untested)));
  416. cmet = (SAFEDIV(static_cast<float>(tested + 10),
  417. static_cast<float>(tested + untested + 10)));
  418. }
  419. total_tested += tested;
  420. total_untested += untested;
  421. covLogXML.EndElement(); // Report
  422. covLogXML.EndElement(); // File
  423. covSumXML.StartElement("File");
  424. covSumXML.Attribute("Name", fileName);
  425. covSumXML.Attribute("FullPath",
  426. this->CTest->GetShortPathToFile(fullFileName));
  427. covSumXML.Attribute("Covered", tested + untested > 0 ? "true" : "false");
  428. covSumXML.Element("LOCTested", tested);
  429. covSumXML.Element("LOCUnTested", untested);
  430. covSumXML.Element("PercentCoverage", cper);
  431. covSumXML.Element("CoverageMetric", cmet);
  432. this->WriteXMLLabels(covSumXML, shortFileName);
  433. covSumXML.EndElement(); // File
  434. }
  435. // Handle all the files in the extra coverage globs that have no cov data
  436. for (std::string const& u : uncovered) {
  437. std::string fileName = cmSystemTools::GetFilenameName(u);
  438. std::string fullPath = cont.SourceDir + "/" + u;
  439. covLogXML.StartElement("File");
  440. covLogXML.Attribute("Name", fileName);
  441. covLogXML.Attribute("FullPath", u);
  442. covLogXML.StartElement("Report");
  443. cmsys::ifstream ifs(fullPath.c_str());
  444. if (!ifs) {
  445. std::ostringstream ostr;
  446. ostr << "Cannot open source file: " << fullPath;
  447. errorsWhileAccumulating.push_back(ostr.str());
  448. error++;
  449. covLogXML.EndElement(); // Report
  450. covLogXML.EndElement(); // File
  451. continue;
  452. }
  453. int untested = 0;
  454. std::string line;
  455. cmCTestOptionalLog(this->CTest, HANDLER_VERBOSE_OUTPUT,
  456. "Actually performing coverage for: " << u << std::endl,
  457. this->Quiet);
  458. while (cmSystemTools::GetLineFromStream(ifs, line)) {
  459. covLogXML.StartElement("Line");
  460. covLogXML.Attribute("Number", untested);
  461. covLogXML.Attribute("Count", 0);
  462. covLogXML.Content(line);
  463. covLogXML.EndElement(); // Line
  464. untested++;
  465. }
  466. covLogXML.EndElement(); // Report
  467. covLogXML.EndElement(); // File
  468. total_untested += untested;
  469. covSumXML.StartElement("File");
  470. covSumXML.Attribute("Name", fileName);
  471. covSumXML.Attribute("FullPath", u);
  472. covSumXML.Attribute("Covered", "true");
  473. covSumXML.Element("LOCTested", 0);
  474. covSumXML.Element("LOCUnTested", untested);
  475. covSumXML.Element("PercentCoverage", 0);
  476. covSumXML.Element("CoverageMetric", 0);
  477. this->WriteXMLLabels(covSumXML, u);
  478. covSumXML.EndElement(); // File
  479. }
  480. this->EndCoverageLogXML(covLogXML);
  481. this->EndCoverageLogFile(covLogFile, logFileCount);
  482. if (!errorsWhileAccumulating.empty()) {
  483. cmCTestLog(this->CTest, ERROR_MESSAGE, std::endl);
  484. cmCTestLog(this->CTest, ERROR_MESSAGE,
  485. "Error(s) while accumulating results:" << std::endl);
  486. for (std::string const& er : errorsWhileAccumulating) {
  487. cmCTestLog(this->CTest, ERROR_MESSAGE, " " << er << std::endl);
  488. }
  489. }
  490. long total_lines = total_tested + total_untested;
  491. float percent_coverage = 100 *
  492. SAFEDIV(static_cast<float>(total_tested), static_cast<float>(total_lines));
  493. if (total_lines == 0) {
  494. percent_coverage = 0;
  495. }
  496. std::string end_time = this->CTest->CurrentTime();
  497. covSumXML.Element("LOCTested", total_tested);
  498. covSumXML.Element("LOCUntested", total_untested);
  499. covSumXML.Element("LOC", total_lines);
  500. covSumXML.Element("PercentCoverage", percent_coverage);
  501. covSumXML.Element("EndDateTime", end_time);
  502. covSumXML.Element("EndTime", std::chrono::system_clock::now());
  503. covSumXML.Element("ElapsedMinutes",
  504. std::chrono::duration_cast<std::chrono::minutes>(
  505. std::chrono::steady_clock::now() - elapsed_time_start)
  506. .count());
  507. covSumXML.EndElement(); // Coverage
  508. this->CTest->EndXML(covSumXML);
  509. cmCTestLog(this->CTest, HANDLER_OUTPUT,
  510. "" << std::endl
  511. << "\tCovered LOC: " << total_tested << std::endl
  512. << "\tNot covered LOC: " << total_untested << std::endl
  513. << "\tTotal LOC: " << total_lines << std::endl
  514. << "\tPercentage Coverage: "
  515. << std::setiosflags(std::ios::fixed) << std::setprecision(2)
  516. << (percent_coverage) << "%" << std::endl);
  517. ofs << "\tCovered LOC: " << total_tested << std::endl
  518. << "\tNot covered LOC: " << total_untested << std::endl
  519. << "\tTotal LOC: " << total_lines << std::endl
  520. << "\tPercentage Coverage: " << std::setiosflags(std::ios::fixed)
  521. << std::setprecision(2) << (percent_coverage) << "%" << std::endl;
  522. if (error) {
  523. return -1;
  524. }
  525. return 0;
  526. }
  527. void cmCTestCoverageHandler::PopulateCustomVectors(cmMakefile* mf)
  528. {
  529. cmCTestOptionalLog(this->CTest, HANDLER_VERBOSE_OUTPUT,
  530. " Add coverage exclude regular expressions." << std::endl,
  531. this->Quiet);
  532. this->CTest->PopulateCustomVector(mf, "CTEST_CUSTOM_COVERAGE_EXCLUDE",
  533. this->CustomCoverageExclude);
  534. this->CTest->PopulateCustomVector(mf, "CTEST_EXTRA_COVERAGE_GLOB",
  535. this->ExtraCoverageGlobs);
  536. for (std::string const& cce : this->CustomCoverageExclude) {
  537. cmCTestOptionalLog(this->CTest, HANDLER_VERBOSE_OUTPUT,
  538. " Add coverage exclude: " << cce << std::endl,
  539. this->Quiet);
  540. }
  541. for (std::string const& ecg : this->ExtraCoverageGlobs) {
  542. cmCTestOptionalLog(this->CTest, HANDLER_VERBOSE_OUTPUT,
  543. " Add coverage glob: " << ecg << std::endl,
  544. this->Quiet);
  545. }
  546. }
  547. // Fix for issue #4971 where the case of the drive letter component of
  548. // the filenames might be different when analyzing gcov output.
  549. //
  550. // Compare file names: fnc(fn1) == fnc(fn2) // fnc == file name compare
  551. //
  552. #ifdef _WIN32
  553. # define fnc(s) cmSystemTools::LowerCase(s)
  554. # define fnc_prefix(s, t) fnc(s.substr(0, t.size())) == fnc(t)
  555. #else
  556. # define fnc_prefix(s, t) cmHasPrefix(s, t)
  557. #endif
  558. static bool IsFileInDir(const std::string& infile, const std::string& indir)
  559. {
  560. std::string file = cmSystemTools::CollapseFullPath(infile);
  561. std::string dir = cmSystemTools::CollapseFullPath(indir);
  562. return file.size() > dir.size() && fnc_prefix(file, dir) &&
  563. file[dir.size()] == '/';
  564. }
  565. int cmCTestCoverageHandler::HandlePHPCoverage(
  566. cmCTestCoverageHandlerContainer* cont)
  567. {
  568. cmParsePHPCoverage cov(*cont, this->CTest);
  569. std::string coverageDir = this->CTest->GetBinaryDir() + "/xdebugCoverage";
  570. if (cmSystemTools::FileIsDirectory(coverageDir)) {
  571. cov.ReadPHPCoverageDirectory(coverageDir.c_str());
  572. }
  573. return static_cast<int>(cont->TotalCoverage.size());
  574. }
  575. int cmCTestCoverageHandler::HandleCoberturaCoverage(
  576. cmCTestCoverageHandlerContainer* cont)
  577. {
  578. cmParseCoberturaCoverage cov(*cont, this->CTest);
  579. // Assume the coverage.xml is in the binary directory
  580. // check for the COBERTURADIR environment variable,
  581. // if it doesn't exist or is empty, assume the
  582. // binary directory is used.
  583. std::string coverageXMLFile;
  584. if (!cmSystemTools::GetEnv("COBERTURADIR", coverageXMLFile) ||
  585. coverageXMLFile.empty()) {
  586. coverageXMLFile = this->CTest->GetBinaryDir();
  587. }
  588. // build the find file string with the directory from above
  589. coverageXMLFile += "/coverage.xml";
  590. if (cmSystemTools::FileExists(coverageXMLFile)) {
  591. // If file exists, parse it
  592. cmCTestOptionalLog(this->CTest, HANDLER_VERBOSE_OUTPUT,
  593. "Parsing Cobertura XML file: " << coverageXMLFile
  594. << std::endl,
  595. this->Quiet);
  596. cov.ReadCoverageXML(coverageXMLFile.c_str());
  597. } else {
  598. cmCTestOptionalLog(this->CTest, HANDLER_VERBOSE_OUTPUT,
  599. " Cannot find Cobertura XML file: " << coverageXMLFile
  600. << std::endl,
  601. this->Quiet);
  602. }
  603. return static_cast<int>(cont->TotalCoverage.size());
  604. }
  605. int cmCTestCoverageHandler::HandleMumpsCoverage(
  606. cmCTestCoverageHandlerContainer* cont)
  607. {
  608. // try gtm coverage
  609. cmParseGTMCoverage cov(*cont, this->CTest);
  610. std::string coverageFile =
  611. this->CTest->GetBinaryDir() + "/gtm_coverage.mcov";
  612. if (cmSystemTools::FileExists(coverageFile)) {
  613. cmCTestOptionalLog(this->CTest, HANDLER_VERBOSE_OUTPUT,
  614. "Parsing Cache Coverage: " << coverageFile << std::endl,
  615. this->Quiet);
  616. cov.ReadCoverageFile(coverageFile.c_str());
  617. return static_cast<int>(cont->TotalCoverage.size());
  618. }
  619. cmCTestOptionalLog(this->CTest, HANDLER_VERBOSE_OUTPUT,
  620. " Cannot find GTM coverage file: " << coverageFile
  621. << std::endl,
  622. this->Quiet);
  623. cmParseCacheCoverage ccov(*cont, this->CTest);
  624. coverageFile = this->CTest->GetBinaryDir() + "/cache_coverage.cmcov";
  625. if (cmSystemTools::FileExists(coverageFile)) {
  626. cmCTestOptionalLog(this->CTest, HANDLER_VERBOSE_OUTPUT,
  627. "Parsing Cache Coverage: " << coverageFile << std::endl,
  628. this->Quiet);
  629. ccov.ReadCoverageFile(coverageFile.c_str());
  630. } else {
  631. cmCTestOptionalLog(this->CTest, HANDLER_VERBOSE_OUTPUT,
  632. " Cannot find Cache coverage file: " << coverageFile
  633. << std::endl,
  634. this->Quiet);
  635. }
  636. return static_cast<int>(cont->TotalCoverage.size());
  637. }
  638. struct cmCTestCoverageHandlerLocale
  639. {
  640. cmCTestCoverageHandlerLocale()
  641. {
  642. std::string l;
  643. if (cmSystemTools::GetEnv("LC_ALL", l)) {
  644. this->lc_all = l;
  645. }
  646. if (this->lc_all != "C") {
  647. cmSystemTools::PutEnv("LC_ALL=C");
  648. }
  649. }
  650. ~cmCTestCoverageHandlerLocale()
  651. {
  652. if (!this->lc_all.empty()) {
  653. cmSystemTools::PutEnv("LC_ALL=" + this->lc_all);
  654. } else {
  655. cmSystemTools::UnsetEnv("LC_ALL");
  656. }
  657. }
  658. cmCTestCoverageHandlerLocale(const cmCTestCoverageHandlerLocale&) = delete;
  659. cmCTestCoverageHandlerLocale& operator=(
  660. const cmCTestCoverageHandlerLocale&) = delete;
  661. std::string lc_all;
  662. };
  663. int cmCTestCoverageHandler::HandleJacocoCoverage(
  664. cmCTestCoverageHandlerContainer* cont)
  665. {
  666. cmParseJacocoCoverage cov = cmParseJacocoCoverage(*cont, this->CTest);
  667. // Search in the source directory.
  668. cmsys::Glob g1;
  669. std::vector<std::string> files;
  670. g1.SetRecurse(true);
  671. std::string SourceDir =
  672. this->CTest->GetCTestConfiguration("SourceDirectory");
  673. std::string coverageFile = SourceDir + "/*jacoco.xml";
  674. g1.FindFiles(coverageFile);
  675. files = g1.GetFiles();
  676. // ...and in the binary directory.
  677. cmsys::Glob g2;
  678. g2.SetRecurse(true);
  679. std::string binaryDir = this->CTest->GetCTestConfiguration("BuildDirectory");
  680. std::string binCoverageFile = binaryDir + "/*jacoco.xml";
  681. g2.FindFiles(binCoverageFile);
  682. cm::append(files, g2.GetFiles());
  683. if (!files.empty()) {
  684. cmCTestOptionalLog(this->CTest, HANDLER_VERBOSE_OUTPUT,
  685. "Found Jacoco Files, Performing Coverage" << std::endl,
  686. this->Quiet);
  687. cov.LoadCoverageData(files);
  688. } else {
  689. cmCTestOptionalLog(this->CTest, HANDLER_VERBOSE_OUTPUT,
  690. " Cannot find Jacoco coverage files: " << coverageFile
  691. << std::endl,
  692. this->Quiet);
  693. }
  694. return static_cast<int>(cont->TotalCoverage.size());
  695. }
  696. int cmCTestCoverageHandler::HandleDelphiCoverage(
  697. cmCTestCoverageHandlerContainer* cont)
  698. {
  699. cmParseDelphiCoverage cov = cmParseDelphiCoverage(*cont, this->CTest);
  700. cmsys::Glob g;
  701. std::vector<std::string> files;
  702. g.SetRecurse(true);
  703. std::string BinDir = this->CTest->GetBinaryDir();
  704. std::string coverageFile = BinDir + "/*(*.pas).html";
  705. g.FindFiles(coverageFile);
  706. files = g.GetFiles();
  707. if (!files.empty()) {
  708. cmCTestOptionalLog(this->CTest, HANDLER_VERBOSE_OUTPUT,
  709. "Found Delphi HTML Files, Performing Coverage"
  710. << std::endl,
  711. this->Quiet);
  712. cov.LoadCoverageData(files);
  713. } else {
  714. cmCTestOptionalLog(this->CTest, HANDLER_VERBOSE_OUTPUT,
  715. " Cannot find Delphi coverage files: " << coverageFile
  716. << std::endl,
  717. this->Quiet);
  718. }
  719. return static_cast<int>(cont->TotalCoverage.size());
  720. }
  721. static std::string joinCommandLine(const std::vector<std::string>& args)
  722. {
  723. std::string ret;
  724. for (std::string const& s : args) {
  725. if (s.find(' ') == std::string::npos) {
  726. ret += s + ' ';
  727. } else {
  728. ret += "\"" + s + "\" ";
  729. }
  730. }
  731. // drop trailing whitespace
  732. ret.erase(ret.size() - 1);
  733. return ret;
  734. }
  735. int cmCTestCoverageHandler::HandleBlanketJSCoverage(
  736. cmCTestCoverageHandlerContainer* cont)
  737. {
  738. cmParseBlanketJSCoverage cov = cmParseBlanketJSCoverage(*cont, this->CTest);
  739. std::string SourceDir =
  740. this->CTest->GetCTestConfiguration("SourceDirectory");
  741. // Look for something other than output.json, still JSON extension.
  742. std::string coverageFile = SourceDir + "/*.json";
  743. cmsys::Glob g;
  744. std::vector<std::string> files;
  745. std::vector<std::string> blanketFiles;
  746. g.FindFiles(coverageFile);
  747. files = g.GetFiles();
  748. // Ensure that the JSON files found are the result of the
  749. // Blanket.js output. Check for the "node-jscoverage"
  750. // string on the second line
  751. std::string line;
  752. for (std::string const& fileEntry : files) {
  753. cmsys::ifstream in(fileEntry.c_str());
  754. cmSystemTools::GetLineFromStream(in, line);
  755. cmSystemTools::GetLineFromStream(in, line);
  756. if (line.find("node-jscoverage") != std::string::npos) {
  757. blanketFiles.push_back(fileEntry);
  758. }
  759. }
  760. // Take all files with the node-jscoverage string and parse those
  761. if (!blanketFiles.empty()) {
  762. cmCTestOptionalLog(this->CTest, HANDLER_VERBOSE_OUTPUT,
  763. "Found BlanketJS output JSON, Performing Coverage"
  764. << std::endl,
  765. this->Quiet);
  766. cov.LoadCoverageData(files);
  767. } else {
  768. cmCTestOptionalLog(
  769. this->CTest, HANDLER_VERBOSE_OUTPUT,
  770. " Cannot find BlanketJS coverage files: " << coverageFile << std::endl,
  771. this->Quiet);
  772. }
  773. return static_cast<int>(cont->TotalCoverage.size());
  774. }
  775. int cmCTestCoverageHandler::HandleGCovCoverage(
  776. cmCTestCoverageHandlerContainer* cont)
  777. {
  778. std::string gcovCommand =
  779. this->CTest->GetCTestConfiguration("CoverageCommand");
  780. if (gcovCommand.empty()) {
  781. cmCTestOptionalLog(this->CTest, HANDLER_VERBOSE_OUTPUT,
  782. "Could not find gcov." << std::endl, this->Quiet);
  783. return 0;
  784. }
  785. std::string gcovExtraFlags =
  786. this->CTest->GetCTestConfiguration("CoverageExtraFlags");
  787. // Immediately skip to next coverage option since codecov is only for Intel
  788. // compiler
  789. if (gcovCommand == "codecov") {
  790. return 0;
  791. }
  792. // Style 1
  793. std::string st1gcovOutputRex1 =
  794. "[0-9]+\\.[0-9]+% of [0-9]+ (source |)lines executed in file (.*)$";
  795. std::string st1gcovOutputRex2 = "^Creating (.*\\.gcov)\\.";
  796. cmsys::RegularExpression st1re1(st1gcovOutputRex1.c_str());
  797. cmsys::RegularExpression st1re2(st1gcovOutputRex2.c_str());
  798. // Style 2
  799. std::string st2gcovOutputRex1 = "^File *[`'](.*)'$";
  800. std::string st2gcovOutputRex2 =
  801. "Lines executed: *[0-9]+\\.[0-9]+% of [0-9]+$";
  802. std::string st2gcovOutputRex3 = "^(.*)reating [`'](.*\\.gcov)'";
  803. std::string st2gcovOutputRex4 = "^(.*):unexpected EOF *$";
  804. std::string st2gcovOutputRex5 = "^(.*):cannot open source file*$";
  805. std::string st2gcovOutputRex6 =
  806. "^(.*):source file is newer than graph file `(.*)'$";
  807. cmsys::RegularExpression st2re1(st2gcovOutputRex1.c_str());
  808. cmsys::RegularExpression st2re2(st2gcovOutputRex2.c_str());
  809. cmsys::RegularExpression st2re3(st2gcovOutputRex3.c_str());
  810. cmsys::RegularExpression st2re4(st2gcovOutputRex4.c_str());
  811. cmsys::RegularExpression st2re5(st2gcovOutputRex5.c_str());
  812. cmsys::RegularExpression st2re6(st2gcovOutputRex6.c_str());
  813. std::vector<std::string> files;
  814. this->FindGCovFiles(files);
  815. if (files.empty()) {
  816. cmCTestOptionalLog(this->CTest, HANDLER_VERBOSE_OUTPUT,
  817. " Cannot find any GCov coverage files." << std::endl,
  818. this->Quiet);
  819. // No coverage files is a valid thing, so the exit code is 0
  820. return 0;
  821. }
  822. std::string testingDir = this->CTest->GetBinaryDir() + "/Testing";
  823. std::string tempDir = testingDir + "/CoverageInfo";
  824. if (!cmSystemTools::MakeDirectory(tempDir)) {
  825. cmCTestLog(this->CTest, ERROR_MESSAGE,
  826. "Unable to make directory: " << tempDir << std::endl);
  827. cont->Error++;
  828. return 0;
  829. }
  830. cmWorkingDirectory workdir(tempDir);
  831. int gcovStyle = 0;
  832. std::set<std::string> missingFiles;
  833. std::string actualSourceFile;
  834. cmCTestOptionalLog(
  835. this->CTest, HANDLER_OUTPUT,
  836. " Processing coverage (each . represents one file):" << std::endl,
  837. this->Quiet);
  838. cmCTestOptionalLog(this->CTest, HANDLER_OUTPUT, " ", this->Quiet);
  839. int file_count = 0;
  840. // make sure output from gcov is in English!
  841. cmCTestCoverageHandlerLocale locale_C;
  842. static_cast<void>(locale_C);
  843. std::vector<std::string> basecovargs =
  844. cmSystemTools::ParseArguments(gcovExtraFlags);
  845. basecovargs.insert(basecovargs.begin(), gcovCommand);
  846. basecovargs.emplace_back("-o");
  847. // files is a list of *.da and *.gcda files with coverage data in them.
  848. // These are binary files that you give as input to gcov so that it will
  849. // give us text output we can analyze to summarize coverage.
  850. //
  851. for (std::string const& f : files) {
  852. cmCTestOptionalLog(this->CTest, HANDLER_OUTPUT, "." << std::flush,
  853. this->Quiet);
  854. // Call gcov to get coverage data for this *.gcda file:
  855. //
  856. std::string fileDir = cmSystemTools::GetFilenamePath(f);
  857. std::vector<std::string> covargs = basecovargs;
  858. covargs.push_back(fileDir);
  859. covargs.push_back(f);
  860. const std::string command = joinCommandLine(covargs);
  861. cmCTestOptionalLog(this->CTest, HANDLER_VERBOSE_OUTPUT,
  862. command << std::endl, this->Quiet);
  863. std::string output;
  864. std::string errors;
  865. int retVal = 0;
  866. *cont->OFS << "* Run coverage for: " << fileDir << std::endl;
  867. *cont->OFS << " Command: " << command << std::endl;
  868. int res = this->CTest->RunCommand(covargs, &output, &errors, &retVal,
  869. tempDir.c_str(),
  870. cmDuration::zero() /*this->TimeOut*/);
  871. *cont->OFS << " Output: " << output << std::endl;
  872. *cont->OFS << " Errors: " << errors << std::endl;
  873. if (!res) {
  874. cmCTestLog(this->CTest, ERROR_MESSAGE,
  875. "Problem running coverage on file: " << f << std::endl);
  876. cmCTestLog(this->CTest, ERROR_MESSAGE,
  877. "Command produced error: " << errors << std::endl);
  878. cont->Error++;
  879. continue;
  880. }
  881. if (retVal != 0) {
  882. cmCTestLog(this->CTest, ERROR_MESSAGE,
  883. "Coverage command returned: "
  884. << retVal << " while processing: " << f << std::endl);
  885. cmCTestLog(this->CTest, ERROR_MESSAGE,
  886. "Command produced error: " << cont->Error << std::endl);
  887. }
  888. cmCTestOptionalLog(
  889. this->CTest, HANDLER_VERBOSE_OUTPUT,
  890. "--------------------------------------------------------------"
  891. << std::endl
  892. << output << std::endl
  893. << "--------------------------------------------------------------"
  894. << std::endl,
  895. this->Quiet);
  896. std::vector<std::string> lines;
  897. cmsys::SystemTools::Split(output, lines);
  898. for (std::string const& line : lines) {
  899. std::string sourceFile;
  900. std::string gcovFile;
  901. cmCTestOptionalLog(this->CTest, DEBUG,
  902. "Line: [" << line << "]" << std::endl, this->Quiet);
  903. if (line.empty()) {
  904. // Ignore empty line; probably style 2
  905. } else if (st1re1.find(line)) {
  906. if (gcovStyle == 0) {
  907. gcovStyle = 1;
  908. }
  909. if (gcovStyle != 1) {
  910. cmCTestLog(this->CTest, ERROR_MESSAGE,
  911. "Unknown gcov output style e1" << std::endl);
  912. cont->Error++;
  913. break;
  914. }
  915. actualSourceFile.clear();
  916. sourceFile = st1re1.match(2);
  917. } else if (st1re2.find(line)) {
  918. if (gcovStyle == 0) {
  919. gcovStyle = 1;
  920. }
  921. if (gcovStyle != 1) {
  922. cmCTestLog(this->CTest, ERROR_MESSAGE,
  923. "Unknown gcov output style e2" << std::endl);
  924. cont->Error++;
  925. break;
  926. }
  927. gcovFile = st1re2.match(1);
  928. } else if (st2re1.find(line)) {
  929. if (gcovStyle == 0) {
  930. gcovStyle = 2;
  931. }
  932. if (gcovStyle != 2) {
  933. cmCTestLog(this->CTest, ERROR_MESSAGE,
  934. "Unknown gcov output style e3" << std::endl);
  935. cont->Error++;
  936. break;
  937. }
  938. actualSourceFile.clear();
  939. sourceFile = st2re1.match(1);
  940. } else if (st2re2.find(line)) {
  941. if (gcovStyle == 0) {
  942. gcovStyle = 2;
  943. }
  944. if (gcovStyle != 2) {
  945. cmCTestLog(this->CTest, ERROR_MESSAGE,
  946. "Unknown gcov output style e4" << std::endl);
  947. cont->Error++;
  948. break;
  949. }
  950. } else if (st2re3.find(line)) {
  951. if (gcovStyle == 0) {
  952. gcovStyle = 2;
  953. }
  954. if (gcovStyle != 2) {
  955. cmCTestLog(this->CTest, ERROR_MESSAGE,
  956. "Unknown gcov output style e5" << std::endl);
  957. cont->Error++;
  958. break;
  959. }
  960. gcovFile = st2re3.match(2);
  961. } else if (st2re4.find(line)) {
  962. if (gcovStyle == 0) {
  963. gcovStyle = 2;
  964. }
  965. if (gcovStyle != 2) {
  966. cmCTestLog(this->CTest, ERROR_MESSAGE,
  967. "Unknown gcov output style e6" << std::endl);
  968. cont->Error++;
  969. break;
  970. }
  971. cmCTestOptionalLog(this->CTest, WARNING,
  972. "Warning: " << st2re4.match(1)
  973. << " had unexpected EOF" << std::endl,
  974. this->Quiet);
  975. } else if (st2re5.find(line)) {
  976. if (gcovStyle == 0) {
  977. gcovStyle = 2;
  978. }
  979. if (gcovStyle != 2) {
  980. cmCTestLog(this->CTest, ERROR_MESSAGE,
  981. "Unknown gcov output style e7" << std::endl);
  982. cont->Error++;
  983. break;
  984. }
  985. cmCTestOptionalLog(this->CTest, WARNING,
  986. "Warning: Cannot open file: " << st2re5.match(1)
  987. << std::endl,
  988. this->Quiet);
  989. } else if (st2re6.find(line)) {
  990. if (gcovStyle == 0) {
  991. gcovStyle = 2;
  992. }
  993. if (gcovStyle != 2) {
  994. cmCTestLog(this->CTest, ERROR_MESSAGE,
  995. "Unknown gcov output style e8" << std::endl);
  996. cont->Error++;
  997. break;
  998. }
  999. cmCTestOptionalLog(this->CTest, WARNING,
  1000. "Warning: File: " << st2re6.match(1)
  1001. << " is newer than "
  1002. << st2re6.match(2) << std::endl,
  1003. this->Quiet);
  1004. } else {
  1005. // gcov 4.7 can have output lines saying "No executable lines" and
  1006. // "Removing 'filename.gcov'"... Don't log those as "errors."
  1007. if (line != "No executable lines" &&
  1008. !cmHasLiteralPrefix(line, "Removing ")) {
  1009. cmCTestLog(this->CTest, ERROR_MESSAGE,
  1010. "Unknown gcov output line: [" << line << "]"
  1011. << std::endl);
  1012. cont->Error++;
  1013. // abort();
  1014. }
  1015. }
  1016. // If the last line of gcov output gave us a valid value for gcovFile,
  1017. // and we have an actualSourceFile, then insert a (or add to existing)
  1018. // SingleFileCoverageVector for actualSourceFile:
  1019. //
  1020. if (!gcovFile.empty() && !actualSourceFile.empty()) {
  1021. cmCTestCoverageHandlerContainer::SingleFileCoverageVector& vec =
  1022. cont->TotalCoverage[actualSourceFile];
  1023. cmCTestOptionalLog(this->CTest, HANDLER_VERBOSE_OUTPUT,
  1024. " in gcovFile: " << gcovFile << std::endl,
  1025. this->Quiet);
  1026. cmsys::ifstream ifile(gcovFile.c_str());
  1027. if (!ifile) {
  1028. cmCTestLog(this->CTest, ERROR_MESSAGE,
  1029. "Cannot open file: " << gcovFile << std::endl);
  1030. } else {
  1031. std::string nl;
  1032. while (cmSystemTools::GetLineFromStream(ifile, nl)) {
  1033. // Skip empty lines
  1034. if (nl.empty()) {
  1035. continue;
  1036. }
  1037. // Skip unused lines
  1038. if (nl.size() < 12) {
  1039. continue;
  1040. }
  1041. // Handle gcov 3.0 non-coverage lines
  1042. // non-coverage lines seem to always start with something not
  1043. // a space and don't have a ':' in the 9th position
  1044. // TODO: Verify that this is actually a robust metric
  1045. if (nl[0] != ' ' && nl[9] != ':') {
  1046. continue;
  1047. }
  1048. // Read the coverage count from the beginning of the gcov output
  1049. // line
  1050. std::string prefix = nl.substr(0, 12);
  1051. int cov = atoi(prefix.c_str());
  1052. // Read the line number starting at the 10th character of the gcov
  1053. // output line
  1054. std::string lineNumber = nl.substr(10, 5);
  1055. int lineIdx = atoi(lineNumber.c_str()) - 1;
  1056. if (lineIdx >= 0) {
  1057. while (vec.size() <= static_cast<size_t>(lineIdx)) {
  1058. vec.push_back(-1);
  1059. }
  1060. // Initially all entries are -1 (not used). If we get coverage
  1061. // information, increment it to 0 first.
  1062. if (vec[lineIdx] < 0) {
  1063. if (cov > 0 || prefix.find('#') != std::string::npos) {
  1064. vec[lineIdx] = 0;
  1065. }
  1066. }
  1067. vec[lineIdx] += cov;
  1068. }
  1069. }
  1070. }
  1071. actualSourceFile.clear();
  1072. }
  1073. if (!sourceFile.empty() && actualSourceFile.empty()) {
  1074. gcovFile.clear();
  1075. // Is it in the source dir or the binary dir?
  1076. //
  1077. if (IsFileInDir(sourceFile, cont->SourceDir)) {
  1078. cmCTestOptionalLog(this->CTest, HANDLER_VERBOSE_OUTPUT,
  1079. " produced s: " << sourceFile << std::endl,
  1080. this->Quiet);
  1081. *cont->OFS << " produced in source dir: " << sourceFile
  1082. << std::endl;
  1083. actualSourceFile = cmSystemTools::CollapseFullPath(sourceFile);
  1084. } else if (IsFileInDir(sourceFile, cont->BinaryDir)) {
  1085. cmCTestOptionalLog(this->CTest, HANDLER_VERBOSE_OUTPUT,
  1086. " produced b: " << sourceFile << std::endl,
  1087. this->Quiet);
  1088. *cont->OFS << " produced in binary dir: " << sourceFile
  1089. << std::endl;
  1090. actualSourceFile = cmSystemTools::CollapseFullPath(sourceFile);
  1091. }
  1092. if (actualSourceFile.empty()) {
  1093. if (missingFiles.find(sourceFile) == missingFiles.end()) {
  1094. cmCTestOptionalLog(this->CTest, HANDLER_VERBOSE_OUTPUT,
  1095. "Something went wrong" << std::endl,
  1096. this->Quiet);
  1097. cmCTestOptionalLog(this->CTest, HANDLER_VERBOSE_OUTPUT,
  1098. "Cannot find file: [" << sourceFile << "]"
  1099. << std::endl,
  1100. this->Quiet);
  1101. cmCTestOptionalLog(this->CTest, HANDLER_VERBOSE_OUTPUT,
  1102. " in source dir: [" << cont->SourceDir << "]"
  1103. << std::endl,
  1104. this->Quiet);
  1105. cmCTestOptionalLog(this->CTest, HANDLER_VERBOSE_OUTPUT,
  1106. " or binary dir: [" << cont->BinaryDir.size()
  1107. << "]" << std::endl,
  1108. this->Quiet);
  1109. *cont->OFS << " Something went wrong. Cannot find file: "
  1110. << sourceFile << " in source dir: " << cont->SourceDir
  1111. << " or binary dir: " << cont->BinaryDir << std::endl;
  1112. missingFiles.insert(sourceFile);
  1113. }
  1114. }
  1115. }
  1116. }
  1117. file_count++;
  1118. if (file_count % 50 == 0) {
  1119. cmCTestOptionalLog(this->CTest, HANDLER_OUTPUT,
  1120. " processed: " << file_count << " out of "
  1121. << files.size() << std::endl,
  1122. this->Quiet);
  1123. cmCTestOptionalLog(this->CTest, HANDLER_OUTPUT, " ", this->Quiet);
  1124. }
  1125. }
  1126. return file_count;
  1127. }
  1128. int cmCTestCoverageHandler::HandleLCovCoverage(
  1129. cmCTestCoverageHandlerContainer* cont)
  1130. {
  1131. std::string lcovCommand =
  1132. this->CTest->GetCTestConfiguration("CoverageCommand");
  1133. std::string lcovExtraFlags =
  1134. this->CTest->GetCTestConfiguration("CoverageExtraFlags");
  1135. if (lcovCommand != "codecov") {
  1136. cmCTestOptionalLog(this->CTest, HANDLER_VERBOSE_OUTPUT,
  1137. " Not a valid Intel Coverage command." << std::endl,
  1138. this->Quiet);
  1139. return 0;
  1140. }
  1141. // There is only percentage completed output from LCOV
  1142. std::string st2lcovOutputRex3 = "[0-9]+%";
  1143. cmsys::RegularExpression st2re3(st2lcovOutputRex3.c_str());
  1144. cmCTestOptionalLog(this->CTest, HANDLER_VERBOSE_OUTPUT,
  1145. " This is coverage command: " << lcovCommand << std::endl,
  1146. this->Quiet);
  1147. cmCTestOptionalLog(this->CTest, HANDLER_VERBOSE_OUTPUT,
  1148. " These are coverage command flags: " << lcovExtraFlags
  1149. << std::endl,
  1150. this->Quiet);
  1151. std::vector<std::string> files;
  1152. if (!this->FindLCovFiles(files)) {
  1153. cmCTestLog(this->CTest, ERROR_MESSAGE,
  1154. "Error while finding LCov files.\n");
  1155. return 0;
  1156. }
  1157. if (files.empty()) {
  1158. cmCTestOptionalLog(this->CTest, HANDLER_VERBOSE_OUTPUT,
  1159. " Cannot find any LCov coverage files." << std::endl,
  1160. this->Quiet);
  1161. // No coverage files is a valid thing, so the exit code is 0
  1162. return 0;
  1163. }
  1164. std::string testingDir = this->CTest->GetBinaryDir();
  1165. std::set<std::string> missingFiles;
  1166. std::string actualSourceFile;
  1167. cmCTestOptionalLog(
  1168. this->CTest, HANDLER_OUTPUT,
  1169. " Processing coverage (each . represents one file):" << std::endl,
  1170. this->Quiet);
  1171. cmCTestOptionalLog(this->CTest, HANDLER_OUTPUT, " ", this->Quiet);
  1172. int file_count = 0;
  1173. // make sure output from lcov is in English!
  1174. cmCTestCoverageHandlerLocale locale_C;
  1175. static_cast<void>(locale_C);
  1176. std::vector<std::string> covargs =
  1177. cmSystemTools::ParseArguments(lcovExtraFlags);
  1178. covargs.insert(covargs.begin(), lcovCommand);
  1179. const std::string command = joinCommandLine(covargs);
  1180. // In intel compiler we have to call codecov only once in each executable
  1181. // directory. It collects all *.dyn files to generate .dpi file.
  1182. for (std::string const& f : files) {
  1183. cmCTestOptionalLog(this->CTest, HANDLER_OUTPUT, "." << std::flush,
  1184. this->Quiet);
  1185. std::string fileDir = cmSystemTools::GetFilenamePath(f);
  1186. cmWorkingDirectory workdir(fileDir);
  1187. if (workdir.Failed()) {
  1188. cmCTestLog(this->CTest, ERROR_MESSAGE,
  1189. "Unable to change working directory to "
  1190. << fileDir << " : "
  1191. << std::strerror(workdir.GetLastResult()) << std::endl);
  1192. cont->Error++;
  1193. continue;
  1194. }
  1195. cmCTestOptionalLog(this->CTest, HANDLER_VERBOSE_OUTPUT,
  1196. "Current coverage dir: " << fileDir << std::endl,
  1197. this->Quiet);
  1198. cmCTestOptionalLog(this->CTest, HANDLER_VERBOSE_OUTPUT,
  1199. command << std::endl, this->Quiet);
  1200. std::string output;
  1201. std::string errors;
  1202. int retVal = 0;
  1203. *cont->OFS << "* Run coverage for: " << fileDir << std::endl;
  1204. *cont->OFS << " Command: " << command << std::endl;
  1205. int res = this->CTest->RunCommand(covargs, &output, &errors, &retVal,
  1206. fileDir.c_str(),
  1207. cmDuration::zero() /*this->TimeOut*/);
  1208. *cont->OFS << " Output: " << output << std::endl;
  1209. *cont->OFS << " Errors: " << errors << std::endl;
  1210. if (!res) {
  1211. cmCTestLog(this->CTest, ERROR_MESSAGE,
  1212. "Problem running coverage on file: " << f << std::endl);
  1213. cmCTestLog(this->CTest, ERROR_MESSAGE,
  1214. "Command produced error: " << errors << std::endl);
  1215. cont->Error++;
  1216. continue;
  1217. }
  1218. if (retVal != 0) {
  1219. cmCTestLog(this->CTest, ERROR_MESSAGE,
  1220. "Coverage command returned: "
  1221. << retVal << " while processing: " << f << std::endl);
  1222. cmCTestLog(this->CTest, ERROR_MESSAGE,
  1223. "Command produced error: " << cont->Error << std::endl);
  1224. }
  1225. cmCTestOptionalLog(
  1226. this->CTest, HANDLER_VERBOSE_OUTPUT,
  1227. "--------------------------------------------------------------"
  1228. << std::endl
  1229. << output << std::endl
  1230. << "--------------------------------------------------------------"
  1231. << std::endl,
  1232. this->Quiet);
  1233. std::vector<std::string> lines;
  1234. cmsys::SystemTools::Split(output, lines);
  1235. for (std::string const& line : lines) {
  1236. std::string sourceFile;
  1237. std::string lcovFile;
  1238. if (line.empty()) {
  1239. // Ignore empty line
  1240. }
  1241. // Look for LCOV files in binary directory
  1242. // Intel Compiler creates a CodeCoverage dir for each subfolder and
  1243. // each subfolder has LCOV files
  1244. cmsys::Glob gl;
  1245. gl.RecurseOn();
  1246. gl.RecurseThroughSymlinksOff();
  1247. std::string dir;
  1248. std::vector<std::string> lcovFiles;
  1249. dir = this->CTest->GetBinaryDir();
  1250. std::string daGlob;
  1251. daGlob = cmStrCat(dir, "/*.LCOV");
  1252. cmCTestOptionalLog(
  1253. this->CTest, HANDLER_VERBOSE_OUTPUT,
  1254. " looking for LCOV files in: " << daGlob << std::endl, this->Quiet);
  1255. gl.FindFiles(daGlob);
  1256. // Keep a list of all LCOV files
  1257. cm::append(lcovFiles, gl.GetFiles());
  1258. for (std::string const& file : lcovFiles) {
  1259. lcovFile = file;
  1260. cmsys::ifstream srcead(lcovFile.c_str());
  1261. if (!srcead) {
  1262. cmCTestLog(this->CTest, ERROR_MESSAGE,
  1263. "Cannot open file: " << lcovFile << std::endl);
  1264. }
  1265. std::string srcname;
  1266. int success = cmSystemTools::GetLineFromStream(srcead, srcname);
  1267. if (!success) {
  1268. cmCTestLog(this->CTest, ERROR_MESSAGE,
  1269. "Error while parsing lcov file '"
  1270. << lcovFile << "':"
  1271. << " No source file name found!" << std::endl);
  1272. return 0;
  1273. }
  1274. srcname = srcname.substr(18);
  1275. // We can directly read found LCOV files to determine the source
  1276. // files
  1277. sourceFile = srcname;
  1278. actualSourceFile = srcname;
  1279. for (std::string const& t : lcovFiles) {
  1280. cmCTestOptionalLog(this->CTest, HANDLER_VERBOSE_OUTPUT,
  1281. "Found LCOV File: " << t << std::endl,
  1282. this->Quiet);
  1283. }
  1284. cmCTestOptionalLog(this->CTest, HANDLER_VERBOSE_OUTPUT,
  1285. "SourceFile: " << sourceFile << std::endl,
  1286. this->Quiet);
  1287. cmCTestOptionalLog(this->CTest, HANDLER_VERBOSE_OUTPUT,
  1288. "lCovFile: " << lcovFile << std::endl, this->Quiet);
  1289. // If we have some LCOV files to process
  1290. if (!lcovFile.empty() && !actualSourceFile.empty()) {
  1291. cmCTestCoverageHandlerContainer::SingleFileCoverageVector& vec =
  1292. cont->TotalCoverage[actualSourceFile];
  1293. cmCTestOptionalLog(this->CTest, HANDLER_VERBOSE_OUTPUT,
  1294. " in lcovFile: " << lcovFile << std::endl,
  1295. this->Quiet);
  1296. cmsys::ifstream ifile(lcovFile.c_str());
  1297. if (!ifile) {
  1298. cmCTestLog(this->CTest, ERROR_MESSAGE,
  1299. "Cannot open file: " << lcovFile << std::endl);
  1300. } else {
  1301. std::string nl;
  1302. // Skip the first line
  1303. cmSystemTools::GetLineFromStream(ifile, nl);
  1304. cmCTestOptionalLog(this->CTest, HANDLER_VERBOSE_OUTPUT,
  1305. "File is ready, start reading." << std::endl,
  1306. this->Quiet);
  1307. while (cmSystemTools::GetLineFromStream(ifile, nl)) {
  1308. // Skip empty lines
  1309. if (nl.empty()) {
  1310. continue;
  1311. }
  1312. // Skip unused lines
  1313. if (nl.size() < 12) {
  1314. continue;
  1315. }
  1316. // Read the coverage count from the beginning of the lcov
  1317. // output line
  1318. std::string prefix = nl.substr(0, 17);
  1319. int cov = atoi(prefix.c_str());
  1320. // Read the line number starting at the 17th character of the
  1321. // lcov output line
  1322. std::string lineNumber = nl.substr(17, 7);
  1323. int lineIdx = atoi(lineNumber.c_str()) - 1;
  1324. if (lineIdx >= 0) {
  1325. while (vec.size() <= static_cast<size_t>(lineIdx)) {
  1326. vec.push_back(-1);
  1327. }
  1328. // Initially all entries are -1 (not used). If we get coverage
  1329. // information, increment it to 0 first.
  1330. if (vec[lineIdx] < 0) {
  1331. if (cov > 0 || prefix.find('#') != std::string::npos) {
  1332. vec[lineIdx] = 0;
  1333. }
  1334. }
  1335. vec[lineIdx] += cov;
  1336. }
  1337. }
  1338. }
  1339. actualSourceFile.clear();
  1340. }
  1341. }
  1342. }
  1343. file_count++;
  1344. if (file_count % 50 == 0) {
  1345. cmCTestOptionalLog(this->CTest, HANDLER_OUTPUT,
  1346. " processed: " << file_count << " out of "
  1347. << files.size() << std::endl,
  1348. this->Quiet);
  1349. cmCTestOptionalLog(this->CTest, HANDLER_OUTPUT, " ", this->Quiet);
  1350. }
  1351. }
  1352. return file_count;
  1353. }
  1354. void cmCTestCoverageHandler::FindGCovFiles(std::vector<std::string>& files)
  1355. {
  1356. cmsys::Glob gl;
  1357. gl.RecurseOn();
  1358. gl.RecurseThroughSymlinksOff();
  1359. for (auto const& lm : this->TargetDirs) {
  1360. // Skip targets containing no interesting labels.
  1361. if (!this->IntersectsFilter(lm.second)) {
  1362. continue;
  1363. }
  1364. // Coverage files appear next to their object files in the target
  1365. // support directory.
  1366. cmCTestOptionalLog(
  1367. this->CTest, HANDLER_VERBOSE_OUTPUT,
  1368. " globbing for coverage in: " << lm.first << std::endl, this->Quiet);
  1369. std::string daGlob = cmStrCat(lm.first, "/*.da");
  1370. gl.FindFiles(daGlob);
  1371. cm::append(files, gl.GetFiles());
  1372. daGlob = cmStrCat(lm.first, "/*.gcda");
  1373. gl.FindFiles(daGlob);
  1374. cm::append(files, gl.GetFiles());
  1375. }
  1376. }
  1377. bool cmCTestCoverageHandler::FindLCovFiles(std::vector<std::string>& files)
  1378. {
  1379. cmsys::Glob gl;
  1380. gl.RecurseOff(); // No need of recurse if -prof_dir${BUILD_DIR} flag is
  1381. // used while compiling.
  1382. gl.RecurseThroughSymlinksOff();
  1383. std::string buildDir = this->CTest->GetCTestConfiguration("BuildDirectory");
  1384. cmWorkingDirectory workdir(buildDir);
  1385. if (workdir.Failed()) {
  1386. cmCTestLog(this->CTest, ERROR_MESSAGE,
  1387. "Unable to change working directory to " << buildDir
  1388. << std::endl);
  1389. return false;
  1390. }
  1391. // Run profmerge to merge all *.dyn files into dpi files
  1392. if (!cmSystemTools::RunSingleCommand("profmerge")) {
  1393. cmCTestLog(this->CTest, ERROR_MESSAGE, "Error while running profmerge.\n");
  1394. return false;
  1395. }
  1396. // DPI file should appear in build directory
  1397. std::string daGlob;
  1398. daGlob = cmStrCat(buildDir, "/*.dpi");
  1399. cmCTestOptionalLog(this->CTest, HANDLER_VERBOSE_OUTPUT,
  1400. " looking for dpi files in: " << daGlob << std::endl,
  1401. this->Quiet);
  1402. if (!gl.FindFiles(daGlob)) {
  1403. cmCTestLog(this->CTest, ERROR_MESSAGE,
  1404. "Error while finding files matching " << daGlob << std::endl);
  1405. return false;
  1406. }
  1407. cm::append(files, gl.GetFiles());
  1408. cmCTestOptionalLog(this->CTest, HANDLER_VERBOSE_OUTPUT,
  1409. "Now searching in: " << daGlob << std::endl, this->Quiet);
  1410. return true;
  1411. }
  1412. int cmCTestCoverageHandler::HandleTracePyCoverage(
  1413. cmCTestCoverageHandlerContainer* cont)
  1414. {
  1415. cmsys::Glob gl;
  1416. gl.RecurseOn();
  1417. gl.RecurseThroughSymlinksOff();
  1418. std::string daGlob = cont->BinaryDir + "/*.cover";
  1419. gl.FindFiles(daGlob);
  1420. std::vector<std::string> files = gl.GetFiles();
  1421. if (files.empty()) {
  1422. cmCTestOptionalLog(this->CTest, HANDLER_VERBOSE_OUTPUT,
  1423. " Cannot find any Python Trace.py coverage files."
  1424. << std::endl,
  1425. this->Quiet);
  1426. // No coverage files is a valid thing, so the exit code is 0
  1427. return 0;
  1428. }
  1429. std::string testingDir = this->CTest->GetBinaryDir() + "/Testing";
  1430. std::string tempDir = testingDir + "/CoverageInfo";
  1431. cmSystemTools::MakeDirectory(tempDir);
  1432. int file_count = 0;
  1433. for (std::string const& file : files) {
  1434. std::string fileName = this->FindFile(cont, file);
  1435. if (fileName.empty()) {
  1436. cmCTestLog(this->CTest, ERROR_MESSAGE,
  1437. "Cannot find source Python file corresponding to: "
  1438. << file << std::endl);
  1439. continue;
  1440. }
  1441. std::string actualSourceFile = cmSystemTools::CollapseFullPath(fileName);
  1442. cmCTestOptionalLog(this->CTest, HANDLER_VERBOSE_OUTPUT,
  1443. " Check coverage for file: " << actualSourceFile
  1444. << std::endl,
  1445. this->Quiet);
  1446. cmCTestCoverageHandlerContainer::SingleFileCoverageVector* vec =
  1447. &cont->TotalCoverage[actualSourceFile];
  1448. cmCTestOptionalLog(this->CTest, HANDLER_VERBOSE_OUTPUT,
  1449. " in file: " << file << std::endl, this->Quiet);
  1450. cmsys::ifstream ifile(file.c_str());
  1451. if (!ifile) {
  1452. cmCTestLog(this->CTest, ERROR_MESSAGE,
  1453. "Cannot open file: " << file << std::endl);
  1454. } else {
  1455. long cnt = -1;
  1456. std::string nl;
  1457. while (cmSystemTools::GetLineFromStream(ifile, nl)) {
  1458. cnt++;
  1459. // Skip empty lines
  1460. if (nl.empty()) {
  1461. continue;
  1462. }
  1463. // Skip unused lines
  1464. if (nl.size() < 12) {
  1465. continue;
  1466. }
  1467. // Read the coverage count from the beginning of the Trace.py output
  1468. // line
  1469. std::string::size_type pos;
  1470. int cov = 0;
  1471. // This is a hack. We should really do something more elaborate
  1472. for (pos = 5; pos < 8; pos++) {
  1473. if (nl[pos] == ' ') {
  1474. // This line does not have ':' so no coverage here. That said,
  1475. // Trace.py does not handle not covered lines versus comments etc.
  1476. // So, this will be set to 0.
  1477. break;
  1478. }
  1479. if (nl[pos] == ':') {
  1480. cov = atoi(nl.substr(0, pos - 1).c_str());
  1481. break;
  1482. }
  1483. }
  1484. if (pos == 8) {
  1485. cmCTestLog(this->CTest, ERROR_MESSAGE,
  1486. "Currently the limit is maximum coverage of 999999"
  1487. << std::endl);
  1488. }
  1489. // Read the line number starting at the 10th character of the gcov
  1490. // output line
  1491. long lineIdx = cnt;
  1492. if (lineIdx >= 0) {
  1493. while (vec->size() <= static_cast<size_t>(lineIdx)) {
  1494. vec->push_back(-1);
  1495. }
  1496. // Initially all entries are -1 (not used). If we get coverage
  1497. // information, increment it to 0 first.
  1498. if ((*vec)[lineIdx] < 0) {
  1499. if (cov >= 0) {
  1500. (*vec)[lineIdx] = 0;
  1501. }
  1502. }
  1503. (*vec)[lineIdx] += cov;
  1504. }
  1505. }
  1506. }
  1507. ++file_count;
  1508. }
  1509. return file_count;
  1510. }
  1511. std::string cmCTestCoverageHandler::FindFile(
  1512. cmCTestCoverageHandlerContainer* cont, std::string const& fileName)
  1513. {
  1514. std::string fileNameNoE =
  1515. cmSystemTools::GetFilenameWithoutLastExtension(fileName);
  1516. // First check in source and binary directory
  1517. std::string fullName = cont->SourceDir + "/" + fileNameNoE + ".py";
  1518. if (cmSystemTools::FileExists(fullName)) {
  1519. return fullName;
  1520. }
  1521. fullName = cont->BinaryDir + "/" + fileNameNoE + ".py";
  1522. if (cmSystemTools::FileExists(fullName)) {
  1523. return fullName;
  1524. }
  1525. return "";
  1526. }
  1527. // This is a header put on each marked up source file
  1528. namespace {
  1529. const char* bullseyeHelp[] = {
  1530. " Coverage produced by bullseye covbr tool: ",
  1531. " www.bullseye.com/help/ref_covbr.html",
  1532. " * An arrow --> indicates incomplete coverage.",
  1533. " * An X indicates a function that was invoked, a switch label that ",
  1534. " was exercised, a try-block that finished, or an exception handler ",
  1535. " that was invoked.",
  1536. " * A T or F indicates a boolean decision that evaluated true or false,",
  1537. " respectively.",
  1538. " * A t or f indicates a boolean condition within a decision if the ",
  1539. " condition evaluated true or false, respectively.",
  1540. " * A k indicates a constant decision or condition.",
  1541. " * The slash / means this probe is excluded from summary results. ",
  1542. nullptr
  1543. };
  1544. }
  1545. int cmCTestCoverageHandler::RunBullseyeCoverageBranch(
  1546. cmCTestCoverageHandlerContainer* cont,
  1547. std::set<std::string>& coveredFileNames, std::vector<std::string>& files,
  1548. std::vector<std::string>& filesFullPath)
  1549. {
  1550. if (files.size() != filesFullPath.size()) {
  1551. cmCTestLog(this->CTest, ERROR_MESSAGE,
  1552. "Files and full path files not the same size?:\n");
  1553. return 0;
  1554. }
  1555. // create the output stream for the CoverageLog-N.xml file
  1556. cmGeneratedFileStream covLogFile;
  1557. cmXMLWriter covLogXML(covLogFile);
  1558. int logFileCount = 0;
  1559. if (!this->StartCoverageLogFile(covLogFile, logFileCount)) {
  1560. return -1;
  1561. }
  1562. this->StartCoverageLogXML(covLogXML);
  1563. // for each file run covbr on that file to get the coverage
  1564. // information for that file
  1565. std::string outputFile;
  1566. cmCTestOptionalLog(this->CTest, HANDLER_VERBOSE_OUTPUT,
  1567. "run covbr: " << std::endl, this->Quiet);
  1568. if (!this->RunBullseyeCommand(cont, "covbr", nullptr, outputFile)) {
  1569. cmCTestLog(this->CTest, ERROR_MESSAGE,
  1570. "error running covbr for."
  1571. << "\n");
  1572. return -1;
  1573. }
  1574. cmCTestOptionalLog(this->CTest, HANDLER_VERBOSE_OUTPUT,
  1575. "covbr output in " << outputFile << std::endl,
  1576. this->Quiet);
  1577. // open the output file
  1578. cmsys::ifstream fin(outputFile.c_str());
  1579. if (!fin) {
  1580. cmCTestLog(this->CTest, ERROR_MESSAGE,
  1581. "Cannot open coverage file: " << outputFile << std::endl);
  1582. return 0;
  1583. }
  1584. std::map<std::string, std::string> fileMap;
  1585. auto fp = filesFullPath.begin();
  1586. for (auto f = files.begin(); f != files.end(); ++f, ++fp) {
  1587. fileMap[*f] = *fp;
  1588. }
  1589. int count = 0; // keep count of the number of files
  1590. // Now parse each line from the bullseye cov log file
  1591. std::string lineIn;
  1592. bool valid = false; // are we in a valid output file
  1593. int line = 0; // line of the current file
  1594. std::string file;
  1595. while (cmSystemTools::GetLineFromStream(fin, lineIn)) {
  1596. bool startFile = false;
  1597. if (lineIn.size() > 1 && lineIn[lineIn.size() - 1] == ':') {
  1598. file = lineIn.substr(0, lineIn.size() - 1);
  1599. if (coveredFileNames.find(file) != coveredFileNames.end()) {
  1600. startFile = true;
  1601. }
  1602. }
  1603. if (startFile) {
  1604. // if we are in a valid file close it because a new one started
  1605. if (valid) {
  1606. covLogXML.EndElement(); // Report
  1607. covLogXML.EndElement(); // File
  1608. }
  1609. // only allow 100 files in each log file
  1610. if (count != 0 && count % 100 == 0) {
  1611. cmCTestOptionalLog(this->CTest, HANDLER_VERBOSE_OUTPUT,
  1612. "start a new log file: " << count << std::endl,
  1613. this->Quiet);
  1614. this->EndCoverageLogXML(covLogXML);
  1615. this->EndCoverageLogFile(covLogFile, logFileCount);
  1616. logFileCount++;
  1617. if (!this->StartCoverageLogFile(covLogFile, logFileCount)) {
  1618. return -1;
  1619. }
  1620. this->StartCoverageLogXML(covLogXML);
  1621. count++; // move on one
  1622. }
  1623. auto i = fileMap.find(file);
  1624. // if the file should be covered write out the header for that file
  1625. if (i != fileMap.end()) {
  1626. // we have a new file so count it in the output
  1627. count++;
  1628. cmCTestOptionalLog(this->CTest, HANDLER_VERBOSE_OUTPUT,
  1629. "Produce coverage for file: " << file << " "
  1630. << count << std::endl,
  1631. this->Quiet);
  1632. // start the file output
  1633. covLogXML.StartElement("File");
  1634. covLogXML.Attribute("Name", i->first);
  1635. covLogXML.Attribute("FullPath",
  1636. this->CTest->GetShortPathToFile(i->second));
  1637. covLogXML.StartElement("Report");
  1638. // write the bullseye header
  1639. line = 0;
  1640. for (int k = 0; bullseyeHelp[k] != nullptr; ++k) {
  1641. covLogXML.StartElement("Line");
  1642. covLogXML.Attribute("Number", line);
  1643. covLogXML.Attribute("Count", -1);
  1644. covLogXML.Content(bullseyeHelp[k]);
  1645. covLogXML.EndElement(); // Line
  1646. line++;
  1647. }
  1648. valid = true; // we are in a valid file section
  1649. } else {
  1650. // this is not a file that we want coverage for
  1651. valid = false;
  1652. }
  1653. }
  1654. // we are not at a start file, and we are in a valid file output the line
  1655. else if (valid) {
  1656. covLogXML.StartElement("Line");
  1657. covLogXML.Attribute("Number", line);
  1658. covLogXML.Attribute("Count", -1);
  1659. covLogXML.Content(lineIn);
  1660. covLogXML.EndElement(); // Line
  1661. line++;
  1662. }
  1663. }
  1664. // if we ran out of lines a valid file then close that file
  1665. if (valid) {
  1666. covLogXML.EndElement(); // Report
  1667. covLogXML.EndElement(); // File
  1668. }
  1669. this->EndCoverageLogXML(covLogXML);
  1670. this->EndCoverageLogFile(covLogFile, logFileCount);
  1671. return 1;
  1672. }
  1673. int cmCTestCoverageHandler::RunBullseyeCommand(
  1674. cmCTestCoverageHandlerContainer* cont, const char* cmd, const char* arg,
  1675. std::string& outputFile)
  1676. {
  1677. std::string program = cmSystemTools::FindProgram(cmd);
  1678. if (program.empty()) {
  1679. cmCTestLog(this->CTest, ERROR_MESSAGE, "Cannot find :" << cmd << "\n");
  1680. return 0;
  1681. }
  1682. std::vector<std::string> args{ cmd };
  1683. if (arg) {
  1684. cmCTestOptionalLog(this->CTest, HANDLER_VERBOSE_OUTPUT,
  1685. "Run : " << program << " " << arg << "\n", this->Quiet);
  1686. args.emplace_back(arg);
  1687. } else {
  1688. cmCTestOptionalLog(this->CTest, HANDLER_VERBOSE_OUTPUT,
  1689. "Run : " << program << "\n", this->Quiet);
  1690. }
  1691. // create a process object and start it
  1692. cmUVProcessChainBuilder builder;
  1693. std::string stdoutFile =
  1694. cmStrCat(cont->BinaryDir, "/Testing/Temporary/",
  1695. this->GetCTestInstance()->GetCurrentTag(), '-', cmd);
  1696. std::string stderrFile = stdoutFile;
  1697. stdoutFile += ".stdout";
  1698. stderrFile += ".stderr";
  1699. std::unique_ptr<FILE, int (*)(FILE*)> stdoutHandle(
  1700. cmsys::SystemTools::Fopen(stdoutFile, "w"), fclose);
  1701. std::unique_ptr<FILE, int (*)(FILE*)> stderrHandle(
  1702. cmsys::SystemTools::Fopen(stderrFile, "w"), fclose);
  1703. builder.AddCommand(args)
  1704. .SetExternalStream(cmUVProcessChainBuilder::Stream_OUTPUT,
  1705. stdoutHandle.get())
  1706. .SetExternalStream(cmUVProcessChainBuilder::Stream_ERROR,
  1707. stderrHandle.get());
  1708. // since we set the output file names wait for it to end
  1709. auto chain = builder.Start();
  1710. chain.Wait();
  1711. outputFile = stdoutFile;
  1712. return 1;
  1713. }
  1714. int cmCTestCoverageHandler::RunBullseyeSourceSummary(
  1715. cmCTestCoverageHandlerContainer* cont)
  1716. {
  1717. // Run the covsrc command and create a temp outputfile
  1718. std::string outputFile;
  1719. if (!this->RunBullseyeCommand(cont, "covsrc", "-c", outputFile)) {
  1720. cmCTestLog(this->CTest, ERROR_MESSAGE, "error running covsrc:\n");
  1721. return 0;
  1722. }
  1723. std::ostream& tmpLog = *cont->OFS;
  1724. // copen the Coverage.xml file in the Testing directory
  1725. cmGeneratedFileStream covSumFile;
  1726. cmXMLWriter xml(covSumFile);
  1727. if (!this->StartResultingXML(cmCTest::PartCoverage, "Coverage",
  1728. covSumFile)) {
  1729. cmCTestLog(this->CTest, ERROR_MESSAGE,
  1730. "Cannot open coverage summary file." << std::endl);
  1731. return 0;
  1732. }
  1733. this->CTest->StartXML(xml, this->AppendXML);
  1734. auto elapsed_time_start = std::chrono::steady_clock::now();
  1735. std::string coverage_start_time = this->CTest->CurrentTime();
  1736. xml.StartElement("Coverage");
  1737. xml.Element("StartDateTime", coverage_start_time);
  1738. xml.Element("StartTime", std::chrono::system_clock::now());
  1739. std::string stdline;
  1740. std::string errline;
  1741. // expected output:
  1742. // first line is:
  1743. // "Source","Function Coverage","out of","%","C/D Coverage","out of","%"
  1744. // after that data follows in that format
  1745. std::string sourceFile;
  1746. int functionsCalled = 0;
  1747. int totalFunctions = 0;
  1748. int percentFunction = 0;
  1749. int branchCovered = 0;
  1750. int totalBranches = 0;
  1751. int percentBranch = 0;
  1752. double total_tested = 0;
  1753. double total_untested = 0;
  1754. double total_functions = 0;
  1755. double percent_coverage = 0;
  1756. double number_files = 0;
  1757. std::vector<std::string> coveredFiles;
  1758. std::vector<std::string> coveredFilesFullPath;
  1759. // Read and parse the summary output file
  1760. cmsys::ifstream fin(outputFile.c_str());
  1761. if (!fin) {
  1762. cmCTestLog(this->CTest, ERROR_MESSAGE,
  1763. "Cannot open coverage summary file: " << outputFile
  1764. << std::endl);
  1765. return 0;
  1766. }
  1767. std::set<std::string> coveredFileNames;
  1768. while (cmSystemTools::GetLineFromStream(fin, stdline)) {
  1769. // if we have a line of output from stdout
  1770. if (!stdline.empty()) {
  1771. // parse the comma separated output
  1772. this->ParseBullsEyeCovsrcLine(
  1773. stdline, sourceFile, functionsCalled, totalFunctions, percentFunction,
  1774. branchCovered, totalBranches, percentBranch);
  1775. // The first line is the header
  1776. if (sourceFile == "Source" || sourceFile == "Total") {
  1777. continue;
  1778. }
  1779. std::string file = sourceFile;
  1780. coveredFileNames.insert(file);
  1781. if (!cmSystemTools::FileIsFullPath(sourceFile)) {
  1782. // file will be relative to the binary dir
  1783. file = cmStrCat(cont->BinaryDir, '/', sourceFile);
  1784. }
  1785. file = cmSystemTools::CollapseFullPath(file);
  1786. bool shouldIDoCoverage =
  1787. this->ShouldIDoCoverage(file, cont->SourceDir, cont->BinaryDir);
  1788. if (!shouldIDoCoverage) {
  1789. cmCTestOptionalLog(
  1790. this->CTest, HANDLER_VERBOSE_OUTPUT,
  1791. ".NoDartCoverage found, so skip coverage check for: " << file
  1792. << std::endl,
  1793. this->Quiet);
  1794. continue;
  1795. }
  1796. cmCTestOptionalLog(this->CTest, HANDLER_VERBOSE_OUTPUT,
  1797. "Doing coverage for: " << file << std::endl,
  1798. this->Quiet);
  1799. coveredFiles.push_back(sourceFile);
  1800. coveredFilesFullPath.push_back(file);
  1801. number_files++;
  1802. total_functions += totalFunctions;
  1803. total_tested += functionsCalled;
  1804. total_untested += (totalFunctions - functionsCalled);
  1805. std::string fileName = cmSystemTools::GetFilenameName(file);
  1806. std::string shortFileName = this->CTest->GetShortPathToFile(file);
  1807. float cper = static_cast<float>(percentBranch + percentFunction);
  1808. if (totalBranches > 0) {
  1809. cper /= 2.0f;
  1810. }
  1811. percent_coverage += static_cast<double>(cper);
  1812. float cmet = static_cast<float>(percentFunction + percentBranch);
  1813. if (totalBranches > 0) {
  1814. cmet /= 2.0f;
  1815. }
  1816. cmet /= 100.0f;
  1817. tmpLog << stdline << "\n";
  1818. tmpLog << fileName << "\n";
  1819. tmpLog << "functionsCalled: " << functionsCalled / 100 << "\n";
  1820. tmpLog << "totalFunctions: " << totalFunctions / 100 << "\n";
  1821. tmpLog << "percentFunction: " << percentFunction << "\n";
  1822. tmpLog << "branchCovered: " << branchCovered << "\n";
  1823. tmpLog << "totalBranches: " << totalBranches << "\n";
  1824. tmpLog << "percentBranch: " << percentBranch << "\n";
  1825. tmpLog << "percentCoverage: " << percent_coverage << "\n";
  1826. tmpLog << "coverage metric: " << cmet << "\n";
  1827. xml.StartElement("File");
  1828. xml.Attribute("Name", sourceFile);
  1829. xml.Attribute("FullPath", shortFileName);
  1830. xml.Attribute("Covered", cmet > 0 ? "true" : "false");
  1831. xml.Element("BranchesTested", branchCovered);
  1832. xml.Element("BranchesUnTested", totalBranches - branchCovered);
  1833. xml.Element("FunctionsTested", functionsCalled);
  1834. xml.Element("FunctionsUnTested", totalFunctions - functionsCalled);
  1835. // Hack for conversion of function to loc assume a function
  1836. // has 100 lines of code
  1837. xml.Element("LOCTested", functionsCalled * 100);
  1838. xml.Element("LOCUnTested", (totalFunctions - functionsCalled) * 100);
  1839. xml.Element("PercentCoverage", cper);
  1840. xml.Element("CoverageMetric", cmet);
  1841. this->WriteXMLLabels(xml, shortFileName);
  1842. xml.EndElement(); // File
  1843. }
  1844. }
  1845. std::string end_time = this->CTest->CurrentTime();
  1846. xml.Element("LOCTested", total_tested);
  1847. xml.Element("LOCUntested", total_untested);
  1848. xml.Element("LOC", total_functions);
  1849. xml.Element("PercentCoverage", SAFEDIV(percent_coverage, number_files));
  1850. xml.Element("EndDateTime", end_time);
  1851. xml.Element("EndTime", std::chrono::system_clock::now());
  1852. xml.Element("ElapsedMinutes",
  1853. std::chrono::duration_cast<std::chrono::minutes>(
  1854. std::chrono::steady_clock::now() - elapsed_time_start)
  1855. .count());
  1856. xml.EndElement(); // Coverage
  1857. this->CTest->EndXML(xml);
  1858. // Now create the coverage information for each file
  1859. return this->RunBullseyeCoverageBranch(cont, coveredFileNames, coveredFiles,
  1860. coveredFilesFullPath);
  1861. }
  1862. int cmCTestCoverageHandler::HandleBullseyeCoverage(
  1863. cmCTestCoverageHandlerContainer* cont)
  1864. {
  1865. std::string covfile;
  1866. if (!cmSystemTools::GetEnv("COVFILE", covfile) || covfile.empty()) {
  1867. cmCTestOptionalLog(this->CTest, HANDLER_VERBOSE_OUTPUT,
  1868. " COVFILE environment variable not found, not running "
  1869. " bullseye\n",
  1870. this->Quiet);
  1871. return 0;
  1872. }
  1873. cmCTestOptionalLog(
  1874. this->CTest, HANDLER_VERBOSE_OUTPUT,
  1875. " run covsrc with COVFILE=[" << covfile << "]" << std::endl, this->Quiet);
  1876. if (!this->RunBullseyeSourceSummary(cont)) {
  1877. cmCTestLog(this->CTest, ERROR_MESSAGE,
  1878. "Error running bullseye summary.\n");
  1879. return 0;
  1880. }
  1881. cmCTestOptionalLog(this->CTest, DEBUG,
  1882. "HandleBullseyeCoverage return 1 " << std::endl,
  1883. this->Quiet);
  1884. return 1;
  1885. }
  1886. bool cmCTestCoverageHandler::GetNextInt(std::string const& inputLine,
  1887. std::string::size_type& pos,
  1888. int& value)
  1889. {
  1890. std::string::size_type start = pos;
  1891. pos = inputLine.find(',', start);
  1892. value = atoi(inputLine.substr(start, pos).c_str());
  1893. if (pos == std::string::npos) {
  1894. return true;
  1895. }
  1896. pos++;
  1897. return true;
  1898. }
  1899. bool cmCTestCoverageHandler::ParseBullsEyeCovsrcLine(
  1900. std::string const& inputLine, std::string& sourceFile, int& functionsCalled,
  1901. int& totalFunctions, int& percentFunction, int& branchCovered,
  1902. int& totalBranches, int& percentBranch)
  1903. {
  1904. // find the first comma
  1905. std::string::size_type pos = inputLine.find(',');
  1906. if (pos == std::string::npos) {
  1907. cmCTestLog(this->CTest, ERROR_MESSAGE,
  1908. "Error parsing string : " << inputLine << "\n");
  1909. return false;
  1910. }
  1911. // the source file has "" around it so extract out the file name
  1912. sourceFile = inputLine.substr(1, pos - 2);
  1913. pos++;
  1914. if (!this->GetNextInt(inputLine, pos, functionsCalled)) {
  1915. return false;
  1916. }
  1917. if (!this->GetNextInt(inputLine, pos, totalFunctions)) {
  1918. return false;
  1919. }
  1920. if (!this->GetNextInt(inputLine, pos, percentFunction)) {
  1921. return false;
  1922. }
  1923. if (!this->GetNextInt(inputLine, pos, branchCovered)) {
  1924. return false;
  1925. }
  1926. if (!this->GetNextInt(inputLine, pos, totalBranches)) {
  1927. return false;
  1928. }
  1929. if (!this->GetNextInt(inputLine, pos, percentBranch)) {
  1930. return false;
  1931. }
  1932. // should be at the end now
  1933. if (pos != std::string::npos) {
  1934. cmCTestLog(this->CTest, ERROR_MESSAGE,
  1935. "Error parsing input : "
  1936. << inputLine << " last pos not npos = " << pos << "\n");
  1937. }
  1938. return true;
  1939. }
  1940. int cmCTestCoverageHandler::GetLabelId(std::string const& label)
  1941. {
  1942. auto i = this->LabelIdMap.find(label);
  1943. if (i == this->LabelIdMap.end()) {
  1944. int n = static_cast<int>(this->Labels.size());
  1945. this->Labels.push_back(label);
  1946. LabelIdMapType::value_type entry(label, n);
  1947. i = this->LabelIdMap.insert(entry).first;
  1948. }
  1949. return i->second;
  1950. }
  1951. void cmCTestCoverageHandler::LoadLabels()
  1952. {
  1953. std::string fileList =
  1954. cmStrCat(this->CTest->GetBinaryDir(), "/CMakeFiles/TargetDirectories.txt");
  1955. cmCTestOptionalLog(this->CTest, HANDLER_VERBOSE_OUTPUT,
  1956. " target directory list [" << fileList << "]\n",
  1957. this->Quiet);
  1958. cmsys::ifstream finList(fileList.c_str());
  1959. std::string line;
  1960. while (cmSystemTools::GetLineFromStream(finList, line)) {
  1961. this->LoadLabels(line.c_str());
  1962. }
  1963. }
  1964. void cmCTestCoverageHandler::LoadLabels(const char* dir)
  1965. {
  1966. LabelSet& dirLabels = this->TargetDirs[dir];
  1967. std::string fname = cmStrCat(dir, "/Labels.txt");
  1968. cmsys::ifstream fin(fname.c_str());
  1969. if (!fin) {
  1970. return;
  1971. }
  1972. cmCTestOptionalLog(this->CTest, HANDLER_VERBOSE_OUTPUT,
  1973. " loading labels from [" << fname << "]\n", this->Quiet);
  1974. bool inTarget = true;
  1975. std::string source;
  1976. std::string line;
  1977. std::vector<int> targetLabels;
  1978. while (cmSystemTools::GetLineFromStream(fin, line)) {
  1979. if (line.empty() || line[0] == '#') {
  1980. // Ignore blank and comment lines.
  1981. continue;
  1982. }
  1983. if (line[0] == ' ') {
  1984. // Label lines appear indented by one space.
  1985. std::string label = line.substr(1);
  1986. int id = this->GetLabelId(label);
  1987. dirLabels.insert(id);
  1988. if (inTarget) {
  1989. targetLabels.push_back(id);
  1990. } else {
  1991. this->SourceLabels[source].insert(id);
  1992. }
  1993. } else {
  1994. // Non-indented lines specify a source file name. The first one
  1995. // is the end of the target-wide labels.
  1996. inTarget = false;
  1997. source = this->CTest->GetShortPathToFile(line);
  1998. // Label the source with the target labels.
  1999. LabelSet& labelSet = this->SourceLabels[source];
  2000. labelSet.insert(targetLabels.begin(), targetLabels.end());
  2001. }
  2002. }
  2003. }
  2004. void cmCTestCoverageHandler::WriteXMLLabels(cmXMLWriter& xml,
  2005. std::string const& source)
  2006. {
  2007. auto li = this->SourceLabels.find(source);
  2008. if (li != this->SourceLabels.end() && !li->second.empty()) {
  2009. xml.StartElement("Labels");
  2010. for (auto const& ls : li->second) {
  2011. xml.Element("Label", this->Labels[ls]);
  2012. }
  2013. xml.EndElement(); // Labels
  2014. }
  2015. }
  2016. void cmCTestCoverageHandler::SetLabelFilter(
  2017. std::set<std::string> const& labels)
  2018. {
  2019. this->LabelFilter.clear();
  2020. for (std::string const& l : labels) {
  2021. this->LabelFilter.insert(this->GetLabelId(l));
  2022. }
  2023. }
  2024. bool cmCTestCoverageHandler::IntersectsFilter(LabelSet const& labels)
  2025. {
  2026. // If there is no label filter then nothing is filtered out.
  2027. if (this->LabelFilter.empty()) {
  2028. return true;
  2029. }
  2030. std::vector<int> ids;
  2031. std::set_intersection(labels.begin(), labels.end(),
  2032. this->LabelFilter.begin(), this->LabelFilter.end(),
  2033. std::back_inserter(ids));
  2034. return !ids.empty();
  2035. }
  2036. bool cmCTestCoverageHandler::IsFilteredOut(std::string const& source)
  2037. {
  2038. // If there is no label filter then nothing is filtered out.
  2039. if (this->LabelFilter.empty()) {
  2040. return false;
  2041. }
  2042. // The source is filtered out if it does not have any labels in
  2043. // common with the filter set.
  2044. std::string shortSrc = this->CTest->GetShortPathToFile(source);
  2045. auto li = this->SourceLabels.find(shortSrc);
  2046. if (li != this->SourceLabels.end()) {
  2047. return !this->IntersectsFilter(li->second);
  2048. }
  2049. return true;
  2050. }
  2051. std::set<std::string> cmCTestCoverageHandler::FindUncoveredFiles(
  2052. cmCTestCoverageHandlerContainer* cont)
  2053. {
  2054. std::set<std::string> extraMatches;
  2055. for (std::string const& ecg : this->ExtraCoverageGlobs) {
  2056. cmsys::Glob gl;
  2057. gl.RecurseOn();
  2058. gl.RecurseThroughSymlinksOff();
  2059. std::string glob = cont->SourceDir + "/" + ecg;
  2060. gl.FindFiles(glob);
  2061. std::vector<std::string> files = gl.GetFiles();
  2062. for (std::string const& f : files) {
  2063. if (this->ShouldIDoCoverage(f, cont->SourceDir, cont->BinaryDir)) {
  2064. extraMatches.insert(this->CTest->GetShortPathToFile(f));
  2065. }
  2066. }
  2067. }
  2068. if (!extraMatches.empty()) {
  2069. for (auto const& i : cont->TotalCoverage) {
  2070. std::string shortPath = this->CTest->GetShortPathToFile(i.first);
  2071. extraMatches.erase(shortPath);
  2072. }
  2073. }
  2074. return extraMatches;
  2075. }