cmCTestCoverageHandler.cxx 80 KB

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