cmCTestCoverageHandler.cxx 82 KB

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