cmCTestCoverageHandler.cxx 81 KB

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