cmCTest.cxx 95 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038
  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 "cmCTest.h"
  4. #include "cm_curl.h"
  5. #include "cm_zlib.h"
  6. #include "cmsys/Base64.h"
  7. #include "cmsys/Directory.hxx"
  8. #include "cmsys/FStream.hxx"
  9. #include "cmsys/Glob.hxx"
  10. #include "cmsys/Process.h"
  11. #include "cmsys/SystemInformation.hxx"
  12. #include <algorithm>
  13. #include <chrono>
  14. #include <ctype.h>
  15. #include <iostream>
  16. #include <map>
  17. #include <memory> // IWYU pragma: keep
  18. #include <sstream>
  19. #include <stdio.h>
  20. #include <stdlib.h>
  21. #include <string.h>
  22. #include <string>
  23. #include <time.h>
  24. #include <utility>
  25. #include <vector>
  26. #if defined(_WIN32)
  27. # include <windows.h> // IWYU pragma: keep
  28. #else
  29. # include <unistd.h> // IWYU pragma: keep
  30. #endif
  31. #include "cmAlgorithms.h"
  32. #include "cmCTestBuildAndTestHandler.h"
  33. #include "cmCTestBuildHandler.h"
  34. #include "cmCTestConfigureHandler.h"
  35. #include "cmCTestCoverageHandler.h"
  36. #include "cmCTestGenericHandler.h"
  37. #include "cmCTestMemCheckHandler.h"
  38. #include "cmCTestScriptHandler.h"
  39. #include "cmCTestStartCommand.h"
  40. #include "cmCTestSubmitHandler.h"
  41. #include "cmCTestTestHandler.h"
  42. #include "cmCTestUpdateHandler.h"
  43. #include "cmCTestUploadHandler.h"
  44. #include "cmCurl.h"
  45. #include "cmDynamicLoader.h"
  46. #include "cmGeneratedFileStream.h"
  47. #include "cmGlobalGenerator.h"
  48. #include "cmMakefile.h"
  49. #include "cmProcessOutput.h"
  50. #include "cmState.h"
  51. #include "cmStateSnapshot.h"
  52. #include "cmStateTypes.h"
  53. #include "cmSystemTools.h"
  54. #include "cmVersion.h"
  55. #include "cmVersionConfig.h"
  56. #include "cmXMLWriter.h"
  57. #include "cmake.h"
  58. #if defined(__BEOS__) || defined(__HAIKU__)
  59. # include <be/kernel/OS.h> /* disable_debugger() API. */
  60. #endif
  61. #define DEBUGOUT \
  62. std::cout << __LINE__ << " "; \
  63. std::cout
  64. #define DEBUGERR \
  65. std::cerr << __LINE__ << " "; \
  66. std::cerr
  67. struct tm* cmCTest::GetNightlyTime(std::string const& str, bool tomorrowtag)
  68. {
  69. struct tm* lctime;
  70. time_t tctime = time(nullptr);
  71. lctime = gmtime(&tctime);
  72. char buf[1024];
  73. // add todays year day and month to the time in str because
  74. // curl_getdate no longer assumes the day is today
  75. sprintf(buf, "%d%02d%02d %s", lctime->tm_year + 1900, lctime->tm_mon + 1,
  76. lctime->tm_mday, str.c_str());
  77. cmCTestLog(this, OUTPUT,
  78. "Determine Nightly Start Time" << std::endl
  79. << " Specified time: " << str
  80. << std::endl);
  81. // Convert the nightly start time to seconds. Since we are
  82. // providing only a time and a timezone, the current date of
  83. // the local machine is assumed. Consequently, nightlySeconds
  84. // is the time at which the nightly dashboard was opened or
  85. // will be opened on the date of the current client machine.
  86. // As such, this time may be in the past or in the future.
  87. time_t ntime = curl_getdate(buf, &tctime);
  88. cmCTestLog(this, DEBUG, " Get curl time: " << ntime << std::endl);
  89. tctime = time(nullptr);
  90. cmCTestLog(this, DEBUG, " Get the current time: " << tctime << std::endl);
  91. const int dayLength = 24 * 60 * 60;
  92. cmCTestLog(this, DEBUG, "Seconds: " << tctime << std::endl);
  93. while (ntime > tctime) {
  94. // If nightlySeconds is in the past, this is the current
  95. // open dashboard, then return nightlySeconds. If
  96. // nightlySeconds is in the future, this is the next
  97. // dashboard to be opened, so subtract 24 hours to get the
  98. // time of the current open dashboard
  99. ntime -= dayLength;
  100. cmCTestLog(this, DEBUG, "Pick yesterday" << std::endl);
  101. cmCTestLog(this, DEBUG,
  102. " Future time, subtract day: " << ntime << std::endl);
  103. }
  104. while (tctime > (ntime + dayLength)) {
  105. ntime += dayLength;
  106. cmCTestLog(this, DEBUG, " Past time, add day: " << ntime << std::endl);
  107. }
  108. cmCTestLog(this, DEBUG, "nightlySeconds: " << ntime << std::endl);
  109. cmCTestLog(this, DEBUG,
  110. " Current time: " << tctime << " Nightly time: " << ntime
  111. << std::endl);
  112. if (tomorrowtag) {
  113. cmCTestLog(this, OUTPUT, " Use future tag, Add a day" << std::endl);
  114. ntime += dayLength;
  115. }
  116. lctime = gmtime(&ntime);
  117. return lctime;
  118. }
  119. std::string cmCTest::CleanString(const std::string& str)
  120. {
  121. std::string::size_type spos = str.find_first_not_of(" \n\t\r\f\v");
  122. std::string::size_type epos = str.find_last_not_of(" \n\t\r\f\v");
  123. if (spos == std::string::npos) {
  124. return std::string();
  125. }
  126. if (epos != std::string::npos) {
  127. epos = epos - spos + 1;
  128. }
  129. return str.substr(spos, epos);
  130. }
  131. std::string cmCTest::CurrentTime()
  132. {
  133. time_t currenttime = time(nullptr);
  134. struct tm* t = localtime(&currenttime);
  135. // return ::CleanString(ctime(&currenttime));
  136. char current_time[1024];
  137. if (this->ShortDateFormat) {
  138. strftime(current_time, 1000, "%b %d %H:%M %Z", t);
  139. } else {
  140. strftime(current_time, 1000, "%a %b %d %H:%M:%S %Z %Y", t);
  141. }
  142. cmCTestLog(this, DEBUG, " Current_Time: " << current_time << std::endl);
  143. return cmCTest::CleanString(current_time);
  144. }
  145. std::string cmCTest::GetCostDataFile()
  146. {
  147. std::string fname = this->GetCTestConfiguration("CostDataFile");
  148. if (fname.empty()) {
  149. fname = this->GetBinaryDir() + "/Testing/Temporary/CTestCostData.txt";
  150. }
  151. return fname;
  152. }
  153. #ifdef CMAKE_BUILD_WITH_CMAKE
  154. static size_t HTTPResponseCallback(void* ptr, size_t size, size_t nmemb,
  155. void* data)
  156. {
  157. int realsize = static_cast<int>(size * nmemb);
  158. std::string* response = static_cast<std::string*>(data);
  159. const char* chPtr = static_cast<char*>(ptr);
  160. *response += chPtr;
  161. return realsize;
  162. }
  163. int cmCTest::HTTPRequest(std::string url, HTTPMethod method,
  164. std::string& response, std::string const& fields,
  165. std::string const& putFile, int timeout)
  166. {
  167. CURL* curl;
  168. FILE* file;
  169. ::curl_global_init(CURL_GLOBAL_ALL);
  170. curl = ::curl_easy_init();
  171. cmCurlSetCAInfo(curl);
  172. // set request options based on method
  173. switch (method) {
  174. case cmCTest::HTTP_POST:
  175. ::curl_easy_setopt(curl, CURLOPT_POST, 1);
  176. ::curl_easy_setopt(curl, CURLOPT_POSTFIELDS, fields.c_str());
  177. break;
  178. case cmCTest::HTTP_PUT:
  179. if (!cmSystemTools::FileExists(putFile)) {
  180. response = "Error: File ";
  181. response += putFile + " does not exist.\n";
  182. return -1;
  183. }
  184. ::curl_easy_setopt(curl, CURLOPT_PUT, 1);
  185. file = cmsys::SystemTools::Fopen(putFile, "rb");
  186. ::curl_easy_setopt(curl, CURLOPT_INFILE, file);
  187. // fall through to append GET fields
  188. CM_FALLTHROUGH;
  189. case cmCTest::HTTP_GET:
  190. if (!fields.empty()) {
  191. url += "?" + fields;
  192. }
  193. break;
  194. }
  195. ::curl_easy_setopt(curl, CURLOPT_URL, url.c_str());
  196. ::curl_easy_setopt(curl, CURLOPT_TIMEOUT, timeout);
  197. ::curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1);
  198. // set response options
  199. ::curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, HTTPResponseCallback);
  200. ::curl_easy_setopt(curl, CURLOPT_FILE, &response);
  201. ::curl_easy_setopt(curl, CURLOPT_FAILONERROR, 1);
  202. CURLcode res = ::curl_easy_perform(curl);
  203. ::curl_easy_cleanup(curl);
  204. ::curl_global_cleanup();
  205. return static_cast<int>(res);
  206. }
  207. #endif
  208. std::string cmCTest::MakeURLSafe(const std::string& str)
  209. {
  210. std::ostringstream ost;
  211. char buffer[10];
  212. for (unsigned char ch : str) {
  213. if ((ch > 126 || ch < 32 || ch == '&' || ch == '%' || ch == '+' ||
  214. ch == '=' || ch == '@') &&
  215. ch != 9) {
  216. sprintf(buffer, "%02x;", static_cast<unsigned int>(ch));
  217. ost << buffer;
  218. } else {
  219. ost << ch;
  220. }
  221. }
  222. return ost.str();
  223. }
  224. std::string cmCTest::DecodeURL(const std::string& in)
  225. {
  226. std::string out;
  227. for (const char* c = in.c_str(); *c; ++c) {
  228. if (*c == '%' && isxdigit(*(c + 1)) && isxdigit(*(c + 2))) {
  229. char buf[3] = { *(c + 1), *(c + 2), 0 };
  230. out.append(1, char(strtoul(buf, nullptr, 16)));
  231. c += 2;
  232. } else {
  233. out.append(1, *c);
  234. }
  235. }
  236. return out;
  237. }
  238. cmCTest::cmCTest()
  239. {
  240. this->LabelSummary = true;
  241. this->SubprojectSummary = true;
  242. this->ParallelLevel = 1;
  243. this->ParallelLevelSetInCli = false;
  244. this->TestLoad = 0;
  245. this->SubmitIndex = 0;
  246. this->Failover = false;
  247. this->ForceNewCTestProcess = false;
  248. this->TomorrowTag = false;
  249. this->TestProgressOutput = false;
  250. this->FlushTestProgressLine = false;
  251. this->Verbose = false;
  252. this->Debug = false;
  253. this->ShowLineNumbers = false;
  254. this->Quiet = false;
  255. this->ExtraVerbose = false;
  256. this->ProduceXML = false;
  257. this->ShowOnly = false;
  258. this->RunConfigurationScript = false;
  259. this->UseHTTP10 = false;
  260. this->PrintLabels = false;
  261. this->CompressTestOutput = true;
  262. this->TestModel = cmCTest::EXPERIMENTAL;
  263. this->MaxTestNameWidth = 30;
  264. this->InteractiveDebugMode = true;
  265. this->TimeOut = cmDuration::zero();
  266. this->GlobalTimeout = cmDuration::zero();
  267. this->CompressXMLFiles = false;
  268. this->ScheduleType.clear();
  269. this->OutputLogFile = nullptr;
  270. this->OutputLogFileLastTag = -1;
  271. this->SuppressUpdatingCTestConfiguration = false;
  272. this->DartVersion = 1;
  273. this->DropSiteCDash = false;
  274. this->BuildID = "";
  275. this->OutputTestOutputOnTestFailure = false;
  276. this->RepeatTests = 1; // default to run each test once
  277. this->RepeatUntilFail = false;
  278. std::string envValue;
  279. if (cmSystemTools::GetEnv("CTEST_OUTPUT_ON_FAILURE", envValue)) {
  280. this->OutputTestOutputOnTestFailure = !cmSystemTools::IsOff(envValue);
  281. }
  282. envValue.clear();
  283. if (cmSystemTools::GetEnv("CTEST_PROGRESS_OUTPUT", envValue)) {
  284. this->TestProgressOutput = !cmSystemTools::IsOff(envValue);
  285. }
  286. this->InitStreams();
  287. this->Parts[PartStart].SetName("Start");
  288. this->Parts[PartUpdate].SetName("Update");
  289. this->Parts[PartConfigure].SetName("Configure");
  290. this->Parts[PartBuild].SetName("Build");
  291. this->Parts[PartTest].SetName("Test");
  292. this->Parts[PartCoverage].SetName("Coverage");
  293. this->Parts[PartMemCheck].SetName("MemCheck");
  294. this->Parts[PartSubmit].SetName("Submit");
  295. this->Parts[PartNotes].SetName("Notes");
  296. this->Parts[PartExtraFiles].SetName("ExtraFiles");
  297. this->Parts[PartUpload].SetName("Upload");
  298. this->Parts[PartDone].SetName("Done");
  299. // Fill the part name-to-id map.
  300. for (Part p = PartStart; p != PartCount; p = Part(p + 1)) {
  301. this->PartMap[cmSystemTools::LowerCase(this->Parts[p].GetName())] = p;
  302. }
  303. this->ShortDateFormat = true;
  304. this->TestingHandlers["build"] = new cmCTestBuildHandler;
  305. this->TestingHandlers["buildtest"] = new cmCTestBuildAndTestHandler;
  306. this->TestingHandlers["coverage"] = new cmCTestCoverageHandler;
  307. this->TestingHandlers["script"] = new cmCTestScriptHandler;
  308. this->TestingHandlers["test"] = new cmCTestTestHandler;
  309. this->TestingHandlers["update"] = new cmCTestUpdateHandler;
  310. this->TestingHandlers["configure"] = new cmCTestConfigureHandler;
  311. this->TestingHandlers["memcheck"] = new cmCTestMemCheckHandler;
  312. this->TestingHandlers["submit"] = new cmCTestSubmitHandler;
  313. this->TestingHandlers["upload"] = new cmCTestUploadHandler;
  314. for (auto& handler : this->TestingHandlers) {
  315. handler.second->SetCTestInstance(this);
  316. }
  317. // Make sure we can capture the build tool output.
  318. cmSystemTools::EnableVSConsoleOutput();
  319. }
  320. cmCTest::~cmCTest()
  321. {
  322. cmDeleteAll(this->TestingHandlers);
  323. this->SetOutputLogFileName(nullptr);
  324. }
  325. void cmCTest::SetParallelLevel(int level)
  326. {
  327. this->ParallelLevel = level < 1 ? 1 : level;
  328. }
  329. void cmCTest::SetTestLoad(unsigned long load)
  330. {
  331. this->TestLoad = load;
  332. }
  333. bool cmCTest::ShouldCompressTestOutput()
  334. {
  335. return this->CompressTestOutput;
  336. }
  337. cmCTest::Part cmCTest::GetPartFromName(const char* name)
  338. {
  339. // Look up by lower-case to make names case-insensitive.
  340. std::string lower_name = cmSystemTools::LowerCase(name);
  341. PartMapType::const_iterator i = this->PartMap.find(lower_name);
  342. if (i != this->PartMap.end()) {
  343. return i->second;
  344. }
  345. // The string does not name a valid part.
  346. return PartCount;
  347. }
  348. int cmCTest::Initialize(const char* binary_dir, cmCTestStartCommand* command)
  349. {
  350. bool quiet = false;
  351. if (command && command->ShouldBeQuiet()) {
  352. quiet = true;
  353. }
  354. cmCTestOptionalLog(this, DEBUG, "Here: " << __LINE__ << std::endl, quiet);
  355. if (!this->InteractiveDebugMode) {
  356. this->BlockTestErrorDiagnostics();
  357. } else {
  358. cmSystemTools::PutEnv("CTEST_INTERACTIVE_DEBUG_MODE=1");
  359. }
  360. this->BinaryDir = binary_dir;
  361. cmSystemTools::ConvertToUnixSlashes(this->BinaryDir);
  362. this->UpdateCTestConfiguration();
  363. cmCTestOptionalLog(this, DEBUG, "Here: " << __LINE__ << std::endl, quiet);
  364. if (this->ProduceXML) {
  365. cmCTestOptionalLog(this, DEBUG, "Here: " << __LINE__ << std::endl, quiet);
  366. cmCTestOptionalLog(this, OUTPUT,
  367. " Site: "
  368. << this->GetCTestConfiguration("Site") << std::endl
  369. << " Build name: "
  370. << cmCTest::SafeBuildIdField(
  371. this->GetCTestConfiguration("BuildName"))
  372. << std::endl,
  373. quiet);
  374. cmCTestOptionalLog(this, DEBUG, "Produce XML is on" << std::endl, quiet);
  375. if (this->TestModel == cmCTest::NIGHTLY &&
  376. this->GetCTestConfiguration("NightlyStartTime").empty()) {
  377. cmCTestOptionalLog(
  378. this, WARNING,
  379. "WARNING: No nightly start time found please set in CTestConfig.cmake"
  380. " or DartConfig.cmake"
  381. << std::endl,
  382. quiet);
  383. cmCTestOptionalLog(this, DEBUG, "Here: " << __LINE__ << std::endl,
  384. quiet);
  385. return 0;
  386. }
  387. }
  388. cmake cm(cmake::RoleScript);
  389. cm.SetHomeDirectory("");
  390. cm.SetHomeOutputDirectory("");
  391. cm.GetCurrentSnapshot().SetDefaultDefinitions();
  392. cmGlobalGenerator gg(&cm);
  393. cmMakefile mf(&gg, cm.GetCurrentSnapshot());
  394. if (!this->ReadCustomConfigurationFileTree(this->BinaryDir.c_str(), &mf)) {
  395. cmCTestOptionalLog(
  396. this, DEBUG, "Cannot find custom configuration file tree" << std::endl,
  397. quiet);
  398. return 0;
  399. }
  400. if (this->ProduceXML) {
  401. // Verify "Testing" directory exists:
  402. //
  403. std::string testingDir = this->BinaryDir + "/Testing";
  404. if (cmSystemTools::FileExists(testingDir)) {
  405. if (!cmSystemTools::FileIsDirectory(testingDir)) {
  406. cmCTestLog(this, ERROR_MESSAGE,
  407. "File " << testingDir
  408. << " is in the place of the testing directory"
  409. << std::endl);
  410. return 0;
  411. }
  412. } else {
  413. if (!cmSystemTools::MakeDirectory(testingDir)) {
  414. cmCTestLog(this, ERROR_MESSAGE,
  415. "Cannot create directory " << testingDir << std::endl);
  416. return 0;
  417. }
  418. }
  419. // Create new "TAG" file or read existing one:
  420. //
  421. bool createNewTag = true;
  422. if (command) {
  423. createNewTag = command->ShouldCreateNewTag();
  424. }
  425. std::string tagfile = testingDir + "/TAG";
  426. cmsys::ifstream tfin(tagfile.c_str());
  427. std::string tag;
  428. if (createNewTag) {
  429. time_t tctime = time(nullptr);
  430. if (this->TomorrowTag) {
  431. tctime += (24 * 60 * 60);
  432. }
  433. struct tm* lctime = gmtime(&tctime);
  434. if (tfin && cmSystemTools::GetLineFromStream(tfin, tag)) {
  435. int year = 0;
  436. int mon = 0;
  437. int day = 0;
  438. int hour = 0;
  439. int min = 0;
  440. sscanf(tag.c_str(), "%04d%02d%02d-%02d%02d", &year, &mon, &day, &hour,
  441. &min);
  442. if (year != lctime->tm_year + 1900 || mon != lctime->tm_mon + 1 ||
  443. day != lctime->tm_mday) {
  444. tag.clear();
  445. }
  446. std::string track;
  447. if (cmSystemTools::GetLineFromStream(tfin, track) &&
  448. !this->Parts[PartStart] && !command) {
  449. this->SpecificTrack = track;
  450. }
  451. std::string model;
  452. if (cmSystemTools::GetLineFromStream(tfin, model) &&
  453. !this->Parts[PartStart] && !command) {
  454. this->TestModel = GetTestModelFromString(model.c_str());
  455. }
  456. tfin.close();
  457. }
  458. if (tag.empty() || (nullptr != command) || this->Parts[PartStart]) {
  459. cmCTestOptionalLog(
  460. this, DEBUG,
  461. "TestModel: " << this->GetTestModelString() << std::endl, quiet);
  462. cmCTestOptionalLog(
  463. this, DEBUG, "TestModel: " << this->TestModel << std::endl, quiet);
  464. if (this->TestModel == cmCTest::NIGHTLY) {
  465. lctime = this->GetNightlyTime(
  466. this->GetCTestConfiguration("NightlyStartTime"),
  467. this->TomorrowTag);
  468. }
  469. char datestring[100];
  470. sprintf(datestring, "%04d%02d%02d-%02d%02d", lctime->tm_year + 1900,
  471. lctime->tm_mon + 1, lctime->tm_mday, lctime->tm_hour,
  472. lctime->tm_min);
  473. tag = datestring;
  474. cmsys::ofstream ofs(tagfile.c_str());
  475. if (ofs) {
  476. ofs << tag << std::endl;
  477. ofs << this->GetTestModelString() << std::endl;
  478. switch (this->TestModel) {
  479. case cmCTest::EXPERIMENTAL:
  480. ofs << "Experimental" << std::endl;
  481. break;
  482. case cmCTest::NIGHTLY:
  483. ofs << "Nightly" << std::endl;
  484. break;
  485. case cmCTest::CONTINUOUS:
  486. ofs << "Continuous" << std::endl;
  487. break;
  488. }
  489. }
  490. ofs.close();
  491. if (nullptr == command) {
  492. cmCTestOptionalLog(this, OUTPUT,
  493. "Create new tag: " << tag << " - "
  494. << this->GetTestModelString()
  495. << std::endl,
  496. quiet);
  497. }
  498. }
  499. } else {
  500. std::string track;
  501. std::string modelStr;
  502. int model = cmCTest::UNKNOWN;
  503. if (tfin) {
  504. cmSystemTools::GetLineFromStream(tfin, tag);
  505. cmSystemTools::GetLineFromStream(tfin, track);
  506. if (cmSystemTools::GetLineFromStream(tfin, modelStr)) {
  507. model = GetTestModelFromString(modelStr.c_str());
  508. }
  509. tfin.close();
  510. }
  511. if (tag.empty()) {
  512. cmCTestLog(this, ERROR_MESSAGE,
  513. "Cannot read existing TAG file in " << testingDir
  514. << std::endl);
  515. return 0;
  516. }
  517. if (this->TestModel == cmCTest::UNKNOWN) {
  518. if (model == cmCTest::UNKNOWN) {
  519. cmCTestLog(this, ERROR_MESSAGE,
  520. "TAG file does not contain model and "
  521. "no model specified in start command"
  522. << std::endl);
  523. return 0;
  524. }
  525. this->SetTestModel(model);
  526. }
  527. if (model != this->TestModel && model != cmCTest::UNKNOWN &&
  528. this->TestModel != cmCTest::UNKNOWN) {
  529. cmCTestOptionalLog(this, WARNING,
  530. "Model given in TAG does not match "
  531. "model given in ctest_start()"
  532. << std::endl,
  533. quiet);
  534. }
  535. if (!this->SpecificTrack.empty() && track != this->SpecificTrack) {
  536. cmCTestOptionalLog(this, WARNING,
  537. "Track given in TAG does not match "
  538. "track given in ctest_start()"
  539. << std::endl,
  540. quiet);
  541. } else {
  542. this->SpecificTrack = track;
  543. }
  544. cmCTestOptionalLog(this, OUTPUT,
  545. " Use existing tag: " << tag << " - "
  546. << this->GetTestModelString()
  547. << std::endl,
  548. quiet);
  549. }
  550. this->CurrentTag = tag;
  551. }
  552. return 1;
  553. }
  554. bool cmCTest::InitializeFromCommand(cmCTestStartCommand* command)
  555. {
  556. std::string src_dir = this->GetCTestConfiguration("SourceDirectory");
  557. std::string bld_dir = this->GetCTestConfiguration("BuildDirectory");
  558. this->DartVersion = 1;
  559. this->DropSiteCDash = false;
  560. this->BuildID = "";
  561. for (Part p = PartStart; p != PartCount; p = Part(p + 1)) {
  562. this->Parts[p].SubmitFiles.clear();
  563. }
  564. cmMakefile* mf = command->GetMakefile();
  565. std::string fname;
  566. std::string src_dir_fname = src_dir;
  567. src_dir_fname += "/CTestConfig.cmake";
  568. cmSystemTools::ConvertToUnixSlashes(src_dir_fname);
  569. std::string bld_dir_fname = bld_dir;
  570. bld_dir_fname += "/CTestConfig.cmake";
  571. cmSystemTools::ConvertToUnixSlashes(bld_dir_fname);
  572. if (cmSystemTools::FileExists(bld_dir_fname)) {
  573. fname = bld_dir_fname;
  574. } else if (cmSystemTools::FileExists(src_dir_fname)) {
  575. fname = src_dir_fname;
  576. }
  577. if (!fname.empty()) {
  578. cmCTestOptionalLog(this, OUTPUT,
  579. " Reading ctest configuration file: " << fname
  580. << std::endl,
  581. command->ShouldBeQuiet());
  582. bool readit = mf->ReadDependentFile(fname.c_str());
  583. if (!readit) {
  584. std::string m = "Could not find include file: ";
  585. m += fname;
  586. command->SetError(m);
  587. return false;
  588. }
  589. } else {
  590. cmCTestOptionalLog(this, WARNING,
  591. "Cannot locate CTest configuration: in BuildDirectory: "
  592. << bld_dir_fname << std::endl,
  593. command->ShouldBeQuiet());
  594. cmCTestOptionalLog(
  595. this, WARNING,
  596. "Cannot locate CTest configuration: in SourceDirectory: "
  597. << src_dir_fname << std::endl,
  598. command->ShouldBeQuiet());
  599. }
  600. this->SetCTestConfigurationFromCMakeVariable(mf, "NightlyStartTime",
  601. "CTEST_NIGHTLY_START_TIME",
  602. command->ShouldBeQuiet());
  603. this->SetCTestConfigurationFromCMakeVariable(mf, "Site", "CTEST_SITE",
  604. command->ShouldBeQuiet());
  605. this->SetCTestConfigurationFromCMakeVariable(
  606. mf, "BuildName", "CTEST_BUILD_NAME", command->ShouldBeQuiet());
  607. const char* dartVersion = mf->GetDefinition("CTEST_DART_SERVER_VERSION");
  608. if (dartVersion) {
  609. this->DartVersion = atoi(dartVersion);
  610. if (this->DartVersion < 0) {
  611. cmCTestLog(this, ERROR_MESSAGE,
  612. "Invalid Dart server version: "
  613. << dartVersion << ". Please specify the version number."
  614. << std::endl);
  615. return false;
  616. }
  617. }
  618. this->DropSiteCDash = mf->IsOn("CTEST_DROP_SITE_CDASH");
  619. if (!this->Initialize(bld_dir.c_str(), command)) {
  620. return false;
  621. }
  622. cmCTestOptionalLog(this, OUTPUT,
  623. " Use " << this->GetTestModelString() << " tag: "
  624. << this->GetCurrentTag() << std::endl,
  625. command->ShouldBeQuiet());
  626. return true;
  627. }
  628. bool cmCTest::UpdateCTestConfiguration()
  629. {
  630. if (this->SuppressUpdatingCTestConfiguration) {
  631. return true;
  632. }
  633. std::string fileName = this->BinaryDir + "/CTestConfiguration.ini";
  634. if (!cmSystemTools::FileExists(fileName)) {
  635. fileName = this->BinaryDir + "/DartConfiguration.tcl";
  636. }
  637. cmCTestLog(this, HANDLER_VERBOSE_OUTPUT,
  638. "UpdateCTestConfiguration from :" << fileName << "\n");
  639. if (!cmSystemTools::FileExists(fileName)) {
  640. // No need to exit if we are not producing XML
  641. if (this->ProduceXML) {
  642. cmCTestLog(this, ERROR_MESSAGE,
  643. "Cannot find file: " << fileName << std::endl);
  644. return false;
  645. }
  646. } else {
  647. cmCTestLog(this, HANDLER_VERBOSE_OUTPUT,
  648. "Parse Config file:" << fileName << "\n");
  649. // parse the dart test file
  650. cmsys::ifstream fin(fileName.c_str());
  651. if (!fin) {
  652. return false;
  653. }
  654. char buffer[1024];
  655. while (fin) {
  656. buffer[0] = 0;
  657. fin.getline(buffer, 1023);
  658. buffer[1023] = 0;
  659. std::string line = cmCTest::CleanString(buffer);
  660. if (line.empty()) {
  661. continue;
  662. }
  663. while (fin && (line[line.size() - 1] == '\\')) {
  664. line = line.substr(0, line.size() - 1);
  665. buffer[0] = 0;
  666. fin.getline(buffer, 1023);
  667. buffer[1023] = 0;
  668. line += cmCTest::CleanString(buffer);
  669. }
  670. if (line[0] == '#') {
  671. continue;
  672. }
  673. std::string::size_type cpos = line.find_first_of(':');
  674. if (cpos == std::string::npos) {
  675. continue;
  676. }
  677. std::string key = line.substr(0, cpos);
  678. std::string value = cmCTest::CleanString(line.substr(cpos + 1));
  679. this->CTestConfiguration[key] = value;
  680. }
  681. fin.close();
  682. }
  683. if (!this->GetCTestConfiguration("BuildDirectory").empty()) {
  684. this->BinaryDir = this->GetCTestConfiguration("BuildDirectory");
  685. cmSystemTools::ChangeDirectory(this->BinaryDir);
  686. }
  687. this->TimeOut =
  688. std::chrono::seconds(atoi(this->GetCTestConfiguration("TimeOut").c_str()));
  689. std::string const& testLoad = this->GetCTestConfiguration("TestLoad");
  690. if (!testLoad.empty()) {
  691. unsigned long load;
  692. if (cmSystemTools::StringToULong(testLoad.c_str(), &load)) {
  693. this->SetTestLoad(load);
  694. } else {
  695. cmCTestLog(this, WARNING,
  696. "Invalid value for 'Test Load' : " << testLoad << std::endl);
  697. }
  698. }
  699. if (this->ProduceXML) {
  700. this->CompressXMLFiles =
  701. cmSystemTools::IsOn(this->GetCTestConfiguration("CompressSubmission"));
  702. }
  703. return true;
  704. }
  705. void cmCTest::BlockTestErrorDiagnostics()
  706. {
  707. cmSystemTools::PutEnv("DART_TEST_FROM_DART=1");
  708. cmSystemTools::PutEnv("DASHBOARD_TEST_FROM_CTEST=" CMake_VERSION);
  709. #if defined(_WIN32)
  710. SetErrorMode(SEM_FAILCRITICALERRORS | SEM_NOGPFAULTERRORBOX);
  711. #elif defined(__BEOS__) || defined(__HAIKU__)
  712. disable_debugger(1);
  713. #endif
  714. }
  715. void cmCTest::SetTestModel(int mode)
  716. {
  717. this->InteractiveDebugMode = false;
  718. this->TestModel = mode;
  719. }
  720. bool cmCTest::SetTest(const char* ttype, bool report)
  721. {
  722. if (cmSystemTools::LowerCase(ttype) == "all") {
  723. for (Part p = PartStart; p != PartCount; p = Part(p + 1)) {
  724. this->Parts[p].Enable();
  725. }
  726. return true;
  727. }
  728. Part p = this->GetPartFromName(ttype);
  729. if (p != PartCount) {
  730. this->Parts[p].Enable();
  731. return true;
  732. }
  733. if (report) {
  734. cmCTestLog(this, ERROR_MESSAGE,
  735. "Don't know about test \"" << ttype << "\" yet..."
  736. << std::endl);
  737. }
  738. return false;
  739. }
  740. void cmCTest::Finalize()
  741. {
  742. }
  743. bool cmCTest::OpenOutputFile(const std::string& path, const std::string& name,
  744. cmGeneratedFileStream& stream, bool compress)
  745. {
  746. std::string testingDir = this->BinaryDir + "/Testing";
  747. if (!path.empty()) {
  748. testingDir += "/" + path;
  749. }
  750. if (cmSystemTools::FileExists(testingDir)) {
  751. if (!cmSystemTools::FileIsDirectory(testingDir)) {
  752. cmCTestLog(this, ERROR_MESSAGE,
  753. "File " << testingDir
  754. << " is in the place of the testing directory"
  755. << std::endl);
  756. return false;
  757. }
  758. } else {
  759. if (!cmSystemTools::MakeDirectory(testingDir)) {
  760. cmCTestLog(this, ERROR_MESSAGE,
  761. "Cannot create directory " << testingDir << std::endl);
  762. return false;
  763. }
  764. }
  765. std::string filename = testingDir + "/" + name;
  766. stream.Open(filename);
  767. if (!stream) {
  768. cmCTestLog(this, ERROR_MESSAGE,
  769. "Problem opening file: " << filename << std::endl);
  770. return false;
  771. }
  772. if (compress) {
  773. if (this->CompressXMLFiles) {
  774. stream.SetCompression(true);
  775. }
  776. }
  777. return true;
  778. }
  779. bool cmCTest::AddIfExists(Part part, const char* file)
  780. {
  781. if (this->CTestFileExists(file)) {
  782. this->AddSubmitFile(part, file);
  783. } else {
  784. std::string name = file;
  785. name += ".gz";
  786. if (this->CTestFileExists(name)) {
  787. this->AddSubmitFile(part, file);
  788. } else {
  789. return false;
  790. }
  791. }
  792. return true;
  793. }
  794. bool cmCTest::CTestFileExists(const std::string& filename)
  795. {
  796. std::string testingDir =
  797. this->BinaryDir + "/Testing/" + this->CurrentTag + "/" + filename;
  798. return cmSystemTools::FileExists(testingDir);
  799. }
  800. cmCTestGenericHandler* cmCTest::GetInitializedHandler(const char* handler)
  801. {
  802. cmCTest::t_TestingHandlers::iterator it =
  803. this->TestingHandlers.find(handler);
  804. if (it == this->TestingHandlers.end()) {
  805. return nullptr;
  806. }
  807. it->second->Initialize();
  808. return it->second;
  809. }
  810. cmCTestGenericHandler* cmCTest::GetHandler(const char* handler)
  811. {
  812. cmCTest::t_TestingHandlers::iterator it =
  813. this->TestingHandlers.find(handler);
  814. if (it == this->TestingHandlers.end()) {
  815. return nullptr;
  816. }
  817. return it->second;
  818. }
  819. int cmCTest::ExecuteHandler(const char* shandler)
  820. {
  821. cmCTestGenericHandler* handler = this->GetHandler(shandler);
  822. if (!handler) {
  823. return -1;
  824. }
  825. handler->Initialize();
  826. return handler->ProcessHandler();
  827. }
  828. int cmCTest::ProcessSteps()
  829. {
  830. int res = 0;
  831. bool notest = true;
  832. int update_count = 0;
  833. for (Part p = PartStart; notest && p != PartCount; p = Part(p + 1)) {
  834. notest = !this->Parts[p];
  835. }
  836. if (this->Parts[PartUpdate] &&
  837. (this->GetRemainingTimeAllowed() > std::chrono::minutes(2))) {
  838. cmCTestGenericHandler* uphandler = this->GetHandler("update");
  839. uphandler->SetPersistentOption(
  840. "SourceDirectory",
  841. this->GetCTestConfiguration("SourceDirectory").c_str());
  842. update_count = uphandler->ProcessHandler();
  843. if (update_count < 0) {
  844. res |= cmCTest::UPDATE_ERRORS;
  845. }
  846. }
  847. if (this->TestModel == cmCTest::CONTINUOUS && !update_count) {
  848. return 0;
  849. }
  850. if (this->Parts[PartConfigure] &&
  851. (this->GetRemainingTimeAllowed() > std::chrono::minutes(2))) {
  852. if (this->GetHandler("configure")->ProcessHandler() < 0) {
  853. res |= cmCTest::CONFIGURE_ERRORS;
  854. }
  855. }
  856. if (this->Parts[PartBuild] &&
  857. (this->GetRemainingTimeAllowed() > std::chrono::minutes(2))) {
  858. this->UpdateCTestConfiguration();
  859. if (this->GetHandler("build")->ProcessHandler() < 0) {
  860. res |= cmCTest::BUILD_ERRORS;
  861. }
  862. }
  863. if ((this->Parts[PartTest] || notest) &&
  864. (this->GetRemainingTimeAllowed() > std::chrono::minutes(2))) {
  865. this->UpdateCTestConfiguration();
  866. if (this->GetHandler("test")->ProcessHandler() < 0) {
  867. res |= cmCTest::TEST_ERRORS;
  868. }
  869. }
  870. if (this->Parts[PartCoverage] &&
  871. (this->GetRemainingTimeAllowed() > std::chrono::minutes(2))) {
  872. this->UpdateCTestConfiguration();
  873. if (this->GetHandler("coverage")->ProcessHandler() < 0) {
  874. res |= cmCTest::COVERAGE_ERRORS;
  875. }
  876. }
  877. if (this->Parts[PartMemCheck] &&
  878. (this->GetRemainingTimeAllowed() > std::chrono::minutes(2))) {
  879. this->UpdateCTestConfiguration();
  880. if (this->GetHandler("memcheck")->ProcessHandler() < 0) {
  881. res |= cmCTest::MEMORY_ERRORS;
  882. }
  883. }
  884. if (!notest) {
  885. std::string notes_dir = this->BinaryDir + "/Testing/Notes";
  886. if (cmSystemTools::FileIsDirectory(notes_dir)) {
  887. cmsys::Directory d;
  888. d.Load(notes_dir);
  889. unsigned long kk;
  890. for (kk = 0; kk < d.GetNumberOfFiles(); kk++) {
  891. const char* file = d.GetFile(kk);
  892. std::string fullname = notes_dir + "/" + file;
  893. if (cmSystemTools::FileExists(fullname) &&
  894. !cmSystemTools::FileIsDirectory(fullname)) {
  895. if (!this->NotesFiles.empty()) {
  896. this->NotesFiles += ";";
  897. }
  898. this->NotesFiles += fullname;
  899. this->Parts[PartNotes].Enable();
  900. }
  901. }
  902. }
  903. }
  904. if (this->Parts[PartNotes]) {
  905. this->UpdateCTestConfiguration();
  906. if (!this->NotesFiles.empty()) {
  907. this->GenerateNotesFile(this->NotesFiles.c_str());
  908. }
  909. }
  910. if (this->Parts[PartSubmit]) {
  911. this->UpdateCTestConfiguration();
  912. if (this->GetHandler("submit")->ProcessHandler() < 0) {
  913. res |= cmCTest::SUBMIT_ERRORS;
  914. }
  915. }
  916. if (res != 0) {
  917. cmCTestLog(this, ERROR_MESSAGE, "Errors while running CTest" << std::endl);
  918. }
  919. return res;
  920. }
  921. std::string cmCTest::GetTestModelString()
  922. {
  923. if (!this->SpecificTrack.empty()) {
  924. return this->SpecificTrack;
  925. }
  926. switch (this->TestModel) {
  927. case cmCTest::NIGHTLY:
  928. return "Nightly";
  929. case cmCTest::CONTINUOUS:
  930. return "Continuous";
  931. }
  932. return "Experimental";
  933. }
  934. int cmCTest::GetTestModelFromString(const char* str)
  935. {
  936. if (!str) {
  937. return cmCTest::EXPERIMENTAL;
  938. }
  939. std::string rstr = cmSystemTools::LowerCase(str);
  940. if (cmHasLiteralPrefix(rstr, "cont")) {
  941. return cmCTest::CONTINUOUS;
  942. }
  943. if (cmHasLiteralPrefix(rstr, "nigh")) {
  944. return cmCTest::NIGHTLY;
  945. }
  946. return cmCTest::EXPERIMENTAL;
  947. }
  948. //######################################################################
  949. //######################################################################
  950. //######################################################################
  951. //######################################################################
  952. int cmCTest::RunMakeCommand(const char* command, std::string& output,
  953. int* retVal, const char* dir, cmDuration timeout,
  954. std::ostream& ofs, Encoding encoding)
  955. {
  956. // First generate the command and arguments
  957. std::vector<std::string> args = cmSystemTools::ParseArguments(command);
  958. if (args.empty()) {
  959. return false;
  960. }
  961. std::vector<const char*> argv;
  962. argv.reserve(args.size() + 1);
  963. for (std::string const& a : args) {
  964. argv.push_back(a.c_str());
  965. }
  966. argv.push_back(nullptr);
  967. output.clear();
  968. cmCTestLog(this, HANDLER_VERBOSE_OUTPUT, "Run command:");
  969. for (char const* arg : argv) {
  970. if (!arg) {
  971. break;
  972. }
  973. cmCTestLog(this, HANDLER_VERBOSE_OUTPUT, " \"" << arg << "\"");
  974. }
  975. cmCTestLog(this, HANDLER_VERBOSE_OUTPUT, std::endl);
  976. // Now create process object
  977. cmsysProcess* cp = cmsysProcess_New();
  978. cmsysProcess_SetCommand(cp, &*argv.begin());
  979. cmsysProcess_SetWorkingDirectory(cp, dir);
  980. cmsysProcess_SetOption(cp, cmsysProcess_Option_HideWindow, 1);
  981. cmsysProcess_SetTimeout(cp, timeout.count());
  982. cmsysProcess_Execute(cp);
  983. // Initialize tick's
  984. std::string::size_type tick = 0;
  985. std::string::size_type tick_len = 1024;
  986. std::string::size_type tick_line_len = 50;
  987. char* data;
  988. int length;
  989. cmProcessOutput processOutput(encoding);
  990. std::string strdata;
  991. cmCTestLog(this, HANDLER_PROGRESS_OUTPUT,
  992. " Each . represents " << tick_len << " bytes of output"
  993. << std::endl
  994. << " " << std::flush);
  995. while (cmsysProcess_WaitForData(cp, &data, &length, nullptr)) {
  996. processOutput.DecodeText(data, length, strdata);
  997. for (char& cc : strdata) {
  998. if (cc == 0) {
  999. cc = '\n';
  1000. }
  1001. }
  1002. output.append(strdata);
  1003. while (output.size() > (tick * tick_len)) {
  1004. tick++;
  1005. cmCTestLog(this, HANDLER_PROGRESS_OUTPUT, "." << std::flush);
  1006. if (tick % tick_line_len == 0 && tick > 0) {
  1007. cmCTestLog(this, HANDLER_PROGRESS_OUTPUT,
  1008. " Size: " << int((double(output.size()) / 1024.0) + 1)
  1009. << "K" << std::endl
  1010. << " " << std::flush);
  1011. }
  1012. }
  1013. cmCTestLog(this, HANDLER_VERBOSE_OUTPUT,
  1014. cmCTestLogWrite(strdata.c_str(), strdata.size()));
  1015. if (ofs) {
  1016. ofs << cmCTestLogWrite(strdata.c_str(), strdata.size());
  1017. }
  1018. }
  1019. processOutput.DecodeText(std::string(), strdata);
  1020. if (!strdata.empty()) {
  1021. output.append(strdata);
  1022. cmCTestLog(this, HANDLER_VERBOSE_OUTPUT,
  1023. cmCTestLogWrite(strdata.c_str(), strdata.size()));
  1024. if (ofs) {
  1025. ofs << cmCTestLogWrite(strdata.c_str(), strdata.size());
  1026. }
  1027. }
  1028. cmCTestLog(this, HANDLER_PROGRESS_OUTPUT,
  1029. " Size of output: " << int(double(output.size()) / 1024.0) << "K"
  1030. << std::endl);
  1031. cmsysProcess_WaitForExit(cp, nullptr);
  1032. int result = cmsysProcess_GetState(cp);
  1033. if (result == cmsysProcess_State_Exited) {
  1034. *retVal = cmsysProcess_GetExitValue(cp);
  1035. cmCTestLog(this, HANDLER_VERBOSE_OUTPUT,
  1036. "Command exited with the value: " << *retVal << std::endl);
  1037. } else if (result == cmsysProcess_State_Exception) {
  1038. *retVal = cmsysProcess_GetExitException(cp);
  1039. cmCTestLog(this, WARNING,
  1040. "There was an exception: " << *retVal << std::endl);
  1041. } else if (result == cmsysProcess_State_Expired) {
  1042. cmCTestLog(this, WARNING, "There was a timeout" << std::endl);
  1043. } else if (result == cmsysProcess_State_Error) {
  1044. output += "\n*** ERROR executing: ";
  1045. output += cmsysProcess_GetErrorString(cp);
  1046. output += "\n***The build process failed.";
  1047. cmCTestLog(this, ERROR_MESSAGE,
  1048. "There was an error: " << cmsysProcess_GetErrorString(cp)
  1049. << std::endl);
  1050. }
  1051. cmsysProcess_Delete(cp);
  1052. return result;
  1053. }
  1054. //######################################################################
  1055. //######################################################################
  1056. //######################################################################
  1057. //######################################################################
  1058. int cmCTest::RunTest(std::vector<const char*> argv, std::string* output,
  1059. int* retVal, std::ostream* log, cmDuration testTimeOut,
  1060. std::vector<std::string>* environment, Encoding encoding)
  1061. {
  1062. bool modifyEnv = (environment && !environment->empty());
  1063. // determine how much time we have
  1064. cmDuration timeout = this->GetRemainingTimeAllowed();
  1065. if (timeout != cmCTest::MaxDuration()) {
  1066. timeout -= std::chrono::minutes(2);
  1067. }
  1068. if (this->TimeOut > cmDuration::zero() && this->TimeOut < timeout) {
  1069. timeout = this->TimeOut;
  1070. }
  1071. if (testTimeOut > cmDuration::zero() &&
  1072. testTimeOut < this->GetRemainingTimeAllowed()) {
  1073. timeout = testTimeOut;
  1074. }
  1075. // always have at least 1 second if we got to here
  1076. if (timeout <= cmDuration::zero()) {
  1077. timeout = std::chrono::seconds(1);
  1078. }
  1079. cmCTestLog(this, HANDLER_VERBOSE_OUTPUT,
  1080. "Test timeout computed to be: "
  1081. << (timeout == cmCTest::MaxDuration()
  1082. ? std::string("infinite")
  1083. : std::to_string(cmDurationTo<unsigned int>(timeout)))
  1084. << "\n");
  1085. if (cmSystemTools::SameFile(argv[0], cmSystemTools::GetCTestCommand()) &&
  1086. !this->ForceNewCTestProcess) {
  1087. cmCTest inst;
  1088. inst.ConfigType = this->ConfigType;
  1089. inst.TimeOut = timeout;
  1090. // Capture output of the child ctest.
  1091. std::ostringstream oss;
  1092. inst.SetStreams(&oss, &oss);
  1093. std::vector<std::string> args;
  1094. for (char const* i : argv) {
  1095. if (i) {
  1096. // make sure we pass the timeout in for any build and test
  1097. // invocations. Since --build-generator is required this is a
  1098. // good place to check for it, and to add the arguments in
  1099. if (strcmp(i, "--build-generator") == 0 &&
  1100. timeout != cmCTest::MaxDuration() &&
  1101. timeout > cmDuration::zero()) {
  1102. args.push_back("--test-timeout");
  1103. std::ostringstream msg;
  1104. msg << cmDurationTo<unsigned int>(timeout);
  1105. args.push_back(msg.str());
  1106. }
  1107. args.push_back(i);
  1108. }
  1109. }
  1110. if (log) {
  1111. *log << "* Run internal CTest" << std::endl;
  1112. }
  1113. std::unique_ptr<cmSystemTools::SaveRestoreEnvironment> saveEnv;
  1114. if (modifyEnv) {
  1115. saveEnv = cm::make_unique<cmSystemTools::SaveRestoreEnvironment>();
  1116. cmSystemTools::AppendEnv(*environment);
  1117. }
  1118. *retVal = inst.Run(args, output);
  1119. if (output) {
  1120. *output += oss.str();
  1121. }
  1122. if (log && output) {
  1123. *log << *output;
  1124. }
  1125. if (output) {
  1126. cmCTestLog(this, HANDLER_VERBOSE_OUTPUT,
  1127. "Internal cmCTest object used to run test." << std::endl
  1128. << *output
  1129. << std::endl);
  1130. }
  1131. return cmsysProcess_State_Exited;
  1132. }
  1133. std::vector<char> tempOutput;
  1134. if (output) {
  1135. output->clear();
  1136. }
  1137. std::unique_ptr<cmSystemTools::SaveRestoreEnvironment> saveEnv;
  1138. if (modifyEnv) {
  1139. saveEnv = cm::make_unique<cmSystemTools::SaveRestoreEnvironment>();
  1140. cmSystemTools::AppendEnv(*environment);
  1141. }
  1142. cmsysProcess* cp = cmsysProcess_New();
  1143. cmsysProcess_SetCommand(cp, &*argv.begin());
  1144. cmCTestLog(this, DEBUG, "Command is: " << argv[0] << std::endl);
  1145. if (cmSystemTools::GetRunCommandHideConsole()) {
  1146. cmsysProcess_SetOption(cp, cmsysProcess_Option_HideWindow, 1);
  1147. }
  1148. cmsysProcess_SetTimeout(cp, timeout.count());
  1149. cmsysProcess_Execute(cp);
  1150. char* data;
  1151. int length;
  1152. cmProcessOutput processOutput(encoding);
  1153. std::string strdata;
  1154. while (cmsysProcess_WaitForData(cp, &data, &length, nullptr)) {
  1155. processOutput.DecodeText(data, length, strdata);
  1156. if (output) {
  1157. tempOutput.insert(tempOutput.end(), data, data + length);
  1158. }
  1159. cmCTestLog(this, HANDLER_VERBOSE_OUTPUT,
  1160. cmCTestLogWrite(strdata.c_str(), strdata.size()));
  1161. if (log) {
  1162. log->write(strdata.c_str(), strdata.size());
  1163. }
  1164. }
  1165. processOutput.DecodeText(std::string(), strdata);
  1166. if (!strdata.empty()) {
  1167. cmCTestLog(this, HANDLER_VERBOSE_OUTPUT,
  1168. cmCTestLogWrite(strdata.c_str(), strdata.size()));
  1169. if (log) {
  1170. log->write(strdata.c_str(), strdata.size());
  1171. }
  1172. }
  1173. cmsysProcess_WaitForExit(cp, nullptr);
  1174. processOutput.DecodeText(tempOutput, tempOutput);
  1175. if (output && tempOutput.begin() != tempOutput.end()) {
  1176. output->append(&*tempOutput.begin(), tempOutput.size());
  1177. }
  1178. cmCTestLog(this, HANDLER_VERBOSE_OUTPUT,
  1179. "-- Process completed" << std::endl);
  1180. int result = cmsysProcess_GetState(cp);
  1181. if (result == cmsysProcess_State_Exited) {
  1182. *retVal = cmsysProcess_GetExitValue(cp);
  1183. if (*retVal != 0 && this->OutputTestOutputOnTestFailure) {
  1184. OutputTestErrors(tempOutput);
  1185. }
  1186. } else if (result == cmsysProcess_State_Exception) {
  1187. if (this->OutputTestOutputOnTestFailure) {
  1188. OutputTestErrors(tempOutput);
  1189. }
  1190. *retVal = cmsysProcess_GetExitException(cp);
  1191. std::string outerr = "\n*** Exception executing: ";
  1192. outerr += cmsysProcess_GetExceptionString(cp);
  1193. if (output) {
  1194. *output += outerr;
  1195. }
  1196. cmCTestLog(this, HANDLER_VERBOSE_OUTPUT,
  1197. outerr << std::endl
  1198. << std::flush);
  1199. } else if (result == cmsysProcess_State_Error) {
  1200. std::string outerr = "\n*** ERROR executing: ";
  1201. outerr += cmsysProcess_GetErrorString(cp);
  1202. if (output) {
  1203. *output += outerr;
  1204. }
  1205. cmCTestLog(this, HANDLER_VERBOSE_OUTPUT,
  1206. outerr << std::endl
  1207. << std::flush);
  1208. }
  1209. cmsysProcess_Delete(cp);
  1210. return result;
  1211. }
  1212. std::string cmCTest::SafeBuildIdField(const std::string& value)
  1213. {
  1214. std::string safevalue(value);
  1215. if (!safevalue.empty()) {
  1216. // Disallow non-filename and non-space whitespace characters.
  1217. // If they occur, replace them with ""
  1218. //
  1219. const char* disallowed = "\\:*?\"<>|\n\r\t\f\v";
  1220. if (safevalue.find_first_of(disallowed) != std::string::npos) {
  1221. std::string::size_type i = 0;
  1222. std::string::size_type n = strlen(disallowed);
  1223. char replace[2];
  1224. replace[1] = 0;
  1225. for (i = 0; i < n; ++i) {
  1226. replace[0] = disallowed[i];
  1227. cmSystemTools::ReplaceString(safevalue, replace, "");
  1228. }
  1229. }
  1230. }
  1231. if (safevalue.empty()) {
  1232. safevalue = "(empty)";
  1233. }
  1234. return safevalue;
  1235. }
  1236. void cmCTest::StartXML(cmXMLWriter& xml, bool append)
  1237. {
  1238. if (this->CurrentTag.empty()) {
  1239. cmCTestLog(this, ERROR_MESSAGE,
  1240. "Current Tag empty, this may mean"
  1241. " NightlStartTime was not set correctly."
  1242. << std::endl);
  1243. cmSystemTools::SetFatalErrorOccured();
  1244. }
  1245. // find out about the system
  1246. cmsys::SystemInformation info;
  1247. info.RunCPUCheck();
  1248. info.RunOSCheck();
  1249. info.RunMemoryCheck();
  1250. std::string buildname =
  1251. cmCTest::SafeBuildIdField(this->GetCTestConfiguration("BuildName"));
  1252. std::string stamp = cmCTest::SafeBuildIdField(this->CurrentTag + "-" +
  1253. this->GetTestModelString());
  1254. std::string site =
  1255. cmCTest::SafeBuildIdField(this->GetCTestConfiguration("Site"));
  1256. xml.StartDocument();
  1257. xml.StartElement("Site");
  1258. xml.Attribute("BuildName", buildname);
  1259. xml.BreakAttributes();
  1260. xml.Attribute("BuildStamp", stamp);
  1261. xml.Attribute("Name", site);
  1262. xml.Attribute("Generator",
  1263. std::string("ctest-") + cmVersion::GetCMakeVersion());
  1264. if (append) {
  1265. xml.Attribute("Append", "true");
  1266. }
  1267. xml.Attribute("CompilerName", this->GetCTestConfiguration("Compiler"));
  1268. xml.Attribute("CompilerVersion",
  1269. this->GetCTestConfiguration("CompilerVersion"));
  1270. xml.Attribute("OSName", info.GetOSName());
  1271. xml.Attribute("Hostname", info.GetHostname());
  1272. xml.Attribute("OSRelease", info.GetOSRelease());
  1273. xml.Attribute("OSVersion", info.GetOSVersion());
  1274. xml.Attribute("OSPlatform", info.GetOSPlatform());
  1275. xml.Attribute("Is64Bits", info.Is64Bits());
  1276. xml.Attribute("VendorString", info.GetVendorString());
  1277. xml.Attribute("VendorID", info.GetVendorID());
  1278. xml.Attribute("FamilyID", info.GetFamilyID());
  1279. xml.Attribute("ModelID", info.GetModelID());
  1280. xml.Attribute("ProcessorCacheSize", info.GetProcessorCacheSize());
  1281. xml.Attribute("NumberOfLogicalCPU", info.GetNumberOfLogicalCPU());
  1282. xml.Attribute("NumberOfPhysicalCPU", info.GetNumberOfPhysicalCPU());
  1283. xml.Attribute("TotalVirtualMemory", info.GetTotalVirtualMemory());
  1284. xml.Attribute("TotalPhysicalMemory", info.GetTotalPhysicalMemory());
  1285. xml.Attribute("LogicalProcessorsPerPhysical",
  1286. info.GetLogicalProcessorsPerPhysical());
  1287. xml.Attribute("ProcessorClockFrequency", info.GetProcessorClockFrequency());
  1288. std::string changeId = this->GetCTestConfiguration("ChangeId");
  1289. if (!changeId.empty()) {
  1290. xml.Attribute("ChangeId", changeId);
  1291. }
  1292. this->AddSiteProperties(xml);
  1293. }
  1294. void cmCTest::AddSiteProperties(cmXMLWriter& xml)
  1295. {
  1296. cmCTestScriptHandler* ch =
  1297. static_cast<cmCTestScriptHandler*>(this->GetHandler("script"));
  1298. cmake* cm = ch->GetCMake();
  1299. // if no CMake then this is the old style script and props like
  1300. // this will not work anyway.
  1301. if (!cm) {
  1302. return;
  1303. }
  1304. // This code should go when cdash is changed to use labels only
  1305. const char* subproject = cm->GetState()->GetGlobalProperty("SubProject");
  1306. if (subproject) {
  1307. xml.StartElement("Subproject");
  1308. xml.Attribute("name", subproject);
  1309. const char* labels =
  1310. ch->GetCMake()->GetState()->GetGlobalProperty("SubProjectLabels");
  1311. if (labels) {
  1312. xml.StartElement("Labels");
  1313. std::string l = labels;
  1314. std::vector<std::string> args;
  1315. cmSystemTools::ExpandListArgument(l, args);
  1316. for (std::string const& i : args) {
  1317. xml.Element("Label", i);
  1318. }
  1319. xml.EndElement();
  1320. }
  1321. xml.EndElement();
  1322. }
  1323. // This code should stay when cdash only does label based sub-projects
  1324. const char* label = cm->GetState()->GetGlobalProperty("Label");
  1325. if (label) {
  1326. xml.StartElement("Labels");
  1327. xml.Element("Label", label);
  1328. xml.EndElement();
  1329. }
  1330. }
  1331. void cmCTest::GenerateSubprojectsOutput(cmXMLWriter& xml)
  1332. {
  1333. for (std::string const& subproj : this->GetLabelsForSubprojects()) {
  1334. xml.StartElement("Subproject");
  1335. xml.Attribute("name", subproj);
  1336. xml.Element("Label", subproj);
  1337. xml.EndElement(); // Subproject
  1338. }
  1339. }
  1340. std::vector<std::string> cmCTest::GetLabelsForSubprojects()
  1341. {
  1342. std::string labelsForSubprojects =
  1343. this->GetCTestConfiguration("LabelsForSubprojects");
  1344. std::vector<std::string> subprojects;
  1345. cmSystemTools::ExpandListArgument(labelsForSubprojects, subprojects);
  1346. // sort the array
  1347. std::sort(subprojects.begin(), subprojects.end());
  1348. // remove duplicates
  1349. std::vector<std::string>::iterator new_end =
  1350. std::unique(subprojects.begin(), subprojects.end());
  1351. subprojects.erase(new_end, subprojects.end());
  1352. return subprojects;
  1353. }
  1354. void cmCTest::EndXML(cmXMLWriter& xml)
  1355. {
  1356. xml.EndElement(); // Site
  1357. xml.EndDocument();
  1358. }
  1359. int cmCTest::GenerateCTestNotesOutput(cmXMLWriter& xml,
  1360. const cmCTest::VectorOfStrings& files)
  1361. {
  1362. std::string buildname =
  1363. cmCTest::SafeBuildIdField(this->GetCTestConfiguration("BuildName"));
  1364. xml.StartDocument();
  1365. xml.ProcessingInstruction("xml-stylesheet",
  1366. "type=\"text/xsl\" "
  1367. "href=\"Dart/Source/Server/XSL/Build.xsl "
  1368. "<file:///Dart/Source/Server/XSL/Build.xsl> \"");
  1369. xml.StartElement("Site");
  1370. xml.Attribute("BuildName", buildname);
  1371. xml.Attribute("BuildStamp",
  1372. this->CurrentTag + "-" + this->GetTestModelString());
  1373. xml.Attribute("Name", this->GetCTestConfiguration("Site"));
  1374. xml.Attribute("Generator",
  1375. std::string("ctest") + cmVersion::GetCMakeVersion());
  1376. this->AddSiteProperties(xml);
  1377. xml.StartElement("Notes");
  1378. for (std::string const& file : files) {
  1379. cmCTestLog(this, OUTPUT, "\tAdd file: " << file << std::endl);
  1380. std::string note_time = this->CurrentTime();
  1381. xml.StartElement("Note");
  1382. xml.Attribute("Name", file);
  1383. xml.Element("Time", std::chrono::system_clock::now());
  1384. xml.Element("DateTime", note_time);
  1385. xml.StartElement("Text");
  1386. cmsys::ifstream ifs(file.c_str());
  1387. if (ifs) {
  1388. std::string line;
  1389. while (cmSystemTools::GetLineFromStream(ifs, line)) {
  1390. xml.Content(line);
  1391. xml.Content("\n");
  1392. }
  1393. ifs.close();
  1394. } else {
  1395. xml.Content("Problem reading file: " + file + "\n");
  1396. cmCTestLog(this, ERROR_MESSAGE,
  1397. "Problem reading file: " << file << " while creating notes"
  1398. << std::endl);
  1399. }
  1400. xml.EndElement(); // Text
  1401. xml.EndElement(); // Note
  1402. }
  1403. xml.EndElement(); // Notes
  1404. xml.EndElement(); // Site
  1405. xml.EndDocument();
  1406. return 1;
  1407. }
  1408. int cmCTest::GenerateNotesFile(const VectorOfStrings& files)
  1409. {
  1410. cmGeneratedFileStream ofs;
  1411. if (!this->OpenOutputFile(this->CurrentTag, "Notes.xml", ofs)) {
  1412. cmCTestLog(this, ERROR_MESSAGE, "Cannot open notes file" << std::endl);
  1413. return 1;
  1414. }
  1415. cmXMLWriter xml(ofs);
  1416. this->GenerateCTestNotesOutput(xml, files);
  1417. return 0;
  1418. }
  1419. int cmCTest::GenerateNotesFile(const char* cfiles)
  1420. {
  1421. if (!cfiles) {
  1422. return 1;
  1423. }
  1424. VectorOfStrings files;
  1425. cmCTestLog(this, OUTPUT, "Create notes file" << std::endl);
  1426. files = cmSystemTools::SplitString(cfiles, ';');
  1427. if (files.empty()) {
  1428. return 1;
  1429. }
  1430. return this->GenerateNotesFile(files);
  1431. }
  1432. int cmCTest::GenerateDoneFile()
  1433. {
  1434. cmGeneratedFileStream ofs;
  1435. if (!this->OpenOutputFile(this->CurrentTag, "Done.xml", ofs)) {
  1436. cmCTestLog(this, ERROR_MESSAGE, "Cannot open done file" << std::endl);
  1437. return 1;
  1438. }
  1439. cmXMLWriter xml(ofs);
  1440. xml.StartDocument();
  1441. xml.StartElement("Done");
  1442. xml.Element("buildId", this->BuildID);
  1443. xml.Element("time", std::chrono::system_clock::now());
  1444. xml.EndElement(); // Done
  1445. xml.EndDocument();
  1446. return 0;
  1447. }
  1448. std::string cmCTest::Base64GzipEncodeFile(std::string const& file)
  1449. {
  1450. std::string tarFile = file + "_temp.tar.gz";
  1451. std::vector<std::string> files;
  1452. files.push_back(file);
  1453. if (!cmSystemTools::CreateTar(tarFile.c_str(), files,
  1454. cmSystemTools::TarCompressGZip, false)) {
  1455. cmCTestLog(this, ERROR_MESSAGE,
  1456. "Error creating tar while "
  1457. "encoding file: "
  1458. << file << std::endl);
  1459. return "";
  1460. }
  1461. std::string base64 = this->Base64EncodeFile(tarFile);
  1462. cmSystemTools::RemoveFile(tarFile);
  1463. return base64;
  1464. }
  1465. std::string cmCTest::Base64EncodeFile(std::string const& file)
  1466. {
  1467. size_t const len = cmSystemTools::FileLength(file);
  1468. cmsys::ifstream ifs(file.c_str(),
  1469. std::ios::in
  1470. #ifdef _WIN32
  1471. | std::ios::binary
  1472. #endif
  1473. );
  1474. std::vector<char> file_buffer(len + 1);
  1475. ifs.read(&file_buffer[0], len);
  1476. ifs.close();
  1477. std::vector<char> encoded_buffer((len * 3) / 2 + 5);
  1478. size_t const rlen = cmsysBase64_Encode(
  1479. reinterpret_cast<unsigned char*>(&file_buffer[0]), len,
  1480. reinterpret_cast<unsigned char*>(&encoded_buffer[0]), 1);
  1481. return std::string(&encoded_buffer[0], rlen);
  1482. }
  1483. bool cmCTest::SubmitExtraFiles(const VectorOfStrings& files)
  1484. {
  1485. for (std::string const& file : files) {
  1486. if (!cmSystemTools::FileExists(file)) {
  1487. cmCTestLog(this, ERROR_MESSAGE,
  1488. "Cannot find extra file: " << file << " to submit."
  1489. << std::endl;);
  1490. return false;
  1491. }
  1492. this->AddSubmitFile(PartExtraFiles, file.c_str());
  1493. }
  1494. return true;
  1495. }
  1496. bool cmCTest::SubmitExtraFiles(const char* cfiles)
  1497. {
  1498. if (!cfiles) {
  1499. return true;
  1500. }
  1501. VectorOfStrings files;
  1502. cmCTestLog(this, OUTPUT, "Submit extra files" << std::endl);
  1503. files = cmSystemTools::SplitString(cfiles, ';');
  1504. if (files.empty()) {
  1505. return true;
  1506. }
  1507. return this->SubmitExtraFiles(files);
  1508. }
  1509. // for a -D argument convert the next argument into
  1510. // the proper list of dashboard steps via SetTest
  1511. bool cmCTest::AddTestsForDashboardType(std::string& targ)
  1512. {
  1513. if (targ == "Experimental") {
  1514. this->SetTestModel(cmCTest::EXPERIMENTAL);
  1515. this->SetTest("Start");
  1516. this->SetTest("Configure");
  1517. this->SetTest("Build");
  1518. this->SetTest("Test");
  1519. this->SetTest("Coverage");
  1520. this->SetTest("Submit");
  1521. } else if (targ == "ExperimentalStart") {
  1522. this->SetTestModel(cmCTest::EXPERIMENTAL);
  1523. this->SetTest("Start");
  1524. } else if (targ == "ExperimentalUpdate") {
  1525. this->SetTestModel(cmCTest::EXPERIMENTAL);
  1526. this->SetTest("Update");
  1527. } else if (targ == "ExperimentalConfigure") {
  1528. this->SetTestModel(cmCTest::EXPERIMENTAL);
  1529. this->SetTest("Configure");
  1530. } else if (targ == "ExperimentalBuild") {
  1531. this->SetTestModel(cmCTest::EXPERIMENTAL);
  1532. this->SetTest("Build");
  1533. } else if (targ == "ExperimentalTest") {
  1534. this->SetTestModel(cmCTest::EXPERIMENTAL);
  1535. this->SetTest("Test");
  1536. } else if (targ == "ExperimentalMemCheck" || targ == "ExperimentalPurify") {
  1537. this->SetTestModel(cmCTest::EXPERIMENTAL);
  1538. this->SetTest("MemCheck");
  1539. } else if (targ == "ExperimentalCoverage") {
  1540. this->SetTestModel(cmCTest::EXPERIMENTAL);
  1541. this->SetTest("Coverage");
  1542. } else if (targ == "ExperimentalSubmit") {
  1543. this->SetTestModel(cmCTest::EXPERIMENTAL);
  1544. this->SetTest("Submit");
  1545. } else if (targ == "Continuous") {
  1546. this->SetTestModel(cmCTest::CONTINUOUS);
  1547. this->SetTest("Start");
  1548. this->SetTest("Update");
  1549. this->SetTest("Configure");
  1550. this->SetTest("Build");
  1551. this->SetTest("Test");
  1552. this->SetTest("Coverage");
  1553. this->SetTest("Submit");
  1554. } else if (targ == "ContinuousStart") {
  1555. this->SetTestModel(cmCTest::CONTINUOUS);
  1556. this->SetTest("Start");
  1557. } else if (targ == "ContinuousUpdate") {
  1558. this->SetTestModel(cmCTest::CONTINUOUS);
  1559. this->SetTest("Update");
  1560. } else if (targ == "ContinuousConfigure") {
  1561. this->SetTestModel(cmCTest::CONTINUOUS);
  1562. this->SetTest("Configure");
  1563. } else if (targ == "ContinuousBuild") {
  1564. this->SetTestModel(cmCTest::CONTINUOUS);
  1565. this->SetTest("Build");
  1566. } else if (targ == "ContinuousTest") {
  1567. this->SetTestModel(cmCTest::CONTINUOUS);
  1568. this->SetTest("Test");
  1569. } else if (targ == "ContinuousMemCheck" || targ == "ContinuousPurify") {
  1570. this->SetTestModel(cmCTest::CONTINUOUS);
  1571. this->SetTest("MemCheck");
  1572. } else if (targ == "ContinuousCoverage") {
  1573. this->SetTestModel(cmCTest::CONTINUOUS);
  1574. this->SetTest("Coverage");
  1575. } else if (targ == "ContinuousSubmit") {
  1576. this->SetTestModel(cmCTest::CONTINUOUS);
  1577. this->SetTest("Submit");
  1578. } else if (targ == "Nightly") {
  1579. this->SetTestModel(cmCTest::NIGHTLY);
  1580. this->SetTest("Start");
  1581. this->SetTest("Update");
  1582. this->SetTest("Configure");
  1583. this->SetTest("Build");
  1584. this->SetTest("Test");
  1585. this->SetTest("Coverage");
  1586. this->SetTest("Submit");
  1587. } else if (targ == "NightlyStart") {
  1588. this->SetTestModel(cmCTest::NIGHTLY);
  1589. this->SetTest("Start");
  1590. } else if (targ == "NightlyUpdate") {
  1591. this->SetTestModel(cmCTest::NIGHTLY);
  1592. this->SetTest("Update");
  1593. } else if (targ == "NightlyConfigure") {
  1594. this->SetTestModel(cmCTest::NIGHTLY);
  1595. this->SetTest("Configure");
  1596. } else if (targ == "NightlyBuild") {
  1597. this->SetTestModel(cmCTest::NIGHTLY);
  1598. this->SetTest("Build");
  1599. } else if (targ == "NightlyTest") {
  1600. this->SetTestModel(cmCTest::NIGHTLY);
  1601. this->SetTest("Test");
  1602. } else if (targ == "NightlyMemCheck" || targ == "NightlyPurify") {
  1603. this->SetTestModel(cmCTest::NIGHTLY);
  1604. this->SetTest("MemCheck");
  1605. } else if (targ == "NightlyCoverage") {
  1606. this->SetTestModel(cmCTest::NIGHTLY);
  1607. this->SetTest("Coverage");
  1608. } else if (targ == "NightlySubmit") {
  1609. this->SetTestModel(cmCTest::NIGHTLY);
  1610. this->SetTest("Submit");
  1611. } else if (targ == "MemoryCheck") {
  1612. this->SetTestModel(cmCTest::EXPERIMENTAL);
  1613. this->SetTest("Start");
  1614. this->SetTest("Configure");
  1615. this->SetTest("Build");
  1616. this->SetTest("MemCheck");
  1617. this->SetTest("Coverage");
  1618. this->SetTest("Submit");
  1619. } else if (targ == "NightlyMemoryCheck") {
  1620. this->SetTestModel(cmCTest::NIGHTLY);
  1621. this->SetTest("Start");
  1622. this->SetTest("Update");
  1623. this->SetTest("Configure");
  1624. this->SetTest("Build");
  1625. this->SetTest("MemCheck");
  1626. this->SetTest("Coverage");
  1627. this->SetTest("Submit");
  1628. } else {
  1629. return false;
  1630. }
  1631. return true;
  1632. }
  1633. void cmCTest::ErrorMessageUnknownDashDValue(std::string& val)
  1634. {
  1635. cmCTestLog(this, ERROR_MESSAGE,
  1636. "CTest -D called with incorrect option: " << val << std::endl);
  1637. cmCTestLog(
  1638. this, ERROR_MESSAGE,
  1639. "Available options are:"
  1640. << std::endl
  1641. << " ctest -D Continuous" << std::endl
  1642. << " ctest -D Continuous(Start|Update|Configure|Build)" << std::endl
  1643. << " ctest -D Continuous(Test|Coverage|MemCheck|Submit)" << std::endl
  1644. << " ctest -D Experimental" << std::endl
  1645. << " ctest -D Experimental(Start|Update|Configure|Build)" << std::endl
  1646. << " ctest -D Experimental(Test|Coverage|MemCheck|Submit)" << std::endl
  1647. << " ctest -D Nightly" << std::endl
  1648. << " ctest -D Nightly(Start|Update|Configure|Build)" << std::endl
  1649. << " ctest -D Nightly(Test|Coverage|MemCheck|Submit)" << std::endl
  1650. << " ctest -D NightlyMemoryCheck" << std::endl);
  1651. }
  1652. bool cmCTest::CheckArgument(const std::string& arg, const char* varg1,
  1653. const char* varg2)
  1654. {
  1655. return (varg1 && arg == varg1) || (varg2 && arg == varg2);
  1656. }
  1657. // Processes one command line argument (and its arguments if any)
  1658. // for many simple options and then returns
  1659. bool cmCTest::HandleCommandLineArguments(size_t& i,
  1660. std::vector<std::string>& args,
  1661. std::string& errormsg)
  1662. {
  1663. std::string arg = args[i];
  1664. if (this->CheckArgument(arg, "-F")) {
  1665. this->Failover = true;
  1666. }
  1667. if (this->CheckArgument(arg, "-j", "--parallel") && i < args.size() - 1) {
  1668. i++;
  1669. int plevel = atoi(args[i].c_str());
  1670. this->SetParallelLevel(plevel);
  1671. this->ParallelLevelSetInCli = true;
  1672. } else if (arg.find("-j") == 0) {
  1673. int plevel = atoi(arg.substr(2).c_str());
  1674. this->SetParallelLevel(plevel);
  1675. this->ParallelLevelSetInCli = true;
  1676. }
  1677. if (this->CheckArgument(arg, "--repeat-until-fail")) {
  1678. if (i >= args.size() - 1) {
  1679. errormsg = "'--repeat-until-fail' requires an argument";
  1680. return false;
  1681. }
  1682. i++;
  1683. long repeat = 1;
  1684. if (!cmSystemTools::StringToLong(args[i].c_str(), &repeat)) {
  1685. errormsg =
  1686. "'--repeat-until-fail' given non-integer value '" + args[i] + "'";
  1687. return false;
  1688. }
  1689. this->RepeatTests = static_cast<int>(repeat);
  1690. if (repeat > 1) {
  1691. this->RepeatUntilFail = true;
  1692. }
  1693. }
  1694. if (this->CheckArgument(arg, "--test-load") && i < args.size() - 1) {
  1695. i++;
  1696. unsigned long load;
  1697. if (cmSystemTools::StringToULong(args[i].c_str(), &load)) {
  1698. this->SetTestLoad(load);
  1699. } else {
  1700. cmCTestLog(this, WARNING,
  1701. "Invalid value for 'Test Load' : " << args[i] << std::endl);
  1702. }
  1703. }
  1704. if (this->CheckArgument(arg, "--no-compress-output")) {
  1705. this->CompressTestOutput = false;
  1706. }
  1707. if (this->CheckArgument(arg, "--print-labels")) {
  1708. this->PrintLabels = true;
  1709. }
  1710. if (this->CheckArgument(arg, "--http1.0")) {
  1711. this->UseHTTP10 = true;
  1712. }
  1713. if (this->CheckArgument(arg, "--timeout") && i < args.size() - 1) {
  1714. i++;
  1715. auto timeout = cmDuration(atof(args[i].c_str()));
  1716. this->GlobalTimeout = timeout;
  1717. }
  1718. if (this->CheckArgument(arg, "--stop-time") && i < args.size() - 1) {
  1719. i++;
  1720. this->SetStopTime(args[i]);
  1721. }
  1722. if (this->CheckArgument(arg, "-C", "--build-config") &&
  1723. i < args.size() - 1) {
  1724. i++;
  1725. this->SetConfigType(args[i].c_str());
  1726. }
  1727. if (this->CheckArgument(arg, "--debug")) {
  1728. this->Debug = true;
  1729. this->ShowLineNumbers = true;
  1730. }
  1731. if (this->CheckArgument(arg, "--track") && i < args.size() - 1) {
  1732. i++;
  1733. this->SpecificTrack = args[i];
  1734. }
  1735. if (this->CheckArgument(arg, "--show-line-numbers")) {
  1736. this->ShowLineNumbers = true;
  1737. }
  1738. if (this->CheckArgument(arg, "--no-label-summary")) {
  1739. this->LabelSummary = false;
  1740. }
  1741. if (this->CheckArgument(arg, "--no-subproject-summary")) {
  1742. this->SubprojectSummary = false;
  1743. }
  1744. if (this->CheckArgument(arg, "-Q", "--quiet")) {
  1745. this->Quiet = true;
  1746. }
  1747. if (this->CheckArgument(arg, "--progress")) {
  1748. this->TestProgressOutput = true;
  1749. }
  1750. if (this->CheckArgument(arg, "-V", "--verbose")) {
  1751. this->Verbose = true;
  1752. }
  1753. if (this->CheckArgument(arg, "-VV", "--extra-verbose")) {
  1754. this->ExtraVerbose = true;
  1755. this->Verbose = true;
  1756. }
  1757. if (this->CheckArgument(arg, "--output-on-failure")) {
  1758. this->OutputTestOutputOnTestFailure = true;
  1759. }
  1760. if (this->CheckArgument(arg, "--test-output-size-passed") &&
  1761. i < args.size() - 1) {
  1762. i++;
  1763. long outputSize;
  1764. if (cmSystemTools::StringToLong(args[i].c_str(), &outputSize)) {
  1765. if (cmCTestTestHandler* pCTestTestHandler =
  1766. static_cast<cmCTestTestHandler*>(this->TestingHandlers["test"])) {
  1767. pCTestTestHandler->SetTestOutputSizePassed(int(outputSize));
  1768. }
  1769. } else {
  1770. cmCTestLog(this, WARNING,
  1771. "Invalid value for '--test-output-size-passed': " << args[i]
  1772. << "\n");
  1773. }
  1774. }
  1775. if (this->CheckArgument(arg, "--test-output-size-failed") &&
  1776. i < args.size() - 1) {
  1777. i++;
  1778. long outputSize;
  1779. if (cmSystemTools::StringToLong(args[i].c_str(), &outputSize)) {
  1780. if (cmCTestTestHandler* pCTestTestHandler =
  1781. static_cast<cmCTestTestHandler*>(this->TestingHandlers["test"])) {
  1782. pCTestTestHandler->SetTestOutputSizeFailed(int(outputSize));
  1783. }
  1784. } else {
  1785. cmCTestLog(this, WARNING,
  1786. "Invalid value for '--test-output-size-failed': " << args[i]
  1787. << "\n");
  1788. }
  1789. }
  1790. if (this->CheckArgument(arg, "-N", "--show-only")) {
  1791. this->ShowOnly = true;
  1792. }
  1793. if (this->CheckArgument(arg, "-O", "--output-log") && i < args.size() - 1) {
  1794. i++;
  1795. this->SetOutputLogFileName(args[i].c_str());
  1796. }
  1797. if (this->CheckArgument(arg, "--tomorrow-tag")) {
  1798. this->TomorrowTag = true;
  1799. }
  1800. if (this->CheckArgument(arg, "--force-new-ctest-process")) {
  1801. this->ForceNewCTestProcess = true;
  1802. }
  1803. if (this->CheckArgument(arg, "-W", "--max-width") && i < args.size() - 1) {
  1804. i++;
  1805. this->MaxTestNameWidth = atoi(args[i].c_str());
  1806. }
  1807. if (this->CheckArgument(arg, "--interactive-debug-mode") &&
  1808. i < args.size() - 1) {
  1809. i++;
  1810. this->InteractiveDebugMode = cmSystemTools::IsOn(args[i]);
  1811. }
  1812. if (this->CheckArgument(arg, "--submit-index") && i < args.size() - 1) {
  1813. i++;
  1814. this->SubmitIndex = atoi(args[i].c_str());
  1815. if (this->SubmitIndex < 0) {
  1816. this->SubmitIndex = 0;
  1817. }
  1818. }
  1819. if (this->CheckArgument(arg, "--overwrite") && i < args.size() - 1) {
  1820. i++;
  1821. this->AddCTestConfigurationOverwrite(args[i]);
  1822. }
  1823. if (this->CheckArgument(arg, "-A", "--add-notes") && i < args.size() - 1) {
  1824. this->ProduceXML = true;
  1825. this->SetTest("Notes");
  1826. i++;
  1827. this->SetNotesFiles(args[i].c_str());
  1828. }
  1829. // options that control what tests are run
  1830. if (this->CheckArgument(arg, "-I", "--tests-information") &&
  1831. i < args.size() - 1) {
  1832. i++;
  1833. this->GetHandler("test")->SetPersistentOption("TestsToRunInformation",
  1834. args[i].c_str());
  1835. this->GetHandler("memcheck")
  1836. ->SetPersistentOption("TestsToRunInformation", args[i].c_str());
  1837. }
  1838. if (this->CheckArgument(arg, "-U", "--union")) {
  1839. this->GetHandler("test")->SetPersistentOption("UseUnion", "true");
  1840. this->GetHandler("memcheck")->SetPersistentOption("UseUnion", "true");
  1841. }
  1842. if (this->CheckArgument(arg, "-R", "--tests-regex") && i < args.size() - 1) {
  1843. i++;
  1844. this->GetHandler("test")->SetPersistentOption("IncludeRegularExpression",
  1845. args[i].c_str());
  1846. this->GetHandler("memcheck")
  1847. ->SetPersistentOption("IncludeRegularExpression", args[i].c_str());
  1848. }
  1849. if (this->CheckArgument(arg, "-L", "--label-regex") && i < args.size() - 1) {
  1850. i++;
  1851. this->GetHandler("test")->SetPersistentOption("LabelRegularExpression",
  1852. args[i].c_str());
  1853. this->GetHandler("memcheck")
  1854. ->SetPersistentOption("LabelRegularExpression", args[i].c_str());
  1855. }
  1856. if (this->CheckArgument(arg, "-LE", "--label-exclude") &&
  1857. i < args.size() - 1) {
  1858. i++;
  1859. this->GetHandler("test")->SetPersistentOption(
  1860. "ExcludeLabelRegularExpression", args[i].c_str());
  1861. this->GetHandler("memcheck")
  1862. ->SetPersistentOption("ExcludeLabelRegularExpression", args[i].c_str());
  1863. }
  1864. if (this->CheckArgument(arg, "-E", "--exclude-regex") &&
  1865. i < args.size() - 1) {
  1866. i++;
  1867. this->GetHandler("test")->SetPersistentOption("ExcludeRegularExpression",
  1868. args[i].c_str());
  1869. this->GetHandler("memcheck")
  1870. ->SetPersistentOption("ExcludeRegularExpression", args[i].c_str());
  1871. }
  1872. if (this->CheckArgument(arg, "-FA", "--fixture-exclude-any") &&
  1873. i < args.size() - 1) {
  1874. i++;
  1875. this->GetHandler("test")->SetPersistentOption(
  1876. "ExcludeFixtureRegularExpression", args[i].c_str());
  1877. this->GetHandler("memcheck")
  1878. ->SetPersistentOption("ExcludeFixtureRegularExpression",
  1879. args[i].c_str());
  1880. }
  1881. if (this->CheckArgument(arg, "-FS", "--fixture-exclude-setup") &&
  1882. i < args.size() - 1) {
  1883. i++;
  1884. this->GetHandler("test")->SetPersistentOption(
  1885. "ExcludeFixtureSetupRegularExpression", args[i].c_str());
  1886. this->GetHandler("memcheck")
  1887. ->SetPersistentOption("ExcludeFixtureSetupRegularExpression",
  1888. args[i].c_str());
  1889. }
  1890. if (this->CheckArgument(arg, "-FC", "--fixture-exclude-cleanup") &&
  1891. i < args.size() - 1) {
  1892. i++;
  1893. this->GetHandler("test")->SetPersistentOption(
  1894. "ExcludeFixtureCleanupRegularExpression", args[i].c_str());
  1895. this->GetHandler("memcheck")
  1896. ->SetPersistentOption("ExcludeFixtureCleanupRegularExpression",
  1897. args[i].c_str());
  1898. }
  1899. if (this->CheckArgument(arg, "--rerun-failed")) {
  1900. this->GetHandler("test")->SetPersistentOption("RerunFailed", "true");
  1901. this->GetHandler("memcheck")->SetPersistentOption("RerunFailed", "true");
  1902. }
  1903. return true;
  1904. }
  1905. bool cmCTest::ProgressOutputSupportedByConsole() const
  1906. {
  1907. #if defined(_WIN32)
  1908. // On Windows we need a console buffer.
  1909. void* console = GetStdHandle(STD_OUTPUT_HANDLE);
  1910. CONSOLE_SCREEN_BUFFER_INFO csbi;
  1911. return GetConsoleScreenBufferInfo(console, &csbi);
  1912. #else
  1913. // On UNIX we need a non-dumb tty.
  1914. std::string term_env_variable;
  1915. if (cmSystemTools::GetEnv("TERM", term_env_variable)) {
  1916. return isatty(1) && term_env_variable != "dumb";
  1917. }
  1918. #endif
  1919. return false;
  1920. }
  1921. // handle the -S -SR and -SP arguments
  1922. void cmCTest::HandleScriptArguments(size_t& i, std::vector<std::string>& args,
  1923. bool& SRArgumentSpecified)
  1924. {
  1925. std::string arg = args[i];
  1926. if (this->CheckArgument(arg, "-SP", "--script-new-process") &&
  1927. i < args.size() - 1) {
  1928. this->RunConfigurationScript = true;
  1929. i++;
  1930. cmCTestScriptHandler* ch =
  1931. static_cast<cmCTestScriptHandler*>(this->GetHandler("script"));
  1932. // -SR is an internal argument, -SP should be ignored when it is passed
  1933. if (!SRArgumentSpecified) {
  1934. ch->AddConfigurationScript(args[i].c_str(), false);
  1935. }
  1936. }
  1937. if (this->CheckArgument(arg, "-SR", "--script-run") && i < args.size() - 1) {
  1938. SRArgumentSpecified = true;
  1939. this->RunConfigurationScript = true;
  1940. i++;
  1941. cmCTestScriptHandler* ch =
  1942. static_cast<cmCTestScriptHandler*>(this->GetHandler("script"));
  1943. ch->AddConfigurationScript(args[i].c_str(), true);
  1944. }
  1945. if (this->CheckArgument(arg, "-S", "--script") && i < args.size() - 1) {
  1946. this->RunConfigurationScript = true;
  1947. i++;
  1948. cmCTestScriptHandler* ch =
  1949. static_cast<cmCTestScriptHandler*>(this->GetHandler("script"));
  1950. // -SR is an internal argument, -S should be ignored when it is passed
  1951. if (!SRArgumentSpecified) {
  1952. ch->AddConfigurationScript(args[i].c_str(), true);
  1953. }
  1954. }
  1955. }
  1956. bool cmCTest::AddVariableDefinition(const std::string& arg)
  1957. {
  1958. std::string name;
  1959. std::string value;
  1960. cmStateEnums::CacheEntryType type = cmStateEnums::UNINITIALIZED;
  1961. if (cmake::ParseCacheEntry(arg, name, value, type)) {
  1962. this->Definitions[name] = value;
  1963. return true;
  1964. }
  1965. return false;
  1966. }
  1967. // the main entry point of ctest, called from main
  1968. int cmCTest::Run(std::vector<std::string>& args, std::string* output)
  1969. {
  1970. const char* ctestExec = "ctest";
  1971. bool cmakeAndTest = false;
  1972. bool executeTests = true;
  1973. bool SRArgumentSpecified = false;
  1974. // copy the command line
  1975. this->InitialCommandLineArguments.insert(
  1976. this->InitialCommandLineArguments.end(), args.begin(), args.end());
  1977. // process the command line arguments
  1978. for (size_t i = 1; i < args.size(); ++i) {
  1979. // handle the simple commandline arguments
  1980. std::string errormsg;
  1981. if (!this->HandleCommandLineArguments(i, args, errormsg)) {
  1982. cmSystemTools::Error(errormsg.c_str());
  1983. return 1;
  1984. }
  1985. // handle the script arguments -S -SR -SP
  1986. this->HandleScriptArguments(i, args, SRArgumentSpecified);
  1987. // --dashboard: handle a request for a dashboard
  1988. std::string arg = args[i];
  1989. if (this->CheckArgument(arg, "-D", "--dashboard") && i < args.size() - 1) {
  1990. this->ProduceXML = true;
  1991. i++;
  1992. std::string targ = args[i];
  1993. // AddTestsForDashboard parses the dashboard type and converts it
  1994. // into the separate stages
  1995. if (!this->AddTestsForDashboardType(targ)) {
  1996. if (!this->AddVariableDefinition(targ)) {
  1997. this->ErrorMessageUnknownDashDValue(targ);
  1998. executeTests = false;
  1999. }
  2000. }
  2001. }
  2002. // If it's not exactly -D, but it starts with -D, then try to parse out
  2003. // a variable definition from it, same as CMake does. Unsuccessful
  2004. // attempts are simply ignored since previous ctest versions ignore
  2005. // this too. (As well as many other unknown command line args.)
  2006. //
  2007. if (arg != "-D" && cmSystemTools::StringStartsWith(arg.c_str(), "-D")) {
  2008. std::string input = arg.substr(2);
  2009. this->AddVariableDefinition(input);
  2010. }
  2011. // --test-action: calls SetTest(<stage>, /*report=*/ false) to enable
  2012. // the corresponding stage
  2013. if (!this->HandleTestActionArgument(ctestExec, i, args)) {
  2014. executeTests = false;
  2015. }
  2016. // --test-model: what type of test model
  2017. if (!this->HandleTestModelArgument(ctestExec, i, args)) {
  2018. executeTests = false;
  2019. }
  2020. // --extra-submit
  2021. if (this->CheckArgument(arg, "--extra-submit") && i < args.size() - 1) {
  2022. this->ProduceXML = true;
  2023. this->SetTest("Submit");
  2024. i++;
  2025. if (!this->SubmitExtraFiles(args[i].c_str())) {
  2026. return 0;
  2027. }
  2028. }
  2029. // --build-and-test options
  2030. if (this->CheckArgument(arg, "--build-and-test") && i < args.size() - 1) {
  2031. cmakeAndTest = true;
  2032. }
  2033. // --schedule-random
  2034. if (this->CheckArgument(arg, "--schedule-random")) {
  2035. this->ScheduleType = "Random";
  2036. }
  2037. // pass the argument to all the handlers as well, but i may no longer be
  2038. // set to what it was originally so I'm not sure this is working as
  2039. // intended
  2040. for (auto& handler : this->TestingHandlers) {
  2041. if (!handler.second->ProcessCommandLineArguments(arg, i, args)) {
  2042. cmCTestLog(this, ERROR_MESSAGE,
  2043. "Problem parsing command line arguments within a handler");
  2044. return 0;
  2045. }
  2046. }
  2047. } // the close of the for argument loop
  2048. // handle CTEST_PARALLEL_LEVEL environment variable
  2049. if (!this->ParallelLevelSetInCli) {
  2050. std::string parallel;
  2051. if (cmSystemTools::GetEnv("CTEST_PARALLEL_LEVEL", parallel)) {
  2052. int plevel = atoi(parallel.c_str());
  2053. this->SetParallelLevel(plevel);
  2054. }
  2055. }
  2056. // TestProgressOutput only supported if console supports it and not logging
  2057. // to a file
  2058. this->TestProgressOutput = this->TestProgressOutput &&
  2059. !this->OutputLogFile && this->ProgressOutputSupportedByConsole();
  2060. #ifdef _WIN32
  2061. if (this->TestProgressOutput) {
  2062. // Disable output line buffering so we can print content without
  2063. // a newline.
  2064. std::setvbuf(stdout, nullptr, _IONBF, 0);
  2065. }
  2066. #endif
  2067. // now what should cmake do? if --build-and-test was specified then
  2068. // we run the build and test handler and return
  2069. if (cmakeAndTest) {
  2070. return this->RunCMakeAndTest(output);
  2071. }
  2072. if (executeTests) {
  2073. return this->ExecuteTests();
  2074. }
  2075. return 1;
  2076. }
  2077. bool cmCTest::HandleTestActionArgument(const char* ctestExec, size_t& i,
  2078. const std::vector<std::string>& args)
  2079. {
  2080. bool success = true;
  2081. std::string arg = args[i];
  2082. if (this->CheckArgument(arg, "-T", "--test-action") &&
  2083. (i < args.size() - 1)) {
  2084. this->ProduceXML = true;
  2085. i++;
  2086. if (!this->SetTest(args[i].c_str(), false)) {
  2087. success = false;
  2088. cmCTestLog(this, ERROR_MESSAGE,
  2089. "CTest -T called with incorrect option: " << args[i]
  2090. << std::endl);
  2091. cmCTestLog(this, ERROR_MESSAGE,
  2092. "Available options are:"
  2093. << std::endl
  2094. << " " << ctestExec << " -T all" << std::endl
  2095. << " " << ctestExec << " -T start" << std::endl
  2096. << " " << ctestExec << " -T update" << std::endl
  2097. << " " << ctestExec << " -T configure" << std::endl
  2098. << " " << ctestExec << " -T build" << std::endl
  2099. << " " << ctestExec << " -T test" << std::endl
  2100. << " " << ctestExec << " -T coverage" << std::endl
  2101. << " " << ctestExec << " -T memcheck" << std::endl
  2102. << " " << ctestExec << " -T notes" << std::endl
  2103. << " " << ctestExec << " -T submit" << std::endl);
  2104. }
  2105. }
  2106. return success;
  2107. }
  2108. bool cmCTest::HandleTestModelArgument(const char* ctestExec, size_t& i,
  2109. const std::vector<std::string>& args)
  2110. {
  2111. bool success = true;
  2112. std::string arg = args[i];
  2113. if (this->CheckArgument(arg, "-M", "--test-model") &&
  2114. (i < args.size() - 1)) {
  2115. i++;
  2116. std::string const& str = args[i];
  2117. if (cmSystemTools::LowerCase(str) == "nightly") {
  2118. this->SetTestModel(cmCTest::NIGHTLY);
  2119. } else if (cmSystemTools::LowerCase(str) == "continuous") {
  2120. this->SetTestModel(cmCTest::CONTINUOUS);
  2121. } else if (cmSystemTools::LowerCase(str) == "experimental") {
  2122. this->SetTestModel(cmCTest::EXPERIMENTAL);
  2123. } else {
  2124. success = false;
  2125. cmCTestLog(this, ERROR_MESSAGE,
  2126. "CTest -M called with incorrect option: " << str
  2127. << std::endl);
  2128. cmCTestLog(this, ERROR_MESSAGE,
  2129. "Available options are:"
  2130. << std::endl
  2131. << " " << ctestExec << " -M Continuous" << std::endl
  2132. << " " << ctestExec << " -M Experimental" << std::endl
  2133. << " " << ctestExec << " -M Nightly" << std::endl);
  2134. }
  2135. }
  2136. return success;
  2137. }
  2138. int cmCTest::ExecuteTests()
  2139. {
  2140. int res;
  2141. // call process directory
  2142. if (this->RunConfigurationScript) {
  2143. if (this->ExtraVerbose) {
  2144. cmCTestLog(this, OUTPUT, "* Extra verbosity turned on" << std::endl);
  2145. }
  2146. for (auto& handler : this->TestingHandlers) {
  2147. handler.second->SetVerbose(this->ExtraVerbose);
  2148. handler.second->SetSubmitIndex(this->SubmitIndex);
  2149. }
  2150. this->GetHandler("script")->SetVerbose(this->Verbose);
  2151. res = this->GetHandler("script")->ProcessHandler();
  2152. if (res != 0) {
  2153. cmCTestLog(this, DEBUG,
  2154. "running script failing returning: " << res << std::endl);
  2155. }
  2156. } else {
  2157. // What is this? -V seems to be the same as -VV,
  2158. // and Verbose is always on in this case
  2159. this->ExtraVerbose = this->Verbose;
  2160. this->Verbose = true;
  2161. for (auto& handler : this->TestingHandlers) {
  2162. handler.second->SetVerbose(this->Verbose);
  2163. handler.second->SetSubmitIndex(this->SubmitIndex);
  2164. }
  2165. std::string cwd = cmSystemTools::GetCurrentWorkingDirectory();
  2166. if (!this->Initialize(cwd.c_str(), nullptr)) {
  2167. res = 12;
  2168. cmCTestLog(this, ERROR_MESSAGE,
  2169. "Problem initializing the dashboard." << std::endl);
  2170. } else {
  2171. res = this->ProcessSteps();
  2172. }
  2173. this->Finalize();
  2174. }
  2175. if (res != 0) {
  2176. cmCTestLog(this, DEBUG,
  2177. "Running a test(s) failed returning : " << res << std::endl);
  2178. }
  2179. return res;
  2180. }
  2181. int cmCTest::RunCMakeAndTest(std::string* output)
  2182. {
  2183. this->Verbose = true;
  2184. cmCTestBuildAndTestHandler* handler =
  2185. static_cast<cmCTestBuildAndTestHandler*>(this->GetHandler("buildtest"));
  2186. int retv = handler->ProcessHandler();
  2187. *output = handler->GetOutput();
  2188. #ifdef CMAKE_BUILD_WITH_CMAKE
  2189. cmDynamicLoader::FlushCache();
  2190. #endif
  2191. if (retv != 0) {
  2192. cmCTestLog(this, DEBUG,
  2193. "build and test failing returning: " << retv << std::endl);
  2194. }
  2195. return retv;
  2196. }
  2197. void cmCTest::SetNotesFiles(const char* notes)
  2198. {
  2199. if (!notes) {
  2200. return;
  2201. }
  2202. this->NotesFiles = notes;
  2203. }
  2204. void cmCTest::SetStopTime(std::string const& time_str)
  2205. {
  2206. struct tm* lctime;
  2207. time_t current_time = time(nullptr);
  2208. lctime = gmtime(&current_time);
  2209. int gm_hour = lctime->tm_hour;
  2210. time_t gm_time = mktime(lctime);
  2211. lctime = localtime(&current_time);
  2212. int local_hour = lctime->tm_hour;
  2213. int tzone_offset = local_hour - gm_hour;
  2214. if (gm_time > current_time && gm_hour < local_hour) {
  2215. // this means gm_time is on the next day
  2216. tzone_offset -= 24;
  2217. } else if (gm_time < current_time && gm_hour > local_hour) {
  2218. // this means gm_time is on the previous day
  2219. tzone_offset += 24;
  2220. }
  2221. tzone_offset *= 100;
  2222. char buf[1024];
  2223. sprintf(buf, "%d%02d%02d %s %+05i", lctime->tm_year + 1900,
  2224. lctime->tm_mon + 1, lctime->tm_mday, time_str.c_str(), tzone_offset);
  2225. time_t stop_time = curl_getdate(buf, &current_time);
  2226. if (stop_time == -1) {
  2227. this->StopTime = std::chrono::system_clock::time_point();
  2228. return;
  2229. }
  2230. this->StopTime = std::chrono::system_clock::from_time_t(stop_time);
  2231. if (stop_time < current_time) {
  2232. this->StopTime += std::chrono::hours(24);
  2233. }
  2234. }
  2235. int cmCTest::ReadCustomConfigurationFileTree(const char* dir, cmMakefile* mf)
  2236. {
  2237. bool found = false;
  2238. VectorOfStrings dirs;
  2239. VectorOfStrings ndirs;
  2240. cmCTestLog(this, DEBUG,
  2241. "* Read custom CTest configuration directory: " << dir
  2242. << std::endl);
  2243. std::string fname = dir;
  2244. fname += "/CTestCustom.cmake";
  2245. cmCTestLog(this, DEBUG, "* Check for file: " << fname << std::endl);
  2246. if (cmSystemTools::FileExists(fname)) {
  2247. cmCTestLog(this, DEBUG,
  2248. "* Read custom CTest configuration file: " << fname
  2249. << std::endl);
  2250. bool erroroc = cmSystemTools::GetErrorOccuredFlag();
  2251. cmSystemTools::ResetErrorOccuredFlag();
  2252. if (!mf->ReadListFile(fname.c_str()) ||
  2253. cmSystemTools::GetErrorOccuredFlag()) {
  2254. cmCTestLog(this, ERROR_MESSAGE,
  2255. "Problem reading custom configuration: " << fname
  2256. << std::endl);
  2257. }
  2258. found = true;
  2259. if (erroroc) {
  2260. cmSystemTools::SetErrorOccured();
  2261. }
  2262. }
  2263. std::string rexpr = dir;
  2264. rexpr += "/CTestCustom.ctest";
  2265. cmCTestLog(this, DEBUG, "* Check for file: " << rexpr << std::endl);
  2266. if (!found && cmSystemTools::FileExists(rexpr)) {
  2267. cmsys::Glob gl;
  2268. gl.RecurseOn();
  2269. gl.FindFiles(rexpr);
  2270. std::vector<std::string>& files = gl.GetFiles();
  2271. std::vector<std::string>::iterator fileIt;
  2272. for (fileIt = files.begin(); fileIt != files.end(); ++fileIt) {
  2273. cmCTestLog(this, DEBUG,
  2274. "* Read custom CTest configuration file: " << *fileIt
  2275. << std::endl);
  2276. if (!mf->ReadListFile(fileIt->c_str()) ||
  2277. cmSystemTools::GetErrorOccuredFlag()) {
  2278. cmCTestLog(this, ERROR_MESSAGE,
  2279. "Problem reading custom configuration: " << *fileIt
  2280. << std::endl);
  2281. }
  2282. }
  2283. found = true;
  2284. }
  2285. if (found) {
  2286. for (auto& handler : this->TestingHandlers) {
  2287. cmCTestLog(this, DEBUG,
  2288. "* Read custom CTest configuration vectors for handler: "
  2289. << handler.first << " (" << handler.second << ")"
  2290. << std::endl);
  2291. handler.second->PopulateCustomVectors(mf);
  2292. }
  2293. }
  2294. return 1;
  2295. }
  2296. void cmCTest::PopulateCustomVector(cmMakefile* mf, const std::string& def,
  2297. std::vector<std::string>& vec)
  2298. {
  2299. const char* dval = mf->GetDefinition(def);
  2300. if (!dval) {
  2301. return;
  2302. }
  2303. cmCTestLog(this, DEBUG, "PopulateCustomVector: " << def << std::endl);
  2304. vec.clear();
  2305. cmSystemTools::ExpandListArgument(dval, vec);
  2306. for (std::string const& it : vec) {
  2307. cmCTestLog(this, DEBUG, " -- " << it << std::endl);
  2308. }
  2309. }
  2310. void cmCTest::PopulateCustomInteger(cmMakefile* mf, const std::string& def,
  2311. int& val)
  2312. {
  2313. const char* dval = mf->GetDefinition(def);
  2314. if (!dval) {
  2315. return;
  2316. }
  2317. val = atoi(dval);
  2318. }
  2319. std::string cmCTest::GetShortPathToFile(const char* cfname)
  2320. {
  2321. const std::string& sourceDir = cmSystemTools::CollapseFullPath(
  2322. this->GetCTestConfiguration("SourceDirectory"));
  2323. const std::string& buildDir = cmSystemTools::CollapseFullPath(
  2324. this->GetCTestConfiguration("BuildDirectory"));
  2325. std::string fname = cmSystemTools::CollapseFullPath(cfname);
  2326. // Find relative paths to both directories
  2327. std::string srcRelpath = cmSystemTools::RelativePath(sourceDir, fname);
  2328. std::string bldRelpath = cmSystemTools::RelativePath(buildDir, fname);
  2329. // If any contains "." it is not parent directory
  2330. bool inSrc = srcRelpath.find("..") == std::string::npos;
  2331. bool inBld = bldRelpath.find("..") == std::string::npos;
  2332. // TODO: Handle files with .. in their name
  2333. std::string* res = nullptr;
  2334. if (inSrc && inBld) {
  2335. // If both have relative path with no dots, pick the shorter one
  2336. if (srcRelpath.size() < bldRelpath.size()) {
  2337. res = &srcRelpath;
  2338. } else {
  2339. res = &bldRelpath;
  2340. }
  2341. } else if (inSrc) {
  2342. res = &srcRelpath;
  2343. } else if (inBld) {
  2344. res = &bldRelpath;
  2345. }
  2346. std::string path;
  2347. if (!res) {
  2348. path = fname;
  2349. } else {
  2350. cmSystemTools::ConvertToUnixSlashes(*res);
  2351. path = "./" + *res;
  2352. if (path[path.size() - 1] == '/') {
  2353. path = path.substr(0, path.size() - 1);
  2354. }
  2355. }
  2356. cmsys::SystemTools::ReplaceString(path, ":", "_");
  2357. cmsys::SystemTools::ReplaceString(path, " ", "_");
  2358. return path;
  2359. }
  2360. std::string cmCTest::GetCTestConfiguration(const std::string& name)
  2361. {
  2362. if (this->CTestConfigurationOverwrites.find(name) !=
  2363. this->CTestConfigurationOverwrites.end()) {
  2364. return this->CTestConfigurationOverwrites[name];
  2365. }
  2366. return this->CTestConfiguration[name];
  2367. }
  2368. void cmCTest::EmptyCTestConfiguration()
  2369. {
  2370. this->CTestConfiguration.clear();
  2371. }
  2372. void cmCTest::SetCTestConfiguration(const char* name, const char* value,
  2373. bool suppress)
  2374. {
  2375. cmCTestOptionalLog(this, HANDLER_VERBOSE_OUTPUT,
  2376. "SetCTestConfiguration:"
  2377. << name << ":" << (value ? value : "(null)") << "\n",
  2378. suppress);
  2379. if (!name) {
  2380. return;
  2381. }
  2382. if (!value) {
  2383. this->CTestConfiguration.erase(name);
  2384. return;
  2385. }
  2386. this->CTestConfiguration[name] = value;
  2387. }
  2388. std::string cmCTest::GetCurrentTag()
  2389. {
  2390. return this->CurrentTag;
  2391. }
  2392. std::string cmCTest::GetBinaryDir()
  2393. {
  2394. return this->BinaryDir;
  2395. }
  2396. std::string const& cmCTest::GetConfigType()
  2397. {
  2398. return this->ConfigType;
  2399. }
  2400. bool cmCTest::GetShowOnly()
  2401. {
  2402. return this->ShowOnly;
  2403. }
  2404. int cmCTest::GetMaxTestNameWidth() const
  2405. {
  2406. return this->MaxTestNameWidth;
  2407. }
  2408. void cmCTest::SetProduceXML(bool v)
  2409. {
  2410. this->ProduceXML = v;
  2411. }
  2412. bool cmCTest::GetProduceXML()
  2413. {
  2414. return this->ProduceXML;
  2415. }
  2416. const char* cmCTest::GetSpecificTrack()
  2417. {
  2418. if (this->SpecificTrack.empty()) {
  2419. return nullptr;
  2420. }
  2421. return this->SpecificTrack.c_str();
  2422. }
  2423. void cmCTest::SetSpecificTrack(const char* track)
  2424. {
  2425. if (!track) {
  2426. this->SpecificTrack.clear();
  2427. return;
  2428. }
  2429. this->SpecificTrack = track;
  2430. }
  2431. void cmCTest::AddSubmitFile(Part part, const char* name)
  2432. {
  2433. this->Parts[part].SubmitFiles.push_back(name);
  2434. }
  2435. void cmCTest::AddCTestConfigurationOverwrite(const std::string& overStr)
  2436. {
  2437. size_t epos = overStr.find('=');
  2438. if (epos == std::string::npos) {
  2439. cmCTestLog(this, ERROR_MESSAGE,
  2440. "CTest configuration overwrite specified in the wrong format."
  2441. << std::endl
  2442. << "Valid format is: --overwrite key=value" << std::endl
  2443. << "The specified was: --overwrite " << overStr << std::endl);
  2444. return;
  2445. }
  2446. std::string key = overStr.substr(0, epos);
  2447. std::string value = overStr.substr(epos + 1);
  2448. this->CTestConfigurationOverwrites[key] = value;
  2449. }
  2450. void cmCTest::SetConfigType(const char* ct)
  2451. {
  2452. this->ConfigType = ct ? ct : "";
  2453. cmSystemTools::ReplaceString(this->ConfigType, ".\\", "");
  2454. std::string confTypeEnv = "CMAKE_CONFIG_TYPE=" + this->ConfigType;
  2455. cmSystemTools::PutEnv(confTypeEnv);
  2456. }
  2457. bool cmCTest::SetCTestConfigurationFromCMakeVariable(
  2458. cmMakefile* mf, const char* dconfig, const std::string& cmake_var,
  2459. bool suppress)
  2460. {
  2461. const char* ctvar;
  2462. ctvar = mf->GetDefinition(cmake_var);
  2463. if (!ctvar) {
  2464. return false;
  2465. }
  2466. cmCTestOptionalLog(this, HANDLER_VERBOSE_OUTPUT,
  2467. "SetCTestConfigurationFromCMakeVariable:"
  2468. << dconfig << ":" << cmake_var << std::endl,
  2469. suppress);
  2470. this->SetCTestConfiguration(dconfig, ctvar, suppress);
  2471. return true;
  2472. }
  2473. bool cmCTest::RunCommand(std::vector<std::string> const& args,
  2474. std::string* stdOut, std::string* stdErr, int* retVal,
  2475. const char* dir, cmDuration timeout,
  2476. Encoding encoding)
  2477. {
  2478. std::vector<const char*> argv;
  2479. argv.reserve(args.size() + 1);
  2480. for (std::string const& a : args) {
  2481. argv.push_back(a.c_str());
  2482. }
  2483. argv.push_back(nullptr);
  2484. stdOut->clear();
  2485. stdErr->clear();
  2486. cmsysProcess* cp = cmsysProcess_New();
  2487. cmsysProcess_SetCommand(cp, &*argv.begin());
  2488. cmsysProcess_SetWorkingDirectory(cp, dir);
  2489. if (cmSystemTools::GetRunCommandHideConsole()) {
  2490. cmsysProcess_SetOption(cp, cmsysProcess_Option_HideWindow, 1);
  2491. }
  2492. cmsysProcess_SetTimeout(cp, timeout.count());
  2493. cmsysProcess_Execute(cp);
  2494. std::vector<char> tempOutput;
  2495. std::vector<char> tempError;
  2496. char* data;
  2497. int length;
  2498. cmProcessOutput processOutput(encoding);
  2499. std::string strdata;
  2500. int res;
  2501. bool done = false;
  2502. while (!done) {
  2503. res = cmsysProcess_WaitForData(cp, &data, &length, nullptr);
  2504. switch (res) {
  2505. case cmsysProcess_Pipe_STDOUT:
  2506. tempOutput.insert(tempOutput.end(), data, data + length);
  2507. break;
  2508. case cmsysProcess_Pipe_STDERR:
  2509. tempError.insert(tempError.end(), data, data + length);
  2510. break;
  2511. default:
  2512. done = true;
  2513. }
  2514. if ((res == cmsysProcess_Pipe_STDOUT || res == cmsysProcess_Pipe_STDERR) &&
  2515. this->ExtraVerbose) {
  2516. processOutput.DecodeText(data, length, strdata);
  2517. cmSystemTools::Stdout(strdata.c_str(), strdata.size());
  2518. }
  2519. }
  2520. if (this->ExtraVerbose) {
  2521. processOutput.DecodeText(std::string(), strdata);
  2522. if (!strdata.empty()) {
  2523. cmSystemTools::Stdout(strdata.c_str(), strdata.size());
  2524. }
  2525. }
  2526. cmsysProcess_WaitForExit(cp, nullptr);
  2527. if (!tempOutput.empty()) {
  2528. processOutput.DecodeText(tempOutput, tempOutput);
  2529. stdOut->append(&*tempOutput.begin(), tempOutput.size());
  2530. }
  2531. if (!tempError.empty()) {
  2532. processOutput.DecodeText(tempError, tempError);
  2533. stdErr->append(&*tempError.begin(), tempError.size());
  2534. }
  2535. bool result = true;
  2536. if (cmsysProcess_GetState(cp) == cmsysProcess_State_Exited) {
  2537. if (retVal) {
  2538. *retVal = cmsysProcess_GetExitValue(cp);
  2539. } else {
  2540. if (cmsysProcess_GetExitValue(cp) != 0) {
  2541. result = false;
  2542. }
  2543. }
  2544. } else if (cmsysProcess_GetState(cp) == cmsysProcess_State_Exception) {
  2545. const char* exception_str = cmsysProcess_GetExceptionString(cp);
  2546. cmCTestLog(this, ERROR_MESSAGE, exception_str << std::endl);
  2547. stdErr->append(exception_str, strlen(exception_str));
  2548. result = false;
  2549. } else if (cmsysProcess_GetState(cp) == cmsysProcess_State_Error) {
  2550. const char* error_str = cmsysProcess_GetErrorString(cp);
  2551. cmCTestLog(this, ERROR_MESSAGE, error_str << std::endl);
  2552. stdErr->append(error_str, strlen(error_str));
  2553. result = false;
  2554. } else if (cmsysProcess_GetState(cp) == cmsysProcess_State_Expired) {
  2555. const char* error_str = "Process terminated due to timeout\n";
  2556. cmCTestLog(this, ERROR_MESSAGE, error_str << std::endl);
  2557. stdErr->append(error_str, strlen(error_str));
  2558. result = false;
  2559. }
  2560. cmsysProcess_Delete(cp);
  2561. return result;
  2562. }
  2563. void cmCTest::SetOutputLogFileName(const char* name)
  2564. {
  2565. if (this->OutputLogFile) {
  2566. delete this->OutputLogFile;
  2567. this->OutputLogFile = nullptr;
  2568. }
  2569. if (name) {
  2570. this->OutputLogFile = new cmGeneratedFileStream(name);
  2571. }
  2572. }
  2573. static const char* cmCTestStringLogType[] = { "DEBUG",
  2574. "OUTPUT",
  2575. "HANDLER_OUTPUT",
  2576. "HANDLER_PROGRESS_OUTPUT",
  2577. "HANDLER_TEST_PROGRESS_OUTPUT",
  2578. "HANDLER_VERBOSE_OUTPUT",
  2579. "WARNING",
  2580. "ERROR_MESSAGE",
  2581. nullptr };
  2582. #define cmCTestLogOutputFileLine(stream) \
  2583. if (this->ShowLineNumbers) { \
  2584. (stream) << std::endl << file << ":" << line << " "; \
  2585. }
  2586. void cmCTest::InitStreams()
  2587. {
  2588. // By default we write output to the process output streams.
  2589. this->StreamOut = &std::cout;
  2590. this->StreamErr = &std::cerr;
  2591. }
  2592. void cmCTest::Log(int logType, const char* file, int line, const char* msg,
  2593. bool suppress)
  2594. {
  2595. if (!msg || !*msg) {
  2596. return;
  2597. }
  2598. if (suppress && logType != cmCTest::ERROR_MESSAGE) {
  2599. return;
  2600. }
  2601. if (logType == cmCTest::HANDLER_PROGRESS_OUTPUT &&
  2602. (this->Debug || this->ExtraVerbose)) {
  2603. return;
  2604. }
  2605. if (this->OutputLogFile) {
  2606. bool display = true;
  2607. if (logType == cmCTest::DEBUG && !this->Debug) {
  2608. display = false;
  2609. }
  2610. if (logType == cmCTest::HANDLER_VERBOSE_OUTPUT && !this->Debug &&
  2611. !this->ExtraVerbose) {
  2612. display = false;
  2613. }
  2614. if (display) {
  2615. cmCTestLogOutputFileLine(*this->OutputLogFile);
  2616. if (logType != this->OutputLogFileLastTag) {
  2617. *this->OutputLogFile << "[";
  2618. if (logType >= OTHER || logType < 0) {
  2619. *this->OutputLogFile << "OTHER";
  2620. } else {
  2621. *this->OutputLogFile << cmCTestStringLogType[logType];
  2622. }
  2623. *this->OutputLogFile << "] " << std::endl << std::flush;
  2624. }
  2625. *this->OutputLogFile << msg << std::flush;
  2626. if (logType != this->OutputLogFileLastTag) {
  2627. *this->OutputLogFile << std::endl << std::flush;
  2628. this->OutputLogFileLastTag = logType;
  2629. }
  2630. }
  2631. }
  2632. if (!this->Quiet) {
  2633. std::ostream& out = *this->StreamOut;
  2634. std::ostream& err = *this->StreamErr;
  2635. if (logType == HANDLER_TEST_PROGRESS_OUTPUT) {
  2636. if (this->TestProgressOutput) {
  2637. cmCTestLogOutputFileLine(out);
  2638. if (this->FlushTestProgressLine) {
  2639. printf("\r");
  2640. this->FlushTestProgressLine = false;
  2641. out.flush();
  2642. }
  2643. std::string msg_str{ msg };
  2644. auto const lineBreakIt = msg_str.find('\n');
  2645. if (lineBreakIt != std::string::npos) {
  2646. this->FlushTestProgressLine = true;
  2647. msg_str.erase(std::remove(msg_str.begin(), msg_str.end(), '\n'),
  2648. msg_str.end());
  2649. }
  2650. out << msg_str;
  2651. #ifndef _WIN32
  2652. printf("\x1B[K"); // move caret to end
  2653. #endif
  2654. out.flush();
  2655. return;
  2656. }
  2657. logType = HANDLER_OUTPUT;
  2658. }
  2659. switch (logType) {
  2660. case DEBUG:
  2661. if (this->Debug) {
  2662. cmCTestLogOutputFileLine(out);
  2663. out << msg;
  2664. out.flush();
  2665. }
  2666. break;
  2667. case OUTPUT:
  2668. case HANDLER_OUTPUT:
  2669. if (this->Debug || this->Verbose) {
  2670. cmCTestLogOutputFileLine(out);
  2671. out << msg;
  2672. out.flush();
  2673. }
  2674. break;
  2675. case HANDLER_VERBOSE_OUTPUT:
  2676. if (this->Debug || this->ExtraVerbose) {
  2677. cmCTestLogOutputFileLine(out);
  2678. out << msg;
  2679. out.flush();
  2680. }
  2681. break;
  2682. case WARNING:
  2683. cmCTestLogOutputFileLine(err);
  2684. err << msg;
  2685. err.flush();
  2686. break;
  2687. case ERROR_MESSAGE:
  2688. cmCTestLogOutputFileLine(err);
  2689. err << msg;
  2690. err.flush();
  2691. cmSystemTools::SetErrorOccured();
  2692. break;
  2693. default:
  2694. cmCTestLogOutputFileLine(out);
  2695. out << msg;
  2696. out.flush();
  2697. }
  2698. }
  2699. }
  2700. cmDuration cmCTest::GetRemainingTimeAllowed()
  2701. {
  2702. if (!this->GetHandler("script")) {
  2703. return cmCTest::MaxDuration();
  2704. }
  2705. cmCTestScriptHandler* ch =
  2706. static_cast<cmCTestScriptHandler*>(this->GetHandler("script"));
  2707. return ch->GetRemainingTimeAllowed();
  2708. }
  2709. cmDuration cmCTest::MaxDuration()
  2710. {
  2711. return cmDuration(1.0e7);
  2712. }
  2713. void cmCTest::SetRunCurrentScript(bool value)
  2714. {
  2715. cmCTestScriptHandler* ch =
  2716. static_cast<cmCTestScriptHandler*>(this->GetHandler("script"));
  2717. ch->SetRunCurrentScript(value);
  2718. }
  2719. void cmCTest::OutputTestErrors(std::vector<char> const& process_output)
  2720. {
  2721. std::string test_outputs("\n*** Test Failed:\n");
  2722. if (!process_output.empty()) {
  2723. test_outputs.append(&*process_output.begin(), process_output.size());
  2724. }
  2725. cmCTestLog(this, HANDLER_OUTPUT, test_outputs << std::endl << std::flush);
  2726. }
  2727. bool cmCTest::CompressString(std::string& str)
  2728. {
  2729. int ret;
  2730. z_stream strm;
  2731. strm.zalloc = Z_NULL;
  2732. strm.zfree = Z_NULL;
  2733. strm.opaque = Z_NULL;
  2734. ret = deflateInit(&strm, -1); // default compression level
  2735. if (ret != Z_OK) {
  2736. return false;
  2737. }
  2738. unsigned char* in =
  2739. reinterpret_cast<unsigned char*>(const_cast<char*>(str.c_str()));
  2740. // zlib makes the guarantee that this is the maximum output size
  2741. int outSize =
  2742. static_cast<int>(static_cast<double>(str.size()) * 1.001 + 13.0);
  2743. std::vector<unsigned char> out(outSize);
  2744. strm.avail_in = static_cast<uInt>(str.size());
  2745. strm.next_in = in;
  2746. strm.avail_out = outSize;
  2747. strm.next_out = &out[0];
  2748. ret = deflate(&strm, Z_FINISH);
  2749. if (ret != Z_STREAM_END) {
  2750. cmCTestLog(this, ERROR_MESSAGE,
  2751. "Error during gzip compression." << std::endl);
  2752. return false;
  2753. }
  2754. (void)deflateEnd(&strm);
  2755. // Now base64 encode the resulting binary string
  2756. std::vector<unsigned char> base64EncodedBuffer((outSize * 3) / 2);
  2757. size_t rlen =
  2758. cmsysBase64_Encode(&out[0], strm.total_out, &base64EncodedBuffer[0], 1);
  2759. str.assign(reinterpret_cast<char*>(&base64EncodedBuffer[0]), rlen);
  2760. return true;
  2761. }