cmCTestCoverageHandler.cxx 51 KB

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