cmCTestCoverageHandler.cxx 81 KB

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