cmCTestCoverageHandler.cxx 81 KB

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