cmCTestCoverageHandler.cxx 81 KB

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