cmCTestBuildHandler.cxx 43 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260
  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 "cmCTestBuildHandler.h"
  4. #include <cstdlib>
  5. #include <memory>
  6. #include <ratio>
  7. #include <set>
  8. #include <utility>
  9. #include <cm/string_view>
  10. #include <cmext/algorithm>
  11. #include <cm3p/json/value.h>
  12. #include <cm3p/uv.h>
  13. #include "cmsys/Directory.hxx"
  14. #include "cmsys/FStream.hxx"
  15. #include "cmCTest.h"
  16. #include "cmCTestLaunchReporter.h"
  17. #include "cmDuration.h"
  18. #include "cmFileTimeCache.h"
  19. #include "cmGeneratedFileStream.h"
  20. #include "cmInstrumentation.h"
  21. #include "cmInstrumentationQuery.h"
  22. #include "cmJSONState.h"
  23. #include "cmList.h"
  24. #include "cmMakefile.h"
  25. #include "cmProcessOutput.h"
  26. #include "cmStringAlgorithms.h"
  27. #include "cmStringReplaceHelper.h"
  28. #include "cmSystemTools.h"
  29. #include "cmUVHandlePtr.h"
  30. #include "cmUVProcessChain.h"
  31. #include "cmUVStream.h"
  32. #include "cmValue.h"
  33. #include "cmXMLWriter.h"
  34. static char const* cmCTestErrorMatches[] = {
  35. "^[Bb]us [Ee]rror", // noqa: spellcheck disable-line
  36. "^[Ss]egmentation [Vv]iolation",
  37. "^[Ss]egmentation [Ff]ault",
  38. ":.*[Pp]ermission [Dd]enied",
  39. "([^ :]+):([0-9]+): ([^ \\t])",
  40. "([^:]+): error[ \\t]*[0-9]+[ \\t]*:",
  41. "^Error ([0-9]+):",
  42. "^Fatal",
  43. "^Error: ",
  44. "^Error ",
  45. "[0-9] ERROR: ",
  46. R"(^"[^"]+", line [0-9]+: [^Ww])",
  47. "^cc[^C]*CC: ERROR File = ([^,]+), Line = ([0-9]+)",
  48. "^ld([^:])*:([ \\t])*ERROR([^:])*:",
  49. R"(^ild:([ \t])*\(undefined symbol\))",
  50. "([^ :]+) : (error|fatal error|catastrophic error)",
  51. "([^:]+): (Error:|error|undefined reference|multiply defined)",
  52. R"(([^:]+)\(([^\)]+)\) ?: (error|fatal error|catastrophic error))",
  53. "^fatal error C[0-9]+:",
  54. ": syntax error ",
  55. "^collect2: ld returned 1 exit status",
  56. "ld terminated with signal",
  57. "Unsatisfied symbol",
  58. "^Unresolved:",
  59. "Undefined symbol",
  60. "^Undefined[ \\t]+first referenced",
  61. "^CMake Error.*:",
  62. ":[ \\t]cannot find",
  63. ":[ \\t]can't find",
  64. R"(: \*\*\* No rule to make target [`'].*\'. Stop)",
  65. R"(: \*\*\* No targets specified and no makefile found)",
  66. ": Invalid loader fixup for symbol",
  67. ": Invalid fixups exist",
  68. ": Can't find library for",
  69. ": internal link edit command failed",
  70. ": Unrecognized option [`'].*\\'",
  71. R"(", line [0-9]+\.[0-9]+: [0-9]+-[0-9]+ \([^WI]\))",
  72. "ld: 0706-006 Cannot find or open library file: -l ",
  73. "ild: \\(argument error\\) can't find library argument ::",
  74. "^could not be found and will not be loaded.",
  75. "s:616 string too big",
  76. "make: Fatal error: ",
  77. "ld: 0711-993 Error occurred while writing to the output file:",
  78. "ld: fatal: ",
  79. "final link failed:",
  80. R"(make: \*\*\*.*Error)",
  81. R"(make\[.*\]: \*\*\*.*Error)",
  82. R"(\*\*\* Error code)",
  83. "nternal error:",
  84. R"(Makefile:[0-9]+: \*\*\* .* Stop\.)",
  85. ": No such file or directory",
  86. ": Invalid argument",
  87. "^The project cannot be built\\.",
  88. "^\\[ERROR\\]",
  89. "^Command .* failed with exit code",
  90. "lcc: \"([^\"]+)\", (line|строка) ([0-9]+): (error|ошибка)",
  91. nullptr
  92. };
  93. static char const* cmCTestErrorExceptions[] = {
  94. "instantiated from ",
  95. "candidates are:",
  96. ": warning",
  97. ": WARNING",
  98. ": \\(Warning\\)",
  99. ": note",
  100. "Note:",
  101. "makefile:",
  102. "Makefile:",
  103. ":[ \\t]+Where:",
  104. "([^ :]+):([0-9]+): Warning",
  105. "------ Build started: .* ------",
  106. nullptr
  107. };
  108. static char const* cmCTestWarningMatches[] = {
  109. "([^ :]+):([0-9]+): warning:",
  110. "([^ :]+):([0-9]+): note:",
  111. "^cc[^C]*CC: WARNING File = ([^,]+), Line = ([0-9]+)",
  112. "^ld([^:])*:([ \\t])*WARNING([^:])*:",
  113. "([^:]+): warning ([0-9]+):",
  114. R"(^"[^"]+", line [0-9]+: [Ww](arning|arnung))",
  115. "([^:]+): warning[ \\t]*[0-9]+[ \\t]*:",
  116. "^(Warning|Warnung) ([0-9]+):",
  117. "^(Warning|Warnung)[ :]",
  118. "WARNING: ",
  119. "([^ :]+) : warning",
  120. "([^:]+): warning",
  121. R"(", line [0-9]+\.[0-9]+: [0-9]+-[0-9]+ \([WI]\))",
  122. "^cxx: Warning:",
  123. ".*file: .* has no symbols",
  124. "([^ :]+):([0-9]+): (Warning|Warnung)",
  125. "\\([0-9]*\\): remark #[0-9]*",
  126. R"(".*", line [0-9]+: remark\([0-9]*\):)",
  127. "cc-[0-9]* CC: REMARK File = .*, Line = [0-9]*",
  128. "^CMake Warning.*:",
  129. "^\\[WARNING\\]",
  130. "lcc: \"([^\"]+)\", (line|строка) ([0-9]+): (warning|предупреждение)",
  131. nullptr
  132. };
  133. static char const* cmCTestWarningExceptions[] = {
  134. R"(/usr/.*/X11/Xlib\.h:[0-9]+: war.*: ANSI C\+\+ forbids declaration)",
  135. R"(/usr/.*/X11/Xutil\.h:[0-9]+: war.*: ANSI C\+\+ forbids declaration)",
  136. R"(/usr/.*/X11/XResource\.h:[0-9]+: war.*: ANSI C\+\+ forbids declaration)",
  137. "WARNING 84 :",
  138. "WARNING 47 :",
  139. "makefile:",
  140. "Makefile:",
  141. "warning: Clock skew detected. Your build may be incomplete.",
  142. "/usr/openwin/include/GL/[^:]+:",
  143. "bind_at_load",
  144. "XrmQGetResource",
  145. "IceFlush",
  146. "warning LNK4089: all references to [^ \\t]+ discarded by .OPT:REF",
  147. "ld32: WARNING 85: definition of dataKey in",
  148. "cc: warning 422: Unknown option \"\\+b",
  149. "_with_warning_C",
  150. nullptr
  151. };
  152. struct cmCTestBuildCompileErrorWarningRex
  153. {
  154. char const* RegularExpressionString;
  155. int FileIndex;
  156. int LineIndex;
  157. };
  158. static cmCTestBuildCompileErrorWarningRex cmCTestWarningErrorFileLine[] = {
  159. { "^Warning W[0-9]+ ([a-zA-Z.\\:/0-9_+ ~-]+) ([0-9]+):", 1, 2 },
  160. { "^([a-zA-Z./0-9_+ ~-]+):([0-9]+):", 1, 2 },
  161. { R"(^([a-zA-Z.\:/0-9_+ ~-]+)\(([0-9]+)\))", 1, 2 },
  162. { R"(^[0-9]+>([a-zA-Z.\:/0-9_+ ~-]+)\(([0-9]+)\))", 1, 2 },
  163. { "^([a-zA-Z./0-9_+ ~-]+)\\(([0-9]+)\\)", 1, 2 },
  164. { "\"([a-zA-Z./0-9_+ ~-]+)\", line ([0-9]+)", 1, 2 },
  165. { "File = ([a-zA-Z./0-9_+ ~-]+), Line = ([0-9]+)", 1, 2 },
  166. { "lcc: \"([^\"]+)\", (line|строка) ([0-9]+): "
  167. "(error|ошибка|warning|предупреждение)",
  168. 1, 3 },
  169. { nullptr, 0, 0 }
  170. };
  171. cmCTestBuildHandler::cmCTestBuildHandler(cmCTest* ctest)
  172. : Superclass(ctest)
  173. , LastErrorOrWarning(this->ErrorsAndWarnings.end())
  174. {
  175. }
  176. void cmCTestBuildHandler::PopulateCustomVectors(cmMakefile* mf)
  177. {
  178. this->CTest->PopulateCustomVector(mf, "CTEST_CUSTOM_ERROR_MATCH",
  179. this->CustomErrorMatches);
  180. this->CTest->PopulateCustomVector(mf, "CTEST_CUSTOM_ERROR_EXCEPTION",
  181. this->CustomErrorExceptions);
  182. this->CTest->PopulateCustomVector(mf, "CTEST_CUSTOM_WARNING_MATCH",
  183. this->CustomWarningMatches);
  184. this->CTest->PopulateCustomVector(mf, "CTEST_CUSTOM_WARNING_EXCEPTION",
  185. this->CustomWarningExceptions);
  186. this->CTest->PopulateCustomInteger(
  187. mf, "CTEST_CUSTOM_MAXIMUM_NUMBER_OF_ERRORS", this->MaxErrors);
  188. this->CTest->PopulateCustomInteger(
  189. mf, "CTEST_CUSTOM_MAXIMUM_NUMBER_OF_WARNINGS", this->MaxWarnings);
  190. int n = -1;
  191. this->CTest->PopulateCustomInteger(mf, "CTEST_CUSTOM_ERROR_PRE_CONTEXT", n);
  192. if (n != -1) {
  193. this->MaxPreContext = static_cast<size_t>(n);
  194. }
  195. n = -1;
  196. this->CTest->PopulateCustomInteger(mf, "CTEST_CUSTOM_ERROR_POST_CONTEXT", n);
  197. if (n != -1) {
  198. this->MaxPostContext = static_cast<size_t>(n);
  199. }
  200. // Record the user-specified custom warning rules.
  201. if (cmValue customWarningMatchers =
  202. mf->GetDefinition("CTEST_CUSTOM_WARNING_MATCH")) {
  203. cmExpandList(*customWarningMatchers, this->ReallyCustomWarningMatches);
  204. }
  205. if (cmValue customWarningExceptions =
  206. mf->GetDefinition("CTEST_CUSTOM_WARNING_EXCEPTION")) {
  207. cmExpandList(*customWarningExceptions,
  208. this->ReallyCustomWarningExceptions);
  209. }
  210. }
  211. std::string cmCTestBuildHandler::GetMakeCommand()
  212. {
  213. std::string makeCommand = this->CTest->GetCTestConfiguration("MakeCommand");
  214. cmCTestOptionalLog(this->CTest, HANDLER_VERBOSE_OUTPUT,
  215. "MakeCommand:" << makeCommand << "\n", this->Quiet);
  216. std::string configType = this->CTest->GetConfigType();
  217. if (configType.empty()) {
  218. configType =
  219. this->CTest->GetCTestConfiguration("DefaultCTestConfigurationType");
  220. }
  221. if (configType.empty()) {
  222. configType = "Release";
  223. }
  224. cmSystemTools::ReplaceString(makeCommand, "${CTEST_CONFIGURATION_TYPE}",
  225. configType.c_str());
  226. return makeCommand;
  227. }
  228. // clearly it would be nice if this were broken up into a few smaller
  229. // functions and commented...
  230. int cmCTestBuildHandler::ProcessHandler()
  231. {
  232. cmCTestOptionalLog(this->CTest, HANDLER_OUTPUT, "Build project" << std::endl,
  233. this->Quiet);
  234. // do we have time for this
  235. if (this->CTest->GetRemainingTimeAllowed() < std::chrono::minutes(2)) {
  236. return 0;
  237. }
  238. int entry;
  239. for (entry = 0; cmCTestWarningErrorFileLine[entry].RegularExpressionString;
  240. ++entry) {
  241. cmCTestBuildHandler::cmCTestCompileErrorWarningRex r;
  242. if (r.RegularExpression.compile(
  243. cmCTestWarningErrorFileLine[entry].RegularExpressionString)) {
  244. r.FileIndex = cmCTestWarningErrorFileLine[entry].FileIndex;
  245. r.LineIndex = cmCTestWarningErrorFileLine[entry].LineIndex;
  246. this->ErrorWarningFileLineRegex.push_back(std::move(r));
  247. } else {
  248. cmCTestLog(
  249. this->CTest, ERROR_MESSAGE,
  250. "Problem Compiling regular expression: "
  251. << cmCTestWarningErrorFileLine[entry].RegularExpressionString
  252. << std::endl);
  253. }
  254. }
  255. // Determine build command and build directory
  256. std::string makeCommand = this->GetMakeCommand();
  257. if (makeCommand.empty()) {
  258. cmCTestLog(this->CTest, ERROR_MESSAGE,
  259. "Cannot find MakeCommand key in the DartConfiguration.tcl"
  260. << std::endl);
  261. return -1;
  262. }
  263. std::string const& buildDirectory =
  264. this->CTest->GetCTestConfiguration("BuildDirectory");
  265. if (buildDirectory.empty()) {
  266. cmCTestLog(this->CTest, ERROR_MESSAGE,
  267. "Cannot find BuildDirectory key in the DartConfiguration.tcl"
  268. << std::endl);
  269. return -1;
  270. }
  271. std::string const& useLaunchers =
  272. this->CTest->GetCTestConfiguration("UseLaunchers");
  273. this->UseCTestLaunch = cmIsOn(useLaunchers);
  274. // Create a last build log
  275. cmGeneratedFileStream ofs;
  276. auto elapsed_time_start = std::chrono::steady_clock::now();
  277. if (!this->StartLogFile("Build", ofs)) {
  278. cmCTestLog(this->CTest, ERROR_MESSAGE,
  279. "Cannot create build log file" << std::endl);
  280. }
  281. this->LogFileName = ofs.GetTempName();
  282. // Create lists of regular expression strings for errors, error exceptions,
  283. // warnings and warning exceptions.
  284. std::vector<std::string>::size_type cc;
  285. for (cc = 0; cmCTestErrorMatches[cc]; cc++) {
  286. this->CustomErrorMatches.emplace_back(cmCTestErrorMatches[cc]);
  287. }
  288. for (cc = 0; cmCTestErrorExceptions[cc]; cc++) {
  289. this->CustomErrorExceptions.emplace_back(cmCTestErrorExceptions[cc]);
  290. }
  291. for (cc = 0; cmCTestWarningMatches[cc]; cc++) {
  292. this->CustomWarningMatches.emplace_back(cmCTestWarningMatches[cc]);
  293. }
  294. for (cc = 0; cmCTestWarningExceptions[cc]; cc++) {
  295. this->CustomWarningExceptions.emplace_back(cmCTestWarningExceptions[cc]);
  296. }
  297. // Pre-compile regular expressions objects for all regular expressions
  298. #define cmCTestBuildHandlerPopulateRegexVector(strings, regexes) \
  299. do { \
  300. regexes.clear(); \
  301. cmCTestOptionalLog(this->CTest, DEBUG, \
  302. this << "Add " #regexes << std::endl, this->Quiet); \
  303. for (std::string const& s : (strings)) { \
  304. cmCTestOptionalLog(this->CTest, DEBUG, \
  305. "Add " #strings ": " << s << std::endl, \
  306. this->Quiet); \
  307. (regexes).emplace_back(s); \
  308. } \
  309. } while (false)
  310. cmCTestBuildHandlerPopulateRegexVector(this->CustomErrorMatches,
  311. this->ErrorMatchRegex);
  312. cmCTestBuildHandlerPopulateRegexVector(this->CustomErrorExceptions,
  313. this->ErrorExceptionRegex);
  314. cmCTestBuildHandlerPopulateRegexVector(this->CustomWarningMatches,
  315. this->WarningMatchRegex);
  316. cmCTestBuildHandlerPopulateRegexVector(this->CustomWarningExceptions,
  317. this->WarningExceptionRegex);
  318. // Determine source and binary tree substitutions to simplify the output.
  319. this->SimplifySourceDir.clear();
  320. this->SimplifyBuildDir.clear();
  321. if (this->CTest->GetCTestConfiguration("SourceDirectory").size() > 20) {
  322. std::string srcdir =
  323. this->CTest->GetCTestConfiguration("SourceDirectory") + "/";
  324. cc = srcdir.rfind('/', srcdir.size() - 2);
  325. if (cc != std::string::npos) {
  326. srcdir.resize(cc + 1);
  327. this->SimplifySourceDir = std::move(srcdir);
  328. }
  329. }
  330. if (this->CTest->GetCTestConfiguration("BuildDirectory").size() > 20) {
  331. std::string bindir =
  332. this->CTest->GetCTestConfiguration("BuildDirectory") + "/";
  333. cc = bindir.rfind('/', bindir.size() - 2);
  334. if (cc != std::string::npos) {
  335. bindir.resize(cc + 1);
  336. this->SimplifyBuildDir = std::move(bindir);
  337. }
  338. }
  339. // Ok, let's do the build
  340. // Remember start build time
  341. this->StartBuild = this->CTest->CurrentTime();
  342. this->StartBuildTime = std::chrono::system_clock::now();
  343. cmStringReplaceHelper colorRemover("\x1b\\[[0-9;]*m", "", nullptr);
  344. this->ColorRemover = &colorRemover;
  345. int retVal = 0;
  346. bool res = true;
  347. if (!this->CTest->GetShowOnly()) {
  348. res = this->RunMakeCommand(makeCommand, &retVal, buildDirectory.c_str(), 0,
  349. ofs);
  350. } else {
  351. cmCTestOptionalLog(this->CTest, DEBUG,
  352. "Build with command: " << makeCommand << std::endl,
  353. this->Quiet);
  354. }
  355. // Remember end build time and calculate elapsed time
  356. this->EndBuild = this->CTest->CurrentTime();
  357. this->EndBuildTime = std::chrono::system_clock::now();
  358. auto elapsed_build_time =
  359. std::chrono::steady_clock::now() - elapsed_time_start;
  360. // Cleanups strings in the errors and warnings list.
  361. if (!this->SimplifySourceDir.empty()) {
  362. for (cmCTestBuildErrorWarning& evit : this->ErrorsAndWarnings) {
  363. cmSystemTools::ReplaceString(evit.Text, this->SimplifySourceDir.c_str(),
  364. "/.../");
  365. cmSystemTools::ReplaceString(evit.PreContext,
  366. this->SimplifySourceDir.c_str(), "/.../");
  367. cmSystemTools::ReplaceString(evit.PostContext,
  368. this->SimplifySourceDir.c_str(), "/.../");
  369. }
  370. }
  371. if (!this->SimplifyBuildDir.empty()) {
  372. for (cmCTestBuildErrorWarning& evit : this->ErrorsAndWarnings) {
  373. cmSystemTools::ReplaceString(evit.Text, this->SimplifyBuildDir.c_str(),
  374. "/.../");
  375. cmSystemTools::ReplaceString(evit.PreContext,
  376. this->SimplifyBuildDir.c_str(), "/.../");
  377. cmSystemTools::ReplaceString(evit.PostContext,
  378. this->SimplifyBuildDir.c_str(), "/.../");
  379. }
  380. }
  381. // Generate XML output
  382. cmGeneratedFileStream xofs;
  383. if (!this->StartResultingXML(cmCTest::PartBuild, "Build", xofs)) {
  384. cmCTestLog(this->CTest, ERROR_MESSAGE,
  385. "Cannot create build XML file" << std::endl);
  386. return -1;
  387. }
  388. cmXMLWriter xml(xofs);
  389. this->GenerateXMLHeader(xml);
  390. if (this->UseCTestLaunch) {
  391. this->GenerateXMLLaunched(xml);
  392. } else {
  393. this->GenerateXMLLogScraped(xml);
  394. }
  395. this->CTest->GetInstrumentation().CollectTimingData(
  396. cmInstrumentationQuery::Hook::PrepareForCDash);
  397. this->GenerateInstrumentationXML(xml);
  398. this->GenerateXMLFooter(xml, elapsed_build_time);
  399. if (!res || retVal || this->TotalErrors > 0) {
  400. cmCTestLog(this->CTest, ERROR_MESSAGE,
  401. "Error(s) when building project" << std::endl);
  402. }
  403. // Display message about number of errors and warnings
  404. cmCTestLog(this->CTest, HANDLER_OUTPUT,
  405. " " << this->TotalErrors
  406. << (this->TotalErrors >= this->MaxErrors ? " or more" : "")
  407. << " Compiler errors" << std::endl);
  408. cmCTestLog(
  409. this->CTest, HANDLER_OUTPUT,
  410. " " << this->TotalWarnings
  411. << (this->TotalWarnings >= this->MaxWarnings ? " or more" : "")
  412. << " Compiler warnings" << std::endl);
  413. return retVal;
  414. }
  415. void cmCTestBuildHandler::GenerateXMLHeader(cmXMLWriter& xml)
  416. {
  417. this->CTest->StartXML(xml, this->CMake, this->AppendXML);
  418. this->CTest->GenerateSubprojectsOutput(xml);
  419. xml.StartElement("Build");
  420. xml.Element("StartDateTime", this->StartBuild);
  421. xml.Element("StartBuildTime", this->StartBuildTime);
  422. xml.Element("BuildCommand", this->GetMakeCommand());
  423. }
  424. class cmCTestBuildHandler::FragmentCompare
  425. {
  426. public:
  427. FragmentCompare(cmFileTimeCache* ftc)
  428. : FTC(ftc)
  429. {
  430. }
  431. FragmentCompare() = default;
  432. bool operator()(std::string const& l, std::string const& r) const
  433. {
  434. // Order files by modification time. Use lexicographic order
  435. // among files with the same time.
  436. int result;
  437. if (this->FTC->Compare(l, r, &result) && result != 0) {
  438. return result < 0;
  439. }
  440. return l < r;
  441. }
  442. private:
  443. cmFileTimeCache* FTC = nullptr;
  444. };
  445. void cmCTestBuildHandler::GenerateXMLLaunched(cmXMLWriter& xml)
  446. {
  447. if (this->CTestLaunchDir.empty()) {
  448. return;
  449. }
  450. // Sort XML fragments in chronological order.
  451. cmFileTimeCache ftc;
  452. FragmentCompare fragmentCompare(&ftc);
  453. using Fragments = std::set<std::string, FragmentCompare>;
  454. Fragments fragments(fragmentCompare);
  455. // only report the first 50 warnings and first 50 errors
  456. int numErrorsAllowed = this->MaxErrors;
  457. int numWarningsAllowed = this->MaxWarnings;
  458. // Identify fragments on disk.
  459. cmsys::Directory launchDir;
  460. launchDir.Load(this->CTestLaunchDir);
  461. unsigned long n = launchDir.GetNumberOfFiles();
  462. for (unsigned long i = 0; i < n; ++i) {
  463. char const* fname = launchDir.GetFile(i);
  464. if (this->IsLaunchedErrorFile(fname) && numErrorsAllowed) {
  465. numErrorsAllowed--;
  466. fragments.insert(this->CTestLaunchDir + '/' + fname);
  467. ++this->TotalErrors;
  468. } else if (this->IsLaunchedWarningFile(fname) && numWarningsAllowed) {
  469. numWarningsAllowed--;
  470. fragments.insert(this->CTestLaunchDir + '/' + fname);
  471. ++this->TotalWarnings;
  472. }
  473. }
  474. // Copy the fragments into the final XML file.
  475. for (std::string const& f : fragments) {
  476. xml.FragmentFile(f.c_str());
  477. }
  478. }
  479. void cmCTestBuildHandler::GenerateXMLLogScraped(cmXMLWriter& xml)
  480. {
  481. std::vector<cmCTestBuildErrorWarning>& ew = this->ErrorsAndWarnings;
  482. std::vector<cmCTestBuildErrorWarning>::iterator it;
  483. // only report the first 50 warnings and first 50 errors
  484. int numErrorsAllowed = this->MaxErrors;
  485. int numWarningsAllowed = this->MaxWarnings;
  486. std::string srcdir = this->CTest->GetCTestConfiguration("SourceDirectory");
  487. for (it = ew.begin();
  488. it != ew.end() && (numErrorsAllowed || numWarningsAllowed); it++) {
  489. cmCTestBuildErrorWarning* cm = &(*it);
  490. if ((cm->Error && numErrorsAllowed) ||
  491. (!cm->Error && numWarningsAllowed)) {
  492. if (cm->Error) {
  493. numErrorsAllowed--;
  494. } else {
  495. numWarningsAllowed--;
  496. }
  497. xml.StartElement(cm->Error ? "Error" : "Warning");
  498. xml.Element("BuildLogLine", cm->LogLine);
  499. xml.Element("Text", cm->Text);
  500. for (cmCTestCompileErrorWarningRex& rit :
  501. this->ErrorWarningFileLineRegex) {
  502. cmsys::RegularExpression* re = &rit.RegularExpression;
  503. if (re->find(cm->Text)) {
  504. cm->SourceFile = re->match(rit.FileIndex);
  505. // At this point we need to make this->SourceFile relative to
  506. // the source root of the project, so cvs links will work
  507. cmSystemTools::ConvertToUnixSlashes(cm->SourceFile);
  508. if (cm->SourceFile.find("/.../") != std::string::npos) {
  509. cmSystemTools::ReplaceString(cm->SourceFile, "/.../", "");
  510. std::string::size_type p = cm->SourceFile.find('/');
  511. if (p != std::string::npos) {
  512. cm->SourceFile =
  513. cm->SourceFile.substr(p + 1, cm->SourceFile.size() - p);
  514. }
  515. } else {
  516. // make sure it is a full path with the correct case
  517. cm->SourceFile =
  518. cmSystemTools::ToNormalizedPathOnDisk(cm->SourceFile);
  519. cmSystemTools::ReplaceString(cm->SourceFile, srcdir, "");
  520. }
  521. cm->LineNumber = atoi(re->match(rit.LineIndex).c_str());
  522. break;
  523. }
  524. }
  525. if (!cm->SourceFile.empty() && cm->LineNumber >= 0) {
  526. if (!cm->SourceFile.empty()) {
  527. xml.Element("SourceFile", cm->SourceFile);
  528. }
  529. if (!cm->SourceFileTail.empty()) {
  530. xml.Element("SourceFileTail", cm->SourceFileTail);
  531. }
  532. if (cm->LineNumber >= 0) {
  533. xml.Element("SourceLineNumber", cm->LineNumber);
  534. }
  535. }
  536. xml.Element("PreContext", cm->PreContext);
  537. xml.StartElement("PostContext");
  538. xml.Content(cm->PostContext);
  539. // is this the last warning or error, if so notify
  540. if ((cm->Error && !numErrorsAllowed) ||
  541. (!cm->Error && !numWarningsAllowed)) {
  542. xml.Content("\nThe maximum number of reported warnings or errors "
  543. "has been reached!!!\n");
  544. }
  545. xml.EndElement(); // PostContext
  546. xml.Element("RepeatCount", "0");
  547. xml.EndElement(); // "Error" / "Warning"
  548. }
  549. }
  550. }
  551. void cmCTestBuildHandler::GenerateInstrumentationXML(cmXMLWriter& xml)
  552. {
  553. // Record instrumentation data on a per-target basis.
  554. cmsys::Directory targets_dir;
  555. std::string targets_snippet_dir = cmStrCat(
  556. this->CTest->GetInstrumentation().GetCDashDir(), "/build/targets");
  557. if (targets_dir.Load(targets_snippet_dir) &&
  558. targets_dir.GetNumberOfFiles() > 0) {
  559. xml.StartElement("Targets");
  560. for (unsigned int i = 0; i < targets_dir.GetNumberOfFiles(); i++) {
  561. if (!targets_dir.FileIsDirectory(i)) {
  562. continue;
  563. }
  564. std::string target_name = targets_dir.GetFile(i);
  565. if (target_name == "." || target_name == "..") {
  566. continue;
  567. }
  568. std::string target_type = "UNKNOWN";
  569. xml.StartElement("Target");
  570. xml.Attribute("name", target_name);
  571. // Check if we have a link snippet for this target.
  572. cmsys::Directory target_dir;
  573. if (!target_dir.Load(targets_dir.GetFilePath(i))) {
  574. cmSystemTools::Error(
  575. cmStrCat("Error loading directory ", targets_dir.GetFilePath(i)));
  576. }
  577. Json::Value link_item;
  578. for (unsigned int j = 0; j < target_dir.GetNumberOfFiles(); j++) {
  579. std::string fname = target_dir.GetFile(j);
  580. if (fname.rfind("link-", 0) == 0) {
  581. std::string fpath = target_dir.GetFilePath(j);
  582. cmJSONState parseState = cmJSONState(fpath, &link_item);
  583. if (!parseState.errors.empty()) {
  584. cmSystemTools::Error(parseState.GetErrorMessage(true));
  585. break;
  586. }
  587. if (!link_item.isObject()) {
  588. std::string error_msg =
  589. cmStrCat("Expected snippet ", fpath, " to contain an object");
  590. cmSystemTools::Error(error_msg);
  591. break;
  592. }
  593. break;
  594. }
  595. }
  596. // If so, parse targetType and targetLabels (optional) from it.
  597. if (link_item.isMember("targetType")) {
  598. target_type = link_item["targetType"].asString();
  599. }
  600. xml.Attribute("type", target_type);
  601. if (link_item.isMember("targetLabels") &&
  602. !link_item["targetLabels"].empty()) {
  603. xml.StartElement("Labels");
  604. for (auto const& json_label_item : link_item["targetLabels"]) {
  605. xml.Element("Label", json_label_item.asString());
  606. }
  607. xml.EndElement(); // Labels
  608. }
  609. // Write instrumendation data for this target.
  610. std::string target_subdir = cmStrCat("build/targets/", target_name);
  611. this->CTest->ConvertInstrumentationSnippetsToXML(xml, target_subdir);
  612. std::string target_dir_fullpath = cmStrCat(
  613. this->CTest->GetInstrumentation().GetCDashDir(), '/', target_subdir);
  614. if (cmSystemTools::FileIsDirectory(target_dir_fullpath)) {
  615. cmSystemTools::RemoveADirectory(target_dir_fullpath);
  616. }
  617. xml.EndElement(); // Target
  618. }
  619. xml.EndElement(); // Targets
  620. }
  621. // Also record instrumentation data for custom commands (no target).
  622. this->CTest->ConvertInstrumentationSnippetsToXML(xml, "build/commands");
  623. }
  624. void cmCTestBuildHandler::GenerateXMLFooter(cmXMLWriter& xml,
  625. cmDuration elapsed_build_time)
  626. {
  627. xml.StartElement("Log");
  628. xml.Attribute("Encoding", "base64");
  629. xml.Attribute("Compression", "bin/gzip");
  630. xml.EndElement(); // Log
  631. xml.Element("EndDateTime", this->EndBuild);
  632. xml.Element("EndBuildTime", this->EndBuildTime);
  633. xml.Element(
  634. "ElapsedMinutes",
  635. std::chrono::duration_cast<std::chrono::minutes>(elapsed_build_time)
  636. .count());
  637. xml.EndElement(); // Build
  638. this->CTest->EndXML(xml);
  639. }
  640. bool cmCTestBuildHandler::IsLaunchedErrorFile(char const* fname)
  641. {
  642. // error-{hash}.xml
  643. return (cmHasLiteralPrefix(fname, "error-") &&
  644. cmHasLiteralSuffix(fname, ".xml"));
  645. }
  646. bool cmCTestBuildHandler::IsLaunchedWarningFile(char const* fname)
  647. {
  648. // warning-{hash}.xml
  649. return (cmHasLiteralPrefix(fname, "warning-") &&
  650. cmHasLiteralSuffix(fname, ".xml"));
  651. }
  652. // ######################################################################
  653. // ######################################################################
  654. // ######################################################################
  655. // ######################################################################
  656. class cmCTestBuildHandler::LaunchHelper
  657. {
  658. public:
  659. LaunchHelper(cmCTestBuildHandler* handler);
  660. ~LaunchHelper();
  661. LaunchHelper(LaunchHelper const&) = delete;
  662. LaunchHelper& operator=(LaunchHelper const&) = delete;
  663. private:
  664. cmCTestBuildHandler* Handler;
  665. cmCTest* CTest;
  666. void WriteLauncherConfig();
  667. void WriteScrapeMatchers(char const* purpose,
  668. std::vector<std::string> const& matchers);
  669. };
  670. cmCTestBuildHandler::LaunchHelper::LaunchHelper(cmCTestBuildHandler* handler)
  671. : Handler(handler)
  672. , CTest(handler->CTest)
  673. {
  674. std::string tag = this->CTest->GetCurrentTag();
  675. if (tag.empty()) {
  676. // This is not for a dashboard submission, so there is no XML.
  677. // Skip enabling the launchers.
  678. this->Handler->UseCTestLaunch = false;
  679. } else {
  680. // Compute a directory in which to store launcher fragments.
  681. std::string& launchDir = this->Handler->CTestLaunchDir;
  682. launchDir =
  683. cmStrCat(this->CTest->GetBinaryDir(), "/Testing/", tag, "/Build");
  684. // Clean out any existing launcher fragments.
  685. cmSystemTools::RemoveADirectory(launchDir);
  686. if (this->Handler->UseCTestLaunch) {
  687. // Enable launcher fragments.
  688. cmSystemTools::MakeDirectory(launchDir);
  689. this->WriteLauncherConfig();
  690. std::string launchEnv = cmStrCat("CTEST_LAUNCH_LOGS=", launchDir);
  691. cmSystemTools::PutEnv(launchEnv);
  692. }
  693. }
  694. // If not using launchers, make sure they passthru.
  695. if (!this->Handler->UseCTestLaunch) {
  696. cmSystemTools::UnsetEnv("CTEST_LAUNCH_LOGS");
  697. }
  698. }
  699. cmCTestBuildHandler::LaunchHelper::~LaunchHelper()
  700. {
  701. if (this->Handler->UseCTestLaunch) {
  702. cmSystemTools::UnsetEnv("CTEST_LAUNCH_LOGS");
  703. }
  704. }
  705. void cmCTestBuildHandler::LaunchHelper::WriteLauncherConfig()
  706. {
  707. this->WriteScrapeMatchers("Warning",
  708. this->Handler->ReallyCustomWarningMatches);
  709. this->WriteScrapeMatchers("WarningSuppress",
  710. this->Handler->ReallyCustomWarningExceptions);
  711. // Give some testing configuration information to the launcher.
  712. std::string fname =
  713. cmStrCat(this->Handler->CTestLaunchDir, "/CTestLaunchConfig.cmake");
  714. cmGeneratedFileStream fout(fname);
  715. std::string srcdir = this->CTest->GetCTestConfiguration("SourceDirectory");
  716. fout << "set(CTEST_SOURCE_DIRECTORY \"" << srcdir << "\")\n";
  717. }
  718. void cmCTestBuildHandler::LaunchHelper::WriteScrapeMatchers(
  719. char const* purpose, std::vector<std::string> const& matchers)
  720. {
  721. if (matchers.empty()) {
  722. return;
  723. }
  724. std::string fname =
  725. cmStrCat(this->Handler->CTestLaunchDir, "/Custom", purpose, ".txt");
  726. cmGeneratedFileStream fout(fname);
  727. for (std::string const& m : matchers) {
  728. fout << m << "\n";
  729. }
  730. }
  731. bool cmCTestBuildHandler::RunMakeCommand(std::string const& command,
  732. int* retVal, char const* dir,
  733. int timeout, std::ostream& ofs,
  734. Encoding encoding)
  735. {
  736. // First generate the command and arguments
  737. std::vector<std::string> args = cmSystemTools::ParseArguments(command);
  738. if (args.empty()) {
  739. return false;
  740. }
  741. cmCTestOptionalLog(this->CTest, HANDLER_VERBOSE_OUTPUT,
  742. "Run command:", this->Quiet);
  743. for (auto const& arg : args) {
  744. cmCTestOptionalLog(this->CTest, HANDLER_VERBOSE_OUTPUT,
  745. " \"" << arg << "\"", this->Quiet);
  746. }
  747. cmCTestOptionalLog(this->CTest, HANDLER_VERBOSE_OUTPUT, std::endl,
  748. this->Quiet);
  749. // Optionally use make rule launchers to record errors and warnings.
  750. LaunchHelper launchHelper(this);
  751. static_cast<void>(launchHelper);
  752. // Now create process object
  753. cmUVProcessChainBuilder builder;
  754. builder.AddCommand(args)
  755. .SetBuiltinStream(cmUVProcessChainBuilder::Stream_OUTPUT)
  756. .SetBuiltinStream(cmUVProcessChainBuilder::Stream_ERROR);
  757. if (dir) {
  758. builder.SetWorkingDirectory(dir);
  759. }
  760. auto chain = builder.Start();
  761. // Initialize tick's
  762. std::string::size_type tick = 0;
  763. static constexpr std::string::size_type tick_len = 1024;
  764. cmProcessOutput processOutput(encoding);
  765. cmCTestOptionalLog(
  766. this->CTest, HANDLER_PROGRESS_OUTPUT,
  767. " Each symbol represents "
  768. << tick_len << " bytes of output." << std::endl
  769. << (this->UseCTestLaunch
  770. ? ""
  771. : " '!' represents an error and '*' a warning.\n")
  772. << " " << std::flush,
  773. this->Quiet);
  774. // Initialize building structures
  775. this->BuildProcessingQueue.clear();
  776. this->OutputLineCounter = 0;
  777. this->ErrorsAndWarnings.clear();
  778. this->TotalErrors = 0;
  779. this->TotalWarnings = 0;
  780. this->BuildOutputLogSize = 0;
  781. this->LastTickChar = '.';
  782. this->WarningQuotaReached = false;
  783. this->ErrorQuotaReached = false;
  784. cm::uv_timer_ptr timer;
  785. bool timedOut = false;
  786. timer.init(chain.GetLoop(), &timedOut);
  787. if (timeout > 0) {
  788. timer.start(
  789. [](uv_timer_t* t) {
  790. auto* timedOutPtr = static_cast<bool*>(t->data);
  791. *timedOutPtr = true;
  792. },
  793. timeout * 1000, 0);
  794. }
  795. // For every chunk of data
  796. cm::uv_pipe_ptr outputStream;
  797. bool outFinished = false;
  798. cm::uv_pipe_ptr errorStream;
  799. bool errFinished = false;
  800. auto startRead = [this, &chain, &processOutput, &tick,
  801. &ofs](cm::uv_pipe_ptr& pipe, int stream,
  802. t_BuildProcessingQueueType& queue, bool& finished,
  803. int id) -> std::unique_ptr<cmUVStreamReadHandle> {
  804. pipe.init(chain.GetLoop(), 0);
  805. uv_pipe_open(pipe, stream);
  806. return cmUVStreamRead(
  807. pipe,
  808. [this, &processOutput, &queue, id, &tick, &ofs](std::vector<char> data) {
  809. // Replace '\0' with '\n', since '\0' does not really make sense. This
  810. // is for Visual Studio output
  811. for (auto& c : data) {
  812. if (c == 0) {
  813. c = '\n';
  814. }
  815. }
  816. // Process the chunk of data
  817. std::string strdata;
  818. processOutput.DecodeText(data.data(), data.size(), strdata, id);
  819. this->ProcessBuffer(strdata.c_str(), strdata.size(), tick, tick_len,
  820. ofs, &queue);
  821. },
  822. [this, &processOutput, &queue, id, &tick, &ofs, &finished]() {
  823. std::string strdata;
  824. processOutput.DecodeText(std::string(), strdata, id);
  825. if (!strdata.empty()) {
  826. this->ProcessBuffer(strdata.c_str(), strdata.size(), tick, tick_len,
  827. ofs, &queue);
  828. }
  829. finished = true;
  830. });
  831. };
  832. auto outputHandle = startRead(outputStream, chain.OutputStream(),
  833. this->BuildProcessingQueue, outFinished, 1);
  834. auto errorHandle =
  835. startRead(errorStream, chain.ErrorStream(),
  836. this->BuildProcessingErrorQueue, errFinished, 2);
  837. while (!timedOut && !(outFinished && errFinished && chain.Finished())) {
  838. uv_run(&chain.GetLoop(), UV_RUN_ONCE);
  839. }
  840. this->ProcessBuffer(nullptr, 0, tick, tick_len, ofs,
  841. &this->BuildProcessingQueue);
  842. this->ProcessBuffer(nullptr, 0, tick, tick_len, ofs,
  843. &this->BuildProcessingErrorQueue);
  844. cmCTestOptionalLog(this->CTest, HANDLER_PROGRESS_OUTPUT,
  845. " Size of output: "
  846. << ((this->BuildOutputLogSize + 512) / 1024) << "K"
  847. << std::endl,
  848. this->Quiet);
  849. if (chain.Finished()) {
  850. auto const& status = chain.GetStatus(0);
  851. auto exception = status.GetException();
  852. switch (exception.first) {
  853. case cmUVProcessChain::ExceptionCode::None:
  854. if (retVal) {
  855. *retVal = static_cast<int>(status.ExitStatus);
  856. cmCTestOptionalLog(this->CTest, HANDLER_VERBOSE_OUTPUT,
  857. "Command exited with the value: " << *retVal
  858. << std::endl,
  859. this->Quiet);
  860. // if a non zero return value
  861. if (*retVal) {
  862. // If there was an error running command, report that on the
  863. // dashboard.
  864. if (this->UseCTestLaunch) {
  865. // For launchers, do not record this top-level error if other
  866. // more granular build errors have already been captured.
  867. bool launcherXMLFound = false;
  868. cmsys::Directory launchDir;
  869. launchDir.Load(this->CTestLaunchDir);
  870. unsigned long n = launchDir.GetNumberOfFiles();
  871. for (unsigned long i = 0; i < n; ++i) {
  872. char const* fname = launchDir.GetFile(i);
  873. if (cmHasLiteralSuffix(fname, ".xml")) {
  874. launcherXMLFound = true;
  875. break;
  876. }
  877. }
  878. if (!launcherXMLFound) {
  879. cmCTestLaunchReporter reporter;
  880. reporter.RealArgs = args;
  881. reporter.ComputeFileNames();
  882. reporter.ExitCode = *retVal;
  883. reporter.Status = status;
  884. // Use temporary BuildLog file to populate this error for
  885. // CDash.
  886. ofs.flush();
  887. reporter.LogOut = this->LogFileName;
  888. reporter.WriteXML();
  889. }
  890. } else {
  891. cmCTestBuildErrorWarning errorwarning;
  892. errorwarning.LineNumber = 0;
  893. errorwarning.LogLine = 1;
  894. errorwarning.Text = cmStrCat(
  895. "*** WARNING non-zero return value in ctest from: ", args[0]);
  896. errorwarning.PreContext.clear();
  897. errorwarning.PostContext.clear();
  898. errorwarning.Error = false;
  899. this->ErrorsAndWarnings.push_back(std::move(errorwarning));
  900. this->TotalWarnings++;
  901. }
  902. }
  903. }
  904. break;
  905. case cmUVProcessChain::ExceptionCode::Spawn: {
  906. // If there was an error running command, report that on the dashboard.
  907. cmCTestBuildErrorWarning errorwarning;
  908. errorwarning.LineNumber = 0;
  909. errorwarning.LogLine = 1;
  910. errorwarning.Text =
  911. cmStrCat("*** ERROR executing: ", exception.second);
  912. errorwarning.PreContext.clear();
  913. errorwarning.PostContext.clear();
  914. errorwarning.Error = true;
  915. this->ErrorsAndWarnings.push_back(std::move(errorwarning));
  916. this->TotalErrors++;
  917. cmCTestLog(this->CTest, ERROR_MESSAGE,
  918. "There was an error: " << exception.second << std::endl);
  919. } break;
  920. default:
  921. if (retVal) {
  922. *retVal = status.TermSignal;
  923. cmCTestOptionalLog(
  924. this->CTest, WARNING,
  925. "There was an exception: " << *retVal << std::endl, this->Quiet);
  926. }
  927. break;
  928. }
  929. } else {
  930. cmCTestOptionalLog(this->CTest, WARNING,
  931. "There was a timeout" << std::endl, this->Quiet);
  932. }
  933. return true;
  934. }
  935. // ######################################################################
  936. // ######################################################################
  937. // ######################################################################
  938. // ######################################################################
  939. void cmCTestBuildHandler::ProcessBuffer(char const* data, size_t length,
  940. size_t& tick, size_t tick_len,
  941. std::ostream& ofs,
  942. t_BuildProcessingQueueType* queue)
  943. {
  944. std::string::size_type const tick_line_len = 50;
  945. char const* ptr;
  946. for (ptr = data; ptr < data + length; ptr++) {
  947. queue->push_back(*ptr);
  948. }
  949. this->BuildOutputLogSize += length;
  950. // until there are any lines left in the buffer
  951. while (true) {
  952. // Find the end of line
  953. t_BuildProcessingQueueType::iterator it;
  954. for (it = queue->begin(); it != queue->end(); ++it) {
  955. if (*it == '\n') {
  956. break;
  957. }
  958. }
  959. // Once certain number of errors or warnings reached, ignore future errors
  960. // or warnings.
  961. if (this->TotalWarnings >= this->MaxWarnings) {
  962. this->WarningQuotaReached = true;
  963. }
  964. if (this->TotalErrors >= this->MaxErrors) {
  965. this->ErrorQuotaReached = true;
  966. }
  967. // If the end of line was found
  968. if (it != queue->end()) {
  969. // Create a contiguous array for the line
  970. this->CurrentProcessingLine.clear();
  971. cm::append(this->CurrentProcessingLine, queue->begin(), it);
  972. this->CurrentProcessingLine.push_back(0);
  973. char const* line = this->CurrentProcessingLine.data();
  974. // Process the line
  975. int lineType = this->ProcessSingleLine(line);
  976. // Erase the line from the queue
  977. queue->erase(queue->begin(), it + 1);
  978. // Depending on the line type, produce error or warning, or nothing
  979. cmCTestBuildErrorWarning errorwarning;
  980. bool found = false;
  981. switch (lineType) {
  982. case b_WARNING_LINE:
  983. this->LastTickChar = '*';
  984. errorwarning.Error = false;
  985. found = true;
  986. this->TotalWarnings++;
  987. break;
  988. case b_ERROR_LINE:
  989. this->LastTickChar = '!';
  990. errorwarning.Error = true;
  991. found = true;
  992. this->TotalErrors++;
  993. break;
  994. }
  995. if (found) {
  996. // This is an error or warning, so generate report
  997. errorwarning.LogLine = static_cast<int>(this->OutputLineCounter + 1);
  998. errorwarning.Text = line;
  999. errorwarning.PreContext.clear();
  1000. errorwarning.PostContext.clear();
  1001. // Copy pre-context to report
  1002. for (std::string const& pc : this->PreContext) {
  1003. errorwarning.PreContext += pc + "\n";
  1004. }
  1005. this->PreContext.clear();
  1006. // Store report
  1007. this->ErrorsAndWarnings.push_back(std::move(errorwarning));
  1008. this->LastErrorOrWarning = this->ErrorsAndWarnings.end() - 1;
  1009. this->PostContextCount = 0;
  1010. } else {
  1011. // This is not an error or warning.
  1012. // So, figure out if this is a post-context line
  1013. if (!this->ErrorsAndWarnings.empty() &&
  1014. this->LastErrorOrWarning != this->ErrorsAndWarnings.end() &&
  1015. this->PostContextCount < this->MaxPostContext) {
  1016. this->PostContextCount++;
  1017. this->LastErrorOrWarning->PostContext += line;
  1018. if (this->PostContextCount < this->MaxPostContext) {
  1019. this->LastErrorOrWarning->PostContext += "\n";
  1020. }
  1021. } else {
  1022. // Otherwise store pre-context for the next error
  1023. this->PreContext.emplace_back(line);
  1024. if (this->PreContext.size() > this->MaxPreContext) {
  1025. this->PreContext.erase(this->PreContext.begin(),
  1026. this->PreContext.end() -
  1027. this->MaxPreContext);
  1028. }
  1029. }
  1030. }
  1031. this->OutputLineCounter++;
  1032. } else {
  1033. break;
  1034. }
  1035. }
  1036. // Now that the buffer is processed, display missing ticks
  1037. int tickDisplayed = false;
  1038. while (this->BuildOutputLogSize > (tick * tick_len)) {
  1039. tick++;
  1040. cmCTestOptionalLog(this->CTest, HANDLER_PROGRESS_OUTPUT,
  1041. this->LastTickChar, this->Quiet);
  1042. tickDisplayed = true;
  1043. if (tick % tick_line_len == 0 && tick > 0) {
  1044. cmCTestOptionalLog(this->CTest, HANDLER_PROGRESS_OUTPUT,
  1045. " Size: "
  1046. << ((this->BuildOutputLogSize + 512) / 1024) << "K"
  1047. << std::endl
  1048. << " ",
  1049. this->Quiet);
  1050. }
  1051. }
  1052. if (tickDisplayed) {
  1053. this->LastTickChar = '.';
  1054. }
  1055. // And if this is verbose output, display the content of the chunk
  1056. cmCTestLog(this->CTest, HANDLER_VERBOSE_OUTPUT,
  1057. cm::string_view(data, length));
  1058. // Always store the chunk to the file
  1059. ofs << cm::string_view(data, length);
  1060. }
  1061. int cmCTestBuildHandler::ProcessSingleLine(char const* data)
  1062. {
  1063. if (this->UseCTestLaunch) {
  1064. // No log scraping when using launchers.
  1065. return b_REGULAR_LINE;
  1066. }
  1067. // Ignore ANSI color codes when checking for errors and warnings.
  1068. std::string input(data);
  1069. std::string line;
  1070. this->ColorRemover->Replace(input, line);
  1071. cmCTestOptionalLog(this->CTest, DEBUG, "Line: [" << line << "]" << std::endl,
  1072. this->Quiet);
  1073. int warningLine = 0;
  1074. int errorLine = 0;
  1075. // Check for regular expressions
  1076. if (!this->ErrorQuotaReached) {
  1077. // Errors
  1078. int wrxCnt = 0;
  1079. for (cmsys::RegularExpression& rx : this->ErrorMatchRegex) {
  1080. if (rx.find(line.c_str())) {
  1081. errorLine = 1;
  1082. cmCTestOptionalLog(this->CTest, DEBUG,
  1083. " Error Line: " << line << " (matches: "
  1084. << this->CustomErrorMatches[wrxCnt]
  1085. << ")" << std::endl,
  1086. this->Quiet);
  1087. break;
  1088. }
  1089. wrxCnt++;
  1090. }
  1091. // Error exceptions
  1092. wrxCnt = 0;
  1093. for (cmsys::RegularExpression& rx : this->ErrorExceptionRegex) {
  1094. if (rx.find(line.c_str())) {
  1095. errorLine = 0;
  1096. cmCTestOptionalLog(this->CTest, DEBUG,
  1097. " Not an error Line: "
  1098. << line << " (matches: "
  1099. << this->CustomErrorExceptions[wrxCnt] << ")"
  1100. << std::endl,
  1101. this->Quiet);
  1102. break;
  1103. }
  1104. wrxCnt++;
  1105. }
  1106. }
  1107. if (!this->WarningQuotaReached) {
  1108. // Warnings
  1109. int wrxCnt = 0;
  1110. for (cmsys::RegularExpression& rx : this->WarningMatchRegex) {
  1111. if (rx.find(line.c_str())) {
  1112. warningLine = 1;
  1113. cmCTestOptionalLog(this->CTest, DEBUG,
  1114. " Warning Line: "
  1115. << line << " (matches: "
  1116. << this->CustomWarningMatches[wrxCnt] << ")"
  1117. << std::endl,
  1118. this->Quiet);
  1119. break;
  1120. }
  1121. wrxCnt++;
  1122. }
  1123. wrxCnt = 0;
  1124. // Warning exceptions
  1125. for (cmsys::RegularExpression& rx : this->WarningExceptionRegex) {
  1126. if (rx.find(line.c_str())) {
  1127. warningLine = 0;
  1128. cmCTestOptionalLog(this->CTest, DEBUG,
  1129. " Not a warning Line: "
  1130. << line << " (matches: "
  1131. << this->CustomWarningExceptions[wrxCnt] << ")"
  1132. << std::endl,
  1133. this->Quiet);
  1134. break;
  1135. }
  1136. wrxCnt++;
  1137. }
  1138. }
  1139. if (errorLine) {
  1140. return b_ERROR_LINE;
  1141. }
  1142. if (warningLine) {
  1143. return b_WARNING_LINE;
  1144. }
  1145. return b_REGULAR_LINE;
  1146. }