cmCTestMemCheckHandler.cxx 51 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404
  1. /* Distributed under the OSI-approved BSD 3-Clause License. See accompanying
  2. file Copyright.txt or https://cmake.org/licensing for details. */
  3. #include "cmCTestMemCheckHandler.h"
  4. #include <algorithm>
  5. #include <chrono>
  6. #include <cstring>
  7. #include <iostream>
  8. #include <iterator>
  9. #include <sstream>
  10. #include <utility>
  11. #include <cmext/algorithm>
  12. #include "cmsys/FStream.hxx"
  13. #include "cmsys/Glob.hxx"
  14. #include "cmsys/RegularExpression.hxx"
  15. #include "cmCTest.h"
  16. #include "cmDuration.h"
  17. #include "cmSystemTools.h"
  18. #include "cmXMLParser.h"
  19. #include "cmXMLWriter.h"
  20. struct CatToErrorType
  21. {
  22. const char* ErrorCategory;
  23. int ErrorCode;
  24. };
  25. static CatToErrorType cmCTestMemCheckBoundsChecker[] = {
  26. // Error tags
  27. { "Write Overrun", cmCTestMemCheckHandler::ABW },
  28. { "Read Overrun", cmCTestMemCheckHandler::ABR },
  29. { "Memory Overrun", cmCTestMemCheckHandler::ABW },
  30. { "Allocation Conflict", cmCTestMemCheckHandler::FMM },
  31. { "Bad Pointer Use", cmCTestMemCheckHandler::FMW },
  32. { "Dangling Pointer", cmCTestMemCheckHandler::FMR },
  33. { nullptr, 0 }
  34. };
  35. static void xmlReportError(int line, const char* msg, void* data)
  36. {
  37. cmCTest* ctest = static_cast<cmCTest*>(data);
  38. cmCTestLog(ctest, ERROR_MESSAGE,
  39. "Error parsing XML in stream at line " << line << ": " << msg
  40. << std::endl);
  41. }
  42. // parse the xml file containing the results of last BoundsChecker run
  43. class cmBoundsCheckerParser : public cmXMLParser
  44. {
  45. public:
  46. cmBoundsCheckerParser(cmCTest* c)
  47. {
  48. this->CTest = c;
  49. this->SetErrorCallback(xmlReportError, c);
  50. }
  51. void StartElement(const std::string& name, const char** atts) override
  52. {
  53. if (name == "MemoryLeak" || name == "ResourceLeak") {
  54. this->Errors.push_back(cmCTestMemCheckHandler::MLK);
  55. } else if (name == "Error" || name == "Dangling Pointer") {
  56. this->ParseError(atts);
  57. }
  58. // Create the log
  59. std::ostringstream ostr;
  60. ostr << name << ":\n";
  61. int i = 0;
  62. for (; atts[i] != nullptr; i += 2) {
  63. ostr << " " << atts[i] << " - " << atts[i + 1] << "\n";
  64. }
  65. ostr << "\n";
  66. this->Log += ostr.str();
  67. }
  68. void EndElement(const std::string& /*name*/) override {}
  69. const char* GetAttribute(const char* name, const char** atts)
  70. {
  71. int i = 0;
  72. for (; atts[i] != nullptr; ++i) {
  73. if (strcmp(name, atts[i]) == 0) {
  74. return atts[i + 1];
  75. }
  76. }
  77. return nullptr;
  78. }
  79. void ParseError(const char** atts)
  80. {
  81. CatToErrorType* ptr = cmCTestMemCheckBoundsChecker;
  82. const char* cat = this->GetAttribute("ErrorCategory", atts);
  83. if (!cat) {
  84. this->Errors.push_back(cmCTestMemCheckHandler::ABW); // do not know
  85. cmCTestLog(this->CTest, ERROR_MESSAGE,
  86. "No Category found in Bounds checker XML\n");
  87. return;
  88. }
  89. while (ptr->ErrorCategory && cat) {
  90. if (strcmp(ptr->ErrorCategory, cat) == 0) {
  91. this->Errors.push_back(ptr->ErrorCode);
  92. return; // found it we are done
  93. }
  94. ptr++;
  95. }
  96. if (ptr->ErrorCategory) {
  97. this->Errors.push_back(cmCTestMemCheckHandler::ABW); // do not know
  98. cmCTestLog(this->CTest, ERROR_MESSAGE,
  99. "Found unknown Bounds Checker error " << ptr->ErrorCategory
  100. << std::endl);
  101. }
  102. }
  103. cmCTest* CTest;
  104. std::vector<int> Errors;
  105. std::string Log;
  106. };
  107. #define BOUNDS_CHECKER_MARKER \
  108. "******######*****Begin BOUNDS CHECKER XML******######******"
  109. cmCTestMemCheckHandler::cmCTestMemCheckHandler()
  110. {
  111. this->MemCheck = true;
  112. this->CustomMaximumPassedTestOutputSize = 0;
  113. this->CustomMaximumFailedTestOutputSize = 0;
  114. this->LogWithPID = false;
  115. }
  116. void cmCTestMemCheckHandler::Initialize()
  117. {
  118. this->Superclass::Initialize();
  119. this->LogWithPID = false;
  120. this->CustomMaximumPassedTestOutputSize = 0;
  121. this->CustomMaximumFailedTestOutputSize = 0;
  122. this->MemoryTester.clear();
  123. this->MemoryTesterDynamicOptions.clear();
  124. this->MemoryTesterOptions.clear();
  125. this->MemoryTesterStyle = UNKNOWN;
  126. this->MemoryTesterOutputFile.clear();
  127. this->DefectCount = 0;
  128. }
  129. int cmCTestMemCheckHandler::PreProcessHandler()
  130. {
  131. if (!this->InitializeMemoryChecking()) {
  132. return 0;
  133. }
  134. if (!this->ExecuteCommands(this->CustomPreMemCheck)) {
  135. cmCTestLog(this->CTest, ERROR_MESSAGE,
  136. "Problem executing pre-memcheck command(s)." << std::endl);
  137. return 0;
  138. }
  139. return 1;
  140. }
  141. int cmCTestMemCheckHandler::PostProcessHandler()
  142. {
  143. if (!this->ExecuteCommands(this->CustomPostMemCheck)) {
  144. cmCTestLog(this->CTest, ERROR_MESSAGE,
  145. "Problem executing post-memcheck command(s)." << std::endl);
  146. return 0;
  147. }
  148. return 1;
  149. }
  150. void cmCTestMemCheckHandler::GenerateTestCommand(
  151. std::vector<std::string>& args, int test)
  152. {
  153. std::string index = std::to_string(test);
  154. std::string memcheckcommand =
  155. cmSystemTools::ConvertToOutputPath(this->MemoryTester);
  156. std::vector<std::string> dirs;
  157. bool nextArgIsDir = false;
  158. for (std::string arg : this->MemoryTesterDynamicOptions) {
  159. std::string::size_type pos = arg.find("??");
  160. if (pos != std::string::npos) {
  161. arg.replace(pos, 2, index);
  162. }
  163. args.push_back(arg);
  164. memcheckcommand += " \"";
  165. memcheckcommand += arg;
  166. memcheckcommand += "\"";
  167. if (nextArgIsDir) {
  168. nextArgIsDir = false;
  169. dirs.push_back(arg);
  170. }
  171. if (this->MemoryTesterStyle == cmCTestMemCheckHandler::DRMEMORY &&
  172. (arg == "-logdir" || arg == "-symcache_dir")) {
  173. nextArgIsDir = true;
  174. }
  175. }
  176. // Create a copy of the memory tester environment variable.
  177. // This is used for memory testing programs that pass options
  178. // via environment variables.
  179. std::string memTesterEnvironmentVariable =
  180. this->MemoryTesterEnvironmentVariable;
  181. for (std::string const& arg : this->MemoryTesterOptions) {
  182. if (!memTesterEnvironmentVariable.empty()) {
  183. // If we are using env to pass options, append all the options to
  184. // this string with space separation.
  185. memTesterEnvironmentVariable += " " + arg;
  186. }
  187. // for regular options just add them to args and memcheckcommand
  188. // which is just used for display
  189. else {
  190. args.push_back(arg);
  191. memcheckcommand += " \"";
  192. memcheckcommand += arg;
  193. memcheckcommand += "\"";
  194. }
  195. }
  196. // if this is an env option type, then add the env string as a single
  197. // argument.
  198. if (!memTesterEnvironmentVariable.empty()) {
  199. std::string::size_type pos = memTesterEnvironmentVariable.find("??");
  200. if (pos != std::string::npos) {
  201. memTesterEnvironmentVariable.replace(pos, 2, index);
  202. }
  203. memcheckcommand += " " + memTesterEnvironmentVariable;
  204. args.push_back(memTesterEnvironmentVariable);
  205. }
  206. for (std::string const& dir : dirs) {
  207. cmSystemTools::MakeDirectory(dir);
  208. }
  209. cmCTestOptionalLog(this->CTest, HANDLER_VERBOSE_OUTPUT,
  210. "Memory check command: " << memcheckcommand << std::endl,
  211. this->Quiet);
  212. }
  213. void cmCTestMemCheckHandler::InitializeResultsVectors()
  214. {
  215. // fill these members
  216. // cmsys::vector<std::string> ResultStrings;
  217. // cmsys::vector<std::string> ResultStringsLong;
  218. // cmsys::vector<int> GlobalResults;
  219. this->ResultStringsLong.clear();
  220. this->ResultStrings.clear();
  221. this->GlobalResults.clear();
  222. // If we are working with style checkers that dynamically fill
  223. // the results strings then return.
  224. if (this->MemoryTesterStyle > cmCTestMemCheckHandler::BOUNDS_CHECKER) {
  225. return;
  226. }
  227. // define the standard set of errors
  228. //----------------------------------------------------------------------
  229. static const char* cmCTestMemCheckResultStrings[] = {
  230. "ABR", "ABW", "ABWL", "COR", "EXU", "FFM", "FIM", "FMM",
  231. "FMR", "FMW", "FUM", "IPR", "IPW", "MAF", "MLK", "MPK",
  232. "NPR", "ODS", "PAR", "PLK", "UMC", "UMR", nullptr
  233. };
  234. static const char* cmCTestMemCheckResultLongStrings[] = {
  235. "Threading Problem",
  236. "ABW",
  237. "ABWL",
  238. "COR",
  239. "EXU",
  240. "FFM",
  241. "FIM",
  242. "Mismatched deallocation",
  243. "FMR",
  244. "FMW",
  245. "FUM",
  246. "IPR",
  247. "IPW",
  248. "MAF",
  249. "Memory Leak",
  250. "Potential Memory Leak",
  251. "NPR",
  252. "ODS",
  253. "Invalid syscall param",
  254. "PLK",
  255. "Uninitialized Memory Conditional",
  256. "Uninitialized Memory Read",
  257. nullptr
  258. };
  259. this->GlobalResults.clear();
  260. for (int i = 0; cmCTestMemCheckResultStrings[i] != nullptr; ++i) {
  261. this->ResultStrings.emplace_back(cmCTestMemCheckResultStrings[i]);
  262. this->ResultStringsLong.emplace_back(cmCTestMemCheckResultLongStrings[i]);
  263. this->GlobalResults.push_back(0);
  264. }
  265. }
  266. void cmCTestMemCheckHandler::PopulateCustomVectors(cmMakefile* mf)
  267. {
  268. this->cmCTestTestHandler::PopulateCustomVectors(mf);
  269. this->CTest->PopulateCustomVector(mf, "CTEST_CUSTOM_PRE_MEMCHECK",
  270. this->CustomPreMemCheck);
  271. this->CTest->PopulateCustomVector(mf, "CTEST_CUSTOM_POST_MEMCHECK",
  272. this->CustomPostMemCheck);
  273. this->CTest->PopulateCustomVector(mf, "CTEST_CUSTOM_MEMCHECK_IGNORE",
  274. this->CustomTestsIgnore);
  275. }
  276. int cmCTestMemCheckHandler::GetDefectCount() const
  277. {
  278. return this->DefectCount;
  279. }
  280. void cmCTestMemCheckHandler::GenerateCTestXML(cmXMLWriter& xml)
  281. {
  282. if (!this->CTest->GetProduceXML()) {
  283. return;
  284. }
  285. this->CTest->StartXML(xml, this->AppendXML);
  286. this->CTest->GenerateSubprojectsOutput(xml);
  287. xml.StartElement("DynamicAnalysis");
  288. switch (this->MemoryTesterStyle) {
  289. case cmCTestMemCheckHandler::VALGRIND:
  290. xml.Attribute("Checker", "Valgrind");
  291. break;
  292. case cmCTestMemCheckHandler::DRMEMORY:
  293. xml.Attribute("Checker", "DrMemory");
  294. break;
  295. case cmCTestMemCheckHandler::PURIFY:
  296. xml.Attribute("Checker", "Purify");
  297. break;
  298. case cmCTestMemCheckHandler::BOUNDS_CHECKER:
  299. xml.Attribute("Checker", "BoundsChecker");
  300. break;
  301. case cmCTestMemCheckHandler::CUDA_SANITIZER:
  302. xml.Attribute("Checker", "CudaSanitizer");
  303. break;
  304. case cmCTestMemCheckHandler::ADDRESS_SANITIZER:
  305. xml.Attribute("Checker", "AddressSanitizer");
  306. break;
  307. case cmCTestMemCheckHandler::LEAK_SANITIZER:
  308. xml.Attribute("Checker", "LeakSanitizer");
  309. break;
  310. case cmCTestMemCheckHandler::THREAD_SANITIZER:
  311. xml.Attribute("Checker", "ThreadSanitizer");
  312. break;
  313. case cmCTestMemCheckHandler::MEMORY_SANITIZER:
  314. xml.Attribute("Checker", "MemorySanitizer");
  315. break;
  316. case cmCTestMemCheckHandler::UB_SANITIZER:
  317. xml.Attribute("Checker", "UndefinedBehaviorSanitizer");
  318. break;
  319. default:
  320. xml.Attribute("Checker", "Unknown");
  321. }
  322. xml.Element("StartDateTime", this->StartTest);
  323. xml.Element("StartTestTime", this->StartTestTime);
  324. xml.StartElement("TestList");
  325. cmCTestMemCheckHandler::TestResultsVector::size_type cc;
  326. for (cmCTestTestResult const& result : this->TestResults) {
  327. std::string testPath = result.Path + "/" + result.Name;
  328. xml.Element("Test", this->CTest->GetShortPathToFile(testPath));
  329. }
  330. xml.EndElement(); // TestList
  331. cmCTestOptionalLog(this->CTest, HANDLER_OUTPUT,
  332. "-- Processing memory checking output:\n", this->Quiet);
  333. size_t total = this->TestResults.size();
  334. for (cc = 0; cc < this->TestResults.size(); cc++) {
  335. cmCTestTestResult const& result = this->TestResults[cc];
  336. std::string memcheckstr;
  337. std::vector<int> memcheckresults(this->ResultStrings.size(), 0);
  338. bool res =
  339. this->ProcessMemCheckOutput(result.Output, memcheckstr, memcheckresults);
  340. if (res && result.Status == cmCTestMemCheckHandler::COMPLETED) {
  341. continue;
  342. }
  343. this->CleanTestOutput(
  344. memcheckstr,
  345. static_cast<size_t>(this->CustomMaximumFailedTestOutputSize));
  346. this->WriteTestResultHeader(xml, result);
  347. xml.StartElement("Results");
  348. int memoryErrors = 0;
  349. for (std::vector<int>::size_type kk = 0; kk < memcheckresults.size();
  350. ++kk) {
  351. if (memcheckresults[kk]) {
  352. xml.StartElement("Defect");
  353. xml.Attribute("type", this->ResultStringsLong[kk]);
  354. xml.Content(memcheckresults[kk]);
  355. memoryErrors += memcheckresults[kk];
  356. xml.EndElement(); // Defect
  357. }
  358. this->GlobalResults[kk] += memcheckresults[kk];
  359. }
  360. xml.EndElement(); // Results
  361. if (memoryErrors > 0) {
  362. const int maxTestNameWidth = this->CTest->GetMaxTestNameWidth();
  363. std::string outname = result.Name + " ";
  364. outname.resize(maxTestNameWidth + 4, '.');
  365. cmCTestOptionalLog(this->CTest, HANDLER_OUTPUT,
  366. cc + 1 << "/" << total << " MemCheck: #"
  367. << result.TestCount << ": " << outname
  368. << " Defects: " << memoryErrors << std::endl,
  369. this->Quiet);
  370. }
  371. xml.StartElement("Log");
  372. if (this->CTest->ShouldCompressTestOutput()) {
  373. this->CTest->CompressString(memcheckstr);
  374. xml.Attribute("compression", "gzip");
  375. xml.Attribute("encoding", "base64");
  376. }
  377. xml.Content(memcheckstr);
  378. xml.EndElement(); // Log
  379. this->WriteTestResultFooter(xml, result);
  380. }
  381. cmCTestOptionalLog(this->CTest, HANDLER_OUTPUT,
  382. "MemCheck log files can be found here: "
  383. "(<#> corresponds to test number)"
  384. << std::endl,
  385. this->Quiet);
  386. std::string output = this->MemoryTesterOutputFile;
  387. cmSystemTools::ReplaceString(output, "??", "<#>");
  388. cmCTestOptionalLog(this->CTest, HANDLER_OUTPUT, output << std::endl,
  389. this->Quiet);
  390. cmCTestOptionalLog(this->CTest, HANDLER_OUTPUT,
  391. "Memory checking results:" << std::endl, this->Quiet);
  392. xml.StartElement("DefectList");
  393. for (cc = 0; cc < this->GlobalResults.size(); cc++) {
  394. if (this->GlobalResults[cc]) {
  395. std::cerr.width(35);
  396. cmCTestOptionalLog(this->CTest, HANDLER_OUTPUT,
  397. this->ResultStringsLong[cc]
  398. << " - " << this->GlobalResults[cc] << std::endl,
  399. this->Quiet);
  400. xml.StartElement("Defect");
  401. xml.Attribute("Type", this->ResultStringsLong[cc]);
  402. xml.EndElement();
  403. }
  404. }
  405. xml.EndElement(); // DefectList
  406. xml.Element("EndDateTime", this->EndTest);
  407. xml.Element("EndTestTime", this->EndTestTime);
  408. xml.Element(
  409. "ElapsedMinutes",
  410. std::chrono::duration_cast<std::chrono::minutes>(this->ElapsedTestingTime)
  411. .count());
  412. xml.EndElement(); // DynamicAnalysis
  413. this->CTest->EndXML(xml);
  414. }
  415. bool cmCTestMemCheckHandler::InitializeMemoryChecking()
  416. {
  417. this->MemoryTesterEnvironmentVariable.clear();
  418. this->MemoryTester.clear();
  419. // Setup the command
  420. if (cmSystemTools::FileExists(
  421. this->CTest->GetCTestConfiguration("MemoryCheckCommand"))) {
  422. this->MemoryTester =
  423. this->CTest->GetCTestConfiguration("MemoryCheckCommand");
  424. std::string testerName =
  425. cmSystemTools::GetFilenameName(this->MemoryTester);
  426. // determine the checker type
  427. if (testerName.find("valgrind") != std::string::npos ||
  428. this->CTest->GetCTestConfiguration("MemoryCheckType") == "Valgrind") {
  429. this->MemoryTesterStyle = cmCTestMemCheckHandler::VALGRIND;
  430. } else if (testerName.find("drmemory") != std::string::npos ||
  431. this->CTest->GetCTestConfiguration("MemoryCheckType") ==
  432. "DrMemory") {
  433. this->MemoryTesterStyle = cmCTestMemCheckHandler::DRMEMORY;
  434. } else if (testerName.find("purify") != std::string::npos) {
  435. this->MemoryTesterStyle = cmCTestMemCheckHandler::PURIFY;
  436. } else if (testerName.find("BC") != std::string::npos) {
  437. this->MemoryTesterStyle = cmCTestMemCheckHandler::BOUNDS_CHECKER;
  438. } else if (testerName.find("cuda-memcheck") != std::string::npos ||
  439. testerName.find("compute-sanitizer") != std::string::npos) {
  440. this->MemoryTesterStyle = cmCTestMemCheckHandler::CUDA_SANITIZER;
  441. } else {
  442. this->MemoryTesterStyle = cmCTestMemCheckHandler::UNKNOWN;
  443. }
  444. } else if (cmSystemTools::FileExists(
  445. this->CTest->GetCTestConfiguration("PurifyCommand"))) {
  446. this->MemoryTester = this->CTest->GetCTestConfiguration("PurifyCommand");
  447. this->MemoryTesterStyle = cmCTestMemCheckHandler::PURIFY;
  448. } else if (cmSystemTools::FileExists(
  449. this->CTest->GetCTestConfiguration("ValgrindCommand"))) {
  450. this->MemoryTester = this->CTest->GetCTestConfiguration("ValgrindCommand");
  451. this->MemoryTesterStyle = cmCTestMemCheckHandler::VALGRIND;
  452. } else if (cmSystemTools::FileExists(
  453. this->CTest->GetCTestConfiguration("DrMemoryCommand"))) {
  454. this->MemoryTester = this->CTest->GetCTestConfiguration("DrMemoryCommand");
  455. this->MemoryTesterStyle = cmCTestMemCheckHandler::DRMEMORY;
  456. } else if (cmSystemTools::FileExists(
  457. this->CTest->GetCTestConfiguration("BoundsCheckerCommand"))) {
  458. this->MemoryTester =
  459. this->CTest->GetCTestConfiguration("BoundsCheckerCommand");
  460. this->MemoryTesterStyle = cmCTestMemCheckHandler::BOUNDS_CHECKER;
  461. } else if (cmSystemTools::FileExists(
  462. this->CTest->GetCTestConfiguration("CudaSanitizerCommand"))) {
  463. this->MemoryTester =
  464. this->CTest->GetCTestConfiguration("CudaSanitizerCommand");
  465. this->MemoryTesterStyle = cmCTestMemCheckHandler::CUDA_SANITIZER;
  466. }
  467. if (this->CTest->GetCTestConfiguration("MemoryCheckType") ==
  468. "AddressSanitizer") {
  469. this->MemoryTester = cmSystemTools::GetCMakeCommand();
  470. this->MemoryTesterStyle = cmCTestMemCheckHandler::ADDRESS_SANITIZER;
  471. this->LogWithPID = true; // even if we give the log file the pid is added
  472. }
  473. if (this->CTest->GetCTestConfiguration("MemoryCheckType") ==
  474. "LeakSanitizer") {
  475. this->MemoryTester = cmSystemTools::GetCMakeCommand();
  476. this->MemoryTesterStyle = cmCTestMemCheckHandler::LEAK_SANITIZER;
  477. this->LogWithPID = true; // even if we give the log file the pid is added
  478. }
  479. if (this->CTest->GetCTestConfiguration("MemoryCheckType") ==
  480. "ThreadSanitizer") {
  481. this->MemoryTester = cmSystemTools::GetCMakeCommand();
  482. this->MemoryTesterStyle = cmCTestMemCheckHandler::THREAD_SANITIZER;
  483. this->LogWithPID = true; // even if we give the log file the pid is added
  484. }
  485. if (this->CTest->GetCTestConfiguration("MemoryCheckType") ==
  486. "MemorySanitizer") {
  487. this->MemoryTester = cmSystemTools::GetCMakeCommand();
  488. this->MemoryTesterStyle = cmCTestMemCheckHandler::MEMORY_SANITIZER;
  489. this->LogWithPID = true; // even if we give the log file the pid is added
  490. }
  491. if (this->CTest->GetCTestConfiguration("MemoryCheckType") ==
  492. "UndefinedBehaviorSanitizer") {
  493. this->MemoryTester = cmSystemTools::GetCMakeCommand();
  494. this->MemoryTesterStyle = cmCTestMemCheckHandler::UB_SANITIZER;
  495. this->LogWithPID = true; // even if we give the log file the pid is added
  496. }
  497. // Check the MemoryCheckType
  498. if (this->MemoryTesterStyle == cmCTestMemCheckHandler::UNKNOWN) {
  499. std::string checkType =
  500. this->CTest->GetCTestConfiguration("MemoryCheckType");
  501. if (checkType == "Purify") {
  502. this->MemoryTesterStyle = cmCTestMemCheckHandler::PURIFY;
  503. } else if (checkType == "BoundsChecker") {
  504. this->MemoryTesterStyle = cmCTestMemCheckHandler::BOUNDS_CHECKER;
  505. } else if (checkType == "Valgrind") {
  506. this->MemoryTesterStyle = cmCTestMemCheckHandler::VALGRIND;
  507. } else if (checkType == "DrMemory") {
  508. this->MemoryTesterStyle = cmCTestMemCheckHandler::DRMEMORY;
  509. } else if (checkType == "CudaSanitizer") {
  510. this->MemoryTesterStyle = cmCTestMemCheckHandler::CUDA_SANITIZER;
  511. }
  512. }
  513. if (this->MemoryTester.empty()) {
  514. cmCTestOptionalLog(this->CTest, WARNING,
  515. "Memory checker (MemoryCheckCommand) "
  516. "not set, or cannot find the specified program."
  517. << std::endl,
  518. this->Quiet);
  519. return false;
  520. }
  521. // Setup the options
  522. std::string memoryTesterOptions;
  523. if (!this->CTest->GetCTestConfiguration("MemoryCheckCommandOptions")
  524. .empty()) {
  525. memoryTesterOptions =
  526. this->CTest->GetCTestConfiguration("MemoryCheckCommandOptions");
  527. } else if (!this->CTest->GetCTestConfiguration("ValgrindCommandOptions")
  528. .empty()) {
  529. memoryTesterOptions =
  530. this->CTest->GetCTestConfiguration("ValgrindCommandOptions");
  531. } else if (!this->CTest->GetCTestConfiguration("DrMemoryCommandOptions")
  532. .empty()) {
  533. memoryTesterOptions =
  534. this->CTest->GetCTestConfiguration("DrMemoryCommandOptions");
  535. } else if (!this->CTest->GetCTestConfiguration("CudaSanitizerCommandOptions")
  536. .empty()) {
  537. memoryTesterOptions =
  538. this->CTest->GetCTestConfiguration("CudaSanitizerCommandOptions");
  539. }
  540. this->MemoryTesterOptions =
  541. cmSystemTools::ParseArguments(memoryTesterOptions);
  542. this->MemoryTesterOutputFile =
  543. this->CTest->GetBinaryDir() + "/Testing/Temporary/MemoryChecker.??.log";
  544. switch (this->MemoryTesterStyle) {
  545. case cmCTestMemCheckHandler::VALGRIND: {
  546. if (this->MemoryTesterOptions.empty()) {
  547. this->MemoryTesterOptions.emplace_back("-q");
  548. this->MemoryTesterOptions.emplace_back("--tool=memcheck");
  549. this->MemoryTesterOptions.emplace_back("--leak-check=yes");
  550. this->MemoryTesterOptions.emplace_back("--show-reachable=yes");
  551. this->MemoryTesterOptions.emplace_back("--num-callers=50");
  552. }
  553. if (!this->CTest->GetCTestConfiguration("MemoryCheckSuppressionFile")
  554. .empty()) {
  555. if (!cmSystemTools::FileExists(this->CTest->GetCTestConfiguration(
  556. "MemoryCheckSuppressionFile"))) {
  557. cmCTestLog(this->CTest, ERROR_MESSAGE,
  558. "Cannot find memory checker suppression file: "
  559. << this->CTest->GetCTestConfiguration(
  560. "MemoryCheckSuppressionFile")
  561. << std::endl);
  562. return false;
  563. }
  564. this->MemoryTesterOptions.push_back(
  565. "--suppressions=" +
  566. this->CTest->GetCTestConfiguration("MemoryCheckSuppressionFile"));
  567. }
  568. this->MemoryTesterDynamicOptions.push_back("--log-file=" +
  569. this->MemoryTesterOutputFile);
  570. break;
  571. }
  572. case cmCTestMemCheckHandler::DRMEMORY: {
  573. std::string tempDrMemoryDir =
  574. this->CTest->GetBinaryDir() + "/Testing/Temporary/DrMemory";
  575. if (!cm::contains(this->MemoryTesterOptions, "-quiet")) {
  576. this->MemoryTesterOptions.emplace_back("-quiet");
  577. }
  578. if (!cm::contains(this->MemoryTesterOptions, "-batch")) {
  579. this->MemoryTesterOptions.emplace_back("-batch");
  580. }
  581. this->MemoryTesterDynamicOptions.emplace_back("-logdir");
  582. auto logdirOption =
  583. std::find(this->MemoryTesterOptions.begin(),
  584. this->MemoryTesterOptions.end(), "-logdir");
  585. if (logdirOption == this->MemoryTesterOptions.end()) {
  586. // No logdir found in memory tester options
  587. std::string drMemoryLogDir = tempDrMemoryDir + "/??";
  588. this->MemoryTesterDynamicOptions.push_back(drMemoryLogDir);
  589. this->MemoryTesterOutputFile = drMemoryLogDir;
  590. } else {
  591. // Use logdir found in memory tester options
  592. auto logdirLocation = std::next(logdirOption);
  593. this->MemoryTesterOutputFile = *logdirLocation;
  594. this->MemoryTesterDynamicOptions.push_back(*logdirLocation);
  595. this->MemoryTesterOptions.erase(logdirOption, logdirLocation + 1);
  596. }
  597. this->MemoryTesterOutputFile += "/*/results.txt";
  598. if (std::find(this->MemoryTesterOptions.begin(),
  599. this->MemoryTesterOptions.end(),
  600. "-symcache_dir") == this->MemoryTesterOptions.end()) {
  601. this->MemoryTesterDynamicOptions.emplace_back("-symcache_dir");
  602. std::string drMemoryCacheDir = tempDrMemoryDir + "/cache";
  603. this->MemoryTesterDynamicOptions.push_back(drMemoryCacheDir);
  604. }
  605. if (!this->CTest->GetCTestConfiguration("MemoryCheckSuppressionFile")
  606. .empty()) {
  607. if (!cmSystemTools::FileExists(this->CTest->GetCTestConfiguration(
  608. "MemoryCheckSuppressionFile"))) {
  609. cmCTestLog(this->CTest, ERROR_MESSAGE,
  610. "Cannot find memory checker suppression file: "
  611. << this->CTest->GetCTestConfiguration(
  612. "MemoryCheckSuppressionFile")
  613. << std::endl);
  614. return false;
  615. }
  616. this->MemoryTesterOptions.emplace_back("-suppress");
  617. this->MemoryTesterOptions.push_back(
  618. this->CTest->GetCTestConfiguration("MemoryCheckSuppressionFile"));
  619. }
  620. this->MemoryTesterOptions.emplace_back("--");
  621. break;
  622. }
  623. case cmCTestMemCheckHandler::PURIFY: {
  624. std::string outputFile;
  625. #ifdef _WIN32
  626. if (this->CTest->GetCTestConfiguration("MemoryCheckSuppressionFile")
  627. .size()) {
  628. if (!cmSystemTools::FileExists(this->CTest->GetCTestConfiguration(
  629. "MemoryCheckSuppressionFile"))) {
  630. cmCTestLog(
  631. this->CTest, ERROR_MESSAGE,
  632. "Cannot find memory checker suppression file: "
  633. << this->CTest
  634. ->GetCTestConfiguration("MemoryCheckSuppressionFile")
  635. .c_str()
  636. << std::endl);
  637. return false;
  638. }
  639. std::string filterFiles = "/FilterFiles=" +
  640. this->CTest->GetCTestConfiguration("MemoryCheckSuppressionFile");
  641. this->MemoryTesterOptions.push_back(filterFiles);
  642. }
  643. outputFile = "/SAVETEXTDATA=";
  644. #else
  645. outputFile = "-log-file=";
  646. #endif
  647. outputFile += this->MemoryTesterOutputFile;
  648. this->MemoryTesterDynamicOptions.push_back(outputFile);
  649. break;
  650. }
  651. case cmCTestMemCheckHandler::BOUNDS_CHECKER: {
  652. this->BoundsCheckerXMLFile = this->MemoryTesterOutputFile;
  653. std::string dpbdFile = this->CTest->GetBinaryDir() +
  654. "/Testing/Temporary/MemoryChecker.??.DPbd";
  655. this->BoundsCheckerDPBDFile = dpbdFile;
  656. this->MemoryTesterDynamicOptions.emplace_back("/B");
  657. this->MemoryTesterDynamicOptions.push_back(std::move(dpbdFile));
  658. this->MemoryTesterDynamicOptions.emplace_back("/X");
  659. this->MemoryTesterDynamicOptions.push_back(this->MemoryTesterOutputFile);
  660. this->MemoryTesterOptions.emplace_back("/M");
  661. break;
  662. }
  663. case cmCTestMemCheckHandler::CUDA_SANITIZER: {
  664. // cuda sanitizer separates flags from arguments by spaces
  665. if (this->MemoryTesterOptions.empty()) {
  666. this->MemoryTesterOptions.emplace_back("--tool");
  667. this->MemoryTesterOptions.emplace_back("memcheck");
  668. this->MemoryTesterOptions.emplace_back("--leak-check");
  669. this->MemoryTesterOptions.emplace_back("full");
  670. }
  671. this->MemoryTesterDynamicOptions.emplace_back("--log-file");
  672. this->MemoryTesterDynamicOptions.push_back(this->MemoryTesterOutputFile);
  673. break;
  674. }
  675. // these are almost the same but the env var used is different
  676. case cmCTestMemCheckHandler::ADDRESS_SANITIZER:
  677. case cmCTestMemCheckHandler::LEAK_SANITIZER:
  678. case cmCTestMemCheckHandler::THREAD_SANITIZER:
  679. case cmCTestMemCheckHandler::MEMORY_SANITIZER:
  680. case cmCTestMemCheckHandler::UB_SANITIZER: {
  681. // To pass arguments to ThreadSanitizer the environment variable
  682. // TSAN_OPTIONS is used. This is done with the cmake -E env command.
  683. // The MemoryTesterDynamicOptions is setup with the -E env
  684. // Then the MemoryTesterEnvironmentVariable gets the
  685. // TSAN_OPTIONS string with the log_path in it.
  686. this->MemoryTesterDynamicOptions.emplace_back("-E");
  687. this->MemoryTesterDynamicOptions.emplace_back("env");
  688. std::string envVar;
  689. std::string extraOptions;
  690. std::string suppressionsOption;
  691. if (!this->CTest->GetCTestConfiguration("MemoryCheckSanitizerOptions")
  692. .empty()) {
  693. extraOptions = ":" +
  694. this->CTest->GetCTestConfiguration("MemoryCheckSanitizerOptions");
  695. }
  696. if (!this->CTest->GetCTestConfiguration("MemoryCheckSuppressionFile")
  697. .empty()) {
  698. suppressionsOption = ":suppressions=" +
  699. this->CTest->GetCTestConfiguration("MemoryCheckSuppressionFile");
  700. }
  701. if (this->MemoryTesterStyle ==
  702. cmCTestMemCheckHandler::ADDRESS_SANITIZER) {
  703. envVar = "ASAN_OPTIONS";
  704. } else if (this->MemoryTesterStyle ==
  705. cmCTestMemCheckHandler::LEAK_SANITIZER) {
  706. envVar = "LSAN_OPTIONS";
  707. } else if (this->MemoryTesterStyle ==
  708. cmCTestMemCheckHandler::THREAD_SANITIZER) {
  709. envVar = "TSAN_OPTIONS";
  710. } else if (this->MemoryTesterStyle ==
  711. cmCTestMemCheckHandler::MEMORY_SANITIZER) {
  712. envVar = "MSAN_OPTIONS";
  713. } else if (this->MemoryTesterStyle ==
  714. cmCTestMemCheckHandler::UB_SANITIZER) {
  715. envVar = "UBSAN_OPTIONS";
  716. }
  717. // Quote log_path with single quotes; see
  718. // https://bugs.chromium.org/p/chromium/issues/detail?id=467936
  719. std::string outputFile =
  720. envVar + "=log_path='" + this->MemoryTesterOutputFile + "'";
  721. this->MemoryTesterEnvironmentVariable =
  722. outputFile + suppressionsOption + extraOptions;
  723. break;
  724. }
  725. default:
  726. cmCTestLog(this->CTest, ERROR_MESSAGE,
  727. "Do not understand memory checker: " << this->MemoryTester
  728. << std::endl);
  729. return false;
  730. }
  731. this->InitializeResultsVectors();
  732. // std::vector<std::string>::size_type cc;
  733. // for ( cc = 0; cmCTestMemCheckResultStrings[cc]; cc ++ )
  734. // {
  735. // this->MemoryTesterGlobalResults[cc] = 0;
  736. // }
  737. return true;
  738. }
  739. bool cmCTestMemCheckHandler::ProcessMemCheckOutput(const std::string& str,
  740. std::string& log,
  741. std::vector<int>& results)
  742. {
  743. switch (this->MemoryTesterStyle) {
  744. case cmCTestMemCheckHandler::VALGRIND:
  745. return this->ProcessMemCheckValgrindOutput(str, log, results);
  746. case cmCTestMemCheckHandler::DRMEMORY:
  747. return this->ProcessMemCheckDrMemoryOutput(str, log, results);
  748. case cmCTestMemCheckHandler::PURIFY:
  749. return this->ProcessMemCheckPurifyOutput(str, log, results);
  750. case cmCTestMemCheckHandler::ADDRESS_SANITIZER:
  751. case cmCTestMemCheckHandler::LEAK_SANITIZER:
  752. case cmCTestMemCheckHandler::THREAD_SANITIZER:
  753. case cmCTestMemCheckHandler::MEMORY_SANITIZER:
  754. case cmCTestMemCheckHandler::UB_SANITIZER:
  755. return this->ProcessMemCheckSanitizerOutput(str, log, results);
  756. case cmCTestMemCheckHandler::BOUNDS_CHECKER:
  757. return this->ProcessMemCheckBoundsCheckerOutput(str, log, results);
  758. case cmCTestMemCheckHandler::CUDA_SANITIZER:
  759. return this->ProcessMemCheckCudaOutput(str, log, results);
  760. default:
  761. log.append("\nMemory checking style used was: ");
  762. log.append("None that I know");
  763. log = str;
  764. return true;
  765. }
  766. }
  767. std::vector<int>::size_type cmCTestMemCheckHandler::FindOrAddWarning(
  768. const std::string& warning)
  769. {
  770. for (std::vector<std::string>::size_type i = 0;
  771. i < this->ResultStrings.size(); ++i) {
  772. if (this->ResultStrings[i] == warning) {
  773. return i;
  774. }
  775. }
  776. this->GlobalResults.push_back(0); // this must stay the same size
  777. this->ResultStrings.push_back(warning);
  778. this->ResultStringsLong.push_back(warning);
  779. return this->ResultStrings.size() - 1;
  780. }
  781. bool cmCTestMemCheckHandler::ProcessMemCheckSanitizerOutput(
  782. const std::string& str, std::string& log, std::vector<int>& result)
  783. {
  784. std::string regex;
  785. switch (this->MemoryTesterStyle) {
  786. case cmCTestMemCheckHandler::ADDRESS_SANITIZER:
  787. regex = "ERROR: AddressSanitizer: (.*) on.*";
  788. break;
  789. case cmCTestMemCheckHandler::LEAK_SANITIZER:
  790. // use leakWarning regex
  791. break;
  792. case cmCTestMemCheckHandler::THREAD_SANITIZER:
  793. regex = "WARNING: ThreadSanitizer: (.*) \\(pid=.*\\)";
  794. break;
  795. case cmCTestMemCheckHandler::MEMORY_SANITIZER:
  796. regex = "WARNING: MemorySanitizer: (.*)";
  797. break;
  798. case cmCTestMemCheckHandler::UB_SANITIZER:
  799. regex = "runtime error: (.*)";
  800. break;
  801. default:
  802. break;
  803. }
  804. cmsys::RegularExpression sanitizerWarning(regex);
  805. cmsys::RegularExpression leakWarning("(Direct|Indirect) leak of .*");
  806. int defects = 0;
  807. std::vector<std::string> lines;
  808. cmsys::SystemTools::Split(str, lines);
  809. std::ostringstream ostr;
  810. log.clear();
  811. for (std::string const& l : lines) {
  812. std::string resultFound;
  813. if (leakWarning.find(l)) {
  814. resultFound = leakWarning.match(1) + " leak";
  815. } else if (sanitizerWarning.find(l)) {
  816. resultFound = sanitizerWarning.match(1);
  817. }
  818. if (!resultFound.empty()) {
  819. std::vector<int>::size_type idx = this->FindOrAddWarning(resultFound);
  820. if (result.empty() || idx > result.size() - 1) {
  821. result.push_back(1);
  822. } else {
  823. result[idx]++;
  824. }
  825. defects++;
  826. ostr << "<b>" << this->ResultStrings[idx] << "</b> ";
  827. }
  828. ostr << l << std::endl;
  829. }
  830. log = ostr.str();
  831. this->DefectCount += defects;
  832. return defects == 0;
  833. }
  834. bool cmCTestMemCheckHandler::ProcessMemCheckPurifyOutput(
  835. const std::string& str, std::string& log, std::vector<int>& results)
  836. {
  837. std::vector<std::string> lines;
  838. cmsys::SystemTools::Split(str, lines);
  839. std::ostringstream ostr;
  840. log.clear();
  841. cmsys::RegularExpression pfW("^\\[[WEI]\\] ([A-Z][A-Z][A-Z][A-Z]*): ");
  842. int defects = 0;
  843. for (std::string const& l : lines) {
  844. std::vector<int>::size_type failure = this->ResultStrings.size();
  845. if (pfW.find(l)) {
  846. std::vector<int>::size_type cc;
  847. for (cc = 0; cc < this->ResultStrings.size(); cc++) {
  848. if (pfW.match(1) == this->ResultStrings[cc]) {
  849. failure = cc;
  850. break;
  851. }
  852. }
  853. if (cc == this->ResultStrings.size()) {
  854. cmCTestLog(this->CTest, ERROR_MESSAGE,
  855. "Unknown Purify memory fault: " << pfW.match(1)
  856. << std::endl);
  857. ostr << "*** Unknown Purify memory fault: " << pfW.match(1)
  858. << std::endl;
  859. }
  860. }
  861. if (failure != this->ResultStrings.size()) {
  862. ostr << "<b>" << this->ResultStrings[failure] << "</b> ";
  863. results[failure]++;
  864. defects++;
  865. }
  866. ostr << l << std::endl;
  867. }
  868. log = ostr.str();
  869. this->DefectCount += defects;
  870. return defects == 0;
  871. }
  872. bool cmCTestMemCheckHandler::ProcessMemCheckValgrindOutput(
  873. const std::string& str, std::string& log, std::vector<int>& results)
  874. {
  875. std::vector<std::string> lines;
  876. cmsys::SystemTools::Split(str, lines);
  877. bool unlimitedOutput = false;
  878. if (str.find("CTEST_FULL_OUTPUT") != std::string::npos ||
  879. this->CustomMaximumFailedTestOutputSize == 0) {
  880. unlimitedOutput = true;
  881. }
  882. std::string::size_type cc;
  883. std::ostringstream ostr;
  884. log.clear();
  885. int defects = 0;
  886. cmsys::RegularExpression valgrindLine("^==[0-9][0-9]*==");
  887. cmsys::RegularExpression vgFIM(
  888. R"(== .*Invalid free\(\) / delete / delete\[\])");
  889. cmsys::RegularExpression vgFMM(
  890. R"(== .*Mismatched free\(\) / delete / delete \[\])");
  891. cmsys::RegularExpression vgMLK1(
  892. "== .*[0-9,]+ bytes in [0-9,]+ blocks are definitely lost"
  893. " in loss record [0-9,]+ of [0-9,]+");
  894. cmsys::RegularExpression vgMLK2(
  895. "== .*[0-9,]+ \\([0-9,]+ direct, [0-9,]+ indirect\\)"
  896. " bytes in [0-9,]+ blocks are definitely lost"
  897. " in loss record [0-9,]+ of [0-9,]+");
  898. cmsys::RegularExpression vgPAR(
  899. "== .*Syscall param .* (contains|points to) unaddressable byte\\(s\\)");
  900. cmsys::RegularExpression vgMPK1(
  901. "== .*[0-9,]+ bytes in [0-9,]+ blocks are possibly lost in"
  902. " loss record [0-9,]+ of [0-9,]+");
  903. cmsys::RegularExpression vgMPK2(
  904. "== .*[0-9,]+ bytes in [0-9,]+ blocks are still reachable"
  905. " in loss record [0-9,]+ of [0-9,]+");
  906. cmsys::RegularExpression vgUMC(
  907. "== .*Conditional jump or move depends on uninitialised value\\(s\\)");
  908. cmsys::RegularExpression vgUMR1(
  909. "== .*Use of uninitialised value of size [0-9,]+");
  910. cmsys::RegularExpression vgUMR2("== .*Invalid read of size [0-9,]+");
  911. cmsys::RegularExpression vgUMR3("== .*Jump to the invalid address ");
  912. cmsys::RegularExpression vgUMR4(
  913. "== .*Syscall param .* contains "
  914. "uninitialised or unaddressable byte\\(s\\)");
  915. cmsys::RegularExpression vgUMR5("== .*Syscall param .* uninitialised");
  916. cmsys::RegularExpression vgIPW("== .*Invalid write of size [0-9,]+");
  917. cmsys::RegularExpression vgABR("== .*pthread_mutex_unlock: mutex is "
  918. "locked by a different thread");
  919. std::vector<std::string::size_type> nonValGrindOutput;
  920. auto sttime = std::chrono::steady_clock::now();
  921. cmCTestOptionalLog(this->CTest, DEBUG,
  922. "Start test: " << lines.size() << std::endl, this->Quiet);
  923. std::string::size_type totalOutputSize = 0;
  924. for (cc = 0; cc < lines.size(); cc++) {
  925. cmCTestOptionalLog(this->CTest, DEBUG,
  926. "test line " << lines[cc] << std::endl, this->Quiet);
  927. if (valgrindLine.find(lines[cc])) {
  928. cmCTestOptionalLog(this->CTest, DEBUG,
  929. "valgrind line " << lines[cc] << std::endl,
  930. this->Quiet);
  931. int failure = cmCTestMemCheckHandler::NO_MEMORY_FAULT;
  932. auto& line = lines[cc];
  933. if (vgFIM.find(line)) {
  934. failure = cmCTestMemCheckHandler::FIM;
  935. } else if (vgFMM.find(line)) {
  936. failure = cmCTestMemCheckHandler::FMM;
  937. } else if (vgMLK1.find(line) || vgMLK2.find(line)) {
  938. failure = cmCTestMemCheckHandler::MLK;
  939. } else if (vgPAR.find(line)) {
  940. failure = cmCTestMemCheckHandler::PAR;
  941. } else if (vgMPK1.find(line) || vgMPK2.find(line)) {
  942. failure = cmCTestMemCheckHandler::MPK;
  943. } else if (vgUMC.find(line)) {
  944. failure = cmCTestMemCheckHandler::UMC;
  945. } else if (vgUMR1.find(line) || vgUMR2.find(line) || vgUMR3.find(line) ||
  946. vgUMR4.find(line) || vgUMR5.find(line)) {
  947. failure = cmCTestMemCheckHandler::UMR;
  948. } else if (vgIPW.find(line)) {
  949. failure = cmCTestMemCheckHandler::IPW;
  950. } else if (vgABR.find(line)) {
  951. failure = cmCTestMemCheckHandler::ABR;
  952. }
  953. if (failure != cmCTestMemCheckHandler::NO_MEMORY_FAULT) {
  954. ostr << "<b>" << this->ResultStrings[failure] << "</b> ";
  955. results[failure]++;
  956. defects++;
  957. }
  958. totalOutputSize += lines[cc].size();
  959. ostr << lines[cc] << std::endl;
  960. } else {
  961. nonValGrindOutput.push_back(cc);
  962. }
  963. }
  964. // Now put all all the non valgrind output into the test output
  965. // This should be last in case it gets truncated by the output
  966. // limiting code
  967. for (std::string::size_type i : nonValGrindOutput) {
  968. totalOutputSize += lines[i].size();
  969. ostr << lines[i] << std::endl;
  970. if (!unlimitedOutput &&
  971. totalOutputSize >
  972. static_cast<size_t>(this->CustomMaximumFailedTestOutputSize)) {
  973. ostr << "....\n";
  974. ostr << "Test Output for this test has been truncated see testing"
  975. " machine logs for full output,\n";
  976. ostr << "or put CTEST_FULL_OUTPUT in the output of "
  977. "this test program.\n";
  978. break; // stop the copy of output if we are full
  979. }
  980. }
  981. cmCTestOptionalLog(this->CTest, DEBUG,
  982. "End test (elapsed: "
  983. << cmDurationTo<unsigned int>(
  984. std::chrono::steady_clock::now() - sttime)
  985. << "s)" << std::endl,
  986. this->Quiet);
  987. log = ostr.str();
  988. this->DefectCount += defects;
  989. return defects == 0;
  990. }
  991. bool cmCTestMemCheckHandler::ProcessMemCheckDrMemoryOutput(
  992. const std::string& str, std::string& log, std::vector<int>& results)
  993. {
  994. std::vector<std::string> lines;
  995. cmsys::SystemTools::Split(str, lines);
  996. cmsys::RegularExpression drMemoryError("^Error #[0-9]+");
  997. cmsys::RegularExpression unaddressableAccess("UNADDRESSABLE ACCESS");
  998. cmsys::RegularExpression uninitializedRead("UNINITIALIZED READ");
  999. cmsys::RegularExpression invalidHeapArgument("INVALID HEAP ARGUMENT");
  1000. cmsys::RegularExpression leak("LEAK");
  1001. cmsys::RegularExpression handleLeak("HANDLE LEAK");
  1002. int defects = 0;
  1003. std::ostringstream ostr;
  1004. for (const auto& l : lines) {
  1005. ostr << l << std::endl;
  1006. if (drMemoryError.find(l)) {
  1007. defects++;
  1008. if (unaddressableAccess.find(l) || uninitializedRead.find(l)) {
  1009. results[cmCTestMemCheckHandler::UMR]++;
  1010. } else if (leak.find(l) || handleLeak.find(l)) {
  1011. results[cmCTestMemCheckHandler::MLK]++;
  1012. } else if (invalidHeapArgument.find(l)) {
  1013. results[cmCTestMemCheckHandler::FMM]++;
  1014. }
  1015. }
  1016. }
  1017. log = ostr.str();
  1018. this->DefectCount += defects;
  1019. return defects == 0;
  1020. }
  1021. bool cmCTestMemCheckHandler::ProcessMemCheckBoundsCheckerOutput(
  1022. const std::string& str, std::string& log, std::vector<int>& results)
  1023. {
  1024. log.clear();
  1025. auto sttime = std::chrono::steady_clock::now();
  1026. std::vector<std::string> lines;
  1027. cmsys::SystemTools::Split(str, lines);
  1028. cmCTestOptionalLog(this->CTest, DEBUG,
  1029. "Start test: " << lines.size() << std::endl, this->Quiet);
  1030. std::vector<std::string>::size_type cc;
  1031. for (cc = 0; cc < lines.size(); cc++) {
  1032. if (lines[cc] == BOUNDS_CHECKER_MARKER) {
  1033. break;
  1034. }
  1035. }
  1036. cmBoundsCheckerParser parser(this->CTest);
  1037. parser.InitializeParser();
  1038. if (cc < lines.size()) {
  1039. for (cc++; cc < lines.size(); ++cc) {
  1040. std::string& theLine = lines[cc];
  1041. // check for command line arguments that are not escaped
  1042. // correctly by BC
  1043. if (theLine.find("TargetArgs=") != std::string::npos) {
  1044. // skip this because BC gets it wrong and we can't parse it
  1045. } else if (!parser.ParseChunk(theLine.c_str(), theLine.size())) {
  1046. cmCTestLog(this->CTest, ERROR_MESSAGE,
  1047. "Error in ParseChunk: " << theLine << std::endl);
  1048. }
  1049. }
  1050. }
  1051. int defects = 0;
  1052. for (int err : parser.Errors) {
  1053. results[err]++;
  1054. defects++;
  1055. }
  1056. cmCTestOptionalLog(this->CTest, DEBUG,
  1057. "End test (elapsed: "
  1058. << cmDurationTo<unsigned int>(
  1059. std::chrono::steady_clock::now() - sttime)
  1060. << "s)" << std::endl,
  1061. this->Quiet);
  1062. if (defects) {
  1063. // only put the output of Bounds Checker if there were
  1064. // errors or leaks detected
  1065. log = parser.Log;
  1066. }
  1067. this->DefectCount += defects;
  1068. return defects == 0;
  1069. }
  1070. bool cmCTestMemCheckHandler::ProcessMemCheckCudaOutput(
  1071. const std::string& str, std::string& log, std::vector<int>& results)
  1072. {
  1073. std::vector<std::string> lines;
  1074. cmsys::SystemTools::Split(str, lines);
  1075. bool unlimitedOutput = false;
  1076. if (str.find("CTEST_FULL_OUTPUT") != std::string::npos ||
  1077. this->CustomMaximumFailedTestOutputSize == 0) {
  1078. unlimitedOutput = true;
  1079. }
  1080. std::string::size_type cc;
  1081. std::ostringstream ostr;
  1082. log.clear();
  1083. int defects = 0;
  1084. cmsys::RegularExpression memcheckLine("^========");
  1085. cmsys::RegularExpression leakExpr("== Leaked [0-9,]+ bytes at");
  1086. // list of matchers for output messages that contain variable content
  1087. // (addresses, sizes, ...) or can be shortened in general. the first match is
  1088. // used as a error name.
  1089. std::vector<cmsys::RegularExpression> matchers{
  1090. // API errors
  1091. "== Malloc/Free error encountered: (.*)",
  1092. "== Program hit error ([^ ]*).* on CUDA API call to",
  1093. "== Program hit ([^ ]*).* on CUDA API call to",
  1094. // memcheck
  1095. "== (Invalid .*) of size [0-9,]+", "== (Fatal UVM [CG]PU fault)",
  1096. // racecheck
  1097. "== .* (Potential .* hazard detected)", "== .* (Race reported)",
  1098. // synccheck
  1099. "== (Barrier error)",
  1100. // initcheck
  1101. "== (Uninitialized .* memory read)", "== (Unused memory)",
  1102. "== (Host API memory access error)",
  1103. // generic error: ignore ERROR SUMMARY, CUDA-MEMCHECK and others
  1104. "== ([A-Z][a-z].*)"
  1105. };
  1106. std::vector<std::string::size_type> nonMemcheckOutput;
  1107. auto sttime = std::chrono::steady_clock::now();
  1108. cmCTestOptionalLog(this->CTest, DEBUG,
  1109. "Start test: " << lines.size() << std::endl, this->Quiet);
  1110. std::string::size_type totalOutputSize = 0;
  1111. for (cc = 0; cc < lines.size(); cc++) {
  1112. cmCTestOptionalLog(this->CTest, DEBUG,
  1113. "test line " << lines[cc] << std::endl, this->Quiet);
  1114. if (memcheckLine.find(lines[cc])) {
  1115. cmCTestOptionalLog(this->CTest, DEBUG,
  1116. "cuda sanitizer line " << lines[cc] << std::endl,
  1117. this->Quiet);
  1118. int failure = -1;
  1119. auto& line = lines[cc];
  1120. if (leakExpr.find(line)) {
  1121. failure = static_cast<int>(this->FindOrAddWarning("Memory leak"));
  1122. } else {
  1123. for (auto& matcher : matchers) {
  1124. if (matcher.find(line)) {
  1125. failure =
  1126. static_cast<int>(this->FindOrAddWarning(matcher.match(1)));
  1127. break;
  1128. }
  1129. }
  1130. }
  1131. if (failure >= 0) {
  1132. ostr << "<b>" << this->ResultStrings[failure] << "</b> ";
  1133. if (results.empty() || unsigned(failure) > results.size() - 1) {
  1134. results.push_back(1);
  1135. } else {
  1136. results[failure]++;
  1137. }
  1138. defects++;
  1139. }
  1140. totalOutputSize += lines[cc].size();
  1141. ostr << lines[cc] << std::endl;
  1142. } else {
  1143. nonMemcheckOutput.push_back(cc);
  1144. }
  1145. }
  1146. // Now put all all the non cuda sanitizer output into the test output
  1147. // This should be last in case it gets truncated by the output
  1148. // limiting code
  1149. for (std::string::size_type i : nonMemcheckOutput) {
  1150. totalOutputSize += lines[i].size();
  1151. ostr << lines[i] << std::endl;
  1152. if (!unlimitedOutput &&
  1153. totalOutputSize >
  1154. static_cast<size_t>(this->CustomMaximumFailedTestOutputSize)) {
  1155. ostr << "....\n";
  1156. ostr << "Test Output for this test has been truncated see testing"
  1157. " machine logs for full output,\n";
  1158. ostr << "or put CTEST_FULL_OUTPUT in the output of "
  1159. "this test program.\n";
  1160. break; // stop the copy of output if we are full
  1161. }
  1162. }
  1163. cmCTestOptionalLog(this->CTest, DEBUG,
  1164. "End test (elapsed: "
  1165. << cmDurationTo<unsigned int>(
  1166. std::chrono::steady_clock::now() - sttime)
  1167. << "s)" << std::endl,
  1168. this->Quiet);
  1169. log = ostr.str();
  1170. this->DefectCount += defects;
  1171. return defects == 0;
  1172. }
  1173. // PostProcessTest memcheck results
  1174. void cmCTestMemCheckHandler::PostProcessTest(cmCTestTestResult& res, int test)
  1175. {
  1176. cmCTestOptionalLog(this->CTest, HANDLER_VERBOSE_OUTPUT,
  1177. "PostProcessTest memcheck results for : " << res.Name
  1178. << std::endl,
  1179. this->Quiet);
  1180. if (this->MemoryTesterStyle == cmCTestMemCheckHandler::BOUNDS_CHECKER) {
  1181. this->PostProcessBoundsCheckerTest(res, test);
  1182. } else if (this->MemoryTesterStyle == cmCTestMemCheckHandler::DRMEMORY) {
  1183. this->PostProcessDrMemoryTest(res, test);
  1184. } else {
  1185. std::vector<std::string> files;
  1186. this->TestOutputFileNames(test, files);
  1187. for (std::string const& f : files) {
  1188. this->AppendMemTesterOutput(res, f);
  1189. }
  1190. }
  1191. }
  1192. // This method puts the bounds checker output file into the output
  1193. // for the test
  1194. void cmCTestMemCheckHandler::PostProcessBoundsCheckerTest(
  1195. cmCTestTestResult& res, int test)
  1196. {
  1197. cmCTestOptionalLog(this->CTest, HANDLER_VERBOSE_OUTPUT,
  1198. "PostProcessBoundsCheckerTest for : " << res.Name
  1199. << std::endl,
  1200. this->Quiet);
  1201. std::vector<std::string> files;
  1202. this->TestOutputFileNames(test, files);
  1203. if (files.empty()) {
  1204. return;
  1205. }
  1206. std::string ofile = files[0];
  1207. if (ofile.empty()) {
  1208. return;
  1209. }
  1210. // put a scope around this to close ifs so the file can be removed
  1211. {
  1212. cmsys::ifstream ifs(ofile.c_str());
  1213. if (!ifs) {
  1214. std::string log = "Cannot read memory tester output file: " + ofile;
  1215. cmCTestLog(this->CTest, ERROR_MESSAGE, log << std::endl);
  1216. return;
  1217. }
  1218. res.Output += BOUNDS_CHECKER_MARKER;
  1219. res.Output += "\n";
  1220. std::string line;
  1221. while (cmSystemTools::GetLineFromStream(ifs, line)) {
  1222. res.Output += line;
  1223. res.Output += "\n";
  1224. }
  1225. }
  1226. cmSystemTools::Delay(1000);
  1227. cmSystemTools::RemoveFile(this->BoundsCheckerDPBDFile);
  1228. cmCTestOptionalLog(this->CTest, HANDLER_VERBOSE_OUTPUT,
  1229. "Remove: " << this->BoundsCheckerDPBDFile << std::endl,
  1230. this->Quiet);
  1231. cmSystemTools::RemoveFile(this->BoundsCheckerXMLFile);
  1232. cmCTestOptionalLog(this->CTest, HANDLER_VERBOSE_OUTPUT,
  1233. "Remove: " << this->BoundsCheckerXMLFile << std::endl,
  1234. this->Quiet);
  1235. }
  1236. void cmCTestMemCheckHandler::PostProcessDrMemoryTest(
  1237. cmCTestTestHandler::cmCTestTestResult& res, int test)
  1238. {
  1239. std::string drMemoryLogDir = this->MemoryTesterOutputFile.substr(
  1240. 0, this->MemoryTesterOutputFile.find("/*/results.txt"));
  1241. // replace placeholder of test
  1242. std::string::size_type pos = drMemoryLogDir.find("??");
  1243. if (pos != std::string::npos) {
  1244. drMemoryLogDir.replace(pos, 2, std::to_string(test));
  1245. }
  1246. cmsys::Glob g;
  1247. g.FindFiles(drMemoryLogDir + "/resfile.*");
  1248. const std::vector<std::string>& files = g.GetFiles();
  1249. for (const std::string& f : files) {
  1250. cmsys::ifstream ifs(f.c_str());
  1251. if (!ifs) {
  1252. std::string log = "Cannot read memory tester output file: " + f;
  1253. cmCTestLog(this->CTest, ERROR_MESSAGE, log << std::endl);
  1254. return;
  1255. }
  1256. std::string resultFileLocation;
  1257. cmSystemTools::GetLineFromStream(ifs, resultFileLocation);
  1258. this->AppendMemTesterOutput(res, resultFileLocation);
  1259. ifs.close();
  1260. cmSystemTools::RemoveFile(f);
  1261. }
  1262. }
  1263. void cmCTestMemCheckHandler::AppendMemTesterOutput(cmCTestTestResult& res,
  1264. std::string const& ofile)
  1265. {
  1266. if (ofile.empty()) {
  1267. return;
  1268. }
  1269. // put ifs in scope so file can be deleted if needed
  1270. {
  1271. cmsys::ifstream ifs(ofile.c_str());
  1272. if (!ifs) {
  1273. std::string log = "Cannot read memory tester output file: " + ofile;
  1274. cmCTestLog(this->CTest, ERROR_MESSAGE, log << std::endl);
  1275. return;
  1276. }
  1277. std::string line;
  1278. while (cmSystemTools::GetLineFromStream(ifs, line)) {
  1279. res.Output += line;
  1280. res.Output += "\n";
  1281. }
  1282. }
  1283. if (this->LogWithPID) {
  1284. auto pos = ofile.find_last_of('.');
  1285. if (pos != std::string::npos) {
  1286. auto ofileWithoutPid = ofile.substr(0, pos);
  1287. cmSystemTools::RenameFile(ofile, ofileWithoutPid);
  1288. cmCTestOptionalLog(this->CTest, HANDLER_VERBOSE_OUTPUT,
  1289. "Renaming: " << ofile << " to: " << ofileWithoutPid
  1290. << "\n",
  1291. this->Quiet);
  1292. }
  1293. }
  1294. }
  1295. void cmCTestMemCheckHandler::TestOutputFileNames(
  1296. int test, std::vector<std::string>& files)
  1297. {
  1298. std::string index = std::to_string(test);
  1299. std::string ofile = this->MemoryTesterOutputFile;
  1300. std::string::size_type pos = ofile.find("??");
  1301. ofile.replace(pos, 2, index);
  1302. if (this->LogWithPID) {
  1303. ofile += ".*";
  1304. cmsys::Glob g;
  1305. g.FindFiles(ofile);
  1306. if (g.GetFiles().empty()) {
  1307. std::string log = "Cannot find memory tester output file: " + ofile;
  1308. cmCTestLog(this->CTest, WARNING, log << std::endl);
  1309. ofile.clear();
  1310. } else {
  1311. files = g.GetFiles();
  1312. return;
  1313. }
  1314. } else if (!cmSystemTools::FileExists(ofile)) {
  1315. std::string log = "Cannot find memory tester output file: " + ofile;
  1316. cmCTestLog(this->CTest, WARNING, log << std::endl);
  1317. ofile.clear();
  1318. }
  1319. files.push_back(std::move(ofile));
  1320. }