cmCTestCoverageHandler.cxx 81 KB

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