cmCTestCoverageHandler.cxx 81 KB

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