cmCTestCoverageHandler.cxx 81 KB

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