cmCTestCoverageHandler.cxx 81 KB

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