cmCTestCoverageHandler.cxx 81 KB

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