cmCTestCoverageHandler.cxx 55 KB

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