cmCTest.cxx 90 KB

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