cmCTestCoverageHandler.cxx 65 KB

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