cmCTestCoverageHandler.cxx 81 KB

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