cmCTestCoverageHandler.cxx 53 KB

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