cmCTestCoverageHandler.cxx 81 KB

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