cmCTestCoverageHandler.cxx 80 KB

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