cmCTestCoverageHandler.cxx 82 KB

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