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