cmCTestCoverageHandler.cxx 80 KB

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