cmCTestCoverageHandler.cxx 61 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908
  1. /*=========================================================================
  2. Program: CMake - Cross-Platform Makefile Generator
  3. Module: $RCSfile$
  4. Language: C++
  5. Date: $Date$
  6. Version: $Revision$
  7. Copyright (c) 2002 Kitware, Inc., Insight Consortium. All rights reserved.
  8. See Copyright.txt or http://www.cmake.org/HTML/Copyright.html for details.
  9. This software is distributed WITHOUT ANY WARRANTY; without even
  10. the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
  11. PURPOSE. See the above copyright notices for more information.
  12. =========================================================================*/
  13. #include "cmCTestCoverageHandler.h"
  14. #include "cmCTest.h"
  15. #include "cmake.h"
  16. #include "cmMakefile.h"
  17. #include "cmSystemTools.h"
  18. #include "cmGeneratedFileStream.h"
  19. #include "cmXMLSafe.h"
  20. #include <cmsys/Process.h>
  21. #include <cmsys/RegularExpression.hxx>
  22. #include <cmsys/Glob.hxx>
  23. #include <cmsys/stl/iterator>
  24. #include <cmsys/stl/algorithm>
  25. #include <stdlib.h>
  26. #include <math.h>
  27. #include <float.h>
  28. #define SAFEDIV(x,y) (((y)!=0)?((x)/(y)):(0))
  29. class cmCTestRunProcess
  30. {
  31. public:
  32. cmCTestRunProcess()
  33. {
  34. this->Process = cmsysProcess_New();
  35. this->PipeState = -1;
  36. this->TimeOut = -1;
  37. }
  38. ~cmCTestRunProcess()
  39. {
  40. if(!(this->PipeState == -1)
  41. && !(this->PipeState == cmsysProcess_Pipe_None )
  42. && !(this->PipeState == cmsysProcess_Pipe_Timeout))
  43. {
  44. this->WaitForExit();
  45. }
  46. cmsysProcess_Delete(this->Process);
  47. }
  48. void SetCommand(const char* command)
  49. {
  50. this->CommandLineStrings.clear();
  51. this->CommandLineStrings.push_back(command);;
  52. }
  53. void AddArgument(const char* arg)
  54. {
  55. if(arg)
  56. {
  57. this->CommandLineStrings.push_back(arg);
  58. }
  59. }
  60. void SetWorkingDirectory(const char* dir)
  61. {
  62. this->WorkingDirectory = dir;
  63. }
  64. void SetTimeout(double t)
  65. {
  66. this->TimeOut = t;
  67. }
  68. bool StartProcess()
  69. {
  70. std::vector<const char*> args;
  71. for(std::vector<std::string>::iterator i =
  72. this->CommandLineStrings.begin();
  73. i != this->CommandLineStrings.end(); ++i)
  74. {
  75. args.push_back(i->c_str());
  76. }
  77. args.push_back(0); // null terminate
  78. cmsysProcess_SetCommand(this->Process, &*args.begin());
  79. if(this->WorkingDirectory.size())
  80. {
  81. cmsysProcess_SetWorkingDirectory(this->Process,
  82. this->WorkingDirectory.c_str());
  83. }
  84. cmsysProcess_SetOption(this->Process,
  85. cmsysProcess_Option_HideWindow, 1);
  86. if(this->TimeOut != -1)
  87. {
  88. cmsysProcess_SetTimeout(this->Process, this->TimeOut);
  89. }
  90. cmsysProcess_Execute(this->Process);
  91. this->PipeState = cmsysProcess_GetState(this->Process);
  92. // if the process is running or exited return true
  93. if(this->PipeState == cmsysProcess_State_Executing
  94. || this->PipeState == cmsysProcess_State_Exited)
  95. {
  96. return true;
  97. }
  98. return false;
  99. }
  100. void SetStdoutFile(const char* fname)
  101. {
  102. cmsysProcess_SetPipeFile(this->Process, cmsysProcess_Pipe_STDOUT, fname);
  103. }
  104. void SetStderrFile(const char* fname)
  105. {
  106. cmsysProcess_SetPipeFile(this->Process, cmsysProcess_Pipe_STDERR, fname);
  107. }
  108. int WaitForExit(double* timeout =0)
  109. {
  110. this->PipeState = cmsysProcess_WaitForExit(this->Process,
  111. timeout);
  112. return this->PipeState;
  113. }
  114. int GetProcessState() { return this->PipeState;}
  115. private:
  116. int PipeState;
  117. cmsysProcess* Process;
  118. std::vector<std::string> CommandLineStrings;
  119. std::string WorkingDirectory;
  120. double TimeOut;
  121. };
  122. //----------------------------------------------------------------------
  123. //**********************************************************************
  124. class cmCTestCoverageHandlerContainer
  125. {
  126. public:
  127. int Error;
  128. std::string SourceDir;
  129. std::string BinaryDir;
  130. typedef std::vector<int> SingleFileCoverageVector;
  131. typedef std::map<std::string, SingleFileCoverageVector> TotalCoverageMap;
  132. TotalCoverageMap TotalCoverage;
  133. std::ostream* OFS;
  134. };
  135. //**********************************************************************
  136. //----------------------------------------------------------------------
  137. //----------------------------------------------------------------------
  138. cmCTestCoverageHandler::cmCTestCoverageHandler()
  139. {
  140. }
  141. //----------------------------------------------------------------------
  142. void cmCTestCoverageHandler::Initialize()
  143. {
  144. this->Superclass::Initialize();
  145. this->CustomCoverageExclude.clear();
  146. this->SourceLabels.clear();
  147. this->LabelIdMap.clear();
  148. this->Labels.clear();
  149. this->LabelFilter.clear();
  150. }
  151. //----------------------------------------------------------------------
  152. bool cmCTestCoverageHandler::StartCoverageLogFile(
  153. cmGeneratedFileStream& covLogFile, int logFileCount)
  154. {
  155. char covLogFilename[1024];
  156. sprintf(covLogFilename, "CoverageLog-%d", logFileCount);
  157. cmCTestLog(this->CTest, HANDLER_VERBOSE_OUTPUT, "Open file: "
  158. << covLogFilename << std::endl);
  159. if(!this->StartResultingXML(cmCTest::PartCoverage,
  160. covLogFilename, covLogFile))
  161. {
  162. cmCTestLog(this->CTest, ERROR_MESSAGE, "Cannot open log file: "
  163. << covLogFilename << std::endl);
  164. return false;
  165. }
  166. std::string local_start_time = this->CTest->CurrentTime();
  167. this->CTest->StartXML(covLogFile, this->AppendXML);
  168. covLogFile << "<CoverageLog>" << std::endl
  169. << "\t<StartDateTime>" << local_start_time << "</StartDateTime>"
  170. << "\t<StartTime>"
  171. << static_cast<unsigned int>(cmSystemTools::GetTime())
  172. << "</StartTime>"
  173. << std::endl;
  174. return true;
  175. }
  176. //----------------------------------------------------------------------
  177. void cmCTestCoverageHandler::EndCoverageLogFile(cmGeneratedFileStream& ostr,
  178. int logFileCount)
  179. {
  180. std::string local_end_time = this->CTest->CurrentTime();
  181. ostr << "\t<EndDateTime>" << local_end_time << "</EndDateTime>" << std::endl
  182. << "\t<EndTime>" <<
  183. static_cast<unsigned int>(cmSystemTools::GetTime())
  184. << "</EndTime>" << std::endl
  185. << "</CoverageLog>" << std::endl;
  186. this->CTest->EndXML(ostr);
  187. char covLogFilename[1024];
  188. sprintf(covLogFilename, "CoverageLog-%d.xml", logFileCount);
  189. cmCTestLog(this->CTest, HANDLER_VERBOSE_OUTPUT, "Close file: "
  190. << covLogFilename << std::endl);
  191. ostr.Close();
  192. }
  193. //----------------------------------------------------------------------
  194. bool cmCTestCoverageHandler::ShouldIDoCoverage(const char* file,
  195. const char* srcDir,
  196. const char* binDir)
  197. {
  198. if(this->IsFilteredOut(file))
  199. {
  200. return false;
  201. }
  202. std::vector<cmsys::RegularExpression>::iterator sit;
  203. for ( sit = this->CustomCoverageExcludeRegex.begin();
  204. sit != this->CustomCoverageExcludeRegex.end(); ++ sit )
  205. {
  206. if ( sit->find(file) )
  207. {
  208. cmCTestLog(this->CTest, HANDLER_VERBOSE_OUTPUT, " File " << file
  209. << " is excluded in CTestCustom.ctest" << std::endl;);
  210. return false;
  211. }
  212. }
  213. std::string fSrcDir = cmSystemTools::CollapseFullPath(srcDir);
  214. std::string fBinDir = cmSystemTools::CollapseFullPath(binDir);
  215. std::string fFile = cmSystemTools::CollapseFullPath(file);
  216. bool sourceSubDir = cmSystemTools::IsSubDirectory(fFile.c_str(),
  217. fSrcDir.c_str());
  218. bool buildSubDir = cmSystemTools::IsSubDirectory(fFile.c_str(),
  219. fBinDir.c_str());
  220. // Always check parent directory of the file.
  221. std::string fileDir = cmSystemTools::GetFilenamePath(fFile.c_str());
  222. std::string checkDir;
  223. // We also need to check the binary/source directory pair.
  224. if ( sourceSubDir && buildSubDir )
  225. {
  226. if ( fSrcDir.size() > fBinDir.size() )
  227. {
  228. checkDir = fSrcDir;
  229. }
  230. else
  231. {
  232. checkDir = fBinDir;
  233. }
  234. }
  235. else if ( sourceSubDir )
  236. {
  237. checkDir = fSrcDir;
  238. }
  239. else if ( buildSubDir )
  240. {
  241. checkDir = fBinDir;
  242. }
  243. std::string ndc
  244. = cmSystemTools::FileExistsInParentDirectories(".NoDartCoverage",
  245. fFile.c_str(), checkDir.c_str());
  246. if ( ndc.size() )
  247. {
  248. cmCTestLog(this->CTest, HANDLER_VERBOSE_OUTPUT, "Found: " << ndc.c_str()
  249. << " so skip coverage of " << file << std::endl);
  250. return false;
  251. }
  252. // By now checkDir should be set to parent directory of the file.
  253. // Get the relative path to the file an apply it to the opposite directory.
  254. // If it is the same as fileDir, then ignore, otherwise check.
  255. std::string relPath;
  256. if(checkDir.size() )
  257. {
  258. relPath = cmSystemTools::RelativePath(checkDir.c_str(),
  259. fFile.c_str());
  260. }
  261. else
  262. {
  263. relPath = fFile;
  264. }
  265. if ( checkDir == fSrcDir )
  266. {
  267. checkDir = fBinDir;
  268. }
  269. else
  270. {
  271. checkDir = fSrcDir;
  272. }
  273. fFile = checkDir + "/" + relPath;
  274. fFile = cmSystemTools::GetFilenamePath(fFile.c_str());
  275. if ( fileDir == fFile )
  276. {
  277. // This is in-source build, so we trust the previous check.
  278. return true;
  279. }
  280. ndc = cmSystemTools::FileExistsInParentDirectories(".NoDartCoverage",
  281. fFile.c_str(), checkDir.c_str());
  282. if ( ndc.size() )
  283. {
  284. cmCTestLog(this->CTest, HANDLER_VERBOSE_OUTPUT, "Found: " << ndc.c_str()
  285. << " so skip coverage of: " << file << std::endl);
  286. return false;
  287. }
  288. // Ok, nothing in source tree, nothing in binary tree
  289. return true;
  290. }
  291. //----------------------------------------------------------------------
  292. //clearly it would be nice if this were broken up into a few smaller
  293. //functions and commented...
  294. int cmCTestCoverageHandler::ProcessHandler()
  295. {
  296. int error = 0;
  297. // do we have time for this
  298. if (this->CTest->GetRemainingTimeAllowed() < 120)
  299. {
  300. return error;
  301. }
  302. std::string coverage_start_time = this->CTest->CurrentTime();
  303. unsigned int coverage_start_time_time = static_cast<unsigned int>(
  304. cmSystemTools::GetTime());
  305. std::string sourceDir
  306. = this->CTest->GetCTestConfiguration("SourceDirectory");
  307. std::string binaryDir
  308. = this->CTest->GetCTestConfiguration("BuildDirectory");
  309. this->LoadLabels();
  310. cmGeneratedFileStream ofs;
  311. double elapsed_time_start = cmSystemTools::GetTime();
  312. if ( !this->StartLogFile("Coverage", ofs) )
  313. {
  314. cmCTestLog(this->CTest, ERROR_MESSAGE,
  315. "Cannot create LastCoverage.log file" << std::endl);
  316. }
  317. ofs << "Performing coverage: " << elapsed_time_start << std::endl;
  318. cmSystemTools::ConvertToUnixSlashes(sourceDir);
  319. cmSystemTools::ConvertToUnixSlashes(binaryDir);
  320. std::string asfGlob = sourceDir + "/*";
  321. std::string abfGlob = binaryDir + "/*";
  322. cmCTestLog(this->CTest, HANDLER_OUTPUT, "Performing coverage" << std::endl);
  323. cmCTestCoverageHandlerContainer cont;
  324. cont.Error = error;
  325. cont.SourceDir = sourceDir;
  326. cont.BinaryDir = binaryDir;
  327. cont.OFS = &ofs;
  328. // setup the regex exclude stuff
  329. this->CustomCoverageExcludeRegex.clear();
  330. std::vector<cmStdString>::iterator rexIt;
  331. for ( rexIt = this->CustomCoverageExclude.begin();
  332. rexIt != this->CustomCoverageExclude.end();
  333. ++ rexIt )
  334. {
  335. this->CustomCoverageExcludeRegex.push_back(
  336. cmsys::RegularExpression(rexIt->c_str()));
  337. }
  338. if(this->HandleBullseyeCoverage(&cont))
  339. {
  340. return cont.Error;
  341. }
  342. int file_count = 0;
  343. file_count += this->HandleGCovCoverage(&cont);
  344. if ( file_count < 0 )
  345. {
  346. return error;
  347. }
  348. file_count += this->HandleTracePyCoverage(&cont);
  349. if ( file_count < 0 )
  350. {
  351. return error;
  352. }
  353. error = cont.Error;
  354. if ( file_count == 0 )
  355. {
  356. cmCTestLog(this->CTest, WARNING,
  357. " Cannot find any coverage files. Ignoring Coverage request."
  358. << std::endl);
  359. return error;
  360. }
  361. cmGeneratedFileStream covSumFile;
  362. cmGeneratedFileStream covLogFile;
  363. if(!this->StartResultingXML(cmCTest::PartCoverage, "Coverage", covSumFile))
  364. {
  365. cmCTestLog(this->CTest, ERROR_MESSAGE,
  366. "Cannot open coverage summary file." << std::endl);
  367. return -1;
  368. }
  369. this->CTest->StartXML(covSumFile, this->AppendXML);
  370. // Produce output xml files
  371. covSumFile << "<Coverage>" << std::endl
  372. << "\t<StartDateTime>" << coverage_start_time << "</StartDateTime>"
  373. << std::endl
  374. << "\t<StartTime>" << coverage_start_time_time << "</StartTime>"
  375. << std::endl;
  376. int logFileCount = 0;
  377. if ( !this->StartCoverageLogFile(covLogFile, logFileCount) )
  378. {
  379. return -1;
  380. }
  381. cmCTestCoverageHandlerContainer::TotalCoverageMap::iterator fileIterator;
  382. int cnt = 0;
  383. long total_tested = 0;
  384. long total_untested = 0;
  385. //std::string fullSourceDir = sourceDir + "/";
  386. //std::string fullBinaryDir = binaryDir + "/";
  387. cmCTestLog(this->CTest, HANDLER_OUTPUT, std::endl);
  388. cmCTestLog(this->CTest, HANDLER_OUTPUT,
  389. " Acumulating results (each . represents one file):" << std::endl);
  390. cmCTestLog(this->CTest, HANDLER_OUTPUT, " ");
  391. std::vector<std::string> errorsWhileAccumulating;
  392. file_count = 0;
  393. for ( fileIterator = cont.TotalCoverage.begin();
  394. fileIterator != cont.TotalCoverage.end();
  395. ++fileIterator )
  396. {
  397. cmCTestLog(this->CTest, HANDLER_OUTPUT, "." << std::flush);
  398. file_count ++;
  399. if ( file_count % 50 == 0 )
  400. {
  401. cmCTestLog(this->CTest, HANDLER_OUTPUT, " processed: " << file_count
  402. << " out of "
  403. << cont.TotalCoverage.size() << std::endl);
  404. cmCTestLog(this->CTest, HANDLER_OUTPUT, " ");
  405. }
  406. if ( cnt % 100 == 0 )
  407. {
  408. this->EndCoverageLogFile(covLogFile, logFileCount);
  409. logFileCount ++;
  410. if ( !this->StartCoverageLogFile(covLogFile, logFileCount) )
  411. {
  412. return -1;
  413. }
  414. }
  415. const std::string fullFileName = fileIterator->first;
  416. const std::string fileName
  417. = cmSystemTools::GetFilenameName(fullFileName.c_str());
  418. cmCTestLog(this->CTest, HANDLER_VERBOSE_OUTPUT,
  419. "Process file: " << fullFileName << std::endl);
  420. if ( !cmSystemTools::FileExists(fullFileName.c_str()) )
  421. {
  422. cmCTestLog(this->CTest, ERROR_MESSAGE, "Cannot find file: "
  423. << fullFileName.c_str() << std::endl);
  424. continue;
  425. }
  426. bool shouldIDoCoverage
  427. = this->ShouldIDoCoverage(fullFileName.c_str(),
  428. sourceDir.c_str(), binaryDir.c_str());
  429. if ( !shouldIDoCoverage )
  430. {
  431. cmCTestLog(this->CTest, HANDLER_VERBOSE_OUTPUT,
  432. ".NoDartCoverage found, so skip coverage check for: "
  433. << fullFileName.c_str()
  434. << std::endl);
  435. continue;
  436. }
  437. std::string shortFileName =
  438. this->CTest->GetShortPathToFile(fullFileName.c_str());
  439. const cmCTestCoverageHandlerContainer::SingleFileCoverageVector& fcov
  440. = fileIterator->second;
  441. covLogFile << "\t<File Name=\"" << cmXMLSafe(fileName)
  442. << "\" FullPath=\"" << cmXMLSafe(shortFileName) << "\">\n"
  443. << "\t\t<Report>" << std::endl;
  444. std::ifstream ifs(fullFileName.c_str());
  445. if ( !ifs)
  446. {
  447. cmOStringStream ostr;
  448. ostr << "Cannot open source file: " << fullFileName.c_str();
  449. errorsWhileAccumulating.push_back(ostr.str());
  450. error ++;
  451. continue;
  452. }
  453. int tested = 0;
  454. int untested = 0;
  455. cmCTestCoverageHandlerContainer::SingleFileCoverageVector::size_type cc;
  456. std::string line;
  457. cmCTestLog(this->CTest, HANDLER_VERBOSE_OUTPUT,
  458. "Actually perfoming coverage for: " << fullFileName << std::endl);
  459. for ( cc= 0; cc < fcov.size(); cc ++ )
  460. {
  461. if ( !cmSystemTools::GetLineFromStream(ifs, line) &&
  462. cc != fcov.size() -1 )
  463. {
  464. cmOStringStream ostr;
  465. ostr << "Problem reading source file: " << fullFileName.c_str()
  466. << " line:" << cc;
  467. errorsWhileAccumulating.push_back(ostr.str());
  468. error ++;
  469. break;
  470. }
  471. covLogFile << "\t\t<Line Number=\"" << cc << "\" Count=\"" << fcov[cc]
  472. << "\">"
  473. << cmXMLSafe(line) << "</Line>" << std::endl;
  474. if ( fcov[cc] == 0 )
  475. {
  476. untested ++;
  477. }
  478. else if ( fcov[cc] > 0 )
  479. {
  480. tested ++;
  481. }
  482. }
  483. if ( cmSystemTools::GetLineFromStream(ifs, line) )
  484. {
  485. cmOStringStream ostr;
  486. ostr << "Looks like there are more lines in the file: " << line;
  487. errorsWhileAccumulating.push_back(ostr.str());
  488. }
  489. float cper = 0;
  490. float cmet = 0;
  491. if ( tested + untested > 0 )
  492. {
  493. cper = (100 * SAFEDIV(static_cast<float>(tested),
  494. static_cast<float>(tested + untested)));
  495. cmet = ( SAFEDIV(static_cast<float>(tested + 10),
  496. static_cast<float>(tested + untested + 10)));
  497. }
  498. total_tested += tested;
  499. total_untested += untested;
  500. covLogFile << "\t\t</Report>" << std::endl
  501. << "\t</File>" << std::endl;
  502. covSumFile << "\t<File Name=\"" << cmXMLSafe(fileName)
  503. << "\" FullPath=\"" << cmXMLSafe(
  504. this->CTest->GetShortPathToFile(fullFileName.c_str()))
  505. << "\" Covered=\"" << (tested > 0 ? "true":"false") << "\">\n"
  506. << "\t\t<LOCTested>" << tested << "</LOCTested>\n"
  507. << "\t\t<LOCUnTested>" << untested << "</LOCUnTested>\n"
  508. << "\t\t<PercentCoverage>";
  509. covSumFile.setf(std::ios::fixed, std::ios::floatfield);
  510. covSumFile.precision(2);
  511. covSumFile << (cper) << "</PercentCoverage>\n"
  512. << "\t\t<CoverageMetric>";
  513. covSumFile.setf(std::ios::fixed, std::ios::floatfield);
  514. covSumFile.precision(2);
  515. covSumFile << (cmet) << "</CoverageMetric>\n";
  516. this->WriteXMLLabels(covSumFile, shortFileName);
  517. covSumFile << "\t</File>" << std::endl;
  518. cnt ++;
  519. }
  520. this->EndCoverageLogFile(covLogFile, logFileCount);
  521. if ( errorsWhileAccumulating.size() > 0 )
  522. {
  523. cmCTestLog(this->CTest, ERROR_MESSAGE, std::endl);
  524. cmCTestLog(this->CTest, ERROR_MESSAGE,
  525. "Error(s) while acumulating results:" << std::endl);
  526. std::vector<std::string>::iterator erIt;
  527. for ( erIt = errorsWhileAccumulating.begin();
  528. erIt != errorsWhileAccumulating.end();
  529. ++ erIt )
  530. {
  531. cmCTestLog(this->CTest, ERROR_MESSAGE,
  532. " " << erIt->c_str() << std::endl);
  533. }
  534. }
  535. long total_lines = total_tested + total_untested;
  536. float percent_coverage = 100 * SAFEDIV(static_cast<float>(total_tested),
  537. static_cast<float>(total_lines));
  538. if ( total_lines == 0 )
  539. {
  540. percent_coverage = 0;
  541. }
  542. std::string end_time = this->CTest->CurrentTime();
  543. covSumFile << "\t<LOCTested>" << total_tested << "</LOCTested>\n"
  544. << "\t<LOCUntested>" << total_untested << "</LOCUntested>\n"
  545. << "\t<LOC>" << total_lines << "</LOC>\n"
  546. << "\t<PercentCoverage>";
  547. covSumFile.setf(std::ios::fixed, std::ios::floatfield);
  548. covSumFile.precision(2);
  549. covSumFile << (percent_coverage)<< "</PercentCoverage>\n"
  550. << "\t<EndDateTime>" << end_time << "</EndDateTime>\n"
  551. << "\t<EndTime>" <<
  552. static_cast<unsigned int>(cmSystemTools::GetTime())
  553. << "</EndTime>\n";
  554. covSumFile << "<ElapsedMinutes>" <<
  555. static_cast<int>((cmSystemTools::GetTime() - elapsed_time_start)/6)/10.0
  556. << "</ElapsedMinutes>"
  557. << "</Coverage>" << std::endl;
  558. this->CTest->EndXML(covSumFile);
  559. cmCTestLog(this->CTest, HANDLER_OUTPUT, "" << std::endl
  560. << "\tCovered LOC: "
  561. << total_tested << std::endl
  562. << "\tNot covered LOC: " << total_untested << std::endl
  563. << "\tTotal LOC: " << total_lines << std::endl
  564. << "\tPercentage Coverage: "
  565. << std::setiosflags(std::ios::fixed)
  566. << std::setprecision(2)
  567. << (percent_coverage) << "%" << std::endl);
  568. ofs << "\tCovered LOC: " << total_tested << std::endl
  569. << "\tNot covered LOC: " << total_untested << std::endl
  570. << "\tTotal LOC: " << total_lines << std::endl
  571. << "\tPercentage Coverage: "
  572. << std::setiosflags(std::ios::fixed)
  573. << std::setprecision(2)
  574. << (percent_coverage) << "%" << std::endl;
  575. if ( error )
  576. {
  577. return -1;
  578. }
  579. return 0;
  580. }
  581. //----------------------------------------------------------------------
  582. void cmCTestCoverageHandler::PopulateCustomVectors(cmMakefile *mf)
  583. {
  584. cmCTestLog(this->CTest, HANDLER_VERBOSE_OUTPUT,
  585. " Add coverage exclude regular expressions." << std::endl);
  586. this->CTest->PopulateCustomVector(mf, "CTEST_CUSTOM_COVERAGE_EXCLUDE",
  587. this->CustomCoverageExclude);
  588. std::vector<cmStdString>::iterator it;
  589. for ( it = this->CustomCoverageExclude.begin();
  590. it != this->CustomCoverageExclude.end();
  591. ++ it )
  592. {
  593. cmCTestLog(this->CTest, HANDLER_VERBOSE_OUTPUT, " Add coverage exclude: "
  594. << it->c_str() << std::endl);
  595. }
  596. }
  597. //----------------------------------------------------------------------
  598. // Fix for issue #4971 where the case of the drive letter component of
  599. // the filenames might be different when analyzing gcov output.
  600. //
  601. // Compare file names: fnc(fn1) == fnc(fn2) // fnc == file name compare
  602. //
  603. #ifdef _WIN32
  604. #define fnc(s) cmSystemTools::LowerCase(s)
  605. #else
  606. #define fnc(s) s
  607. #endif
  608. //----------------------------------------------------------------------
  609. int cmCTestCoverageHandler::HandleGCovCoverage(
  610. cmCTestCoverageHandlerContainer* cont)
  611. {
  612. std::string gcovCommand
  613. = this->CTest->GetCTestConfiguration("CoverageCommand");
  614. // Style 1
  615. std::string st1gcovOutputRex1
  616. = "[0-9]+\\.[0-9]+% of [0-9]+ (source |)lines executed in file (.*)$";
  617. std::string st1gcovOutputRex2 = "^Creating (.*\\.gcov)\\.";
  618. cmsys::RegularExpression st1re1(st1gcovOutputRex1.c_str());
  619. cmsys::RegularExpression st1re2(st1gcovOutputRex2.c_str());
  620. // Style 2
  621. std::string st2gcovOutputRex1 = "^File *[`'](.*)'$";
  622. std::string st2gcovOutputRex2
  623. = "Lines executed: *[0-9]+\\.[0-9]+% of [0-9]+$";
  624. std::string st2gcovOutputRex3 = "^(.*):creating [`'](.*\\.gcov)'";
  625. std::string st2gcovOutputRex4 = "^(.*):unexpected EOF *$";
  626. std::string st2gcovOutputRex5 = "^(.*):cannot open source file*$";
  627. std::string st2gcovOutputRex6
  628. = "^(.*):source file is newer than graph file `(.*)'$";
  629. cmsys::RegularExpression st2re1(st2gcovOutputRex1.c_str());
  630. cmsys::RegularExpression st2re2(st2gcovOutputRex2.c_str());
  631. cmsys::RegularExpression st2re3(st2gcovOutputRex3.c_str());
  632. cmsys::RegularExpression st2re4(st2gcovOutputRex4.c_str());
  633. cmsys::RegularExpression st2re5(st2gcovOutputRex5.c_str());
  634. cmsys::RegularExpression st2re6(st2gcovOutputRex6.c_str());
  635. std::vector<std::string> files;
  636. this->FindGCovFiles(files);
  637. std::vector<std::string>::iterator it;
  638. if ( files.size() == 0 )
  639. {
  640. cmCTestLog(this->CTest, HANDLER_VERBOSE_OUTPUT,
  641. " Cannot find any GCov coverage files."
  642. << std::endl);
  643. // No coverage files is a valid thing, so the exit code is 0
  644. return 0;
  645. }
  646. std::string testingDir = this->CTest->GetBinaryDir() + "/Testing";
  647. std::string tempDir = testingDir + "/CoverageInfo";
  648. std::string currentDirectory = cmSystemTools::GetCurrentWorkingDirectory();
  649. cmSystemTools::MakeDirectory(tempDir.c_str());
  650. cmSystemTools::ChangeDirectory(tempDir.c_str());
  651. int gcovStyle = 0;
  652. std::set<std::string> missingFiles;
  653. std::string actualSourceFile = "";
  654. cmCTestLog(this->CTest, HANDLER_OUTPUT,
  655. " Processing coverage (each . represents one file):" << std::endl);
  656. cmCTestLog(this->CTest, HANDLER_OUTPUT, " ");
  657. int file_count = 0;
  658. // make sure output from gcov is in English!
  659. cmSystemTools::PutEnv("LC_ALL=POSIX");
  660. for ( it = files.begin(); it != files.end(); ++ it )
  661. {
  662. cmCTestLog(this->CTest, HANDLER_OUTPUT, "." << std::flush);
  663. std::string fileDir = cmSystemTools::GetFilenamePath(it->c_str());
  664. std::string command = "\"" + gcovCommand + "\" -l -o \"" + fileDir
  665. + "\" \"" + *it + "\"";
  666. cmCTestLog(this->CTest, HANDLER_VERBOSE_OUTPUT, command.c_str()
  667. << std::endl);
  668. std::string output = "";
  669. std::string errors = "";
  670. int retVal = 0;
  671. *cont->OFS << "* Run coverage for: " << fileDir.c_str() << std::endl;
  672. *cont->OFS << " Command: " << command.c_str() << std::endl;
  673. int res = this->CTest->RunCommand(command.c_str(), &output, &errors,
  674. &retVal, tempDir.c_str(), 0 /*this->TimeOut*/);
  675. *cont->OFS << " Output: " << output.c_str() << std::endl;
  676. *cont->OFS << " Errors: " << errors.c_str() << std::endl;
  677. if ( ! res )
  678. {
  679. cmCTestLog(this->CTest, ERROR_MESSAGE,
  680. "Problem running coverage on file: " << it->c_str() << std::endl);
  681. cmCTestLog(this->CTest, ERROR_MESSAGE,
  682. "Command produced error: " << errors << std::endl);
  683. cont->Error ++;
  684. continue;
  685. }
  686. if ( retVal != 0 )
  687. {
  688. cmCTestLog(this->CTest, ERROR_MESSAGE, "Coverage command returned: "
  689. << retVal << " while processing: " << it->c_str() << std::endl);
  690. cmCTestLog(this->CTest, ERROR_MESSAGE,
  691. "Command produced error: " << cont->Error << std::endl);
  692. }
  693. cmCTestLog(this->CTest, HANDLER_VERBOSE_OUTPUT,
  694. "--------------------------------------------------------------"
  695. << std::endl
  696. << output << std::endl
  697. << "--------------------------------------------------------------"
  698. << std::endl);
  699. std::vector<cmStdString> lines;
  700. std::vector<cmStdString>::iterator line;
  701. // Globals for storing current source file and current gcov file;
  702. cmSystemTools::Split(output.c_str(), lines);
  703. for ( line = lines.begin(); line != lines.end(); ++line)
  704. {
  705. std::string sourceFile;
  706. std::string gcovFile;
  707. cmCTestLog(this->CTest, DEBUG, "Line: [" << line->c_str() << "]"
  708. << std::endl);
  709. if ( line->size() == 0 )
  710. {
  711. // Ignore empty line; probably style 2
  712. }
  713. else if ( st1re1.find(line->c_str()) )
  714. {
  715. if ( gcovStyle != 0 )
  716. {
  717. if ( gcovStyle != 1 )
  718. {
  719. cmCTestLog(this->CTest, ERROR_MESSAGE, "Unknown gcov output style"
  720. << std::endl);
  721. cont->Error ++;
  722. break;
  723. }
  724. gcovStyle = 1;
  725. }
  726. actualSourceFile = "";
  727. sourceFile = st1re1.match(2);
  728. }
  729. else if ( st1re2.find(line->c_str() ) )
  730. {
  731. if ( gcovStyle != 0 )
  732. {
  733. if ( gcovStyle != 1 )
  734. {
  735. cmCTestLog(this->CTest, ERROR_MESSAGE, "Unknown gcov output style"
  736. << std::endl);
  737. cont->Error ++;
  738. break;
  739. }
  740. gcovStyle = 1;
  741. }
  742. gcovFile = st1re2.match(1);
  743. }
  744. else if ( st2re1.find(line->c_str() ) )
  745. {
  746. if ( gcovStyle != 0 )
  747. {
  748. if ( gcovStyle != 2 )
  749. {
  750. cmCTestLog(this->CTest, ERROR_MESSAGE, "Unknown gcov output style"
  751. << std::endl);
  752. cont->Error ++;
  753. break;
  754. }
  755. gcovStyle = 2;
  756. }
  757. actualSourceFile = "";
  758. sourceFile = st2re1.match(1);
  759. }
  760. else if ( st2re2.find(line->c_str() ) )
  761. {
  762. if ( gcovStyle != 0 )
  763. {
  764. if ( gcovStyle != 2 )
  765. {
  766. cmCTestLog(this->CTest, ERROR_MESSAGE, "Unknown gcov output style"
  767. << std::endl);
  768. cont->Error ++;
  769. break;
  770. }
  771. gcovStyle = 2;
  772. }
  773. }
  774. else if ( st2re3.find(line->c_str() ) )
  775. {
  776. if ( gcovStyle != 0 )
  777. {
  778. if ( gcovStyle != 2 )
  779. {
  780. cmCTestLog(this->CTest, ERROR_MESSAGE, "Unknown gcov output style"
  781. << std::endl);
  782. cont->Error ++;
  783. break;
  784. }
  785. gcovStyle = 2;
  786. }
  787. gcovFile = st2re3.match(2);
  788. }
  789. else if ( st2re4.find(line->c_str() ) )
  790. {
  791. if ( gcovStyle != 0 )
  792. {
  793. if ( gcovStyle != 2 )
  794. {
  795. cmCTestLog(this->CTest, ERROR_MESSAGE, "Unknown gcov output style"
  796. << std::endl);
  797. cont->Error ++;
  798. break;
  799. }
  800. gcovStyle = 2;
  801. }
  802. cmCTestLog(this->CTest, WARNING, "Warning: " << st2re4.match(1)
  803. << " had unexpected EOF" << std::endl);
  804. }
  805. else if ( st2re5.find(line->c_str() ) )
  806. {
  807. if ( gcovStyle != 0 )
  808. {
  809. if ( gcovStyle != 2 )
  810. {
  811. cmCTestLog(this->CTest, ERROR_MESSAGE, "Unknown gcov output style"
  812. << std::endl);
  813. cont->Error ++;
  814. break;
  815. }
  816. gcovStyle = 2;
  817. }
  818. cmCTestLog(this->CTest, WARNING, "Warning: Cannot open file: "
  819. << st2re5.match(1) << std::endl);
  820. }
  821. else if ( st2re6.find(line->c_str() ) )
  822. {
  823. if ( gcovStyle != 0 )
  824. {
  825. if ( gcovStyle != 2 )
  826. {
  827. cmCTestLog(this->CTest, ERROR_MESSAGE, "Unknown gcov output style"
  828. << std::endl);
  829. cont->Error ++;
  830. break;
  831. }
  832. gcovStyle = 2;
  833. }
  834. cmCTestLog(this->CTest, WARNING, "Warning: File: " << st2re6.match(1)
  835. << " is newer than " << st2re6.match(2) << std::endl);
  836. }
  837. else
  838. {
  839. cmCTestLog(this->CTest, ERROR_MESSAGE,
  840. "Unknown line: [" << line->c_str() << "]" << std::endl);
  841. cont->Error ++;
  842. //abort();
  843. }
  844. if ( !gcovFile.empty() && actualSourceFile.size() )
  845. {
  846. cmCTestCoverageHandlerContainer::SingleFileCoverageVector* vec
  847. = &cont->TotalCoverage[actualSourceFile];
  848. cmCTestLog(this->CTest, HANDLER_VERBOSE_OUTPUT, " in file: "
  849. << gcovFile << std::endl);
  850. std::ifstream ifile(gcovFile.c_str());
  851. if ( ! ifile )
  852. {
  853. cmCTestLog(this->CTest, ERROR_MESSAGE, "Cannot open file: "
  854. << gcovFile << std::endl);
  855. }
  856. else
  857. {
  858. long cnt = -1;
  859. std::string nl;
  860. while ( cmSystemTools::GetLineFromStream(ifile, nl) )
  861. {
  862. cnt ++;
  863. //TODO: Handle gcov 3.0 non-coverage lines
  864. // Skip empty lines
  865. if ( !nl.size() )
  866. {
  867. continue;
  868. }
  869. // Skip unused lines
  870. if ( nl.size() < 12 )
  871. {
  872. continue;
  873. }
  874. // Read the coverage count from the beginning of the gcov output
  875. // line
  876. std::string prefix = nl.substr(0, 12);
  877. int cov = atoi(prefix.c_str());
  878. // Read the line number starting at the 10th character of the gcov
  879. // output line
  880. std::string lineNumber = nl.substr(10, 5);
  881. int lineIdx = atoi(lineNumber.c_str())-1;
  882. if ( lineIdx >= 0 )
  883. {
  884. while ( vec->size() <=
  885. static_cast<size_t>(lineIdx) )
  886. {
  887. vec->push_back(-1);
  888. }
  889. // Initially all entries are -1 (not used). If we get coverage
  890. // information, increment it to 0 first.
  891. if ( (*vec)[lineIdx] < 0 )
  892. {
  893. if ( cov > 0 || prefix.find("#") != prefix.npos )
  894. {
  895. (*vec)[lineIdx] = 0;
  896. }
  897. }
  898. (*vec)[lineIdx] += cov;
  899. }
  900. }
  901. }
  902. actualSourceFile = "";
  903. }
  904. if ( !sourceFile.empty() && actualSourceFile.empty() )
  905. {
  906. gcovFile = "";
  907. // Is it in the source dir?
  908. if ( sourceFile.size() > cont->SourceDir.size() &&
  909. (fnc(sourceFile.substr(0, cont->SourceDir.size())) ==
  910. fnc(cont->SourceDir)) &&
  911. sourceFile[cont->SourceDir.size()] == '/' )
  912. {
  913. cmCTestLog(this->CTest, HANDLER_VERBOSE_OUTPUT, " produced s: "
  914. << sourceFile.c_str() << std::endl);
  915. *cont->OFS << " produced in source dir: " << sourceFile.c_str()
  916. << std::endl;
  917. actualSourceFile
  918. = cmSystemTools::CollapseFullPath(sourceFile.c_str());
  919. }
  920. // Binary dir?
  921. if ( sourceFile.size() > cont->BinaryDir.size() &&
  922. (fnc(sourceFile.substr(0, cont->BinaryDir.size())) ==
  923. fnc(cont->BinaryDir)) &&
  924. sourceFile[cont->BinaryDir.size()] == '/' )
  925. {
  926. cmCTestLog(this->CTest, HANDLER_VERBOSE_OUTPUT, " produced b: "
  927. << sourceFile.c_str() << std::endl);
  928. *cont->OFS << " produced in binary dir: " << sourceFile.c_str()
  929. << std::endl;
  930. actualSourceFile
  931. = cmSystemTools::CollapseFullPath(sourceFile.c_str());
  932. }
  933. if ( actualSourceFile.empty() )
  934. {
  935. if ( missingFiles.find(actualSourceFile) == missingFiles.end() )
  936. {
  937. cmCTestLog(this->CTest, HANDLER_VERBOSE_OUTPUT,
  938. "Something went wrong" << std::endl);
  939. cmCTestLog(this->CTest, HANDLER_VERBOSE_OUTPUT,
  940. "Cannot find file: ["
  941. << sourceFile.c_str() << "]" << std::endl);
  942. cmCTestLog(this->CTest, HANDLER_VERBOSE_OUTPUT,
  943. " in source dir: ["
  944. << cont->SourceDir.c_str() << "]"
  945. << std::endl);
  946. cmCTestLog(this->CTest, HANDLER_VERBOSE_OUTPUT,
  947. " or binary dir: ["
  948. << cont->BinaryDir.size() << "]"
  949. << std::endl);
  950. *cont->OFS << " Something went wrong. Cannot find file: "
  951. << sourceFile.c_str()
  952. << " in source dir: " << cont->SourceDir.c_str()
  953. << " or binary dir: " << cont->BinaryDir.c_str() << std::endl;
  954. missingFiles.insert(actualSourceFile);
  955. }
  956. }
  957. }
  958. }
  959. file_count ++;
  960. if ( file_count % 50 == 0 )
  961. {
  962. cmCTestLog(this->CTest, HANDLER_OUTPUT, " processed: " << file_count
  963. << " out of " << files.size() << std::endl);
  964. cmCTestLog(this->CTest, HANDLER_OUTPUT, " ");
  965. }
  966. }
  967. cmSystemTools::ChangeDirectory(currentDirectory.c_str());
  968. return file_count;
  969. }
  970. //----------------------------------------------------------------------------
  971. void cmCTestCoverageHandler::FindGCovFiles(std::vector<std::string>& files)
  972. {
  973. cmsys::Glob gl;
  974. gl.RecurseOn();
  975. gl.RecurseThroughSymlinksOff();
  976. for(LabelMapType::const_iterator lmi = this->TargetDirs.begin();
  977. lmi != this->TargetDirs.end(); ++lmi)
  978. {
  979. // Skip targets containing no interesting labels.
  980. if(!this->IntersectsFilter(lmi->second))
  981. {
  982. continue;
  983. }
  984. // Coverage files appear next to their object files in the target
  985. // support directory.
  986. cmCTestLog(this->CTest, HANDLER_VERBOSE_OUTPUT,
  987. " globbing for coverage in: " << lmi->first << std::endl);
  988. std::string daGlob = lmi->first;
  989. daGlob += "/*.da";
  990. gl.FindFiles(daGlob);
  991. files.insert(files.end(), gl.GetFiles().begin(), gl.GetFiles().end());
  992. daGlob = lmi->first;
  993. daGlob += "/*.gcda";
  994. gl.FindFiles(daGlob);
  995. files.insert(files.end(), gl.GetFiles().begin(), gl.GetFiles().end());
  996. }
  997. }
  998. //----------------------------------------------------------------------
  999. int cmCTestCoverageHandler::HandleTracePyCoverage(
  1000. cmCTestCoverageHandlerContainer* cont)
  1001. {
  1002. cmsys::Glob gl;
  1003. gl.RecurseOn();
  1004. gl.RecurseThroughSymlinksOff();
  1005. std::string daGlob = cont->BinaryDir + "/*.cover";
  1006. gl.FindFiles(daGlob);
  1007. std::vector<std::string> files = gl.GetFiles();
  1008. if ( files.size() == 0 )
  1009. {
  1010. cmCTestLog(this->CTest, HANDLER_VERBOSE_OUTPUT,
  1011. " Cannot find any Python Trace.py coverage files."
  1012. << std::endl);
  1013. // No coverage files is a valid thing, so the exit code is 0
  1014. return 0;
  1015. }
  1016. std::string testingDir = this->CTest->GetBinaryDir() + "/Testing";
  1017. std::string tempDir = testingDir + "/CoverageInfo";
  1018. std::string currentDirectory = cmSystemTools::GetCurrentWorkingDirectory();
  1019. cmSystemTools::MakeDirectory(tempDir.c_str());
  1020. cmSystemTools::ChangeDirectory(tempDir.c_str());
  1021. cmSystemTools::ChangeDirectory(currentDirectory.c_str());
  1022. std::vector<std::string>::iterator fileIt;
  1023. int file_count = 0;
  1024. for ( fileIt = files.begin(); fileIt != files.end(); ++ fileIt )
  1025. {
  1026. std::string fileName = this->FindFile(cont, *fileIt);
  1027. if ( fileName.empty() )
  1028. {
  1029. cmCTestLog(this->CTest, ERROR_MESSAGE,
  1030. "Cannot find source Python file corresponding to: "
  1031. << fileIt->c_str() << std::endl);
  1032. continue;
  1033. }
  1034. std::string actualSourceFile
  1035. = cmSystemTools::CollapseFullPath(fileName.c_str());
  1036. cmCTestLog(this->CTest, HANDLER_VERBOSE_OUTPUT,
  1037. " Check coverage for file: " << actualSourceFile.c_str()
  1038. << std::endl);
  1039. cmCTestCoverageHandlerContainer::SingleFileCoverageVector* vec
  1040. = &cont->TotalCoverage[actualSourceFile];
  1041. cmCTestLog(this->CTest, HANDLER_VERBOSE_OUTPUT,
  1042. " in file: " << fileIt->c_str() << std::endl);
  1043. std::ifstream ifile(fileIt->c_str());
  1044. if ( ! ifile )
  1045. {
  1046. cmCTestLog(this->CTest, ERROR_MESSAGE, "Cannot open file: "
  1047. << fileIt->c_str() << std::endl);
  1048. }
  1049. else
  1050. {
  1051. long cnt = -1;
  1052. std::string nl;
  1053. while ( cmSystemTools::GetLineFromStream(ifile, nl) )
  1054. {
  1055. cnt ++;
  1056. // Skip empty lines
  1057. if ( !nl.size() )
  1058. {
  1059. continue;
  1060. }
  1061. // Skip unused lines
  1062. if ( nl.size() < 12 )
  1063. {
  1064. continue;
  1065. }
  1066. // Read the coverage count from the beginning of the Trace.py output
  1067. // line
  1068. std::string prefix = nl.substr(0, 6);
  1069. if ( prefix[5] != ' ' && prefix[5] != ':' )
  1070. {
  1071. // This is a hack. We should really do something more elaborate
  1072. prefix = nl.substr(0, 7);
  1073. if ( prefix[6] != ' ' && prefix[6] != ':' )
  1074. {
  1075. prefix = nl.substr(0, 8);
  1076. if ( prefix[7] != ' ' && prefix[7] != ':' )
  1077. {
  1078. cmCTestLog(this->CTest, ERROR_MESSAGE,
  1079. "Currently the limit is maximum coverage of 999999"
  1080. << std::endl);
  1081. }
  1082. }
  1083. }
  1084. int cov = atoi(prefix.c_str());
  1085. if ( prefix[prefix.size()-1] != ':' )
  1086. {
  1087. // This line does not have ':' so no coverage here. That said,
  1088. // Trace.py does not handle not covered lines versus comments etc.
  1089. // So, this will be set to 0.
  1090. cov = 0;
  1091. }
  1092. cmCTestLog(this->CTest, DEBUG, "Prefix: " << prefix.c_str()
  1093. << " cov: " << cov
  1094. << std::endl);
  1095. // Read the line number starting at the 10th character of the gcov
  1096. // output line
  1097. long lineIdx = cnt;
  1098. if ( lineIdx >= 0 )
  1099. {
  1100. while ( vec->size() <=
  1101. static_cast<size_t>(lineIdx) )
  1102. {
  1103. vec->push_back(-1);
  1104. }
  1105. // Initially all entries are -1 (not used). If we get coverage
  1106. // information, increment it to 0 first.
  1107. if ( (*vec)[lineIdx] < 0 )
  1108. {
  1109. if ( cov >= 0 )
  1110. {
  1111. (*vec)[lineIdx] = 0;
  1112. }
  1113. }
  1114. (*vec)[lineIdx] += cov;
  1115. }
  1116. }
  1117. }
  1118. ++ file_count;
  1119. }
  1120. cmSystemTools::ChangeDirectory(currentDirectory.c_str());
  1121. return file_count;
  1122. }
  1123. //----------------------------------------------------------------------
  1124. std::string cmCTestCoverageHandler::FindFile(
  1125. cmCTestCoverageHandlerContainer* cont,
  1126. std::string fileName)
  1127. {
  1128. std::string fileNameNoE
  1129. = cmSystemTools::GetFilenameWithoutLastExtension(fileName);
  1130. // First check in source and binary directory
  1131. std::string fullName = cont->SourceDir + "/" + fileNameNoE + ".py";
  1132. if ( cmSystemTools::FileExists(fullName.c_str()) )
  1133. {
  1134. return fullName;
  1135. }
  1136. fullName = cont->BinaryDir + "/" + fileNameNoE + ".py";
  1137. if ( cmSystemTools::FileExists(fullName.c_str()) )
  1138. {
  1139. return fullName;
  1140. }
  1141. return "";
  1142. }
  1143. // This is a header put on each marked up source file
  1144. namespace
  1145. {
  1146. const char* bullseyeHelp[] =
  1147. {" Coverage produced by bullseye covbr tool: ",
  1148. " www.bullseye.com/help/ref_covbr.html",
  1149. " * An arrow --> indicates incomplete coverage.",
  1150. " * An X indicates a function that was invoked, a switch label that ",
  1151. " was exercised, a try-block that finished, or an exception handler ",
  1152. " that was invoked.",
  1153. " * A T or F indicates a boolean decision that evaluated true or false,",
  1154. " respectively.",
  1155. " * A t or f indicates a boolean condition within a decision if the ",
  1156. " condition evaluated true or false, respectively.",
  1157. " * A k indicates a constant decision or condition.",
  1158. " * The slash / means this probe is excluded from summary results. ",
  1159. 0};
  1160. }
  1161. //----------------------------------------------------------------------
  1162. int cmCTestCoverageHandler::RunBullseyeCoverageBranch(
  1163. cmCTestCoverageHandlerContainer* cont,
  1164. std::set<cmStdString>& coveredFileNames,
  1165. std::vector<std::string>& files,
  1166. std::vector<std::string>& filesFullPath)
  1167. {
  1168. if(files.size() != filesFullPath.size())
  1169. {
  1170. cmCTestLog(this->CTest, ERROR_MESSAGE,
  1171. "Files and full path files not the same size?:\n");
  1172. return 0;
  1173. }
  1174. // create the output stream for the CoverageLog-N.xml file
  1175. cmGeneratedFileStream covLogFile;
  1176. int logFileCount = 0;
  1177. if ( !this->StartCoverageLogFile(covLogFile, logFileCount) )
  1178. {
  1179. return -1;
  1180. }
  1181. // for each file run covbr on that file to get the coverage
  1182. // information for that file
  1183. std::string outputFile;
  1184. cmCTestLog(this->CTest, HANDLER_VERBOSE_OUTPUT,
  1185. "run covbr: "
  1186. << std::endl);
  1187. if(!this->RunBullseyeCommand(cont, "covbr", 0, outputFile))
  1188. {
  1189. cmCTestLog(this->CTest, ERROR_MESSAGE, "error running covbr for." << "\n");
  1190. return -1;
  1191. }
  1192. cmCTestLog(this->CTest, HANDLER_VERBOSE_OUTPUT,
  1193. "covbr output in " << outputFile
  1194. << std::endl);
  1195. // open the output file
  1196. std::ifstream fin(outputFile.c_str());
  1197. if(!fin)
  1198. {
  1199. cmCTestLog(this->CTest, ERROR_MESSAGE,
  1200. "Cannot open coverage file: " <<
  1201. outputFile.c_str() << std::endl);
  1202. return 0;
  1203. }
  1204. std::map<cmStdString, cmStdString> fileMap;
  1205. std::vector<std::string>::iterator fp = filesFullPath.begin();
  1206. for(std::vector<std::string>::iterator f = files.begin();
  1207. f != files.end(); ++f, ++fp)
  1208. {
  1209. fileMap[*f] = *fp;
  1210. }
  1211. int count =0; // keep count of the number of files
  1212. // Now parse each line from the bullseye cov log file
  1213. std::string lineIn;
  1214. bool valid = false; // are we in a valid output file
  1215. int line = 0; // line of the current file
  1216. cmStdString file;
  1217. while(cmSystemTools::GetLineFromStream(fin, lineIn))
  1218. {
  1219. bool startFile = false;
  1220. if(lineIn.size() > 1 && lineIn[lineIn.size()-1] == ':')
  1221. {
  1222. file = lineIn.substr(0, lineIn.size()-1);
  1223. if(coveredFileNames.find(file) != coveredFileNames.end())
  1224. {
  1225. startFile = true;
  1226. }
  1227. }
  1228. if(startFile)
  1229. {
  1230. // if we are in a valid file close it because a new one started
  1231. if(valid)
  1232. {
  1233. covLogFile << "\t\t</Report>" << std::endl
  1234. << "\t</File>" << std::endl;
  1235. }
  1236. // only allow 100 files in each log file
  1237. if ( count != 0 && count % 100 == 0 )
  1238. {
  1239. cmCTestLog(this->CTest, HANDLER_VERBOSE_OUTPUT,
  1240. "start a new log file: "
  1241. << count
  1242. << std::endl);
  1243. this->EndCoverageLogFile(covLogFile, logFileCount);
  1244. logFileCount ++;
  1245. if ( !this->StartCoverageLogFile(covLogFile, logFileCount) )
  1246. {
  1247. return -1;
  1248. }
  1249. count++; // move on one
  1250. }
  1251. std::map<cmStdString, cmStdString>::iterator
  1252. i = fileMap.find(file);
  1253. // if the file should be covered write out the header for that file
  1254. if(i != fileMap.end())
  1255. {
  1256. // we have a new file so count it in the output
  1257. count++;
  1258. cmCTestLog(this->CTest, HANDLER_VERBOSE_OUTPUT,
  1259. "Produce coverage for file: "
  1260. << file.c_str() << " " << count
  1261. << std::endl);
  1262. // start the file output
  1263. covLogFile << "\t<File Name=\""
  1264. << cmXMLSafe(i->first)
  1265. << "\" FullPath=\"" << cmXMLSafe(
  1266. this->CTest->GetShortPathToFile(
  1267. i->second.c_str())) << "\">" << std::endl
  1268. << "\t\t<Report>" << std::endl;
  1269. // write the bullseye header
  1270. line =0;
  1271. for(int k =0; bullseyeHelp[k] != 0; ++k)
  1272. {
  1273. covLogFile << "\t\t<Line Number=\"" << line << "\" Count=\"-1\">"
  1274. << cmXMLSafe(bullseyeHelp[k])
  1275. << "</Line>" << std::endl;
  1276. line++;
  1277. }
  1278. valid = true; // we are in a valid file section
  1279. }
  1280. else
  1281. {
  1282. // this is not a file that we want coverage for
  1283. valid = false;
  1284. }
  1285. }
  1286. // we are not at a start file, and we are in a valid file output the line
  1287. else if(valid)
  1288. {
  1289. covLogFile << "\t\t<Line Number=\"" << line << "\" Count=\"-1\">"
  1290. << cmXMLSafe(lineIn)
  1291. << "</Line>" << std::endl;
  1292. line++;
  1293. }
  1294. }
  1295. // if we ran out of lines a valid file then close that file
  1296. if(valid)
  1297. {
  1298. covLogFile << "\t\t</Report>" << std::endl
  1299. << "\t</File>" << std::endl;
  1300. }
  1301. this->EndCoverageLogFile(covLogFile, logFileCount);
  1302. return 1;
  1303. }
  1304. //----------------------------------------------------------------------
  1305. int cmCTestCoverageHandler::RunBullseyeCommand(
  1306. cmCTestCoverageHandlerContainer* cont,
  1307. const char* cmd,
  1308. const char* arg,
  1309. std::string& outputFile)
  1310. {
  1311. std::string program = cmSystemTools::FindProgram(cmd);
  1312. if(program.size() == 0)
  1313. {
  1314. cmCTestLog(this->CTest, ERROR_MESSAGE, "Cannot find :" << cmd << "\n");
  1315. return 0;
  1316. }
  1317. if(arg)
  1318. {
  1319. cmCTestLog(this->CTest, HANDLER_VERBOSE_OUTPUT,
  1320. "Run : " << program.c_str() << " " << arg << "\n");
  1321. }
  1322. else
  1323. {
  1324. cmCTestLog(this->CTest, HANDLER_VERBOSE_OUTPUT,
  1325. "Run : " << program.c_str() << "\n");
  1326. }
  1327. // create a process object and start it
  1328. cmCTestRunProcess runCoverageSrc;
  1329. runCoverageSrc.SetCommand(program.c_str());
  1330. runCoverageSrc.AddArgument(arg);
  1331. std::string stdoutFile = cont->BinaryDir + "/Testing/Temporary/";
  1332. stdoutFile += this->GetCTestInstance()->GetCurrentTag();
  1333. stdoutFile += "-";
  1334. stdoutFile += cmd;
  1335. std::string stderrFile = stdoutFile;
  1336. stdoutFile += ".stdout";
  1337. stderrFile += ".stderr";
  1338. runCoverageSrc.SetStdoutFile(stdoutFile.c_str());
  1339. runCoverageSrc.SetStderrFile(stderrFile.c_str());
  1340. if(!runCoverageSrc.StartProcess())
  1341. {
  1342. cmCTestLog(this->CTest, ERROR_MESSAGE, "Could not run : "
  1343. << program.c_str() << " " << arg << "\n"
  1344. << "kwsys process state : "
  1345. << runCoverageSrc.GetProcessState());
  1346. return 0;
  1347. }
  1348. // since we set the output file names wait for it to end
  1349. runCoverageSrc.WaitForExit();
  1350. outputFile = stdoutFile;
  1351. return 1;
  1352. }
  1353. //----------------------------------------------------------------------
  1354. int cmCTestCoverageHandler::RunBullseyeSourceSummary(
  1355. cmCTestCoverageHandlerContainer* cont)
  1356. {
  1357. // Run the covsrc command and create a temp outputfile
  1358. std::string outputFile;
  1359. if(!this->RunBullseyeCommand(cont, "covsrc", "-c", outputFile))
  1360. {
  1361. cmCTestLog(this->CTest, ERROR_MESSAGE, "error running covsrc:\n");
  1362. return 0;
  1363. }
  1364. std::ostream& tmpLog = *cont->OFS;
  1365. // copen the Coverage.xml file in the Testing directory
  1366. cmGeneratedFileStream covSumFile;
  1367. if(!this->StartResultingXML(cmCTest::PartCoverage, "Coverage", covSumFile))
  1368. {
  1369. cmCTestLog(this->CTest, ERROR_MESSAGE,
  1370. "Cannot open coverage summary file." << std::endl);
  1371. return 0;
  1372. }
  1373. this->CTest->StartXML(covSumFile, this->AppendXML);
  1374. double elapsed_time_start = cmSystemTools::GetTime();
  1375. std::string coverage_start_time = this->CTest->CurrentTime();
  1376. covSumFile << "<Coverage>" << std::endl
  1377. << "\t<StartDateTime>"
  1378. << coverage_start_time << "</StartDateTime>"
  1379. << std::endl
  1380. << "\t<StartTime>"
  1381. << static_cast<unsigned int>(cmSystemTools::GetTime())
  1382. << "</StartTime>"
  1383. << std::endl;
  1384. std::string stdline;
  1385. std::string errline;
  1386. // expected output:
  1387. // first line is:
  1388. // "Source","Function Coverage","out of","%","C/D Coverage","out of","%"
  1389. // after that data follows in that format
  1390. std::string sourceFile;
  1391. int functionsCalled = 0;
  1392. int totalFunctions = 0;
  1393. int percentFunction = 0;
  1394. int branchCovered = 0;
  1395. int totalBranches = 0;
  1396. int percentBranch = 0;
  1397. double total_tested = 0;
  1398. double total_untested = 0;
  1399. double total_functions = 0;
  1400. double percent_coverage =0;
  1401. double number_files = 0;
  1402. std::vector<std::string> coveredFiles;
  1403. std::vector<std::string> coveredFilesFullPath;
  1404. // Read and parse the summary output file
  1405. std::ifstream fin(outputFile.c_str());
  1406. if(!fin)
  1407. {
  1408. cmCTestLog(this->CTest, ERROR_MESSAGE,
  1409. "Cannot open coverage summary file: " <<
  1410. outputFile.c_str() << std::endl);
  1411. return 0;
  1412. }
  1413. std::set<cmStdString> coveredFileNames;
  1414. while(cmSystemTools::GetLineFromStream(fin, stdline))
  1415. {
  1416. // if we have a line of output from stdout
  1417. if(stdline.size())
  1418. {
  1419. // parse the comma separated output
  1420. this->ParseBullsEyeCovsrcLine(stdline,
  1421. sourceFile,
  1422. functionsCalled,
  1423. totalFunctions,
  1424. percentFunction,
  1425. branchCovered,
  1426. totalBranches,
  1427. percentBranch);
  1428. // The first line is the header
  1429. if(sourceFile == "Source" || sourceFile == "Total")
  1430. {
  1431. continue;
  1432. }
  1433. std::string file = sourceFile;
  1434. coveredFileNames.insert(file);
  1435. if(!cmSystemTools::FileIsFullPath(sourceFile.c_str()))
  1436. {
  1437. // file will be relative to the binary dir
  1438. file = cont->BinaryDir;
  1439. file += "/";
  1440. file += sourceFile;
  1441. }
  1442. file = cmSystemTools::CollapseFullPath(file.c_str());
  1443. bool shouldIDoCoverage
  1444. = this->ShouldIDoCoverage(file.c_str(),
  1445. cont->SourceDir.c_str(),
  1446. cont->BinaryDir.c_str());
  1447. if ( !shouldIDoCoverage )
  1448. {
  1449. cmCTestLog(this->CTest, HANDLER_VERBOSE_OUTPUT,
  1450. ".NoDartCoverage found, so skip coverage check for: "
  1451. << file.c_str()
  1452. << std::endl);
  1453. continue;
  1454. }
  1455. cmCTestLog(this->CTest, HANDLER_VERBOSE_OUTPUT,
  1456. "Doing coverage for: "
  1457. << file.c_str()
  1458. << std::endl);
  1459. coveredFiles.push_back(sourceFile);
  1460. coveredFilesFullPath.push_back(file);
  1461. number_files++;
  1462. total_functions += totalFunctions;
  1463. total_tested += functionsCalled;
  1464. total_untested += (totalFunctions - functionsCalled);
  1465. std::string fileName = cmSystemTools::GetFilenameName(file.c_str());
  1466. std::string shortFileName =
  1467. this->CTest->GetShortPathToFile(file.c_str());
  1468. float cper = percentBranch + percentFunction;
  1469. if(totalBranches > 0)
  1470. {
  1471. cper /= 2.0f;
  1472. }
  1473. percent_coverage += cper;
  1474. float cmet = percentFunction + percentBranch;
  1475. if(totalBranches > 0)
  1476. {
  1477. cmet /= 2.0f;
  1478. }
  1479. cmet /= 100.0f;
  1480. tmpLog << stdline.c_str() << "\n";
  1481. tmpLog << fileName << "\n";
  1482. tmpLog << "functionsCalled: " << functionsCalled/100 << "\n";
  1483. tmpLog << "totalFunctions: " << totalFunctions/100 << "\n";
  1484. tmpLog << "percentFunction: " << percentFunction << "\n";
  1485. tmpLog << "branchCovered: " << branchCovered << "\n";
  1486. tmpLog << "totalBranches: " << totalBranches << "\n";
  1487. tmpLog << "percentBranch: " << percentBranch << "\n";
  1488. tmpLog << "percentCoverage: " << percent_coverage << "\n";
  1489. tmpLog << "coverage metric: " << cmet << "\n";
  1490. covSumFile << "\t<File Name=\"" << cmXMLSafe(sourceFile)
  1491. << "\" FullPath=\"" << cmXMLSafe(shortFileName)
  1492. << "\" Covered=\"" << (cmet>0?"true":"false") << "\">\n"
  1493. << "\t\t<BranchesTested>"
  1494. << branchCovered
  1495. << "</BranchesTested>\n"
  1496. << "\t\t<BranchesUnTested>"
  1497. << totalBranches - branchCovered
  1498. << "</BranchesUnTested>\n"
  1499. << "\t\t<FunctionsTested>"
  1500. << functionsCalled
  1501. << "</FunctionsTested>\n"
  1502. << "\t\t<FunctionsUnTested>"
  1503. << totalFunctions - functionsCalled
  1504. << "</FunctionsUnTested>\n"
  1505. // Hack for conversion of function to loc assume a function
  1506. // has 100 lines of code
  1507. << "\t\t<LOCTested>" << functionsCalled *100
  1508. << "</LOCTested>\n"
  1509. << "\t\t<LOCUnTested>"
  1510. << (totalFunctions - functionsCalled)*100
  1511. << "</LOCUnTested>\n"
  1512. << "\t\t<PercentCoverage>";
  1513. covSumFile.setf(std::ios::fixed, std::ios::floatfield);
  1514. covSumFile.precision(2);
  1515. covSumFile << (cper) << "</PercentCoverage>\n"
  1516. << "\t\t<CoverageMetric>";
  1517. covSumFile.setf(std::ios::fixed, std::ios::floatfield);
  1518. covSumFile.precision(2);
  1519. covSumFile << (cmet) << "</CoverageMetric>\n";
  1520. this->WriteXMLLabels(covSumFile, shortFileName);
  1521. covSumFile << "\t</File>" << std::endl;
  1522. }
  1523. }
  1524. std::string end_time = this->CTest->CurrentTime();
  1525. covSumFile << "\t<LOCTested>" << total_tested << "</LOCTested>\n"
  1526. << "\t<LOCUntested>" << total_untested << "</LOCUntested>\n"
  1527. << "\t<LOC>" << total_functions << "</LOC>\n"
  1528. << "\t<PercentCoverage>";
  1529. covSumFile.setf(std::ios::fixed, std::ios::floatfield);
  1530. covSumFile.precision(2);
  1531. covSumFile
  1532. << SAFEDIV(percent_coverage,number_files)<< "</PercentCoverage>\n"
  1533. << "\t<EndDateTime>" << end_time << "</EndDateTime>\n"
  1534. << "\t<EndTime>" << static_cast<unsigned int>(cmSystemTools::GetTime())
  1535. << "</EndTime>\n";
  1536. covSumFile
  1537. << "<ElapsedMinutes>" <<
  1538. static_cast<int>((cmSystemTools::GetTime() - elapsed_time_start)/6)/10.0
  1539. << "</ElapsedMinutes>"
  1540. << "</Coverage>" << std::endl;
  1541. this->CTest->EndXML(covSumFile);
  1542. // Now create the coverage information for each file
  1543. return this->RunBullseyeCoverageBranch(cont,
  1544. coveredFileNames,
  1545. coveredFiles,
  1546. coveredFilesFullPath);
  1547. }
  1548. //----------------------------------------------------------------------
  1549. int cmCTestCoverageHandler::HandleBullseyeCoverage(
  1550. cmCTestCoverageHandlerContainer* cont)
  1551. {
  1552. const char* covfile = cmSystemTools::GetEnv("COVFILE");
  1553. if(!covfile)
  1554. {
  1555. cmCTestLog(this->CTest, HANDLER_VERBOSE_OUTPUT,
  1556. " COVFILE environment variable not found, not running "
  1557. " bullseye\n");
  1558. return 0;
  1559. }
  1560. cmCTestLog(this->CTest, HANDLER_VERBOSE_OUTPUT,
  1561. " run covsrc with COVFILE=["
  1562. << covfile
  1563. << "]" << std::endl);
  1564. if(!this->RunBullseyeSourceSummary(cont))
  1565. {
  1566. cmCTestLog(this->CTest, ERROR_MESSAGE,
  1567. "Error running bullseye summary.\n");
  1568. return 0;
  1569. }
  1570. cmCTestLog(this->CTest, DEBUG, "HandleBullseyeCoverage return 1 "
  1571. << std::endl);
  1572. return 1;
  1573. }
  1574. bool cmCTestCoverageHandler::GetNextInt(std::string const& inputLine,
  1575. std::string::size_type& pos,
  1576. int& value)
  1577. {
  1578. std::string::size_type start = pos;
  1579. pos = inputLine.find(',', start);
  1580. value = atoi(inputLine.substr(start, pos).c_str());
  1581. if(pos == inputLine.npos)
  1582. {
  1583. return true;
  1584. }
  1585. pos++;
  1586. return true;
  1587. }
  1588. bool cmCTestCoverageHandler::ParseBullsEyeCovsrcLine(
  1589. std::string const& inputLine,
  1590. std::string& sourceFile,
  1591. int& functionsCalled,
  1592. int& totalFunctions,
  1593. int& percentFunction,
  1594. int& branchCovered,
  1595. int& totalBranches,
  1596. int& percentBranch)
  1597. {
  1598. // find the first comma
  1599. std::string::size_type pos = inputLine.find(',');
  1600. if(pos == inputLine.npos)
  1601. {
  1602. cmCTestLog(this->CTest, ERROR_MESSAGE, "Error parsing string : "
  1603. << inputLine.c_str() << "\n");
  1604. return false;
  1605. }
  1606. // the source file has "" around it so extract out the file name
  1607. sourceFile = inputLine.substr(1,pos-2);
  1608. pos++;
  1609. if(!this->GetNextInt(inputLine, pos, functionsCalled))
  1610. {
  1611. return false;
  1612. }
  1613. if(!this->GetNextInt(inputLine, pos, totalFunctions))
  1614. {
  1615. return false;
  1616. }
  1617. if(!this->GetNextInt(inputLine, pos, percentFunction))
  1618. {
  1619. return false;
  1620. }
  1621. if(!this->GetNextInt(inputLine, pos, branchCovered))
  1622. {
  1623. return false;
  1624. }
  1625. if(!this->GetNextInt(inputLine, pos, totalBranches))
  1626. {
  1627. return false;
  1628. }
  1629. if(!this->GetNextInt(inputLine, pos, percentBranch))
  1630. {
  1631. return false;
  1632. }
  1633. // should be at the end now
  1634. if(pos != inputLine.npos)
  1635. {
  1636. cmCTestLog(this->CTest, ERROR_MESSAGE, "Error parsing input : "
  1637. << inputLine.c_str() << " last pos not npos = " << pos <<
  1638. "\n");
  1639. }
  1640. return true;
  1641. }
  1642. //----------------------------------------------------------------------
  1643. int cmCTestCoverageHandler::GetLabelId(std::string const& label)
  1644. {
  1645. LabelIdMapType::iterator i = this->LabelIdMap.find(label);
  1646. if(i == this->LabelIdMap.end())
  1647. {
  1648. int n = int(this->Labels.size());
  1649. this->Labels.push_back(label);
  1650. LabelIdMapType::value_type entry(label, n);
  1651. i = this->LabelIdMap.insert(entry).first;
  1652. }
  1653. return i->second;
  1654. }
  1655. //----------------------------------------------------------------------
  1656. void cmCTestCoverageHandler::LoadLabels()
  1657. {
  1658. std::string fileList = this->CTest->GetBinaryDir();
  1659. fileList += cmake::GetCMakeFilesDirectory();
  1660. fileList += "/TargetDirectories.txt";
  1661. cmCTestLog(this->CTest, HANDLER_VERBOSE_OUTPUT,
  1662. " target directory list [" << fileList << "]\n");
  1663. std::ifstream finList(fileList.c_str());
  1664. std::string line;
  1665. while(cmSystemTools::GetLineFromStream(finList, line))
  1666. {
  1667. this->LoadLabels(line.c_str());
  1668. }
  1669. }
  1670. //----------------------------------------------------------------------
  1671. void cmCTestCoverageHandler::LoadLabels(const char* dir)
  1672. {
  1673. LabelSet& dirLabels = this->TargetDirs[dir];
  1674. std::string fname = dir;
  1675. fname += "/Labels.txt";
  1676. std::ifstream fin(fname.c_str());
  1677. if(!fin)
  1678. {
  1679. return;
  1680. }
  1681. cmCTestLog(this->CTest, HANDLER_VERBOSE_OUTPUT,
  1682. " loading labels from [" << fname << "]\n");
  1683. bool inTarget = true;
  1684. std::string source;
  1685. std::string line;
  1686. std::vector<int> targetLabels;
  1687. while(cmSystemTools::GetLineFromStream(fin, line))
  1688. {
  1689. if(line.empty() || line[0] == '#')
  1690. {
  1691. // Ignore blank and comment lines.
  1692. continue;
  1693. }
  1694. else if(line[0] == ' ')
  1695. {
  1696. // Label lines appear indented by one space.
  1697. std::string label = line.substr(1);
  1698. int id = this->GetLabelId(label);
  1699. dirLabels.insert(id);
  1700. if(inTarget)
  1701. {
  1702. targetLabels.push_back(id);
  1703. }
  1704. else
  1705. {
  1706. this->SourceLabels[source].insert(id);
  1707. }
  1708. }
  1709. else
  1710. {
  1711. // Non-indented lines specify a source file name. The first one
  1712. // is the end of the target-wide labels.
  1713. inTarget = false;
  1714. source = this->CTest->GetShortPathToFile(line.c_str());
  1715. // Label the source with the target labels.
  1716. LabelSet& labelSet = this->SourceLabels[source];
  1717. for(std::vector<int>::const_iterator li = targetLabels.begin();
  1718. li != targetLabels.end(); ++li)
  1719. {
  1720. labelSet.insert(*li);
  1721. }
  1722. }
  1723. }
  1724. }
  1725. //----------------------------------------------------------------------
  1726. void cmCTestCoverageHandler::WriteXMLLabels(std::ofstream& os,
  1727. std::string const& source)
  1728. {
  1729. LabelMapType::const_iterator li = this->SourceLabels.find(source);
  1730. if(li != this->SourceLabels.end() && !li->second.empty())
  1731. {
  1732. os << "\t\t<Labels>\n";
  1733. for(LabelSet::const_iterator lsi = li->second.begin();
  1734. lsi != li->second.end(); ++lsi)
  1735. {
  1736. os << "\t\t\t<Label>" << cmXMLSafe(this->Labels[*lsi]) << "</Label>\n";
  1737. }
  1738. os << "\t\t</Labels>\n";
  1739. }
  1740. }
  1741. //----------------------------------------------------------------------------
  1742. void
  1743. cmCTestCoverageHandler::SetLabelFilter(std::set<cmStdString> const& labels)
  1744. {
  1745. this->LabelFilter.clear();
  1746. for(std::set<cmStdString>::const_iterator li = labels.begin();
  1747. li != labels.end(); ++li)
  1748. {
  1749. this->LabelFilter.insert(this->GetLabelId(*li));
  1750. }
  1751. }
  1752. //----------------------------------------------------------------------
  1753. bool cmCTestCoverageHandler::IntersectsFilter(LabelSet const& labels)
  1754. {
  1755. // If there is no label filter then nothing is filtered out.
  1756. if(this->LabelFilter.empty())
  1757. {
  1758. return true;
  1759. }
  1760. std::vector<int> ids;
  1761. cmsys_stl::set_intersection
  1762. (labels.begin(), labels.end(),
  1763. this->LabelFilter.begin(), this->LabelFilter.end(),
  1764. cmsys_stl::back_inserter(ids));
  1765. return !ids.empty();
  1766. }
  1767. //----------------------------------------------------------------------
  1768. bool cmCTestCoverageHandler::IsFilteredOut(std::string const& source)
  1769. {
  1770. // If there is no label filter then nothing is filtered out.
  1771. if(this->LabelFilter.empty())
  1772. {
  1773. return false;
  1774. }
  1775. // The source is filtered out if it does not have any labels in
  1776. // common with the filter set.
  1777. std::string shortSrc = this->CTest->GetShortPathToFile(source.c_str());
  1778. LabelMapType::const_iterator li = this->SourceLabels.find(shortSrc);
  1779. if(li != this->SourceLabels.end())
  1780. {
  1781. return !this->IntersectsFilter(li->second);
  1782. }
  1783. return true;
  1784. }