cmCTestCoverageHandler.cxx 81 KB

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